From 001237c7a42b62581dd3b43b39ede68eb3ce6cf3 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Thu, 6 Aug 2026 12:00:22 -0700 Subject: [PATCH 001/206] chore: update lance dependency to v11.0.0-beta.2 (#3886) Updates the Lance dependencies and Java lance-core to v11.0.0-beta.2. Includes required compatibility fixes for the LanceFileVersion module move and the updated GooseFS/OpenDAL dependency. Lance tag: https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.2 --------- Co-authored-by: Daniel Rammer Co-authored-by: Claude Opus 5 (1M context) --- .github/workflows/rust.yml | 14 +- Cargo.lock | 492 +++++++++++++----------- Cargo.toml | 28 +- java/pom.xml | 2 +- rust/lancedb/Cargo.toml | 4 +- rust/lancedb/src/blob.rs | 2 +- rust/lancedb/src/connection.rs | 2 +- rust/lancedb/src/database/listing.rs | 2 +- rust/lancedb/src/database/namespace.rs | 4 +- rust/lancedb/src/remote/table.rs | 8 +- rust/lancedb/src/remote/table/blobs.rs | 2 +- rust/lancedb/src/remote/table/insert.rs | 4 +- rust/lancedb/tests/blob_integration.rs | 2 +- 13 files changed, 297 insertions(+), 269 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 1a0b65c4a..471da43e0 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -296,16 +296,18 @@ jobs: cargo update -p aws-types --precise 1.3.9 cargo update -p aws-sigv4 --precise 1.3.5 cargo update -p aws-credential-types --precise 1.2.8 - cargo update -p aws-smithy-checksums --precise 0.63.9 + # aws-smithy-checksums must stay at or above 0.63.13: OpenDAL's S3 + # service needs crc-fast ~1.9, and older releases pin it to ~1.3. + cargo update -p aws-smithy-checksums --precise 0.63.13 cargo update -p aws-smithy-runtime --precise 1.9.3 - cargo update -p aws-smithy-http --precise 0.62.4 - cargo update -p aws-smithy-eventstream --precise 0.60.12 + cargo update -p aws-smithy-http --precise 0.62.6 + cargo update -p aws-smithy-eventstream --precise 0.60.14 cargo update -p aws-smithy-http-client --precise 1.1.3 cargo update -p aws-smithy-observability --precise 0.1.4 cargo update -p aws-smithy-query --precise 0.60.8 - cargo update -p aws-smithy-runtime-api --precise 1.9.1 - cargo update -p aws-smithy-async --precise 1.2.6 - cargo update -p aws-smithy-types --precise 1.3.5 + cargo update -p aws-smithy-runtime-api --precise 1.9.3 + cargo update -p aws-smithy-async --precise 1.2.7 + cargo update -p aws-smithy-types --precise 1.3.6 cargo update -p aws-smithy-xml --precise 0.60.11 cargo update -p home --precise 0.5.9 - name: cargo +${{ matrix.msrv }} check diff --git a/Cargo.lock b/Cargo.lock index 995424b20..93e16c06d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -775,7 +775,7 @@ dependencies = [ "http 0.2.12", "http 1.5.0", "http-body 1.1.0", - "lru", + "lru 0.16.4", "percent-encoding", "regex-lite", "sha2 0.11.0", @@ -1241,6 +1241,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64-simd" version = "0.8.0" @@ -1964,15 +1970,6 @@ dependencies = [ "spin 0.10.1", ] -[[package]] -name = "crc32c" -version = "0.6.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a47af21622d091a8f0fb295b88bc886ac74efcc613efc19f5d0b21de5c89e47" -dependencies = [ - "rustc_version", -] - [[package]] name = "crc32fast" version = "1.5.0" @@ -2174,9 +2171,9 @@ dependencies = [ [[package]] name = "ctor" -version = "1.0.5" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "378f0974ae2468eaf63aa036dbe9c926b0dc7ea64c156f2ea618bc2f75b934f0" +checksum = "2d83cb7e7a873830708d6b02a78cd36a592c6fa14bf267b68725103b85c0d77f" dependencies = [ "link-section", "linktime-proc-macro", @@ -2902,6 +2899,37 @@ dependencies = [ "uuid", ] +[[package]] +name = "defmt" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 2.0.117", +] + +[[package]] +name = "defmt-parser" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +dependencies = [ + "thiserror 2.0.18", +] + [[package]] name = "der" version = "0.6.1" @@ -3413,6 +3441,12 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "frostem" +version = "1.20260804.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82eb03a32a1d50555353c85a7b9d3279a6f1e91af9890b789acdf544ed57c8d7" + [[package]] name = "fs_extra" version = "1.3.0" @@ -3421,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow-array", "rand 0.9.5", @@ -3779,14 +3813,23 @@ dependencies = [ [[package]] name = "goosefs-sdk" -version = "0.1.5" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ae079b88ffe7772d12cfc5c40a5a324babb357893d95b5e3a22ae857f236c5f" +checksum = "e1ea4eee6dcbc31b25ab4fd577adc55b677d2bed3aa3016c44c58fbe1b2298a5" dependencies = [ + "arc-swap", "async-trait", "bytes", "dashmap", + "fastrand", + "futures", "hostname", + "io-uring", + "itoa", + "libc", + "lru 0.18.2", + "memmap2 0.9.10", + "moka", "prost", "prost-types", "rand 0.9.5", @@ -3799,6 +3842,7 @@ dependencies = [ "tonic-prost", "tracing", "uuid", + "xxhash-rust", ] [[package]] @@ -4599,10 +4643,12 @@ dependencies = [ [[package]] name = "jiff" -version = "0.2.24" +version = "0.2.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f00b5dbd620d61dfdcb6007c9c1f6054ebd75319f163d886a9055cec1155073d" +checksum = "668b7183bd07af9a4885f5c35b0cc5c83c4607a913c16b7e17291832910d2dcc" dependencies = [ + "defmt", + "jiff-core", "jiff-static", "jiff-tzdb-platform", "js-sys", @@ -4611,15 +4657,25 @@ dependencies = [ "portable-atomic-util", "serde_core", "wasm-bindgen", - "windows-sys 0.61.2", + "windows-link", +] + +[[package]] +name = "jiff-core" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7feca88439efe53da3754500c1851dedf3cb36c524dd5cf8225cc0794de95d09" +dependencies = [ + "defmt", ] [[package]] name = "jiff-static" -version = "0.2.24" +version = "0.2.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e000de030ff8022ea1da3f466fbb0f3a809f5e51ed31f6dd931c35181ad8e6d7" +checksum = "3a69dcb3a21cfb32ce1cd056169337ca284af0766dd766e7878819b251a49204" dependencies = [ + "jiff-core", "proc-macro2", "quote", "syn 2.0.117", @@ -4731,24 +4787,6 @@ dependencies = [ "zmij", ] -[[package]] -name = "jsonwebtoken" -version = "10.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eba32bfb4ffdeaca3e34431072faf01745c9b26d25504aa7a6cf5684334fc4fc" -dependencies = [ - "aws-lc-rs", - "base64 0.22.1", - "getrandom 0.2.17", - "js-sys", - "pem", - "serde", - "serde_json", - "signature 2.2.0", - "simple_asn1", - "zeroize", -] - [[package]] name = "kanaria" version = "0.2.0" @@ -4777,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arc-swap", "arrow", @@ -4852,8 +4890,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow-array", "arrow-buffer", @@ -4875,7 +4913,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow-array", "arrow-buffer", @@ -4889,7 +4927,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow-array", "arrow-schema", @@ -4898,8 +4936,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrayref", "crunchy", @@ -4909,8 +4947,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow-array", "arrow-buffer", @@ -4950,8 +4988,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow", "arrow-array", @@ -4981,8 +5019,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow", "arrow-array", @@ -4999,8 +5037,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "proc-macro2", "quote", @@ -5009,8 +5047,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow-arith", "arrow-array", @@ -5036,7 +5074,6 @@ dependencies = [ "prost", "prost-build", "rand 0.9.5", - "strum 0.26.3", "tokio", "tracing", "xxhash-rust", @@ -5045,8 +5082,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow-arith", "arrow-array", @@ -5077,8 +5114,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arc-swap", "arrow", @@ -5145,8 +5182,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow-array", "arrow-schema", @@ -5168,8 +5205,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow", "arrow-array", @@ -5181,7 +5218,6 @@ dependencies = [ "bytes", "chrono", "futures", - "goosefs-sdk", "http 1.5.0", "io-uring", "lance-arrow", @@ -5206,8 +5242,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow-array", "arrow-buffer", @@ -5223,8 +5259,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow", "async-trait", @@ -5236,8 +5272,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow", "arrow-ipc", @@ -5291,8 +5327,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow-array", "arrow-buffer", @@ -5307,8 +5343,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow", "arrow-array", @@ -5347,8 +5383,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ "arrow-array", "arrow-schema", @@ -5361,13 +5397,13 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "10.1.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v10.1.0-beta.1#68f4d4c1d0c4871b067557c61fc405078f1ab3b7" +version = "11.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" dependencies = [ + "frostem", "icu_segmenter", "jieba-rs", "lindera", - "rust-stemmers", "serde", "stop-words", "unicode-normalization", @@ -5645,7 +5681,7 @@ dependencies = [ "serde", "serde_json", "serde_yaml_ng", - "strum 0.28.0", + "strum", "strum_macros 0.28.0", "unicode-blocks", "unicode-normalization", @@ -5675,22 +5711,22 @@ dependencies = [ "rkyv", "serde", "serde_json", - "strum 0.28.0", + "strum", "strum_macros 0.28.0", "thiserror 2.0.18", ] [[package]] name = "link-section" -version = "0.16.1" +version = "0.19.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c8600ca3dbe044f07955b443ff606c50f45295b863289bbe7d0844d50cf11e4" +checksum = "5ee1a0d6e252afe82e7bc2db42fba60e02ddf3b1accaf8cb21d96e34ba61f3d4" [[package]] name = "linktime-proc-macro" -version = "0.1.0" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a44cd706ff0d503ee32b2071166510ca27e281228de10cd3aa8d35ff94560f81" +checksum = "348d0075b1fc163b26d72a7f75fc5141daf2fd1bdf128d873cbaf6785d495bdf" [[package]] name = "linux-raw-sys" @@ -5747,6 +5783,15 @@ dependencies = [ "hashbrown 0.16.1", ] +[[package]] +name = "lru" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d2f2f9b4ba7e6b24d95e7e899329d35be83bcded72c8540cdd5368932d1d90a" +dependencies = [ + "hashbrown 0.17.1", +] + [[package]] name = "lru-slab" version = "0.1.2" @@ -6067,7 +6112,7 @@ checksum = "de33522036981030a75c231829566bc63414e08101a6f5ff4ac6cef19c8e0941" dependencies = [ "bitflags 2.11.1", "chrono", - "ctor 1.0.5", + "ctor 1.0.12", "futures", "napi-build", "napi-sys", @@ -6091,7 +6136,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d5c9c02556ea6dc99dffd36c1ce60141411657438501a125b675776d011ce92" dependencies = [ "convert_case", - "ctor 1.0.5", + "ctor 1.0.12", "napi-derive-backend", "proc-macro2", "quote", @@ -6384,9 +6429,9 @@ dependencies = [ [[package]] name = "object_store_opendal" -version = "0.57.0" +version = "0.58.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eb12a624a41fce745838d0ef3701ff6c47797c13cd18ad3612fd2a3134fdbd8" +checksum = "88f165780495c17aa3ce86846600504198c3fffd99073521552751c2430fa6ac" dependencies = [ "async-trait", "bytes", @@ -6447,12 +6492,13 @@ checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] name = "opendal" -version = "0.57.0" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96c9c85ce253ff87225e7669979d877a20c98a06604ec9d6dd5f4473e08f1ae1" +checksum = "4f20562cc7447fcc915fc5c23df305a412ea80a733c9f2fd9e2d267e2815be6d" dependencies = [ - "ctor 1.0.5", + "ctor 1.0.12", "opendal-core", + "opendal-http-transport-reqwest", "opendal-layer-concurrent-limit", "opendal-layer-logging", "opendal-layer-retry", @@ -6469,24 +6515,22 @@ dependencies = [ [[package]] name = "opendal-core" -version = "0.57.0" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4f8607c90e2c963a91467f50fb49fbc7fb3d573f88cea219ca59ccd3740b309" +checksum = "ec75551ff4cf3e57da98979f6a937aaa9ddb3915bf68cc17d03df733be6646ed" dependencies = [ "anyhow", - "base64 0.22.1", + "base64 0.23.1", "bytes", "futures", "http 1.5.0", - "http-body 1.1.0", "jiff", "log", "md-5 0.11.0", "mea", "percent-encoding", - "quick-xml 0.39.4", + "quick-xml 0.41.0", "reqsign-core", - "reqwest 0.13.3", "serde", "serde_json", "tokio", @@ -6496,10 +6540,24 @@ dependencies = [ ] [[package]] -name = "opendal-layer-concurrent-limit" -version = "0.57.0" +name = "opendal-http-transport-reqwest" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d6f81ba6960e3fae1882f253b114b21d7e444e1534f209c7737a79f6243eb6f" +checksum = "ad4d4f19c3ce01126a30611f8e544eaa217104a278c889ac17c9374fe4f9e4ef" +dependencies = [ + "bytes", + "futures", + "http 1.5.0", + "http-body 1.1.0", + "opendal-core", + "reqwest 0.13.4", +] + +[[package]] +name = "opendal-layer-concurrent-limit" +version = "0.58.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "249ac5b0aa5a7a6c3737342d10456067937f9c9a6f3f02544271f7908ab91081" dependencies = [ "futures", "http 1.5.0", @@ -6509,9 +6567,9 @@ dependencies = [ [[package]] name = "opendal-layer-logging" -version = "0.57.0" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58ada45c6d81d1aa4c9305d0c7d4bc317c59c85866a0908a2d75a7a978aa5ee2" +checksum = "5c75411ab00f77851ff086b686c1e9ca8175ac18c15afa2cb75b9036436cb06c" dependencies = [ "log", "opendal-core", @@ -6519,9 +6577,9 @@ dependencies = [ [[package]] name = "opendal-layer-retry" -version = "0.57.0" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b2a25a718afb81fad81cb9a0580a1cb989221fa2317f888c6a37f8dad408eb7" +checksum = "80b7738bd5f233ad8da39af9b9316b9b7a4eaddd91e8e32a1e19b7030688121d" dependencies = [ "backon", "log", @@ -6530,9 +6588,9 @@ dependencies = [ [[package]] name = "opendal-layer-timeout" -version = "0.57.0" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e91f731724c213af81e9d03517859c8fc47b4578e64ad61ae4f099f10fe36e3" +checksum = "a704141924500f3803c05ed871b53305d2a2f11cb5ef20160c3ee688a1857f66" dependencies = [ "opendal-core", "tokio", @@ -6540,17 +6598,17 @@ dependencies = [ [[package]] name = "opendal-service-azblob" -version = "0.57.0" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0030644366ef5d8cbe3a4a5822bf99a4aafddc1666e9d24b44d158d9062fc76a" +checksum = "b3310fbbb48f111c6f590473c2cd15e1b7f8e384444b0d4e328f0464c864d767" dependencies = [ - "base64 0.22.1", + "base64 0.23.1", "bytes", "http 1.5.0", "log", "opendal-core", "opendal-service-azure-common", - "quick-xml 0.39.4", + "quick-xml 0.41.0", "reqsign-azure-storage", "reqsign-core", "reqsign-file-read-tokio", @@ -6561,17 +6619,18 @@ dependencies = [ [[package]] name = "opendal-service-azdls" -version = "0.57.0" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dea4908d490143a9b0b7f7a790e139ff829b06a023f670455ed3d44f664b361" +checksum = "2e3c406729935fe214ce574d68681a1ff7e0b322548f14094912bdbfe50e5c53" dependencies = [ - "base64 0.22.1", + "base64 0.23.1", "bytes", "http 1.5.0", "log", + "mea", "opendal-core", "opendal-service-azure-common", - "quick-xml 0.39.4", + "quick-xml 0.41.0", "reqsign-azure-storage", "reqsign-core", "reqsign-file-read-tokio", @@ -6581,9 +6640,9 @@ dependencies = [ [[package]] name = "opendal-service-azure-common" -version = "0.57.0" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b489f13c42e69d69bdd72952b634356ec43a7881a20259b38b540fcecdf4051" +checksum = "7348c88edf15af435b7be930077746b569fac5e738c1bf6a363b675e7317c9df" dependencies = [ "http 1.5.0", "opendal-core", @@ -6591,15 +6650,15 @@ dependencies = [ [[package]] name = "opendal-service-cos" -version = "0.57.0" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa8cafe9729213375c7331019b0cb756ad3e1aff7f45cd32c45eae91ebde8901" +checksum = "d533d4582105d269c8aebeee5f0e8bcf960f41b8aab6197df7012254d9f39bf0" dependencies = [ "bytes", "http 1.5.0", "log", "opendal-core", - "quick-xml 0.39.4", + "quick-xml 0.41.0", "reqsign-core", "reqsign-file-read-tokio", "reqsign-tencent-cos", @@ -6608,9 +6667,9 @@ dependencies = [ [[package]] name = "opendal-service-gcs" -version = "0.57.0" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48de101aac565ed06af4b47903c24eafd249075553ec1fb18256751c45148d47" +checksum = "007f3fba63c21e516c956b891e96ff9892d8175662bfb781cdada9d3766a11e6" dependencies = [ "async-trait", "bytes", @@ -6618,7 +6677,7 @@ dependencies = [ "log", "opendal-core", "percent-encoding", - "quick-xml 0.39.4", + "quick-xml 0.41.0", "reqsign-core", "reqsign-file-read-tokio", "reqsign-google", @@ -6629,9 +6688,9 @@ dependencies = [ [[package]] name = "opendal-service-goosefs" -version = "0.57.0" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69e43048bde419947ba826fbdc2f134d6c03f44ebf48bd33a03b72f9fc45fcb4" +checksum = "60871e6386f04d831e6a5bdbc032af4a91aeba49963252d0ef456a2cf36a9b78" dependencies = [ "bytes", "goosefs-sdk", @@ -6643,9 +6702,9 @@ dependencies = [ [[package]] name = "opendal-service-hf" -version = "0.57.0" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4922661976a1d40794a2adfbdb888cc3c23097690f825a92f773af38908a848" +checksum = "b41fd41eb7ed03c5e66cefda61e8e117808ffd2908f2916737cb020a6beb02c7" dependencies = [ "bytes", "hf-xet", @@ -6653,22 +6712,21 @@ dependencies = [ "log", "opendal-core", "percent-encoding", - "reqwest 0.13.3", "serde", "serde_json", ] [[package]] name = "opendal-service-oss" -version = "0.57.0" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "328fa55e8888cbdfe00826bfea2a79042422b720e8369e9e021e46121dea5ace" +checksum = "cd528ec2d49c5ca69e674ffed7b3e0686fb9cfcfea0596870de381467fda4f1b" dependencies = [ "bytes", "http 1.5.0", "log", "opendal-core", - "quick-xml 0.39.4", + "quick-xml 0.41.0", "reqsign-aliyun-oss", "reqsign-core", "reqsign-file-read-tokio", @@ -6677,18 +6735,18 @@ dependencies = [ [[package]] name = "opendal-service-s3" -version = "0.57.0" +version = "0.58.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "313d46c9f5ae70bca26b7c3e3fbb9b639292625f28af73aa016f47e788af9deb" +checksum = "58e80cdf192d7eff05feed747894d64f81905ac4eaf132edf7ea270abdd2d663" dependencies = [ - "base64 0.22.1", + "base64 0.23.1", "bytes", - "crc32c", + "crc-fast", "http 1.5.0", "log", "md-5 0.11.0", "opendal-core", - "quick-xml 0.39.4", + "quick-xml 0.41.0", "reqsign-aws-v4", "reqsign-core", "reqsign-file-read-tokio", @@ -7583,7 +7641,7 @@ version = "0.14.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7" dependencies = [ - "heck 0.4.1", + "heck 0.5.0", "itertools 0.14.0", "log", "multimap", @@ -7799,6 +7857,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", + "serde", +] + [[package]] name = "quick_cache" version = "0.6.24" @@ -8220,9 +8288,9 @@ dependencies = [ [[package]] name = "reqsign-aliyun-oss" -version = "3.0.0" +version = "3.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57ac2757f3140aa2e213b554148ae0b52733e624fc6723f0cc6bb3d440176c95" +checksum = "a5e6d659fcdbca6fe2d7ef109c2e28499b7be80501f1bb86c10caf5ec8ac1219" dependencies = [ "anyhow", "form_urlencoded", @@ -8236,38 +8304,52 @@ dependencies = [ ] [[package]] -name = "reqsign-aws-v4" -version = "3.0.0" +name = "reqsign-aws-core" +version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44eaca382e94505a49f1a4849658d153aebf79d9c1a58e5dd3b10361511e9f43" +checksum = "e4af084e1f3cbf3e67e0c972765399bce54ecec804cceba46b39a8331f3c1bff" dependencies = [ - "anyhow", "bytes", "form_urlencoded", + "hex", "http 1.5.0", "log", "percent-encoding", - "quick-xml 0.39.4", + "quick-xml 0.41.0", "reqsign-core", "rust-ini", "serde", "serde_json", "serde_urlencoded", - "sha1 0.10.6", + "sha1 0.11.0", +] + +[[package]] +name = "reqsign-aws-v4" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ac5b3b7cefa28933792b439186459f77f19f9b6edbeab41b8b187150361a206" +dependencies = [ + "bytes", + "http 1.5.0", + "log", + "quick-xml 0.41.0", + "reqsign-aws-core", + "reqsign-core", + "serde", ] [[package]] name = "reqsign-azure-storage" -version = "3.0.0" +version = "3.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a321980405d596bd34aaf95c4722a3de4128a67fd19e74a81a83aa3fdf082e6" +checksum = "2824e7da3c2cc42ac3406c674eb57c89127fdcd97f3a73c608cfc680505ea134" dependencies = [ "anyhow", - "base64 0.22.1", + "base64 0.23.1", "bytes", "form_urlencoded", "http 1.5.0", - "jsonwebtoken", "log", "pem", "percent-encoding", @@ -8275,36 +8357,38 @@ dependencies = [ "rsa", "serde", "serde_json", - "sha1 0.10.6", + "sha1 0.11.0", ] [[package]] name = "reqsign-core" -version = "3.0.0" +version = "3.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b10302cf0a7d7e7352ba211fc92c3c5bebf1286153e49cc5aa87348078a8e102" +checksum = "c07dd510b1e1b9b241883e483358147fb2ed2d497a7b39b065ba61eb93deceb0" dependencies = [ "anyhow", - "base64 0.22.1", + "base64 0.23.1", "bytes", - "form_urlencoded", "futures", "hex", - "hmac 0.12.1", + "hmac 0.13.0", "http 1.5.0", "jiff", "log", "percent-encoding", - "sha1 0.10.6", - "sha2 0.10.9", + "rsa", + "serde", + "serde_json", + "sha1 0.11.0", + "sha2 0.11.0", "windows-sys 0.61.2", ] [[package]] name = "reqsign-file-read-tokio" -version = "3.0.0" +version = "3.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2d89295b3d17abea31851cc8de55d843d89c52132c864963c38d41920613dc5" +checksum = "663d9d55abd0df0830ef0ae43708297cc1371cf4e8ca91f3ac813c309cca8c98" dependencies = [ "anyhow", "reqsign-core", @@ -8313,13 +8397,12 @@ dependencies = [ [[package]] name = "reqsign-google" -version = "3.0.0" +version = "3.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35cc609b49c69e76ecaceb775a03f792d1ed3e7755ab3548d4534fd801e3242e" +checksum = "4080a227f82a09f68540ecd028622065d7ac4c0bcb8727a25bdcfc0526235792" dependencies = [ "form_urlencoded", "http 1.5.0", - "jsonwebtoken", "log", "percent-encoding", "reqsign-aws-v4", @@ -8327,15 +8410,14 @@ dependencies = [ "rsa", "serde", "serde_json", - "sha2 0.10.9", "tokio", ] [[package]] name = "reqsign-tencent-cos" -version = "3.0.0" +version = "3.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e128f19525861dbded59e1e7c17653a8ed63d573ca04aed708d552dbef5bb32a" +checksum = "764629c90f7c3566a6d4e4641ebab9acd604ce02e16eda4d37c7d7e79e16ed90" dependencies = [ "anyhow", "http 1.5.0", @@ -8394,9 +8476,9 @@ dependencies = [ [[package]] name = "reqwest" -version = "0.13.3" +version = "0.13.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62e0021ea2c22aed41653bc7e1419abb2c97e038ff2c33d0e1309e49a97deec0" +checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3" dependencies = [ "base64 0.22.1", "bytes", @@ -8457,7 +8539,7 @@ dependencies = [ "anyhow", "async-trait", "http 1.5.0", - "reqwest 0.13.3", + "reqwest 0.13.4", "thiserror 2.0.18", "tower-service", ] @@ -8597,16 +8679,6 @@ dependencies = [ "ordered-multimap", ] -[[package]] -name = "rust-stemmers" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e46a2036019fdb888131db7a4c847a1063a7493f971ed94ea82c67eada63ca54" -dependencies = [ - "serde", - "serde_derive", -] - [[package]] name = "rustc-demangle" version = "0.1.27" @@ -9206,18 +9278,6 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" -[[package]] -name = "simple_asn1" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" -dependencies = [ - "num-bigint", - "num-traits", - "thiserror 2.0.18", - "time", -] - [[package]] name = "siphasher" version = "1.0.3" @@ -9277,7 +9337,7 @@ version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451" dependencies = [ - "heck 0.4.1", + "heck 0.5.0", "proc-macro2", "quote", "syn 2.0.117", @@ -9289,7 +9349,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "54254b8531cafa275c5e096f62d48c81435d1015405a91198ddb11e967301d40" dependencies = [ - "heck 0.4.1", + "heck 0.5.0", "proc-macro2", "quote", "syn 2.0.117", @@ -9492,15 +9552,6 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" -[[package]] -name = "strum" -version = "0.26.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06" -dependencies = [ - "strum_macros 0.26.4", -] - [[package]] name = "strum" version = "0.28.0" @@ -9523,19 +9574,6 @@ dependencies = [ "syn 2.0.117", ] -[[package]] -name = "strum_macros" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "rustversion", - "syn 2.0.117", -] - [[package]] name = "strum_macros" version = "0.28.0" @@ -9730,7 +9768,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.2", "once_cell", "rustix", "windows-sys 0.61.2", @@ -11161,7 +11199,7 @@ dependencies = [ "more-asserts", "rand 0.10.1", "redb", - "reqwest 0.13.3", + "reqwest 0.13.4", "reqwest-middleware", "serde", "serde_json", @@ -11274,7 +11312,7 @@ dependencies = [ "oneshot", "pin-project", "rand 0.10.1", - "reqwest 0.13.3", + "reqwest 0.13.4", "serde", "serde_json", "shellexpand", @@ -11370,20 +11408,6 @@ name = "zeroize" version = "1.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" -dependencies = [ - "zeroize_derive", -] - -[[package]] -name = "zeroize_derive" -version = "1.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", -] [[package]] name = "zerotrie" diff --git a/Cargo.toml b/Cargo.toml index 35370e58f..a879d1f8b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=10.1.0-beta.1", default-features = false, "tag" = "v10.1.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=10.1.0-beta.1", "tag" = "v10.1.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=10.1.0-beta.1", "tag" = "v10.1.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=10.1.0-beta.1", "tag" = "v10.1.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=10.1.0-beta.1", default-features = false, "tag" = "v10.1.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=10.1.0-beta.1", "tag" = "v10.1.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=10.1.0-beta.1", "tag" = "v10.1.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=10.1.0-beta.1", "tag" = "v10.1.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=10.1.0-beta.1", default-features = false, "tag" = "v10.1.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=10.1.0-beta.1", "tag" = "v10.1.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=10.1.0-beta.1", "tag" = "v10.1.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=10.1.0-beta.1", "tag" = "v10.1.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=10.1.0-beta.1", "tag" = "v10.1.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=10.1.0-beta.1", "tag" = "v10.1.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.2", default-features = false, "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.2", default-features = false, "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.2", default-features = false, "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } ahash = "0.8" # Note that this one does not include pyarrow arrow = { version = "58.0.0", optional = false } diff --git a/java/pom.xml b/java/pom.xml index 1b96cbcab..e8f030b27 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 10.1.0-beta.1 + 11.0.0-beta.2 false 2.30.0 1.7 diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 816f095de..96ea9ec95 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -49,8 +49,8 @@ lance-namespace = { workspace = true } lance-namespace-impls = { workspace = true } metrics = { workspace = true, optional = true } metrics-util = { workspace = true, optional = true } -# Pin the transitive GooseFS SDK until the 0.1.6 compile break is fixed upstream. -goosefs-sdk = { version = "=0.1.5", optional = true } +# Pin the GooseFS SDK to the version required by Lance's OpenDAL dependency. +goosefs-sdk = { version = "=0.1.9", optional = true } moka = { workspace = true } pin-project = { workspace = true } tokio = { version = "1.23", features = ["rt-multi-thread", "sync"] } diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index 3448257ab..e1c18dd84 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -17,7 +17,7 @@ use arrow_array::builder::LargeBinaryBuilder; use arrow_schema::{DataType, Field, Schema}; use lance::dataset::{BlobRangeRequest as LanceBlobRangeRequest, Dataset, WriteParams}; use lance_arrow::FieldExt; -use lance_encoding::version::LanceFileVersion; +use lance_file::version::LanceFileVersion; use lance_io::object_store::ObjectStore; use object_store::path::Path; diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 89e59e12e..dd53a2d2e 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -34,7 +34,7 @@ use crate::remote::{ db::{OPT_REMOTE_API_KEY, OPT_REMOTE_HOST_OVERRIDE, OPT_REMOTE_REGION}, }; use lance::io::ObjectStoreParams; -pub use lance_encoding::version::LanceFileVersion; +pub use lance_file::version::LanceFileVersion; #[cfg(feature = "remote")] use lance_io::object_store::StorageOptions; use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider}; diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index 4fea6767c..fea34bb48 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -12,7 +12,7 @@ use lance::dataset::refs::Ref; use lance::dataset::{ReadParams, WriteMode, builder::DatasetBuilder}; use lance::io::{ObjectStore, ObjectStoreParams, WrappingObjectStore}; use lance_datafusion::utils::StreamingWriteSource; -use lance_encoding::version::LanceFileVersion; +use lance_file::version::LanceFileVersion; use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider}; use lance_table::io::commit::commit_handler_from_url; use object_store::local::LocalFileSystem; diff --git a/rust/lancedb/src/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index d18c78682..740e11645 100644 --- a/rust/lancedb/src/database/namespace.rs +++ b/rust/lancedb/src/database/namespace.rs @@ -201,7 +201,7 @@ impl LanceNamespaceDatabase { &self, request: &DbCreateTableRequest, ) -> Result<( - Option, + Option, Option, Option, )> { @@ -214,7 +214,7 @@ impl LanceNamespaceDatabase { let storage_version_override = storage_options .and_then(|opts| opts.get(OPT_NEW_TABLE_STORAGE_VERSION)) - .map(|s| s.parse::()) + .map(|s| s.parse::()) .transpose()?; let v2_manifest_override = storage_options diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 29b6b698d..388bed0f7 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2942,7 +2942,7 @@ impl BaseTable for RemoteTable { } #[derive(Serialize, Clone, Debug)] -pub(crate) struct MergeInsertRequest { +pub struct MergeInsertRequest { on: String, when_matched_update_all: bool, when_matched_update_all_filt: Option, @@ -5907,16 +5907,18 @@ mod tests { .await .unwrap(); + // Positions are relative to the first retained token, so dropping the + // leading "hello" stop word does not shift the remaining tokens. assert_eq!( tokens, vec![ FtsToken { text: "こんにちは".to_string(), - position: 1, + position: 0, }, FtsToken { text: "世界".to_string(), - position: 2, + position: 1, }, ] ); diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index bb8a5d103..387d3c6dc 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -90,7 +90,7 @@ struct RemoteBlobState { /// Seekable Cloud blob handle over HTTP Range. #[derive(Debug)] -pub(crate) struct RemoteBlobFile { +pub struct RemoteBlobFile { requester: Arc, state: Mutex, closed: AtomicBool, diff --git a/rust/lancedb/src/remote/table/insert.rs b/rust/lancedb/src/remote/table/insert.rs index 67ea7765d..a4a28a9c6 100644 --- a/rust/lancedb/src/remote/table/insert.rs +++ b/rust/lancedb/src/remote/table/insert.rs @@ -33,7 +33,7 @@ use crate::table::{AddResult, MergeResult}; /// same Arrow-IPC streaming body and error side-channel; only the target /// endpoint, query parameters, and parsed result type differ. #[derive(Debug, Clone)] -pub(crate) enum WriteOp { +pub enum WriteOp { /// `add`: stream to `/v1/table/{id}/insert/`, optionally overwriting. Insert { overwrite: bool }, /// `merge_insert`: stream to `/v1/table/{id}/merge_insert/` with the merge @@ -49,7 +49,7 @@ pub(crate) enum WriteOp { /// The parsed server response for a completed write, discriminated by the /// operation that produced it. #[derive(Debug, Clone)] -pub(crate) enum WriteResult { +pub enum WriteResult { Add(AddResult), Merge(MergeResult), } diff --git a/rust/lancedb/tests/blob_integration.rs b/rust/lancedb/tests/blob_integration.rs index 3d327766e..77d49abd9 100644 --- a/rust/lancedb/tests/blob_integration.rs +++ b/rust/lancedb/tests/blob_integration.rs @@ -10,7 +10,7 @@ use arrow_array::{ use arrow_schema::{DataType, Field, Fields, Schema}; use futures::TryStreamExt; use lance::Dataset; -use lance_encoding::version::LanceFileVersion; +use lance_file::version::LanceFileVersion; use lancedb::{ Connection, Error, Result, Table, blob::{BlobRangeRequest, blob}, From b1cfe6edb15c3904001a99e98560b80970fd711e Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 7 Aug 2026 16:31:40 +0800 Subject: [PATCH 002/206] ci(docs): add scheduled doc link check (#3888) The docs have no link checking at all, so external links rot silently: a trial run already found `docs/src/python/python.md` pointing at `lancedb.github.io/lance-namespace`, which returns 404 since the repository moved to the lance-format org. Checking external links on the blocking path would be the wrong trade: third-party hosts rate-limit automated clients, reject non-browser user agents, and go down temporarily, so any of them having a bad minute would turn unrelated PRs red. Following lance-format/lance#8315, this adds a daily `lychee` run that reports broken links into a single tracking issue, rewritten in place on each run and closed automatically once every link resolves. The scan job runs the downloaded lychee binary with a read-only token; everything that writes lives in a separate report job, and a non-verdict lychee exit fails the run instead of publishing a bogus report. The check is restricted to http(s) links because much of `docs/src` is generated API reference (the `js/` tree comes from `npm run docs`) and the hand-written pages use mkdocstrings cross-references and nav-relative paths that only resolve in the site mkdocs builds, so relative links would be reported as broken on every run. The one broken link the trial run surfaced is fixed here; after the fix, a local run over all 154 files reports 0 errors across 216 unique links. --- .github/workflows/docs-link-check.yml | 222 ++++++++++++++++++++++++++ docs/src/python/python.md | 2 +- 2 files changed, 223 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/docs-link-check.yml diff --git a/.github/workflows/docs-link-check.yml b/.github/workflows/docs-link-check.yml new file mode 100644 index 000000000..0e22100eb --- /dev/null +++ b/.github/workflows/docs-link-check.yml @@ -0,0 +1,222 @@ +name: Check doc links + +# Checking external links is inherently noisy: third-party sites rate-limit +# automated clients, reject non-browser user agents, and go down temporarily. +# Blocking pull requests on that trades a lot of false failures for very little +# signal, so this runs on a schedule and reports findings in a single tracking +# issue instead of failing anyone's build. +on: + schedule: + - cron: "0 7 * * *" + workflow_dispatch: + +# The report lives in one repository-global issue, so runs must not overlap: a +# lookup racing a create produces duplicate issues, and a healthy run closing +# the issue while a failing run only rewrites its body would leave a broken +# report closed. The group is deliberately ref-independent so that a manual +# dispatch serializes against the scheduled run. +concurrency: + group: docs-link-check + cancel-in-progress: false + +permissions: {} + +env: + REPORT_TITLE: "Docs link checker report" + +jobs: + scan: + name: Scan links + runs-on: ubuntu-24.04 + # lychee-action is pinned by SHA, but its wrapper downloads the lychee + # release tarball at run time without verifying a digest, and hands the + # resulting binary a GitHub token. Release assets remain replaceable, so + # that binary is confined to a job whose token can only read public + # content; everything that writes runs in the report job below. + permissions: + contents: read + outputs: + exit_code: ${{ steps.lychee.outputs.exit_code }} + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + # workflow_dispatch can run from any ref, but the report is + # repository-global. Always measure the default branch so a manual + # run from a topic branch cannot close a report that main warrants, + # or overwrite it with branch-only findings. + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + + - name: Check links + id: lychee + uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0 + with: + # Restricted to http(s) on purpose. Much of docs/src is generated + # API reference (the js/ tree comes from `npm run docs` in nodejs) + # and the hand-written pages use mkdocstrings cross-references and + # nav-relative paths that only resolve in the site mkdocs builds, + # not in this checkout, so relative links would be reported as + # broken on every run. + args: >- + --scheme https + --scheme http + --no-progress + --max-retries 3 + --timeout 20 + 'docs/src/**/*.md' + format: json + output: ./lychee/out.json + jobSummary: false + # The report, not a red build, is the signal for broken links. The + # validation step below still fails the run if the check itself + # breaks. + fail: false + + - name: Validate report + # lychee does not reserve exit code 2 for broken links: its CLI + # parser also exits 2 on an invalid option, before any link was + # checked or any report written. Only a parseable report whose + # counts agree with the exit code counts as a link verdict; anything + # else fails here, and the report job below is skipped entirely, so + # the tracking issue is never touched. Exit 2 covers timeouts as + # well as errors, and a timed-out host is exactly the transient + # unavailability this report exists to surface, so both count as + # findings. Requiring total > 0 also catches a glob that silently + # stopped matching any file. + if: steps.lychee.outputs.exit_code == 0 || steps.lychee.outputs.exit_code == 2 + env: + EXIT_CODE: ${{ steps.lychee.outputs.exit_code }} + run: | + jq -e --argjson code "$EXIT_CODE" ' + (.total > 0) and + (if $code == 0 + then .errors == 0 and .timeouts == 0 + and (.error_map | length == 0) and (.timeout_map | length == 0) + else (.errors + .timeouts) > 0 + and ((.error_map | length) + (.timeout_map | length)) > 0 + end) + ' ./lychee/out.json + + - name: Upload report + if: steps.lychee.outputs.exit_code == 2 + uses: actions/upload-artifact@v7 + with: + name: link-report + path: ./lychee/out.json + retention-days: 7 + + report: + name: Update report issue + needs: scan + runs-on: ubuntu-24.04 + # Deliberately no checkout: this job needs the report artifact and the + # issues API, not the repository contents. + permissions: + issues: write + env: + EXIT_CODE: ${{ needs.scan.outputs.exit_code }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - name: Classify checker result + # lychee exits 0 when every link resolves and 2 when links fail, + # both already cross-checked against the report by the scan job's + # validation step. Anything else (1 runtime, 3 bad config) means the + # check never produced a link verdict, which must surface as a failed + # run rather than be published as "broken documentation links". + run: | + case "$EXIT_CODE" in + 0|2) + echo "lychee exit code $EXIT_CODE" + ;; + *) + echo "::error::lychee exited with '$EXIT_CODE': the link check did not complete. Leaving the report issue untouched." + exit 1 + ;; + esac + + - name: Find existing report issue + id: report + # Matched on title alone, and through search rather than a listing: + # the issue action applies labels in a separate call after creating the + # issue, so a label filter misses a half-created report, and this + # repository has far more open issues than one listing page holds. + # Closed issues are included because a healthy run closes the report: + # an open-only lookup would forget that identity and the next failing + # run would open a duplicate. The oldest match stays the canonical + # report and is reopened below when links break again. + run: | + match=$(gh issue list --repo "$GITHUB_REPOSITORY" --state all \ + --search "in:title \"$REPORT_TITLE\" author:app/github-actions" \ + --limit 50 --json number,title,state \ + --jq "[.[] | select(.title == \"$REPORT_TITLE\")] | sort_by(.number) | first // empty") + echo "number=$(jq -r '.number // empty' <<<"$match")" >> "$GITHUB_OUTPUT" + echo "state=$(jq -r '.state // empty' <<<"$match")" >> "$GITHUB_OUTPUT" + + - name: Download report + if: env.EXIT_CODE == 2 + uses: actions/download-artifact@v8 + with: + name: link-report + path: ./lychee + + - name: Compose report + if: env.EXIT_CODE == 2 + run: | + run_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + { + echo "Broken documentation links found by [\`$GITHUB_WORKFLOW\`]($run_url)." + echo + echo "This issue is rewritten by every scheduled run and closed automatically once all links resolve." + echo + echo "Entries can be false positives: some sites rate-limit or block automated clients while working fine in a browser. Confirm before editing the docs, and add persistent offenders to \`--exclude\` in \`.github/workflows/docs-link-check.yml\`." + echo + # Timeouts are reported alongside errors: entries land in + # timeout_map with a status text instead of an HTTP code. + jq -r ' + "\(.errors) of \(.total) links failed, \(.timeouts) timed out.", + "", + ([(.error_map | to_entries[]), (.timeout_map | to_entries[])] + | group_by(.key)[] | + "### Errors in \(.[0].key)", + "", + (map(.value[])[] | "* [\(.status.code // .status.text // "ERR")] <\(.url)> — \(.status.details // .status.text // "unknown error")"), + "") + ' ./lychee/out.json + } > ./lychee/issue.md + + - name: Reopen report issue + # A healthy run closes the report, and the issue action below only + # rewrites the body of whatever number it is given. Without an + # explicit reopen, the 2 -> 0 -> 2 sequence would keep rewriting a + # closed issue while links are broken. A CLOSED state implies the + # lookup found a canonical issue, so no separate emptiness check. + if: env.EXIT_CODE == 2 && steps.report.outputs.state == 'CLOSED' + env: + ISSUE_NUMBER: ${{ steps.report.outputs.number }} + run: | + run_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + gh issue reopen "$ISSUE_NUMBER" --repo "$GITHUB_REPOSITORY" \ + --comment "Broken documentation links found again in [the latest run]($run_url)." + + - name: Report broken links + if: env.EXIT_CODE == 2 + uses: peter-evans/create-issue-from-file@fca9117c27cdc29c6c4db3b86c48e4115a786710 # v6.0.0 + with: + # Empty on the first failing run, which creates the issue; afterwards + # the same issue is updated in place. + issue-number: ${{ steps.report.outputs.number }} + title: ${{ env.REPORT_TITLE }} + content-filepath: ./lychee/issue.md + labels: documentation + + - name: Close report issue once links are healthy + # An OPEN state implies the lookup found a canonical issue; a report + # that is already closed needs nothing. + if: env.EXIT_CODE == 0 && steps.report.outputs.state == 'OPEN' + env: + ISSUE_NUMBER: ${{ steps.report.outputs.number }} + run: | + run_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + gh issue close "$ISSUE_NUMBER" --repo "$GITHUB_REPOSITORY" \ + --comment "All documentation links resolved in [the latest run]($run_url)." diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 36044d35d..3dd6f59f4 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -31,7 +31,7 @@ is also an [asynchronous API client](#connections-asynchronous). ## Namespaces (Synchronous) A namespace-backed connection resolves tables through a -[Lance namespace](https://lancedb.github.io/lance-namespace/) service instead of +[Lance namespace](https://lance-format.github.io/lance-namespace/) service instead of listing a storage directory. ::: lancedb.connect_namespace From f4c668e2441a3c5ab31a024eb8e1ec6a68920f17 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Fri, 7 Aug 2026 02:24:38 -0700 Subject: [PATCH 003/206] chore(deps): declare more specific futures dependency (#3800) Lancedb does not work with any other version of `futures`. With futures 0.1 it fails like this: ```console error[E0432]: unresolved imports `futures::StreamExt`, `futures::TryStreamExt` --> rust/lancedb/src/arrow.rs:21:23 | 21 | use futures::{Stream, StreamExt, TryStreamExt}; | ^^^^^^^^^ ^^^^^^^^^^^^ no `TryStreamExt` in the root | | | no `StreamExt` in the root | error[E0432]: unresolved import `futures::StreamExt` --> rust/lancedb/src/data/scannable.rs:24:5 | 24 | use futures::StreamExt; | ^^^^^^^^^^^^^^^^^^ no `StreamExt` in the root | error[E0432]: unresolved import `futures::TryStreamExt` --> rust/lancedb/src/dataloader/permutation/builder.rs:9:5 | 9 | use futures::TryStreamExt; | ^^^^^^^^^^^^^^^^^^^^^ no `TryStreamExt` in the root error[E0432]: unresolved imports `futures::StreamExt`, `futures::TryStreamExt` --> rust/lancedb/src/dataloader/permutation/reader.rs:25:15 | 25 | use futures::{StreamExt, TryStreamExt}; | ^^^^^^^^^ ^^^^^^^^^^^^ no `TryStreamExt` in the root | | | no `StreamExt` in the root | error[E0432]: unresolved imports `futures::StreamExt`, `futures::TryStreamExt` --> rust/lancedb/src/dataloader/permutation/shuffle.rs:8:15 | 8 | use futures::{StreamExt, TryStreamExt}; | ^^^^^^^^^ ^^^^^^^^^^^^ no `TryStreamExt` in the root | | | no `StreamExt` in the root | error[E0432]: unresolved imports `futures::StreamExt`, `futures::TryStreamExt` --> rust/lancedb/src/dataloader/permutation/split.rs:12:15 | 12 | use futures::{StreamExt, TryStreamExt}; | ^^^^^^^^^ ^^^^^^^^^^^^ no `TryStreamExt` in the root | | | no `StreamExt` in the root | error[E0432]: unresolved import `futures::TryStreamExt` --> rust/lancedb/src/dataloader/permutation/util.rs:9:5 | 9 | use futures::TryStreamExt; | ^^^^^^^^^^^^^^^^^^^^^ no `TryStreamExt` in the root error[E0432]: unresolved imports `futures::StreamExt`, `futures::TryFutureExt` --> rust/lancedb/src/io/object_store.rs:8:15 | 8 | use futures::{StreamExt, TryFutureExt, stream::BoxStream}; | ^^^^^^^^^ ^^^^^^^^^^^^ no `TryFutureExt` in the root | | | no `StreamExt` in the root | error[E0432]: unresolved imports `futures::FutureExt`, `futures::TryFutureExt`, `futures::TryStreamExt`, `futures::try_join` --> rust/lancedb/src/query.rs:12:15 | 12 | use futures::{FutureExt, TryFutureExt, TryStreamExt, stream, try_join}; | ^^^^^^^^^ ^^^^^^^^^^^^ ^^^^^^^^^^^^ ^^^^^^^^ no `try_join` in the root | | | | | | | no `TryStreamExt` in the root | | no `TryFutureExt` in the root | no `FutureExt` in the root | error[E0432]: unresolved imports `futures::StreamExt`, `futures::TryStreamExt` --> rust/lancedb/src/remote/table/blobs.rs:13:15 | 13 | use futures::{StreamExt, TryStreamExt}; | ^^^^^^^^^ ^^^^^^^^^^^^ no `TryStreamExt` in the root | | | no `StreamExt` in the root | error[E0432]: unresolved imports `futures::SinkExt`, `futures::StreamExt` --> rust/lancedb/src/remote/table/insert.rs:20:15 | 20 | use futures::{SinkExt, StreamExt}; | ^^^^^^^ ^^^^^^^^^ no `StreamExt` in the root | | | no `SinkExt` in the root | error[E0432]: unresolved imports `futures::StreamExt`, `futures::TryStreamExt` --> rust/lancedb/src/remote/table.rs:58:15 | 58 | use futures::{StreamExt, TryStreamExt}; | ^^^^^^^^^ ^^^^^^^^^^^^ no `TryStreamExt` in the root | | | no `StreamExt` in the root | error[E0432]: unresolved import `futures::StreamExt` --> rust/lancedb/src/remote/util.rs:5:23 | 5 | use futures::{Stream, StreamExt}; | ^^^^^^^^^ no `StreamExt` in the root | error[E0432]: unresolved import `futures::StreamExt` --> rust/lancedb/src/table.rs:14:5 | 14 | use futures::StreamExt; | ^^^^^^^^^^^^^^^^^^ no `StreamExt` in the root | error[E0432]: unresolved import `futures::TryStreamExt` --> rust/lancedb/src/table/datafusion/insert.rs:20:5 | 20 | use futures::TryStreamExt; | ^^^^^^^^^^^^^^^^^^^^^ no `TryStreamExt` in the root error[E0432]: unresolved import `futures::TryStreamExt` --> rust/lancedb/src/table/datafusion/scannable_exec.rs:14:5 | 14 | use futures::TryStreamExt; | ^^^^^^^^^^^^^^^^^^^^^ no `TryStreamExt` in the root error[E0432]: unresolved imports `futures::TryFutureExt`, `futures::TryStreamExt` --> rust/lancedb/src/table/datafusion.rs:25:15 | 25 | use futures::{TryFutureExt, TryStreamExt}; | ^^^^^^^^^^^^ ^^^^^^^^^^^^ no `TryStreamExt` in the root | | | no `TryFutureExt` in the root error[E0432]: unresolved import `futures::FutureExt` --> rust/lancedb/src/table/delete.rs:3:5 | 3 | use futures::FutureExt; | ^^^^^^^^^^^^^^^^^^ no `FutureExt` in the root | error[E0432]: unresolved imports `futures::FutureExt`, `futures::TryFutureExt` --> rust/lancedb/src/table/merge.rs:9:15 | 9 | use futures::{FutureExt, TryFutureExt}; | ^^^^^^^^^ ^^^^^^^^^^^^ no `TryFutureExt` in the root | | | no `FutureExt` in the root | error[E0432]: unresolved import `futures::future::try_join_all` --> rust/lancedb/src/table/query.rs:24:5 | 24 | use futures::future::try_join_all; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no `try_join_all` in `future` | error[E0432]: unresolved import `futures::FutureExt` --> rust/lancedb/src/utils/background_cache.rs:12:5 | 12 | use futures::FutureExt; | ^^^^^^^^^^^^^^^^^^ no `FutureExt` in the root | error[E0432]: unresolved import `futures::FutureExt` --> rust/lancedb/src/utils/mod.rs:12:15 | 12 | use futures::{FutureExt, Stream}; | ^^^^^^^^^ no `FutureExt` in the root | error[E0433]: cannot find `join` in `futures` --> rust/lancedb/src/remote/table/insert.rs:504:55 | 504 | let (producer_result, send_result) = futures::join!(producer, send); | ^^^^ could not find `join` in `futures` error[E0407]: method `poll_next` is not a member of trait `Stream` --> rust/lancedb/src/arrow.rs:108:5 | 108 | / fn poll_next( 109 | | self: Pin<&mut Self>, 110 | | cx: &mut std::task::Context<'_>, 111 | | ) -> std::task::Poll> { 112 | | let this = self.project(); 113 | | this.stream.poll_next(cx) 114 | | } | |_____^ not a member of trait `Stream` error[E0407]: method `poll_next` is not a member of trait `Stream` --> rust/lancedb/src/utils/mod.rs:362:5 | 362 | / fn poll_next( 363 | | mut self: std::pin::Pin<&mut Self>, 364 | | cx: &mut std::task::Context<'_>, 365 | | ) -> std::task::Poll> { ... | 391 | | } | |_____^ not a member of trait `Stream` error[E0407]: method `poll_next` is not a member of trait `Stream` --> rust/lancedb/src/utils/mod.rs:433:5 | 433 | / fn poll_next( 434 | | mut self: Pin<&mut Self>, 435 | | cx: &mut std::task::Context<'_>, 436 | | ) -> std::task::Poll> { ... | 470 | | } | |_____^ not a member of trait `Stream` error[E0425]: cannot find function `try_unfold` in module `futures::stream` --> rust/lancedb/src/remote/table/insert.rs:230:39 | 230 | let stream = futures::stream::try_unfold( | ^^^^^^^^^^ not found in `futures::stream` error[E0433]: cannot find `channel` in `futures` --> rust/lancedb/src/remote/table/insert.rs:418:22 | 418 | futures::channel::mpsc::channel::, std::io::Error>>(2); | ^^^^^^^ could not find `channel` in `futures` | error[E0425]: cannot find function `try_join_all` in module `futures::future` --> rust/lancedb/src/remote/table.rs:1062:40 | 1062 | let streams = futures::future::try_join_all(futures); | ^^^^^^^^^^^^ | ::: $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/future/join_all.rs:76:1 | 76 | / pub fn join_all(i: I) -> JoinAll 77 | | where I: IntoIterator, 78 | | I::Item: IntoFuture, | |______________________________- similarly named function `join_all` defined here | error[E0425]: cannot find function `try_join_all` in module `futures::future` --> rust/lancedb/src/remote/table.rs:1660:40 | 1660 | let results = futures::future::try_join_all(futures).await?; | ^^^^^^^^^^^^ | ::: $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/future/join_all.rs:76:1 | 76 | / pub fn join_all(i: I) -> JoinAll 77 | | where I: IntoIterator, 78 | | I::Item: IntoFuture, | |______________________________- similarly named function `join_all` defined here | error[E0425]: cannot find function `try_join_all` in module `futures::future` --> rust/lancedb/src/remote/table.rs:2243:43 | 2243 | let plan_texts = futures::future::try_join_all(futures).await?; | ^^^^^^^^^^^^ | ::: $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/future/join_all.rs:76:1 | 76 | / pub fn join_all(i: I) -> JoinAll 77 | | where I: IntoIterator, 78 | | I::Item: IntoFuture, | |______________________________- similarly named function `join_all` defined here | error[E0425]: cannot find function `try_join_all` in module `futures::future` --> rust/lancedb/src/remote/table.rs:2290:53 | 2290 | let analyze_result_texts = futures::future::try_join_all(futures).await?; | ^^^^^^^^^^^^ | ::: $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/future/join_all.rs:76:1 | 76 | / pub fn join_all(i: I) -> JoinAll 77 | | where I: IntoIterator, 78 | | I::Item: IntoFuture, | |______________________________- similarly named function `join_all` defined here | error[E0425]: cannot find function `try_unfold` in module `futures::stream` --> rust/lancedb/src/remote/util.rs:21:35 | 21 | let stream = futures::stream::try_unfold( | ^^^^^^^^^^ not found in `futures::stream` error[E0191]: the value of the associated type `Error` in `futures::Stream` must be specified --> rust/lancedb/src/arrow.rs:70:50 | 70 | pub type SendableRecordBatchStream = Pin>; | ^^^^^^^^^^^^^^^^^ | help: specify the associated type | 70 | pub type SendableRecordBatchStream = Pin + Send>>; | ++++++++++++++++++++ error[E0107]: type alias takes 0 lifetime arguments but 1 lifetime argument was supplied --> rust/lancedb/src/utils/background_cache.rs:15:31 | 15 | type SharedFut = Shared>>>; | ^^^^^^^^^ ------- help: remove the lifetime argument | | | expected 0 lifetime arguments | note: type alias defined here, with 0 lifetime parameters --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/future/mod.rs:106:14 | 106 | pub type BoxFuture = ::std::boxed::Box + Send>; | ^^^^^^^^^ error[E0107]: type alias takes 2 generic arguments but 1 generic argument was supplied --> rust/lancedb/src/utils/background_cache.rs:15:31 | 15 | type SharedFut = Shared>>>; | ^^^^^^^^^ ----------------- supplied 1 generic argument | | | expected 2 generic arguments | note: type alias defined here, with 2 generic parameters: `T`, `E` --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/future/mod.rs:106:14 | 106 | pub type BoxFuture = ::std::boxed::Box + Send>; | ^^^^^^^^^ - - help: add missing generic argument | 15 | type SharedFut = Shared>, E>>; | +++ error[E0046]: not all trait items implemented, missing: `Error`, `poll` --> rust/lancedb/src/arrow.rs:105:1 | 105 | impl>> Stream for SimpleRecordBatchStream { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `Error`, `poll` in implementation | = help: implement the missing item: `type Error = /* Type */;` = help: implement the missing item: `fn poll(&mut self) -> std::result::Result::Item>>, ::Error> { todo!() }` error[E0107]: type alias takes 0 lifetime arguments but 1 lifetime argument was supplied --> rust/lancedb/src/io/object_store.rs:97:46 | 97 | fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, Result> { | ^^^^^^^^^ ------- help: remove the lifetime argument | | | expected 0 lifetime arguments | note: type alias defined here, with 0 lifetime parameters --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/mod.rs:132:14 | 132 | pub type BoxStream = ::std::boxed::Box + Send>; | ^^^^^^^^^ error[E0107]: type alias takes 2 generic arguments but 1 generic argument was supplied --> rust/lancedb/src/io/object_store.rs:97:46 | 97 | fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, Result> { | ^^^^^^^^^ ------------------ supplied 1 generic argument | | | expected 2 generic arguments | note: type alias defined here, with 2 generic parameters: `T`, `E` --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/mod.rs:132:14 | 132 | pub type BoxStream = ::std::boxed::Box + Send>; | ^^^^^^^^^ - - help: add missing generic argument | 97 | fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, Result, E> { | +++ error[E0107]: type alias takes 0 lifetime arguments but 1 lifetime argument was supplied --> rust/lancedb/src/io/object_store.rs:107:20 | 107 | locations: BoxStream<'static, Result>, | ^^^^^^^^^ ------- help: remove the lifetime argument | | | expected 0 lifetime arguments | note: type alias defined here, with 0 lifetime parameters --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/mod.rs:132:14 | 132 | pub type BoxStream = ::std::boxed::Box + Send>; | ^^^^^^^^^ error[E0107]: type alias takes 2 generic arguments but 1 generic argument was supplied --> rust/lancedb/src/io/object_store.rs:107:20 | 107 | locations: BoxStream<'static, Result>, | ^^^^^^^^^ ------------ supplied 1 generic argument | | | expected 2 generic arguments | note: type alias defined here, with 2 generic parameters: `T`, `E` --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/mod.rs:132:14 | 132 | pub type BoxStream = ::std::boxed::Box + Send>; | ^^^^^^^^^ - - help: add missing generic argument | 107 | locations: BoxStream<'static, Result, E>, | +++ error[E0107]: type alias takes 0 lifetime arguments but 1 lifetime argument was supplied --> rust/lancedb/src/io/object_store.rs:108:10 | 108 | ) -> BoxStream<'static, Result> { | ^^^^^^^^^ ------- help: remove the lifetime argument | | | expected 0 lifetime arguments | note: type alias defined here, with 0 lifetime parameters --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/mod.rs:132:14 | 132 | pub type BoxStream = ::std::boxed::Box + Send>; | ^^^^^^^^^ error[E0107]: type alias takes 2 generic arguments but 1 generic argument was supplied --> rust/lancedb/src/io/object_store.rs:108:10 | 108 | ) -> BoxStream<'static, Result> { | ^^^^^^^^^ ------------ supplied 1 generic argument | | | expected 2 generic arguments | note: type alias defined here, with 2 generic parameters: `T`, `E` --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/mod.rs:132:14 | 132 | pub type BoxStream = ::std::boxed::Box + Send>; | ^^^^^^^^^ - - help: add missing generic argument | 108 | ) -> BoxStream<'static, Result, E> { | +++ error[E0599]: no method named `map_err` found for struct `Pin>` in the current scope --> rust/lancedb/src/dataloader/permutation/builder.rs:208:32 | 208 | let stream = df_stream.map_err(|e| Error::Other { | ----------^^^^^^^ method not found in `Pin>` | ::: $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-util-0.3.32/src/stream/try_stream/mod.rs:248:8 | 248 | fn map_err(self, f: F) -> MapErr | ------- the method is available for `Pin>` here | error[E0599]: no method named `try_collect` found for struct `DatasetRecordBatchStream` in the current scope --> rust/lancedb/src/dataloader/permutation/reader.rs:220:28 | 220 | let batches = data.try_collect::>().await?; | ^^^^^^^^^^^ | error[E0599]: no method named `map_err` found for struct `DatasetRecordBatchStream` in the current scope --> rust/lancedb/src/dataloader/permutation/reader.rs:287:14 | 286 | let mut stream = row_ids | __________________________- 287 | | .map_err(Error::from) | | -^^^^^^^ method not found in `DatasetRecordBatchStream` | |_____________| | error[E0599]: the method `chain` exists for struct `futures::stream::Once<_, _>`, but its trait bounds were not satisfied --> rust/lancedb/src/dataloader/permutation/reader.rs:307:81 | 307 | let stream = futures::stream::once(std::future::ready(Ok(first_batch))).chain(stream); | ^^^^^ method cannot be called on `futures::stream::Once<_, _>` due to unsatisfied trait bounds error[E0308]: mismatched types --> rust/lancedb/src/dataloader/permutation/shuffle.rs:120:35 | 120 | futures::stream::once(async move { Ok(shuffled) }), | --------------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Result<_, _>`, found `async` block | | | arguments to this function are incorrect | = note: expected enum `std::result::Result<_, _>` found `async` block `{async block@rust/lancedb/src/dataloader/permutation/shuffle.rs:120:35: 120:45}` note: function defined here --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/once.rs:20:8 | 20 | pub fn once(item: Result) -> Once { | ^^^^ help: try wrapping the expression in a variant of `std::result::Result` | 120 | futures::stream::once(Ok(async move { Ok(shuffled) })), | +++ + 120 | futures::stream::once(Err(async move { Ok(shuffled) })), | ++++ + error[E0271]: type mismatch resolving ` as IntoIterator>::Item == Result<_, _>` --> rust/lancedb/src/dataloader/permutation/shuffle.rs:228:44 | 228 | let stream = futures::stream::iter(0..num_files) | --------------------- ^^^^^^^^^^^^ expected `Result<_, _>`, found `u64` | | | required by a bound introduced by this call | = note: expected enum `std::result::Result<_, _>` found type `u64` note: required by a bound in `futures::stream::iter` --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/iter.rs:31:27 | 30 | pub fn iter(i: J) -> Iter | ---- required by a bound in this function 31 | where J: IntoIterator>, | ^^^^^^^^^^^^^^^^^ required by this bound in `iter` error[E0599]: no method named `then` found for struct `IterStream` in the current scope --> rust/lancedb/src/dataloader/permutation/shuffle.rs:229:14 | 228 | let stream = futures::stream::iter(0..num_files) | ______________________- 229 | | .then(move |file_index| { | | -^^^^ method not found in `IterStream>` | |_____________| | error[E0599]: no method named `try_collect` found for struct `Pin>` in the current scope --> rust/lancedb/src/dataloader/permutation/shuffle.rs:258:26 | 250 | let batches = reader | ___________________________________- 251 | | .read_stream( 252 | | ReadBatchParams::RangeFull, 253 | | reader.num_rows() as u32, ... | 257 | | .await? 258 | | .try_collect::>() | |_________________________-^^^^^^^^^^^ error[E0599]: no method named `and_then` found for associated type `impl Future, ...>> + Send` in the current scope --> rust/lancedb/src/query.rs:766:14 | 765 | / self.create_plan(QueryExecutionOptions::default()) 766 | | .and_then(|plan| std::future::ready(Ok(plan.schema()))) | |_____________-^^^^^^^^ | ::: $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-util-0.3.32/src/future/try_future/mod.rs:395:8 | 395 | fn and_then(self, f: F) -> AndThen | -------- the method is available for `impl std::future::Future, error::Error>> + std::marker::Send` here error[E0599]: no method named `boxed` found for `async` block `{async block@rust/lancedb/src/query.rs:1492:33: 1492:43}` in the current scope --> rust/lancedb/src/query.rs:1493:18 | 1492 | let hybrid_result = async move { self.execute_hybrid(options).await } | _________________________________- 1493 | | .boxed() | | -^^^^^ method not found in `{async block@rust/lancedb/src/query.rs:1492:33: 1492:43}` | |_________________| error[E0271]: expected `{closure@blobs.rs:181:58}` to return `Result<_, _>`, but it returns `impl Future>` --> rust/lancedb/src/remote/table/blobs.rs:181:66 | 181 | futures::stream::iter(ranges.iter().cloned().map(|range| self.read_range(range))) | --------------------- ------- ^^^^^^^^^^^^^^^^^^^^^^ expected `Result<_, _>`, found future | | | | | this closure | required by a bound introduced by this call error[E0599]: no method named `buffered` found for struct `IterStream` in the current scope --> rust/lancedb/src/remote/table/blobs.rs:182:14 | 181 | / futures::stream::iter(ranges.iter().cloned().map(|range| self.read_range(range))) 182 | | .buffered(BLOB_REQUEST_CONCURRENCY) | | -^^^^^^^^ method not found in `Iter>>, {closure@...}>>` | |_____________| error[E0599]: no method named `try_next` found for struct `Pin>` in the current scope --> rust/lancedb/src/remote/table/blobs.rs:379:40 | 379 | while let Some(batch) = stream.try_next().await? { | ^^^^^^^^ method not found in `Pin>` error[E0271]: type mismatch resolving ` as IntoIterator>::Item == Result<_, _>` --> rust/lancedb/src/remote/table/blobs.rs:481:27 | 481 | futures::stream::iter(probe_futures) | --------------------- ^^^^^^^^^^^^^ expected `Result<_, _>`, found future | | | required by a bound introduced by this call error[E0599]: no method named `buffered` found for struct `IterStream` in the current scope --> rust/lancedb/src/remote/table/blobs.rs:482:10 | 481 | / futures::stream::iter(probe_futures) 482 | | .buffered(BLOB_REQUEST_CONCURRENCY) | | -^^^^^^^^ method not found in `Iter>>>` | |_________| error[E0599]: no method named `next` found for struct `Pin>` in the current scope --> rust/lancedb/src/remote/table/insert.rs:324:37 | 324 | let mut first = match input.next().await { | ^^^^ method not found in `Pin>` error[E0599]: no method named `next` found for struct `Pin>` in the current scope --> rust/lancedb/src/remote/table/insert.rs:345:33 | 345 | first = match input.next().await { | ^^^^ method not found in `Pin>` error[E0599]: the method `next` exists for mutable reference `&mut Pin>`, but its trait bounds were not satisfied --> rust/lancedb/src/remote/table/insert.rs:446:41 | 446 | None => match input.next().await { | ^^^^ method cannot be called on `&mut Pin>` due to unsatisfied trait bounds | = note: the following trait bounds were not satisfied: `Pin>: Iterator` which is required by `&mut Pin>: Iterator` error[E0599]: no method named `map_err` found for struct `IterStream` in the current scope --> rust/lancedb/src/remote/table.rs:688:53 | 688 | let stream = futures::stream::iter(batches).map_err(DataFusionError::from); | ^^^^^^^ method not found in `Iter> + Send>>` error[E0599]: no method named `try_collect` found for struct `Pin>` in the current scope --> rust/lancedb/src/remote/table.rs:1378:49 | 1378 | let result: Result> = stream.try_collect().await.map_err(Error::from); | ^^^^^^^^^^^ error[E0599]: no method named `next` found for struct `Pin>` in the current scope --> rust/lancedb/src/remote/table.rs:1509:48 | 1509 | while let Some(batch) = stream.next().await { | ^^^^ method not found in `Pin>` error[E0599]: no method named `boxed` found for opaque type `impl Future>` in the current scope --> rust/lancedb/src/table/delete.rs:35:51 | 35 | let delete_result = dataset.delete(s).boxed().await?; | ^^^^^ method not found in `impl Future>` error[E0599]: no variant, associated function, or constant named `Left` found for enum `Either` in the current scope --> rust/lancedb/src/table/merge.rs:292:17 | 292 | Either::Left(tokio::time::timeout(timeout, future).map(|res| match res { | ^^^^ variant, associated function, or constant not found in `Either<_, _>` error[E0599]: `Timeout, ...), ...>>>` is not an iterator --> rust/lancedb/src/table/merge.rs:292:60 | 292 | Either::Left(tokio::time::timeout(timeout, future).map(|res| match res { | --------------------------------------^^^ `Timeout, ...), ...>>>` is not an iterator | ::: $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/pin-project-lite-0.2.17/src/lib.rs:745:9 | 745 | / $vis struct $ident $($def_generics)* 746 | | $(where 747 | | $($where_clause)*)? ... | 751 | | ),+ 752 | | } | |_________- doesn't satisfy `_: Iterator` | = note: the following trait bounds were not satisfied: `tokio::time::Timeout, MergeStats), lance::Error>>>: Iterator` which is required by `&mut tokio::time::Timeout, MergeStats), lance::Error>>>: Iterator` error[E0599]: no variant, associated function, or constant named `Right` found for enum `Either` in the current scope --> rust/lancedb/src/table/merge.rs:301:17 | 301 | Either::Right(job.execute_reader(new_data).map_err(|e| e.into())) | ^^^^^ variant, associated function, or constant not found in `Either<_, _>` error[E0599]: no method named `map_err` found for opaque type `impl Future, ...), ...>>` in the current scope --> rust/lancedb/src/table/merge.rs:301:52 | 301 | Either::Right(job.execute_reader(new_data).map_err(|e| e.into())) | ^^^^^^^ method not found in `impl Future, ...), ...>>` error[E0277]: the trait bound `Iter, ...>>: Stream` is not satisfied --> rust/lancedb/src/table/query.rs:681:38 | 681 | Ok(DatasetRecordBatchStream::new(record_batch_stream)) | ^^^^^^^^^^^^^^^^^^^ the trait `futures_core::stream::Stream` is not implemented for `Iter, ...>>` error[E0277]: the trait bound `TimeoutStream: futures_core::stream::Stream` is not satisfied --> rust/lancedb/src/utils/mod.rs:353:28 | 353 | impl RecordBatchStream for TimeoutStream { | ^^^^^^^^^^^^^ unsatisfied trait bound error[E0046]: not all trait items implemented, missing: `Error`, `poll` --> rust/lancedb/src/utils/mod.rs:359:1 | 359 | impl Stream for TimeoutStream { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `Error`, `poll` in implementation | = help: implement the missing item: `type Error = /* Type */;` = help: implement the missing item: `fn poll(&mut self) -> std::result::Result::Item>>, ::Error> { todo!() }` error[E0277]: the trait bound `MaxBatchLengthStream: futures_core::stream::Stream` is not satisfied --> rust/lancedb/src/utils/mod.rs:424:28 | 424 | impl RecordBatchStream for MaxBatchLengthStream { | ^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound error[E0046]: not all trait items implemented, missing: `Error`, `poll` --> rust/lancedb/src/utils/mod.rs:430:1 | 430 | impl Stream for MaxBatchLengthStream { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `Error`, `poll` in implementation | = help: implement the missing item: `type Error = /* Type */;` = help: implement the missing item: `fn poll(&mut self) -> std::result::Result::Item>>, ::Error> { todo!() }` error[E0599]: no method named `map` found for type parameter `I` in the current scope --> rust/lancedb/src/arrow.rs:75:45 | 72 | impl From for SendableRecordBatchStream { | - method `map` not found for this type parameter ... 75 | let mapped_stream = Box::pin(stream.map(|r| r.map_err(Into::into))); | ^^^ error[E0599]: no method named `poll_next` found for struct `Pin<&mut S>` in the current scope --> rust/lancedb/src/arrow.rs:113:21 | 113 | this.stream.poll_next(cx) | ^^^^^^^^^ | = help: items from traits can only be used if the trait is implemented and in scope = note: the following traits define an item `poll_next`, perhaps you need to implement one of them: candidate #1: `futures_core::stream::Stream` candidate #2: `sorts::stream::PartitionedStream` help: there is a method `collect` with a similar name, but with different arguments --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/mod.rs:563:5 | 563 | / fn collect(self) -> Collect 564 | | where Self: Sized | |_________________________^ error[E0599]: the method `map_err` exists for struct `Pin> + Send>>`, but its trait bounds were not satisfied --> rust/lancedb/src/arrow.rs:150:29 | 150 | let stream = stream.map_err(|err| Error::Arrow { source: err }); | ^^^^^^^ method cannot be called due to unsatisfied trait bounds error[E0308]: mismatched types --> rust/lancedb/src/data/scannable.rs:80:26 | 80 | stream: once(async move { Ok(batch) }), | ---- ^^^^^^^^^^^^^^^^^^^^^^^^ expected `Result<_, _>`, found `async` block | | | arguments to this function are incorrect | = note: expected enum `std::result::Result<_, _>` found `async` block `{async block@rust/lancedb/src/data/scannable.rs:80:26: 80:36}` note: function defined here --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/once.rs:20:8 | 20 | pub fn once(item: Result) -> Once { | ^^^^ help: try wrapping the expression in a variant of `std::result::Result` | 80 | stream: once(Ok(async move { Ok(batch) })), | +++ + 80 | stream: once(Err(async move { Ok(batch) })), | ++++ + error[E0308]: mismatched types --> rust/lancedb/src/data/scannable.rs:107:30 | 107 | stream: once(async { | _________________________----_^ | | | | | arguments to this function are incorrect 108 | | Err(Error::InvalidInput { 109 | | message: "Cannot scan an empty Vec".to_string(), 110 | | }) 111 | | }), | |_________________^ expected `Result<_, _>`, found `async` block | = note: expected enum `std::result::Result<_, _>` found `async` block `{async block@rust/lancedb/src/data/scannable.rs:107:30: 107:35}` note: function defined here --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/once.rs:20:8 | 20 | pub fn once(item: Result) -> Once { | ^^^^ help: try wrapping the expression in a variant of `std::result::Result` | 107 ~ stream: once(Ok(async { 108 | Err(Error::InvalidInput { 109 | message: "Cannot scan an empty Vec".to_string(), 110 | }) 111 ~ })), | 107 ~ stream: once(Err(async { 108 | Err(Error::InvalidInput { 109 | message: "Cannot scan an empty Vec".to_string(), 110 | }) 111 ~ })), | error[E0271]: expected `Ok` to return `Result, _>`, but it returns `Result` --> rust/lancedb/src/data/scannable.rs:117:52 | 117 | Box::pin(SimpleRecordBatchStream { schema, stream }) | ^^^^^^ expected `Result, _>`, found `Result` error[E0308]: mismatched types --> rust/lancedb/src/data/scannable.rs:158:59 | 158 | let stream = futures::stream::unfold(rx, |mut rx| async move { | ___________________________________________________________^ 159 | | rx.recv().await.map(|batch| (batch, rx)) 160 | | }) | |_________^ expected `Option<_>`, found `async` block | = note: expected enum `std::option::Option<_>` found `async` block `{async block@rust/lancedb/src/data/scannable.rs:158:59: 158:69}` help: try wrapping the expression in `Some` | 158 ~ let stream = futures::stream::unfold(rx, |mut rx| Some(async move { 159 | rx.recv().await.map(|batch| (batch, rx)) 160 ~ })) | error[E0599]: the method `fuse` exists for struct `Unfold>, ..., _>`, but its trait bounds were not satisfied --> rust/lancedb/src/data/scannable.rs:161:10 | 158 | let stream = futures::stream::unfold(rx, |mut rx| async move { | ______________________- 159 | | rx.recv().await.map(|batch| (batch, rx)) 160 | | }) 161 | | .fuse(); | | -^^^^ method cannot be called due to unsatisfied trait bounds | |_________| error[E0308]: mismatched types --> rust/lancedb/src/data/scannable.rs:178:26 | 178 | stream: once(async { | _____________________----_^ | | | | | arguments to this function are incorrect 179 | | Err(Error::InvalidInput { 180 | | message: "Stream has already been consumed".to_string(), 181 | | }) 182 | | }), | |_____________^ expected `Result<_, _>`, found `async` block | = note: expected enum `std::result::Result<_, _>` found `async` block `{async block@rust/lancedb/src/data/scannable.rs:178:26: 178:31}` note: function defined here --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/once.rs:20:8 | 20 | pub fn once(item: Result) -> Once { | ^^^^ help: try wrapping the expression in a variant of `std::result::Result` | 178 ~ stream: once(Ok(async { 179 | Err(Error::InvalidInput { 180 | message: "Stream has already been consumed".to_string(), 181 | }) 182 ~ })), | 178 ~ stream: once(Err(async { 179 | Err(Error::InvalidInput { 180 | message: "Stream has already been consumed".to_string(), 181 | }) 182 ~ })), | error[E0308]: mismatched types --> rust/lancedb/src/data/scannable.rs:474:53 | 474 | let prepend = futures::stream::once(std::future::ready(Ok(batch))); | --------------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Result<_, _>`, found `Ready>` | | | arguments to this function are incorrect | = note: expected enum `std::result::Result<_, _>` found struct `std::future::Ready>` note: function defined here --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/once.rs:20:8 | 20 | pub fn once(item: Result) -> Once { | ^^^^ help: try wrapping the expression in a variant of `std::result::Result` | 474 | let prepend = futures::stream::once(Ok(std::future::ready(Ok(batch)))); | +++ + 474 | let prepend = futures::stream::once(Err(std::future::ready(Ok(batch)))); | ++++ + error[E0599]: the method `chain` exists for struct `futures::stream::Once<_, _>`, but its trait bounds were not satisfied --> rust/lancedb/src/data/scannable.rs:477:37 | 477 | stream: prepend.chain(rest), | ^^^^^ method cannot be called on `futures::stream::Once<_, _>` due to unsatisfied trait bounds error[E0308]: mismatched types --> rust/lancedb/src/data/scannable.rs:482:47 | 482 | stream: futures::stream::once(std::future::ready(Ok(batch))), | --------------------- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Result<_, _>`, found `Ready>` | | | arguments to this function are incorrect | = note: expected enum `std::result::Result<_, _>` found struct `std::future::Ready>` note: function defined here --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/once.rs:20:8 | 20 | pub fn once(item: Result) -> Once { | ^^^^ help: try wrapping the expression in a variant of `std::result::Result` | 482 | stream: futures::stream::once(Ok(std::future::ready(Ok(batch)))), | +++ + 482 | stream: futures::stream::once(Err(std::future::ready(Ok(batch)))), | ++++ + error[E0308]: mismatched types --> rust/lancedb/src/data/scannable.rs:486:56 | 486 | let stream = futures::stream::once(std::future::ready(err)); | --------------------- ^^^^^^^^^^^^^^^^^^^^^^^ expected `Result<_, _>`, found `Ready>` | | | arguments to this function are incorrect | = note: expected enum `std::result::Result<_, _>` found struct `std::future::Ready>` note: function defined here --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/once.rs:20:8 | 20 | pub fn once(item: Result) -> Once { | ^^^^ help: try wrapping the expression in a variant of `std::result::Result` | 486 | let stream = futures::stream::once(Ok(std::future::ready(err))); | +++ + 486 | let stream = futures::stream::once(Err(std::future::ready(err))); | ++++ + error[E0599]: no method named `and_then` found for struct `Pin> + Send>>` in the current scope --> rust/lancedb/src/io/object_store.rs:153:32 | 153 | Box::pin(put_secondary.and_then(|_| put_primary)) | ^^^^^^^^ error[E0271]: expected `IntoIter, 1>` to be an iterator that yields `Result, _>`, but it yields `Result` --> rust/lancedb/src/query.rs:1465:25 | 1465 | return Box::pin(SimpleRecordBatchStream::new( | ^^^^^^^^^^^^^^^^^^^^^^^ expected `Result, _>`, found `Result` error[E0271]: expected `IntoIter>` to be an iterator that yields `Result, _>`, but it yields `Result` --> rust/lancedb/src/query.rs:1478:14 | 1478 | Box::pin(SimpleRecordBatchStream::new(stream::iter(batches), schema)) | ^^^^^^^^^^^^^^^^^^^^^^^ expected `Result, _>`, found `Result` error[E0308]: mismatched types --> rust/lancedb/src/remote/table/insert.rs:626:44 | 626 | let stream = futures::stream::once(async move { | ______________________---------------------_^ | | | | | arguments to this function are incorrect ... | 791 | | Ok::<_, DataFusionError>(batch) 792 | | }); | |_________^ expected `Result<_, _>`, found `async` block | = note: expected enum `std::result::Result<_, _>` found `async` block `{async block@rust/lancedb/src/remote/table/insert.rs:626:44: 626:54}` note: function defined here --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/once.rs:20:8 | 20 | pub fn once(item: Result) -> Once { | ^^^^ help: try wrapping the expression in a variant of `std::result::Result` | 626 ~ let stream = futures::stream::once(Ok(async move { 627 | // Multipart writes with a byte budget split the partition into ... 791 | Ok::<_, DataFusionError>(batch) 792 ~ })); | 626 ~ let stream = futures::stream::once(Err(async move { 627 | // Multipart writes with a byte budget split the partition into ... 791 | Ok::<_, DataFusionError>(batch) 792 ~ })); | error[E0277]: the trait bound `futures::stream::Once<_, _>: futures_core::stream::Stream` is not satisfied --> rust/lancedb/src/remote/table/insert.rs:794:12 | 794 | Ok(Box::pin(RecordBatchStreamAdapter::new( | ____________^ 795 | | COUNT_SCHEMA.clone(), 796 | | stream, 797 | | ))) | |__________^ the trait `futures_core::stream::Stream` is not implemented for `futures::stream::Once<_, _>` error[E0599]: no method named `try_collect` found for struct `Pin>` in the current scope --> rust/lancedb/src/remote/table.rs:2442:49 | 2442 | let result: Result> = stream.try_collect().await.map_err(Error::from); | ^^^^^^^^^^^ error[E0277]: the trait bound `impl Stream>: TryStream` is not satisfied --> rust/lancedb/src/remote/util.rs:47:35 | 47 | Ok(reqwest::Body::wrap_stream(stream)) | -------------------------- ^^^^^^ unsatisfied trait bound | | | required by a bound introduced by this call error[E0599]: no method named `map_ok` found for struct `Pin>` in the current scope --> rust/lancedb/src/table/datafusion/insert.rs:200:30 | 200 | input_stream.map_ok(move |batch| { | -------------^^^^^^ method not found in `Pin>` error[E0308]: mismatched types --> rust/lancedb/src/table/datafusion/insert.rs:208:44 | 208 | let stream = futures::stream::once(async move { | ______________________---------------------_^ | | | | | arguments to this function are incorrect 209 | | if let Some(tracker) = tracker 210 | | && write_params.write_progress.is_none() ... | 255 | | )?) 256 | | }); | |_________^ expected `Result<_, _>`, found `async` block | = note: expected enum `std::result::Result<_, _>` found `async` block `{async block@rust/lancedb/src/table/datafusion/insert.rs:208:44: 208:54}` note: function defined here --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/once.rs:20:8 | 20 | pub fn once(item: Result) -> Once { | ^^^^ help: try wrapping the expression in a variant of `std::result::Result` | 208 ~ let stream = futures::stream::once(Ok(async move { 209 | if let Some(tracker) = tracker ... 255 | )?) 256 ~ })); | 208 ~ let stream = futures::stream::once(Err(async move { 209 | if let Some(tracker) = tracker ... 255 | )?) 256 ~ })); | error[E0277]: the trait bound `futures::stream::Once<_, _>: futures_core::stream::Stream` is not satisfied --> rust/lancedb/src/table/datafusion/insert.rs:258:12 | 258 | Ok(Box::pin(RecordBatchStreamAdapter::new( | ____________^ 259 | | COUNT_SCHEMA.clone(), 260 | | stream, 261 | | ))) | |__________^ the trait `futures_core::stream::Stream` is not implemented for `futures::stream::Once<_, _>` error[E0599]: no method named `map_ok` found for struct `Pin>` in the current scope --> rust/lancedb/src/table/datafusion.rs:128:29 | 128 | let stream = stream.map_ok(move |batch| { | -------^^^^^^ method not found in `Pin>` error[E0599]: no method named `map_err` found for struct `Pin, ...>> + Send>>` in the current scope --> rust/lancedb/src/table/datafusion.rs:245:14 | 242 | let plan = self | ____________________- 243 | | .table 244 | | .create_plan(&AnyQuery::Query(query), options) 245 | | .map_err(|err| DataFusionError::External(err.into())) | | -^^^^^^^ method not found in `Pin, ...>> + Send>>` | |_____________| error[E0599]: no method named `next` found for struct `Pin>` in the current scope --> rust/lancedb/src/table.rs:3048:48 | 3048 | while let Some(batch) = stream.next().await { | ^^^^ method not found in `Pin>` error[E0277]: the trait bound `JoinHandle>: Future` is not satisfied --> rust/lancedb/src/table.rs:3038:23 | 3038 | let handles = FuturesUnordered::new(); | ^^^^^^^^^^^^^^^^^^^^^^^ the trait `futures::Future` is not implemented for `tokio::task::JoinHandle>` error[E0277]: `FuturesUnordered>>` is not an iterator --> rust/lancedb/src/table.rs:3054:23 | 3054 | for handle in handles { | ^^^^^^^ `FuturesUnordered>>` is not an iterator error[E0277]: the trait bound `{async block@rust/lancedb/src/table.rs:3452:29: 3452:39}: futures::IntoFuture` is not satisfied --> rust/lancedb/src/table.rs:3450:13 | 3449 | let mut sorted_sizes = join_all( | -------- required by a bound introduced by this call 3450 | / frags 3451 | | .iter() 3452 | | .map(|frag| async move { frag.physical_rows().await.unwrap_or(0) }), | |___________________________________________________________________________________^ the trait `futures::Future` is not implemented for `{async block@rust/lancedb/src/table.rs:3452:29: 3452:39}` | = note: `{async block@rust/lancedb/src/table.rs:3452:29: 3452:39}` implements similarly named trait `std::future::Future`, but not `futures::Future` = help: the following other types implement trait `futures::Future`: &'a mut F AssertUnwindSafe BiLockAcquire Box Concat2 Either Finished Fold and 43 others = note: required for `{async block@rust/lancedb/src/table.rs:3452:29: 3452:39}` to implement `futures::IntoFuture` note: required by a bound in `join_all` --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/future/join_all.rs:78:20 | 76 | pub fn join_all(i: I) -> JoinAll | -------- required by a bound in this function 77 | where I: IntoIterator, 78 | I::Item: IntoFuture, | ^^^^^^^^^^ required by this bound in `join_all` error[E0277]: the trait bound `{async block@rust/lancedb/src/table.rs:3452:29: 3452:39}: futures::Future` is not satisfied --> rust/lancedb/src/table.rs:3449:32 | 3449 | let mut sorted_sizes = join_all( | ________________________________^ 3450 | | frags 3451 | | .iter() 3452 | | .map(|frag| async move { frag.physical_rows().await.unwrap_or(0) }), 3453 | | ) | |_________^ the trait `futures::Future` is not implemented for `{async block@rust/lancedb/src/table.rs:3452:29: 3452:39}` | = note: `{async block@rust/lancedb/src/table.rs:3452:29: 3452:39}` implements similarly named trait `std::future::Future`, but not `futures::Future` = help: the following other types implement trait `futures::Future`: &'a mut F AssertUnwindSafe BiLockAcquire Box Concat2 Either Finished Fold and 43 others = note: required for `{async block@rust/lancedb/src/table.rs:3452:29: 3452:39}` to implement `futures::IntoFuture` note: required by a bound in `JoinAll` --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/future/join_all.rs:24:20 | 22 | pub struct JoinAll | ------- required by a bound in this struct 23 | where I: IntoIterator, 24 | I::Item: IntoFuture, | ^^^^^^^^^^ required by this bound in `JoinAll` error[E0277]: `JoinAll, {closure@...}>>` is not a future --> rust/lancedb/src/table.rs:3454:10 | 3449 | let mut sorted_sizes = join_all( | ________________________________- 3450 | | frags 3451 | | .iter() 3452 | | .map(|frag| async move { frag.physical_rows().await.unwrap_or(0) }), 3453 | | ) | |_________- this call returns `JoinAll, {closure@rust/lancedb/src/table.rs:3452:22: 3452:28}>>` 3454 | .await; | ^^^^^ `JoinAll, {closure@...}>>` is not a future error[E0277]: the trait bound `{async block@rust/lancedb/src/table.rs:3452:29: 3452:39}: futures::Future` is not satisfied --> rust/lancedb/src/table.rs:3454:10 | 3454 | .await; | ^^^^^ the trait `futures::Future` is not implemented for `{async block@rust/lancedb/src/table.rs:3452:29: 3452:39}` | = note: `{async block@rust/lancedb/src/table.rs:3452:29: 3452:39}` implements similarly named trait `std::future::Future`, but not `futures::Future` = help: the following other types implement trait `futures::Future`: &'a mut F AssertUnwindSafe BiLockAcquire Box Concat2 Either Finished Fold and 43 others = note: required for `{async block@rust/lancedb/src/table.rs:3452:29: 3452:39}` to implement `futures::IntoFuture` note: required by a bound in `JoinAll` --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/future/join_all.rs:24:20 | 22 | pub struct JoinAll | ------- required by a bound in this struct 23 | where I: IntoIterator, 24 | I::Item: IntoFuture, | ^^^^^^^^^^ required by this bound in `JoinAll` error[E0282]: type annotations needed --> rust/lancedb/src/utils/background_cache.rs:119:40 | 119 | inner: Arc::new(Mutex::new(CacheInner { | ________________________________________^ 120 | | state: State::Empty, 121 | | generation: 0, 122 | | })), | |_____________^ cannot infer type of the type parameter `E` declared on the struct `CacheInner` | help: consider specifying the generic arguments | 119 | inner: Arc::new(Mutex::new(CacheInner:: { | ++++++++ error[E0282]: type annotations needed --> rust/lancedb/src/utils/background_cache.rs:134:9 | 134 | cache.state.fresh_value(self.ttl, self.refresh_window) | ^^^^^^^^^^^ cannot infer type for type parameter `E` error[E0282]: type annotations needed --> rust/lancedb/src/utils/background_cache.rs:173:23 | 173 | cache.state = State::Current(value, clock::now()); | ^^^^^^^^^^^^^^ cannot infer type of the type parameter `E` declared on the enum `State` | help: consider specifying the generic arguments | 173 | cache.state = State::::Current(value, clock::now()); | ++++++++ error[E0282]: type annotations needed --> rust/lancedb/src/utils/background_cache.rs:182:23 | 182 | cache.state = State::Empty; | ^^^^^^^^^^^^ cannot infer type of the type parameter `E` declared on the enum `State` | help: consider specifying the generic arguments | 182 | cache.state = State::::Empty; | ++++++++ error[E0599]: no method named `boxed` found for `async` block `{async block@rust/lancedb/src/utils/background_cache.rs:269:22: 269:32}` in the current scope --> rust/lancedb/src/utils/background_cache.rs:270:14 | 269 | let shared = async move { (fetch)().await.map_err(Arc::new) } | ______________________- 270 | | .boxed() | | -^^^^^ method not found in `{async block@rust/lancedb/src/utils/background_cache.rs:269:22: 269:32}` | |_____________| error[E0277]: the trait bound `TimeoutStream: futures_core::stream::Stream` is not satisfied --> rust/lancedb/src/utils/mod.rs:345:9 | 345 | Box::pin(Self::new(inner, timeout)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound error[E0599]: no method named `poll_next` found for struct `Pin<&mut TimeoutStream>` in the current scope --> rust/lancedb/src/utils/mod.rs:376:22 | 376 | self.poll_next(cx) | ^^^^^^^^^ | = help: items from traits can only be used if the trait is implemented and in scope = note: the following traits define an item `poll_next`, perhaps you need to implement one of them: candidate #1: `futures_core::stream::Stream` candidate #2: `sorts::stream::PartitionedStream` help: there is a method `collect` with a similar name, but with different arguments --> $CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/futures-0.1.31/src/stream/mod.rs:563:5 | 563 | / fn collect(self) -> Collect 564 | | where Self: Sized | |_________________________^ error[E0599]: no method named `poll_unpin` found for mutable reference `&mut Pin>` in the current scope --> rust/lancedb/src/utils/mod.rs:378:75 | 378 | TimeoutState::Started { deadline, timeout } => match deadline.poll_unpin(cx) { | ^^^^^^^^^^ method not found in `&mut Pin>` error[E0599]: no method named `poll_next` found for struct `Pin<&mut Pin>>` in the current scope --> rust/lancedb/src/utils/mod.rs:386:27 | 386 | inner.poll_next(cx) | ^^^^^^^^^ error[E0277]: the trait bound `MaxBatchLengthStream: futures_core::stream::Stream` is not satisfied --> rust/lancedb/src/utils/mod.rs:419:13 | 419 | Box::pin(Self::new(inner, max_batch_length)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unsatisfied trait bound error[E0599]: no method named `poll_next` found for struct `Pin<&mut Pin>>` in the current scope --> rust/lancedb/src/utils/mod.rs:439:50 | 439 | return Pin::new(&mut self.inner).poll_next(cx); | ^^^^^^^^^ error[E0599]: no method named `poll_next` found for struct `Pin<&mut Pin>>` in the current scope --> rust/lancedb/src/utils/mod.rs:459:45 | 459 | match Pin::new(&mut self.inner).poll_next(cx) { | ^^^^^^^^^ Some errors have detailed explanations: E0046, E0107, E0191, E0271, E0277, E0282, E0308, E0407, E0425... For more information about an error, try `rustc --explain E0046`. error: could not compile `lancedb` (lib) due to 118 previous errors ``` --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index a879d1f8b..78474cd16 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,7 +52,7 @@ env_logger = "0.11" half = { "version" = "2.7.1", default-features = false, features = [ "num-traits", ] } -futures = "0" +futures = "0.3" log = "0.4" metrics = "0.24" metrics-util = "0.19" From c5f9efefe9396c058b3ce6aa2298c0ef635477fb Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:30:55 +0800 Subject: [PATCH 004/206] test(python): cover local sync multiple-vector search (#3830) ## Summary - add regression coverage for multiple query vectors in the local synchronous Python API - verify that each query vector receives its own limited nearest-neighbor result and `query_index` ## Root cause In LanceDB v0.16, the local synchronous scanner passed a nested vector array as one query, unlike the async and remote implementations. The subsequent sync-to-async table migration supplied the correct shared runtime path, but this local sync behavior was never regression-tested and issue #1857 remained open. ## Validation - `uv run --extra tests pytest python/tests/test_query.py::test_query_multiple_vectors -q` - `uv run --project python --extra tests --extra dev ruff format --check python/python/tests/test_query.py` - `uv run --project python --extra tests --extra dev ruff check .` Fixes #1857 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/tests/test_query.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 6840be052..d2629d1a8 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -570,6 +570,15 @@ def test_query_builder(table): assert all(np.array(rs[0]["vector"]) == [1, 2]) +def test_query_multiple_vectors(table): + results = table.search([np.array([1, 2]), np.array([4, 5])]).limit(1).to_list() + + assert len(results) == 2 + results_by_query = {result["query_index"]: result for result in results} + assert results_by_query[0]["id"] == 1 + assert results_by_query[1]["id"] == 2 + + def test_with_row_id(table: lancedb.table.Table): rs = table.search().with_row_id(True).to_arrow() assert "_rowid" in rs.column_names From 2922c171f7feecc6ce6ab63621fb4e3791e36420 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:31:08 +0800 Subject: [PATCH 005/206] test(rust): cover Azure table URI separators (#3837) ## Root cause The former listing-database table URI builder used OS-native `Path::join` for object-store URIs. On Windows this inserted backslashes into `az://` table paths, so `table_names` found slash-delimited objects while `open_table` addressed a different key. The production path now builds URI paths with forward slashes after the equivalent S3 report was fixed in #2575, but #1072 remained open without Azure-specific regression coverage. ## Fix - Add Azure URI regression assertions at the Rust table URI construction boundary. - Cover connection bases both with and without a trailing slash, matching the behavior reported in #1072. - Verify the resulting table URI always uses forward slashes on every platform. ## Validation - `cargo fmt --all -- --check` - `cargo test --quiet -p lancedb --lib database::listing::tests::test_table_uri` - `cargo check --quiet --features remote --tests --examples` - `cargo clippy --quiet --features remote --tests --examples` - `cargo test --quiet --features remote --tests` (866 passed, 1 ignored) Fixes #1072 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- rust/lancedb/src/database/listing.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index fea34bb48..a4624112e 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -2342,7 +2342,7 @@ mod tests { #[tokio::test] async fn test_table_uri() { - let (_tempdir, db) = setup_database().await; + let (_tempdir, mut db) = setup_database().await; let mut pb = PathBuf::new(); pb.push(db.uri.clone()); @@ -2351,6 +2351,18 @@ mod tests { let expected = pb.to_str().unwrap(); let uri = db.table_uri("test").ok().unwrap(); assert_eq!(uri, expected); + + // URI paths always use forward slashes, even on Windows. Using + // `Path::join` here used to produce `az://container/prefix\\test.lance`, + // which Azure treated as a different object from the table returned by + // `table_names` (https://github.com/lancedb/lancedb/issues/1072). + for base_uri in ["az://container/prefix", "az://container/prefix/"] { + db.uri = base_uri.to_string(); + assert_eq!( + db.table_uri("test").unwrap(), + "az://container/prefix/test.lance" + ); + } } /// Regression: connecting via a URL-style URI (which goes through From 4048150fdd3bc19d7c651f1e4e7e16c82b6b5888 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:31:19 +0800 Subject: [PATCH 006/206] test(python): cover nullable fixed-size-list ingestion (#3812) ## Summary - add regression coverage for adding dictionary rows with a nullable fixed-size-list column - verify ordinary list columns remain aligned alongside the null fixed-size-list value ## Root cause PyArrow infers an all-`None` dictionary column as the generic `null` type. The original schema-alignment path treated the target fixed-size-list type as proof that the inferred source was also list-like and unconditionally accessed `value_field`, which raised `AttributeError`. Current alignment logic correctly falls back to the target type when the source is not list-like; this test locks in that repair for the reported ingestion path. ## Validation - `uv run --extra tests pytest python/tests/test_table.py::test_add_with_empty_fixed_size_list_drops_bad_rows python/tests/test_table.py::test_add_nullable_fixed_size_list_with_none python/tests/test_table.py::test_add_nullable_struct_with_none -q` - `uv run --with pyarrow==19.0.1 --extra tests pytest python/tests/test_table.py::test_add_nullable_fixed_size_list_with_none -q` - `uv run --project python --extra dev ruff format --check python/python/tests/test_table.py` - `uv run --project python --extra dev ruff check .` Fixes #2340 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/tests/test_table.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index b2bfa2a68..e5c4ad801 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1845,6 +1845,27 @@ def test_add_with_empty_fixed_size_list_drops_bad_rows(mem_db: DBConnection): assert np.allclose(data["embedding"].to_pylist()[0], np.array([0.1] * 16)) +def test_add_nullable_fixed_size_list_with_none(mem_db: DBConnection): + """Regression test for issue #2340.""" + table = mem_db.create_table( + "test_nullable_fixed_size_list", + schema=pa.schema( + [ + pa.field("id", pa.string()), + pa.field("feature", pa.list_(pa.float32(), 256)), + pa.field("tags", pa.list_(pa.string())), + ] + ), + ) + + table.add([{"id": "1", "feature": None, "tags": ["tag1", "tag2"]}]) + + result = table.to_arrow() + assert result.to_pylist() == [ + {"id": "1", "feature": None, "tags": ["tag1", "tag2"]} + ] + + def test_add_nullable_struct_with_none(mem_db: DBConnection): """Regression test for issue #2654: a nullable struct column whose first batch contains only None values must not crash in From fc44535ceeac0fd73ae94d0a0151c35753cb3e40 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:31:30 +0800 Subject: [PATCH 007/206] fix(python): clarify bare Vector annotations (#3809) ## Summary - raise a clear `TypeError` when `Vector` is used without a dimension - preserve normal `Vector(dim)` behavior across Pydantic v1 and v2 - add a regression test that defines a model without importing PyArrow ## Root cause Pydantic interpreted the bare `Vector` factory as a callable field type and inspected its postponed annotations in the user model's namespace. Because that namespace did not define LanceDB's internal `pa` alias, model construction failed with the misleading `NameError: name 'pa' is not defined` instead of explaining that `Vector` must be parameterized. The factory now exposes Pydantic's v1 and v2 schema hooks and rejects bare use before signature introspection with guidance to use `Vector(dim)`. ## Validation - `uvx --from 'ruff==0.15.20' ruff check .` - `uvx --from 'ruff==0.15.20' ruff format --check python/python/lancedb/pydantic.py python/python/tests/test_pydantic.py` - `cd python && uv run --extra tests pytest python/tests/test_pydantic.py::test_bare_vector_raises_clear_error -q` - `cd python && uv run --extra tests pytest python/tests/test_pydantic.py -q` - compatibility checks with Pydantic 1.10.22, 2.11.4, and 2.13.4 Fixes #2384 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/lancedb/pydantic.py | 10 ++++++++++ python/python/tests/test_pydantic.py | 11 +++++++++++ 2 files changed, 21 insertions(+) diff --git a/python/python/lancedb/pydantic.py b/python/python/lancedb/pydantic.py index c4dedc0e6..1ab6e6fcc 100644 --- a/python/python/lancedb/pydantic.py +++ b/python/python/lancedb/pydantic.py @@ -153,6 +153,16 @@ def Vector( return FixedSizeList +def _raise_bare_vector_error(*_args): + raise TypeError("Vector must be parameterized with a dimension, e.g. Vector(128).") + + +# Pydantic v1 and v2 otherwise treat the bare Vector factory as a field validator +# and inspect its signature, which produces misleading errors about internal types. +setattr(Vector, "__get_validators__", _raise_bare_vector_error) +setattr(Vector, "__get_pydantic_core_schema__", _raise_bare_vector_error) + + def MultiVector( dim: int, value_type: pa.DataType = pa.float32(), nullable: bool = True ) -> Type: diff --git a/python/python/tests/test_pydantic.py b/python/python/tests/test_pydantic.py index e1d533784..db93d7c64 100644 --- a/python/python/tests/test_pydantic.py +++ b/python/python/tests/test_pydantic.py @@ -415,6 +415,17 @@ def test_nullable_vector(): assert schema == pa.schema([pa.field("vec", pa.list_(pa.float32(), 16), True)]) +def test_bare_vector_raises_clear_error(): + namespace = { + "__name__": "test_model_without_pyarrow", + "LanceModel": LanceModel, + "Vector": Vector, + } + + with pytest.raises(TypeError, match=r"Vector must be parameterized.*Vector\(128\)"): + exec("class TestModel(LanceModel):\n vector: Vector", namespace) + + def test_fixed_size_list_field(): class TestModel(pydantic.BaseModel): vec: Vector(16) From ec80acb668b361e395ecfa5ee381391bd3b3b859 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:31:42 +0800 Subject: [PATCH 008/206] fix(python): expose inline types to downstream checkers (#3817) ## Summary - publish the PEP 561 `py.typed` marker so downstream type checkers consume the inline public annotations - add a Pyright contract test that distinguishes synchronous `connect` from awaited `connect_async` - verify the marker is present in the installed package ## Root cause The public Python module already annotated `lancedb.connect` as synchronous and `lancedb.connect_async` as asynchronous. The private native `_lancedb.connect` stub is intentionally awaitable because it backs `connect_async`. However, the distribution did not include a PEP 561 marker, so downstream tools such as mypy could ignore the public inline annotations and expose misleading or incomplete type information. ## Validation - `python/.venv/bin/ruff format --check python/python/tests/test_db.py python/python/type_tests/connect.py` - `python/.venv/bin/ruff check .` - `cd python && .venv/bin/pytest python/tests/test_db.py::test_package_includes_pep_561_marker -q` - `cd python && .venv/bin/pyright --pythonpath .venv/bin/python` - downstream mypy contract check for both public connection functions Fixes #2159 Co-authored-by: lancedb-gatefixer[bot] <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/pyproject.toml | 1 + python/python/lancedb/py.typed | 1 + python/python/tests/test_db.py | 5 +++++ python/python/type_tests/connect.py | 15 +++++++++++++++ 4 files changed, 22 insertions(+) create mode 100644 python/python/lancedb/py.typed create mode 100644 python/python/type_tests/connect.py diff --git a/python/pyproject.toml b/python/pyproject.toml index cb175bd6d..348058957 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -140,6 +140,7 @@ include = [ "python/lancedb/remote/errors.py", "python/lancedb/embeddings/__init__.py", "python/lancedb/_lancedb.pyi", + "python/type_tests/connect.py", ] exclude = ["python/tests/"] pythonVersion = "3.13" diff --git a/python/python/lancedb/py.typed b/python/python/lancedb/py.typed new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/python/python/lancedb/py.typed @@ -0,0 +1 @@ + diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index 8f4a8850c..84e78fd8f 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -6,6 +6,7 @@ import inspect import re import sys from datetime import timedelta +from importlib import resources import os from types import SimpleNamespace @@ -18,6 +19,10 @@ from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError from lancedb.pydantic import LanceModel, Vector +def test_package_includes_pep_561_marker(): + assert resources.files(lancedb).joinpath("py.typed").is_file() + + def test_basic(tmp_path): db = lancedb.connect(tmp_path) diff --git a/python/python/type_tests/connect.py b/python/python/type_tests/connect.py new file mode 100644 index 000000000..eb2cba37c --- /dev/null +++ b/python/python/type_tests/connect.py @@ -0,0 +1,15 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from typing import assert_type + +import lancedb +from lancedb import AsyncConnection, DBConnection + + +def check_connect_type() -> None: + assert_type(lancedb.connect("memory://"), DBConnection) + + +async def check_connect_async_type() -> None: + assert_type(await lancedb.connect_async("memory://"), AsyncConnection) From dbc3687c7b9cfc2e5923d2c8a28a94cb6b9e56da Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:31:53 +0800 Subject: [PATCH 009/206] fix(node): require compatible Node.js types (#3829) ## Summary - require Node.js 18-compatible type declarations when TypeScript consumers install them - keep the type peer optional for JavaScript-only consumers - add a regression test tying the Node type peer range to the supported runtime ## Root cause LanceDB requires Node.js 18 or newer, and its public types expose Apache Arrow declarations that import built-ins through the node: scheme. The package did not declare a matching @types/node peer requirement, so npm accepted projects pinned to Node 12 declarations and TypeScript then reported that node:stream and node:fs/promises did not exist. ## Validation - pnpm lint - pnpm build - pnpm run docs - pnpm test --runInBand (678 passed, 5 skipped) - packed-package consumer probe rejects @types/node 12.20.55 and installs with @types/node 18.19.130 Fixes #1713 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- nodejs/__test__/package.test.ts | 14 ++++++++++++++ nodejs/package-lock.json | 6 ++++++ nodejs/package.json | 6 ++++++ 3 files changed, 26 insertions(+) create mode 100644 nodejs/__test__/package.test.ts diff --git a/nodejs/__test__/package.test.ts b/nodejs/__test__/package.test.ts new file mode 100644 index 000000000..7743d73d6 --- /dev/null +++ b/nodejs/__test__/package.test.ts @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import packageJson = require("../package.json"); + +describe("package metadata", () => { + it("requires Node.js type declarations compatible with the runtime", () => { + expect(packageJson.engines.node).toBe(">= 18"); + expect(packageJson.peerDependencies["@types/node"]).toBe(">=18"); + expect(packageJson.peerDependenciesMeta["@types/node"]).toEqual({ + optional: true, + }); + }); +}); diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index 8e30b0fab..bdbd3cf79 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -55,7 +55,13 @@ "openai": "4.29.2" }, "peerDependencies": { + "@types/node": ">=18", "apache-arrow": ">=15.0.0 <=18.1.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } }, "node_modules/@aws-crypto/crc32": { diff --git a/nodejs/package.json b/nodejs/package.json index f3f719af2..671f3f94d 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -101,6 +101,12 @@ "openai": "4.29.2" }, "peerDependencies": { + "@types/node": ">=18", "apache-arrow": ">=15.0.0 <=18.1.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } } } From dd5cb4d805b6cd79c7ecf9fb25754285d5d631bd Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:32:05 +0800 Subject: [PATCH 010/206] test(python): cover float16 table creation from Arrow data (#3785) ## Summary - exercise float16 sanitization through the reported direct Arrow-data table creation path - assert that the inferred fixed-size vector schema remains float16 - retain end-to-end index creation and vector search coverage ## Root cause and fix PyArrow 16 does not provide an is_nan kernel for half-float arrays, so passing float16 vector values directly to that kernel raises ArrowNotImplementedError. LanceDB's sanitizer already carries the compatibility fix from #837: it casts float16 values to float32 only for NaN detection while preserving the stored vector type. The existing end-to-end regression created an empty schema-defined table and added data afterward. This change aligns that regression with the issue reproduction by creating a table directly from a FixedSizeList Arrow table and verifying the persisted schema. ## Validation - uv run --extra tests pytest python/tests/test_table.py::test_create_f16_table_from_arrow_data -q - direct 1,000-row by 128-dimension float16 Arrow-table reproduction - PyArrow 16.1 half-float is_nan kernel reproduction - uvx ruff@0.15.20 format --check python/python/tests/test_table.py - uvx ruff@0.15.20 check . Fixes #835 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/tests/test_table.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index e5c4ad801..8fc06ea69 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -2759,15 +2759,40 @@ def test_create_with_embedding_function(mem_db: DBConnection): assert actual == expected +def test_create_f16_table_from_arrow_data(mem_db: DBConnection): + dimension = 32 + num_rows = 512 + values = pa.array( + np.random.default_rng(42) + .standard_normal(num_rows * dimension) + .astype(np.float16) + ) + df = pa.table( + { + "text": [f"s-{i}" for i in range(num_rows)], + "vector": pa.FixedSizeListArray.from_arrays(values, dimension), + } + ) + table = mem_db.create_table("f16_tbl", data=df) + assert table.schema.field("vector").type == pa.list_(pa.float16(), dimension) + table.create_index(num_partitions=2, num_sub_vectors=2) + + query = df["vector"][2].as_py() + expected = table.search(query).limit(2).to_arrow() + + assert "s-2" in expected["text"].to_pylist() + + def test_create_f16_table(mem_db: DBConnection): class MyTable(LanceModel): text: str vector: Vector(32, value_type=pa.float16()) + rng = np.random.default_rng(42) df = pa.table( { "text": [f"s-{i}" for i in range(512)], - "vector": [np.random.randn(32).astype(np.float16) for _ in range(512)], + "vector": [rng.standard_normal(32).astype(np.float16) for _ in range(512)], } ) table = mem_db.create_table( From 564e5d0d56802bfd2c025e9337b8dd810d42759a Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:32:17 +0800 Subject: [PATCH 011/206] fix(python): support Polars 1.32 table scans (#3801) ## Root cause `Table.to_polars()` disabled PyArrow predicate pushdown by selecting the non-PyArrow Polars scan callback. Polars 1.32.3 invokes that callback with `batch_size` both positionally and through its partial, so collecting the returned lazy frame raises `TypeError: _scan_pyarrow_dataset_impl() got multiple values for argument batch_size`. ## Fix - Keep the compatible PyArrow callback path. - Add an identity `map_batches` barrier so predicates stay in Polars instead of reaching the LanceDB adapter as unsupported PyArrow expressions. - Extend the tested Polars range through 1.32.3 and retain lazy-frame regression coverage. ## Validation - `python/tests/test_table.py::test_polars` with Polars 1.32.3 - `python/tests/test_table.py::test_polars` with the locked Polars 1.3.0 baseline - `ruff format --check` on the changed Python files - `ruff check .` - `uv lock --check` Fixes #2619 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/pyproject.toml | 2 +- python/python/lancedb/table.py | 28 +++++++++++++++++++++++----- python/python/tests/test_table.py | 1 + python/uv.lock | 2 +- 4 files changed, 26 insertions(+), 7 deletions(-) diff --git a/python/pyproject.toml b/python/pyproject.toml index 348058957..ce71484de 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -60,7 +60,7 @@ tests = [ "pytest-asyncio>=0.21", "duckdb>=0.9.0", "pytz>=2023.3", - "polars>=0.19, <=1.3.0", + "polars>=0.19, <=1.32.3", "pyarrow<25", "pyarrow-stubs>=16.0", "pylance==9.0.0rc1", diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index ae36bac7a..59e2650eb 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -108,6 +108,11 @@ def _should_push_down_query_table( return namespace_client is not None and "QueryTable" in pushdown_operations +def _polars_predicate_pushdown_barrier(frame: Any) -> Any: + """Return a Polars frame unchanged while blocking predicate pushdown.""" + return frame + + _MODEL_BACKED_TOKENIZER_PREFIXES = ("jieba", "lindera") _MODEL_BACKED_TOKENIZER_ERRORS = ( "unknown base tokenizer", @@ -864,12 +869,18 @@ class Table(ABC): """ raise NotImplementedError - def to_polars(self, **kwargs) -> "pl.DataFrame": - """Return the table as a polars.DataFrame. + def to_polars(self, **kwargs) -> "pl.LazyFrame": + """Return the table as a Polars LazyFrame. + + Note + ---- + The Polars streaming engine is not supported because it does not currently + implement Python PyArrow dataset scans. Use the default engine when collecting + this LazyFrame. Returns ------- - polars.DataFrame + polars.LazyFrame """ raise NotImplementedError @@ -2569,6 +2580,9 @@ class LanceTable(Table): 2. Currently we've disabled push-down of the filters from polars because polars pushdown into pyarrow uses pyarrow compute expressions rather than SQl strings (which LanceDB supports) + 3. The Polars streaming engine is not supported because it does not + currently implement Python PyArrow dataset scans. Use the default + engine when collecting this LazyFrame. Returns ------- @@ -2577,8 +2591,12 @@ class LanceTable(Table): from lancedb.integrations.pyarrow import PyarrowDatasetAdapter dataset = PyarrowDatasetAdapter(self) - return pl.scan_pyarrow_dataset( - dataset, allow_pyarrow_filter=False, batch_size=batch_size + # Polars 1.32's non-PyArrow callback path passes batch_size twice. Keep + # the compatible PyArrow path, but block predicates because this adapter + # cannot translate PyArrow expressions into LanceDB filters. + return pl.scan_pyarrow_dataset(dataset, batch_size=batch_size).map_batches( + _polars_predicate_pushdown_barrier, + predicate_pushdown=False, ) # New unified API overload diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 8fc06ea69..4ad5d7c3d 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -929,6 +929,7 @@ def test_polars(mem_db: DBConnection): # enter table to polars dataframe result = table.to_polars() + assert isinstance(result, pl.LazyFrame) assert np.allclose(result.collect()["vector"].to_list(), data["vector"]) # make sure filtering isn't broken diff --git a/python/uv.lock b/python/uv.lock index 551dc3f68..2cdcb182e 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -1998,7 +1998,7 @@ requires-dist = [ { name = "pillow", marker = "extra == 'clip'", specifier = ">=12.1.1" }, { name = "pillow", marker = "extra == 'embeddings'", specifier = ">=12.1.1" }, { name = "pillow", marker = "extra == 'siglip'", specifier = ">=12.1.1" }, - { name = "polars", marker = "extra == 'tests'", specifier = ">=0.19,<=1.3.0" }, + { 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" }, From 607e5569276e68fc9b7bd6803b2748e6028007e1 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:32:28 +0800 Subject: [PATCH 012/206] test(python): cover search after schema merge (#3784) ## Summary - add an end-to-end regression for indexed vector search after merging a pandas column - verify unmatched rows retain a null merged value instead of failing Arrow batch assembly ## Root cause Historical Lance readers could assemble schema-evolved columns in physical data-file order. Indexed row-ID reads after a merge could therefore omit or misorder the newly merged column for unmatched rows. The currently pinned Lance release contains the reader correction, but LanceDB did not cover the reported merge-then-search path. ## Validation - uv run --extra tests pytest python/tests/test_table.py::test_merge python/tests/test_table.py::test_search_after_merge -q - uv run --project python --extra dev ruff check . - uv run --project python --extra dev ruff format --check python/python/tests/test_table.py Fixes #599 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/tests/test_table.py | 39 +++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 4ad5d7c3d..eb6eaefaa 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -2218,6 +2218,45 @@ def test_merge(tmp_db: DBConnection, tmp_path): table.merge(other_dataset, left_on="id") +@pytest.mark.parametrize("storage_version", ["legacy", "stable"]) +def test_search_after_merge(tmp_path, storage_version): + pytest.importorskip("lance") + pd = pytest.importorskip("pandas") + + db = lancedb.connect( + tmp_path, + storage_options={"new_table_data_storage_version": storage_version}, + ) + rng = np.random.default_rng(42) + row_count = 512 + vectors = rng.standard_normal((row_count, 8)).astype(np.float32) + table = db.create_table( + "search_after_merge", + data=pd.DataFrame( + { + "id": [str(i) for i in range(row_count)], + "vector": list(vectors), + } + ), + ) + table.create_index("vector", config=IvfPq(num_partitions=1, num_sub_vectors=2)) + + links = pd.DataFrame( + { + "id": [str(i) for i in range(row_count // 2)], + "link": [f"https://example.com/{i}" for i in range(row_count // 2)], + } + ) + table.merge(links, left_on="id") + + query = table.search(vectors[-1]).refine_factor(50).limit(10) + assert "ANN" in query.explain_plan(verbose=True) + + result = query.to_arrow() + links_by_id = dict(zip(result["id"].to_pylist(), result["link"].to_pylist())) + assert links_by_id[str(row_count - 1)] is None + + def test_delete(mem_db: DBConnection): table = mem_db.create_table( "my_table", From 2ba7407dc36f4989dc720d96bd765601b94566ba Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:32:39 +0800 Subject: [PATCH 013/206] fix(node): cover non-nullable embedding schema append (#3835) ## Summary - Add an issue-specific regression for appending generated embeddings to an empty table with a non-nullable vector field. - Verify the custom embedding function produces the declared Float64 vectors and both appended rows are readable. ## Root cause In v0.4.19, records without a vector value were materialized against the explicit schema before embeddings were inserted. Apache Arrow inferred the generated batch vector field as nullable while the table retained the user-provided non-nullable field, then rejected the mismatched schemas. The current conversion path excludes the generated field from the initial record conversion and realigns the completed batch to the stored schema after embedding, but the reported empty-table append sequence lacked permanent regression coverage. ## Validation - `pnpm exec biome format --write __test__/embedding.test.ts` - `pnpm lint-ci` - `pnpm test -- --runInBand __test__/embedding.test.ts` (12 passed, 1 skipped integration test) - `pnpm build` - `pnpm run docs` Fixes #1281 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- nodejs/__test__/embedding.test.ts | 60 +++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/nodejs/__test__/embedding.test.ts b/nodejs/__test__/embedding.test.ts index e56e80631..06184751e 100644 --- a/nodejs/__test__/embedding.test.ts +++ b/nodejs/__test__/embedding.test.ts @@ -11,8 +11,11 @@ import { Float16, Float32, Float64, + Int32, Schema, Utf8, + fromDataToBuffer, + tableFromIPC, } from "../lancedb/arrow"; import { EmbeddingFunction, LanceSchema } from "../lancedb/embedding"; import { getRegistry, register } from "../lancedb/embedding/registry"; @@ -184,6 +187,63 @@ describe("embedding functions", () => { const vector0 = JSON.parse(JSON.stringify(arr[0].vector)); expect(vector0).toEqual([1, 2, 3]); }); + + it("should append generated vectors to a non-nullable schema", async () => { + @register("non_nullable_schema_test") + class MockEmbeddingFunction extends EmbeddingFunction { + ndims() { + return 3; + } + embeddingDataType(): Float { + return new Float64(); + } + async computeSourceEmbeddings(data: string[]) { + return data.map(() => [1, 2, 3]); + } + } + + const schema = new Schema([ + new Field("id", new Int32()), + new Field("text", new Utf8()), + new Field("type", new Utf8()), + new Field( + "vector", + new FixedSizeList(3, new Field("item", new Float64())), + ), + ]); + const func = new MockEmbeddingFunction(); + const db = await connect(tmpDir.name); + const table = await db.createEmptyTable("test_non_nullable", schema, { + embeddingFunction: { + function: func, + sourceColumn: "text", + }, + }); + + const data = [ + { id: 1, text: "Carrot", type: "vegetable" }, + { id: 2, text: "Apple", type: "fruit" }, + ]; + const buffer = await fromDataToBuffer( + data, + undefined, + await table.schema(), + ); + const generatedTable = tableFromIPC(buffer); + const vectorField = generatedTable.schema.fields.find( + (field) => field.name === "vector", + ); + expect(vectorField?.nullable).toBe(false); + + await table.add(data); + + const rows = await table.query().toArray(); + expect(rows).toHaveLength(2); + for (const row of rows) { + expect([...row.vector]).toEqual([1, 2, 3]); + } + }); + it("should error when appending to a table with an unregistered embedding function", async () => { @register("mock") class MockEmbeddingFunction extends EmbeddingFunction { From 11f24b1df408306d9a7801f83fe7fbed20b99e46 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:33:02 +0800 Subject: [PATCH 014/206] fix: explain unsupported object storage mounts (#3823) ## Summary - classify unsupported local-filesystem operations from Lance as a NotSupported error - explain that object-storage mounts cannot provide the safe commit operations Lance requires and direct users to native object-store URIs - preserve existing error behavior for other local I/O failures and non-local backends ## Root cause Mountpoint for Amazon S3 exposes an S3 bucket as a local path but does not implement atomic rename. Lance uses atomic rename for safe local commits, and the resulting unsupported I/O error was previously passed through as a generic Lance error, leaving Python users with an opaque low-level failure. Transparent support for such mounts is not safe; direct s3:// access remains the supported path. ## Validation - cargo test --quiet --features remote -p lancedb error::tests - cargo test --quiet --features remote -p lancedb --lib (807 passed, 1 ignored) - cargo check --quiet --features remote --tests --examples - cargo clippy --quiet --features remote --tests --examples - cargo fmt --all -- --check Fixes #2016 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- rust/lancedb/src/error.rs | 70 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index f6f596f3d..4a6e6d8d9 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -169,6 +169,12 @@ impl From for Error { impl From for Error { fn from(source: lance::Error) -> Self { + if has_unsupported_local_filesystem_source(&source) { + return Self::NotSupported { + message: "the filesystem does not support an operation required for safe Lance commits (such as atomic rename). Object-storage mounts such as Mountpoint for Amazon S3 are not supported; use the native object-store URI (for example, s3://bucket/path) instead".to_string(), + }; + } + // Try to unwrap external errors that were wrapped by lance match source { lance::Error::Wrapped { error, .. } => Self::from_box_error(error), @@ -181,6 +187,27 @@ impl From for Error { } } +fn has_unsupported_local_filesystem_source(error: &(dyn std::error::Error + 'static)) -> bool { + let mut current = Some(error); + let mut is_local_filesystem = false; + let mut is_unsupported = false; + while let Some(error) = current { + is_local_filesystem |= error + .downcast_ref::() + .is_some_and(|error| { + matches!(error, object_store::Error::Generic { store, .. } if *store == "LocalFileSystem") + }); + is_unsupported |= error + .downcast_ref::() + .is_some_and(|error| error.kind() == std::io::ErrorKind::Unsupported); + if is_local_filesystem && is_unsupported { + return true; + } + current = error.source(); + } + false +} + impl Error { fn from_box_error(mut source: Box) -> Self { source = match source.downcast::() { @@ -270,3 +297,46 @@ impl From for Error { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unsupported_filesystem_operations_have_actionable_error() { + let object_store_error = object_store::Error::Generic { + store: "LocalFileSystem", + source: Box::new(std::io::Error::from(std::io::ErrorKind::Unsupported)), + }; + let lance_error = lance::Error::io_source(Box::new(object_store_error)); + + let error = Error::from(lance_error); + + assert!(matches!( + error, + Error::NotSupported { message } + if message.contains("Mountpoint for Amazon S3") + && message.contains("s3://bucket/path") + )); + } + + #[test] + fn other_io_errors_remain_lance_errors() { + let object_store_error = object_store::Error::Generic { + store: "LocalFileSystem", + source: Box::new(std::io::Error::from(std::io::ErrorKind::PermissionDenied)), + }; + let lance_error = lance::Error::io_source(Box::new(object_store_error)); + + assert!(matches!(Error::from(lance_error), Error::Lance { .. })); + } + + #[test] + fn unsupported_non_filesystem_errors_remain_lance_errors() { + let lance_error = lance::Error::io_source(Box::new(std::io::Error::from( + std::io::ErrorKind::Unsupported, + ))); + + assert!(matches!(Error::from(lance_error), Error::Lance { .. })); + } +} From 6ba80a960cd1a54f6d8b625124743301beaf4173 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:33:13 +0800 Subject: [PATCH 015/206] fix(node): cover offset pagination in search (#3814) ## Summary - add Node regression coverage for vector-search offset pagination - add equivalent coverage for full-text search - compare later pages with the corresponding complete-result slice and assert page sizes ## Root cause The historical query path requested only the user limit from nearest-neighbor or full-text search before applying the offset, so a page became empty when its offset reached that limit. The production query path on current main already incorporates the later fix from #2592; this change adds the missing Node binding coverage for the still-open report and protects both affected APIs from regression. ## Validation - corepack pnpm build - corepack pnpm test -- query.test.ts --runInBand --testNamePattern="Search pagination" - corepack pnpm lint-ci - corepack pnpm tsc - corepack pnpm run docs Fixes #2229 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- nodejs/__test__/query.test.ts | 75 +++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/nodejs/__test__/query.test.ts b/nodejs/__test__/query.test.ts index da001b1eb..5f3e68b16 100644 --- a/nodejs/__test__/query.test.ts +++ b/nodejs/__test__/query.test.ts @@ -110,6 +110,81 @@ describe("Query outputSchema", () => { }); }); +describe("Search pagination", () => { + let tmpDir: tmp.DirResult; + let table: Table; + + beforeEach(async () => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + const db = await connect(tmpDir.name); + const schema = new Schema([ + new Field("id", new Int64(), false), + new Field("text", new Utf8(), false), + new Field( + "vector", + new FixedSizeList(2, new Field("item", new Float32())), + false, + ), + ]); + const data = makeArrowTable( + [ + { id: 1n, text: "common", vector: [0, 0] }, + { id: 2n, text: "common common", vector: [1, 1] }, + { id: 3n, text: "common common common", vector: [2, 2] }, + { id: 4n, text: "common common common common", vector: [3, 3] }, + ], + { schema }, + ); + table = await db.createTable("test", data); + }); + + afterEach(() => { + tmpDir.removeCallback(); + }); + + it("applies offset after the vector search limit", async () => { + const allResults = await table + .vectorSearch([0, 0]) + .select(["id"]) + .limit(4) + .toArray(); + const secondPage = await table + .vectorSearch([0, 0]) + .select(["id"]) + .limit(2) + .offset(2) + .toArray(); + + expect(allResults).toHaveLength(4); + expect(secondPage).toHaveLength(2); + expect(secondPage.map((row) => row.id)).toEqual( + allResults.slice(2, 4).map((row) => row.id), + ); + }); + + it("applies offset after the full-text search limit", async () => { + await table.createIndex("text", { config: Index.fts() }); + + const allResults = await table + .search("common", "fts") + .select(["id"]) + .limit(4) + .toArray(); + const secondPage = await table + .search("common", "fts") + .select(["id"]) + .limit(2) + .offset(2) + .toArray(); + + expect(allResults).toHaveLength(4); + expect(secondPage).toHaveLength(2); + expect(secondPage.map((row) => row.id)).toEqual( + allResults.slice(2, 4).map((row) => row.id), + ); + }); +}); + describe("Query orderBy", () => { let tmpDir: tmp.DirResult; let table: Table; From ec21e370401a2d74b43ca3efa187238905bf5fa8 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:37:37 +0800 Subject: [PATCH 016/206] test(rust): cover Hugging Face table symlinks (#3887) ## Summary - cover Hugging Face cache layouts where both manifests and Lance data files are relative symlinks into a blob directory - reconnect with a fresh session before opening so the test exercises filesystem discovery instead of cached manifest metadata - scan the reopened table to verify both manifest recovery and data-file reads ## Root cause Lance 3.0.1 recorded Unix symlink metadata as the known manifest size, so the short link length caused a file size is too small error. The current Lance v11.0.0-beta.2 dependency repairs this by detecting an invalid footer from a stale known size and retrying with the target file metadata. This regression test locks that behavior into the LanceDB open-table path used by Node. ## Validation - cargo fmt --all - cargo test --quiet --features remote -p lancedb --lib test_open_table_follows_hugging_face_symlinks -- --nocapture - cargo test --quiet --features remote -p lancedb --lib database::listing::tests - cargo clippy --quiet --features remote -p lancedb --lib --tests -- -D warnings - cargo check --quiet --features remote --tests --examples Fixes #3197 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- rust/lancedb/src/database/listing.rs | 92 +++++++++++++++++++++++++++- 1 file changed, 91 insertions(+), 1 deletion(-) diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index a4624112e..0ab3614e7 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -1294,9 +1294,11 @@ mod tests { use crate::connection::ConnectRequest; use crate::data::scannable::Scannable; use crate::database::{CreateTableMode, CreateTableRequest}; - use crate::table::WriteOptions; + use crate::query::QueryRequest; + use crate::table::{AnyQuery, WriteOptions}; use arrow_array::{Int32Array, RecordBatch, StringArray}; use arrow_schema::{DataType, Field, Schema}; + use futures::TryStreamExt; use std::path::PathBuf; use tempfile::tempdir; @@ -1438,6 +1440,94 @@ mod tests { assert!(after_open.hits >= before_open.hits + 3); } + /// Regression test for https://github.com/lancedb/lancedb/issues/3197. + #[cfg(unix)] + #[tokio::test] + async fn test_open_table_follows_hugging_face_symlinks() { + let (tempdir, db) = setup_database().await; + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + db.create_table(CreateTableRequest { + name: "test".to_string(), + namespace_path: vec![], + data: Box::new( + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![1, 2, 3]))]) + .unwrap(), + ) as Box, + mode: CreateTableMode::Create, + write_options: Default::default(), + location: None, + namespace_client: None, + }) + .await + .unwrap(); + + let table_dir = tempdir.path().join("test.lance"); + let versions_dir = table_dir.join("_versions"); + let manifest_path = std::fs::read_dir(&versions_dir) + .unwrap() + .map(|entry| entry.unwrap().path()) + .find(|path| path.extension().is_some_and(|ext| ext == "manifest")) + .unwrap(); + let data_path = std::fs::read_dir(table_dir.join("data")) + .unwrap() + .map(|entry| entry.unwrap().path()) + .find(|path| path.extension().is_some_and(|ext| ext == "lance")) + .unwrap(); + + // Hugging Face snapshots keep dataset objects in a separate blob directory and + // expose them through relative symlinks. + let blobs_dir = tempdir.path().join("blobs"); + std::fs::create_dir(&blobs_dir).unwrap(); + let manifest_blob = "9b603c63d0e692e05d58be25605f2f2064cc781e5ff94fe983a405059547b816"; + let data_blob = "be64f20e5723bd0a27cfdbdb41cf7d6fad94cd572a71973b717fb8340f4310c5"; + std::fs::rename(&manifest_path, blobs_dir.join(manifest_blob)).unwrap(); + std::fs::rename(&data_path, blobs_dir.join(data_blob)).unwrap(); + std::os::unix::fs::symlink(Path::new("../../blobs").join(manifest_blob), &manifest_path) + .unwrap(); + std::os::unix::fs::symlink(Path::new("../../blobs").join(data_blob), &data_path).unwrap(); + let symlink_len = std::fs::symlink_metadata(&manifest_path).unwrap().len(); + let target_len = std::fs::metadata(&manifest_path).unwrap().len(); + assert_ne!(symlink_len, target_len); + + drop(db); + let db = ListingDatabase::connect_with_options(&ConnectRequest { + uri: tempdir.path().to_str().unwrap().to_string(), + #[cfg(feature = "remote")] + client_config: Default::default(), + options: Default::default(), + namespace_client_properties: Default::default(), + manifest_enabled: false, + read_consistency_interval: None, + session: None, + }) + .await + .unwrap(); + + let table = db + .open_table(OpenTableRequest { + name: "test".to_string(), + namespace_path: vec![], + index_cache_size: None, + lance_read_params: None, + location: None, + namespace_client: None, + managed_versioning: None, + }) + .await + .unwrap(); + let batches = table + .query( + &AnyQuery::Query(QueryRequest::default()), + Default::default(), + ) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 3); + } + #[tokio::test] async fn test_clone_table_basic() { let (_tempdir, db) = setup_database().await; From 79ba076429d60dbdc245278ea3959d97bd5b5aa3 Mon Sep 17 00:00:00 2001 From: Dan Rammer Date: Fri, 7 Aug 2026 13:44:49 -0500 Subject: [PATCH 017/206] feat(table): checkpoint_lsm, flush_lsm, compact_lsm, get_lsm_stats (#3736) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Converge a table's LSM write path into its base table, and inspect it. `checkpoint_lsm` is `flush` then `compact`, repeated until the fresh tier is empty — and the loop runs **client-side**. Putting it on the server would mean a background task, which means a single-flight intent, an intent that leaks on panic, a bounded-iteration policy, an "is it done" observable, and a story for every way a client can vanish mid-operation. None of that exists in this shape: each request does a bounded unit of work and reports what is left, so completion is *carried in the responses* rather than inferred from a shared counter that cannot distinguish "converged" from "hasn't started yet". Best-effort by construction. Nothing is frozen, so `converged` means L0 was empty as of the last pass. It is idempotent, abandonable at any point with zero consequence, and safe to run on a cadence — an already-converged table costs one round trip and zero compaction passes, because `flush` reports `generations_remaining` and the loop is never entered. ## The failure taxonomy is the load-bearing part Five distinct conditions used to arrive at a client as one 503. `Error::LsmRoute` carries a classification read from the response body's namespace error code **at the point of receipt** — before any generic helper folds the body into a string and keeps only the status. | condition | wire | client action | |---|---|---| | contention (latch held / pool saturated) | 429, code 21 | retry with backoff | | owning node draining | 503, code 19 `InvalidTableState` | **stop** | | fenced / no slot / transport | 503, code 17 | retry with backoff | | registry entry vanished | 404 | re-issue from `flush` (capped) | | table being dropped / not WAL-backed | 409 / 400 | stop | Draining is terminal because the drain gate is a one-way latch — retrying spins until the deadline to report a failure that was knowable on the first response. Transport retry is disabled on these routes for the same reason: it treats every 503 alike and would burn its budget before the classifier ever saw the body. `get_lsm_stats` returns `Option`, matching `get_lsm_write_spec` — `None` only when the table has no LSM write path, since a struct of zeros would read as measurements. Python bindings mirror all four, preserving per-bucket detail rather than flattening to a table-level summary. ## Testing Six new unit tests against the mocked endpoint, plus the taxonomy round-trip: - flush into an empty L0 issues **zero** compact calls (asserts the call count — `generations_consumed: 0` is also true of a loop that ran a pointless pass) - the loop drives compact until the server reports zero remaining - **contention is not draining**: a 429 retries and converges; asserts the retry count - a draining node stops after **exactly one** request, no retries - stats round-trips fully populated; `include_generation_rows` off by default - every `(status, code)` pair classifies correctly, including unparseable 503 bodies falling back to *retryable* rather than terminal `cargo test -p lancedb --features remote --lib`: 723 passed. ## Notes for review - Depends on the sibling lance change returning `SealedGeneration` from `force_seal_active` only at the *server* level — no lance API is used here. - The branch is based on `codex/update-lance-10-0-0-beta-5`, so it carries one extra commit (`chore: update lance dependency to v10.0.0-beta.5`) that is not part of this change. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: lancedb automation Co-authored-by: Claude Opus 5 (1M context) --- python/python/lancedb/_lancedb.pyi | 4 + python/python/lancedb/table.py | 83 ++++ python/src/table.rs | 108 +++++- rust/lancedb/Cargo.toml | 2 +- rust/lancedb/src/remote/table.rs | 541 +++++++++++++++++++++++++++ rust/lancedb/src/table.rs | 107 ++++++ rust/lancedb/src/table/checkpoint.rs | 315 ++++++++++++++++ rust/lancedb/src/table/lsm_stats.rs | 162 ++++++++ 8 files changed, 1320 insertions(+), 2 deletions(-) create mode 100644 rust/lancedb/src/table/checkpoint.rs create mode 100644 rust/lancedb/src/table/lsm_stats.rs diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 47e727f99..fad2744d3 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -355,6 +355,10 @@ class Table: async def set_lsm_write_spec(self, spec: LsmWriteSpec) -> None: ... async def unset_lsm_write_spec(self) -> None: ... async def get_lsm_write_spec(self) -> Optional[LsmWriteSpec]: ... + async def checkpoint_lsm(self) -> None: ... + async def flush_lsm(self) -> None: ... + async def compact_lsm(self) -> None: ... + async def get_lsm_stats(self, include_generation_rows: bool) -> Optional[dict]: ... async def close_lsm_writers(self) -> None: ... @property def tags(self) -> Tags: ... diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 59e2650eb..0828f04dc 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -3976,6 +3976,28 @@ class LanceTable(Table): [`AsyncTable.get_lsm_write_spec`][lancedb.AsyncTable.get_lsm_write_spec].""" return LOOP.run(self._table.get_lsm_write_spec()) + def checkpoint_lsm(self) -> None: + """Synchronous version of + [`AsyncTable.checkpoint_lsm`][lancedb.AsyncTable.checkpoint_lsm].""" + return LOOP.run(self._table.checkpoint_lsm()) + + def flush_lsm(self) -> None: + """Synchronous version of + [`AsyncTable.flush_lsm`][lancedb.AsyncTable.flush_lsm].""" + return LOOP.run(self._table.flush_lsm()) + + def compact_lsm(self) -> None: + """Synchronous version of + [`AsyncTable.compact_lsm`][lancedb.AsyncTable.compact_lsm].""" + return LOOP.run(self._table.compact_lsm()) + + def get_lsm_stats(self, *, include_generation_rows: bool = False) -> Optional[dict]: + """Synchronous version of + [`AsyncTable.get_lsm_stats`][lancedb.AsyncTable.get_lsm_stats].""" + return LOOP.run( + self._table.get_lsm_stats(include_generation_rows=include_generation_rows) + ) + def close_lsm_writers(self) -> None: """Close cached MemWAL shard writers. See [`AsyncTable.close_lsm_writers`][lancedb.AsyncTable.close_lsm_writers].""" @@ -4686,6 +4708,67 @@ class AsyncTable: """ return await self._inner.get_lsm_write_spec() + async def checkpoint_lsm(self) -> None: + """Converge this table's LSM write path into its base table. + + One flush, sealing every memtable into L0, then compaction triggers + until every generation that existed at that moment has reached base. + The loop runs client-side, reading progress from ``get_lsm_stats``. + + Best-effort: generations created *while* it runs are deliberately not + waited on, which is what lets it terminate on a table taking writes. + Idempotent and safe on a cadence. + + There is no deadline, and the caller owns that. It returns when the + target generations are gone, raises on a terminal server fault, and + otherwise waits however long the server takes. A slow table and a + stuck one are the same picture from the client: the compactor pool is + shared across every table on the node, so a checkpoint queued behind + unrelated work looks exactly like one that is merging. Wrap this in + ``asyncio.wait_for`` for a wall-clock bound; abandoning it partway + costs nothing. + """ + return await self._inner.checkpoint_lsm() + + async def flush_lsm(self) -> None: + """Seal every bucket's active memtable into L0. + + Does not touch the base table — moving L0 into base is + `compact_lsm`. On a node that has not claimed this table, this claims + it and replays its WAL log first. + """ + return await self._inner.flush_lsm() + + async def compact_lsm(self) -> None: + """Trigger a background L0 to base compaction pass per bucket. + + Returns once the passes are dispatched, not once they finish: watch + ``get_lsm_stats`` for progress, or use ``checkpoint_lsm`` to loop + until the current L0 has reached base. + """ + return await self._inner.compact_lsm() + + async def get_lsm_stats( + self, *, include_generation_rows: bool = False + ) -> Optional[dict]: + """Read live per-bucket LSM state. + + Answers "how far behind is my fresh tier", "which bucket is hot", and + "why is my fresh-tier vector search brute-force". Mutates no table + state, though on a node that has not claimed this table it claims it, + exactly as a read would. + + Returns ``None`` only when the LSM write path is not enabled. + + Parameters + ---------- + include_generation_rows + Report a row count per L0 generation. Off by default: each count + opens an uncached Lance dataset, and ``checkpoint_lsm`` polls this + needing only generation numbers. + """ + return await self._inner.get_lsm_stats(include_generation_rows) + async def close_lsm_writers(self) -> None: """Drain and close any cached MemWAL shard writers for this table. diff --git a/python/src/table.rs b/python/src/table.rs index 5b5d6596a..119388708 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -28,11 +28,72 @@ use pyo3::{ Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python, exceptions::{PyRuntimeError, PyValueError}, pyclass, pyfunction, pymethods, - types::{IntoPyDict, PyAnyMethods, PyBytes, PyDict, PyDictMethods}, + types::{IntoPyDict, PyAnyMethods, PyBytes, PyDict, PyDictMethods, PyList, PyListMethods}, }; mod scannable; +/// Convert `LsmStats` to a Python dict, preserving the per-bucket list. +/// +/// Deliberately not flattened to a table-level summary: a table is N +/// buckets on one node, and the per-bucket detail is the reason the +/// endpoint exists — flattening hides the single hot bucket someone opened +/// it to find. +fn lsm_stats_to_py(py: Python<'_>, stats: &lancedb::table::LsmStats) -> PyResult> { + let out = PyDict::new(py); + let buckets = PyList::empty(py); + for b in &stats.buckets { + let e = PyDict::new(py); + e.set_item("shard_id", &b.shard_id)?; + e.set_item("status", &b.status)?; + e.set_item("writer_epoch", b.writer_epoch)?; + e.set_item("manifest_version", b.manifest_version)?; + e.set_item("current_generation", b.current_generation)?; + e.set_item( + "replay_after_wal_entry_position", + b.replay_after_wal_entry_position, + )?; + e.set_item( + "wal_entry_position_last_seen", + b.wal_entry_position_last_seen, + )?; + + let generations = PyList::empty(py); + for g in &b.generations { + let ge = PyDict::new(py); + ge.set_item("generation", g.generation)?; + ge.set_item("bytes", g.bytes)?; + ge.set_item("rows", g.rows)?; + generations.append(ge)?; + } + e.set_item("generations", generations)?; + e.set_item("compacting", b.compacting)?; + + e.set_item( + "memtables", + b.memtables + .as_ref() + .map(|ms| { + let l = PyList::empty(py); + for m in ms { + let d = PyDict::new(py); + d.set_item("generation", m.generation)?; + d.set_item("rows", m.rows)?; + d.set_item("bytes", m.bytes)?; + d.set_item("batches", m.batches)?; + d.set_item("indexes", m.indexes.clone())?; + l.append(d)?; + } + PyResult::Ok(l.unbind()) + }) + .transpose()?, + )?; + buckets.append(e)?; + } + out.set_item("buckets", buckets)?; + Ok(out.unbind()) +} + #[derive(FromPyObject)] enum PredicateArg { Expr(PyExpr), @@ -1339,6 +1400,51 @@ impl Table { }) } + /// Converge the table's LSM write path into its base table. + /// + /// Best-effort: with writes flowing, new rows may land after the last + /// pass. Errors if the table stops making progress. + pub fn checkpoint_lsm(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + inner.checkpoint_lsm().await.infer_error() + }) + } + + /// Seal every bucket's active memtable into L0. + pub fn flush_lsm(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py( + self_.py(), + async move { inner.flush_lsm().await.infer_error() }, + ) + } + + /// Trigger a background L0 → base pass per bucket. Returns once the + /// passes are dispatched, not once they finish — watch `get_lsm_stats`. + pub fn compact_lsm(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + inner.compact_lsm().await.infer_error() + }) + } + + /// Live LSM state, or `None` when the LSM write path is not enabled. + #[pyo3(signature = (include_generation_rows=false))] + pub fn get_lsm_stats( + self_: PyRef<'_, Self>, + include_generation_rows: bool, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let stats = inner + .get_lsm_stats(include_generation_rows) + .await + .infer_error()?; + Python::attach(|py| stats.map(|s| lsm_stats_to_py(py, &s)).transpose()) + }) + } + pub fn close_lsm_writers(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 96ea9ec95..c2137d0b5 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -100,7 +100,7 @@ anyhow = "1" lance-testing = { workspace = true } tempfile = "3.5.0" random_word = { version = "0.4.3", features = ["en"] } -tokio = { version = "1.23", features = ["io-util", "macros", "net", "rt-multi-thread", "sync"] } +tokio = { version = "1.23", features = ["io-util", "macros", "net", "rt-multi-thread", "sync", "test-util"] } uuid = { version = "1.7.0", features = ["v4"] } walkdir = "2" aws-sdk-dynamodb = { version = "1.55.0" } diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 388bed0f7..f3e872cbe 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -23,11 +23,13 @@ use crate::table::AddResult; use crate::table::BranchDiff; use crate::table::DeleteResult; use crate::table::DropColumnsResult; +use crate::table::LsmStats; use crate::table::LsmWriteSpec; use crate::table::MergeBranchResult; use crate::table::MergeResult; use crate::table::Tags; use crate::table::UpdateResult; +use crate::table::lsm_stats::GetLsmStatsResponse; use crate::table::merge::MergeFilter; use crate::table::query::create_multi_vector_plan; use crate::table::write_progress::FinishOnDrop; @@ -991,6 +993,18 @@ impl RemoteTable { } } + /// Send an LSM operator request with the transport retry layer **off**. + /// + /// Retry policy on these routes belongs to the checkpoint loop, which + /// reads the status and can tell contention from a lost claim. Leaving the + /// transport layer on would re-ask on its own schedule first, and surface + /// an `Error::Retry` whose status the loop would then have to unwrap. + async fn send_lsm_route(&self, request: RequestBuilder) -> Result<(String, reqwest::Response)> { + let (request_id, response) = self.send(request, false).await?; + let response = self.check_table_response(&request_id, response).await?; + Ok((request_id, response)) + } + /// Build a POST request and attach the read-freshness headers /// (`x-lancedb-min-version`, `x-lancedb-min-timestamp`). fn post_read(&self, uri: &str) -> RequestBuilder { @@ -2468,6 +2482,40 @@ impl BaseTable for RemoteTable { }) } + async fn flush_lsm(&self) -> Result<()> { + let request = self + .client + .post(&format!("/v1/table/{}/flush_lsm/", self.identifier)); + self.send_lsm_route(request).await?; + Ok(()) + } + + async fn compact_lsm(&self) -> Result<()> { + let request = self + .client + .post(&format!("/v1/table/{}/compact_lsm/", self.identifier)); + self.send_lsm_route(request).await?; + Ok(()) + } + + async fn get_lsm_stats(&self, include_generation_rows: bool) -> Result> { + // Read-semantics POST, like `get_lsm_write_spec`. + let request = self + .post_read(&format!("/v1/table/{}/get_lsm_stats/", self.identifier)) + .json(&serde_json::json!({ + "include_generation_rows": include_generation_rows, + })); + let (request_id, response) = self.send_lsm_route(request).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let parsed: GetLsmStatsResponse = serde_json::from_str(&body).map_err(|e| Error::Http { + source: format!("Failed to parse get_lsm_stats response: {e}").into(), + request_id, + status_code: None, + })?; + // `null` — and only — when the table has no LSM write path. + Ok(parsed.lsm_stats) + } + async fn set_lsm_write_spec(&self, spec: LsmWriteSpec) -> Result<()> { self.check_mutable().await?; @@ -6682,6 +6730,499 @@ mod tests { assert!(table.get_lsm_write_spec().await.unwrap().is_none()); } + /// Build a `get_lsm_stats` body for one bucket holding `generations`. + fn stats_body(generations: &[u64], compacting: bool) -> String { + serde_json::json!({ + "lsm_stats": { + "buckets": [{ + "shard_id": "b0", + "status": "Active", + "writer_epoch": 1, + "manifest_version": 1, + "current_generation": generations.iter().max().copied().unwrap_or(0) + 1, + "replay_after_wal_entry_position": 0, + "wal_entry_position_last_seen": 0, + "generations": generations.iter() + .map(|g| serde_json::json!({ "generation": g, "bytes": 1 })) + .collect::>(), + "compacting": compacting, + "memtables": [], + }], + } + }) + .to_string() + } + + /// `flush_lsm` / `compact_lsm` answer 202 with no body at all. + fn accepted() -> http::Response { + http::Response::builder() + .status(202) + .body(String::new()) + .unwrap() + } + + fn ok_json(body: String) -> http::Response { + http::Response::builder().status(200).body(body).unwrap() + } + + /// A flush landing in an empty L0 finishes on the opening stats read + /// alone. Asserting zero compacts is the point: "it returned Ok" is also + /// true of a loop that ran a pointless pass. + #[tokio::test(start_paused = true)] + async fn test_checkpoint_short_circuits_on_empty_l0() { + let compacts = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = compacts.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let path = request.url().path().to_string(); + if path.contains("compact_lsm") { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + panic!("an already-converged table must issue no compact calls"); + } + if path.contains("flush_lsm") { + return accepted(); + } + assert_eq!(path, "/v1/table/my_table/get_lsm_stats/"); + ok_json(stats_body(&[], false)) + }); + + table.checkpoint_lsm().await.unwrap(); + assert_eq!(compacts.load(std::sync::atomic::Ordering::SeqCst), 0); + } + + /// The loop triggers compaction until every generation that existed at + /// the start is gone, one bounded prefix per pass. + #[tokio::test(start_paused = true)] + async fn test_checkpoint_triggers_until_targets_are_drained() { + let compacts = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = compacts.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let path = request.url().path().to_string(); + if path.contains("flush_lsm") { + return accepted(); + } + if path.contains("compact_lsm") { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + return accepted(); + } + // Each pass drains the oldest generation. + let drained = seen.load(std::sync::atomic::Ordering::SeqCst); + let left: Vec = [1u64, 2, 3].into_iter().skip(drained).collect(); + ok_json(stats_body(&left, false)) + }); + + table.checkpoint_lsm().await.unwrap(); + assert_eq!( + compacts.load(std::sync::atomic::Ordering::SeqCst), + 3, + "one trigger per generation prefix, then stop" + ); + } + + /// Generations created *during* the checkpoint are not waited on, which + /// is what lets the loop terminate on a table taking writes where "L0 is + /// empty" never becomes true. + #[tokio::test(start_paused = true)] + async fn test_checkpoint_ignores_generations_created_while_it_runs() { + let compacts = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = compacts.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let path = request.url().path().to_string(); + if path.contains("flush_lsm") { + return accepted(); + } + if path.contains("compact_lsm") { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + return accepted(); + } + // Target is 5. One pass drains it; a writer keeps adding above. + let n = seen.load(std::sync::atomic::Ordering::SeqCst); + let body = if n == 0 { + stats_body(&[5], false) + } else { + stats_body(&[6, 7], false) + }; + ok_json(body) + }); + + table.checkpoint_lsm().await.unwrap(); + assert_eq!( + compacts.load(std::sync::atomic::Ordering::SeqCst), + 1, + "the loop must not chase generations written after it started" + ); + } + + /// Contention is a 429 and must be retried. The server keeps it off 503 + /// precisely so the client can act on the status alone — reading it as + /// terminal stops the checkpoint early on a healthy node. + #[tokio::test(start_paused = true)] + async fn test_checkpoint_retries_contention() { + let compacts = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = compacts.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let path = request.url().path().to_string(); + if path.contains("flush_lsm") { + return accepted(); + } + if path.contains("compact_lsm") { + // First two triggers: every bucket already latched. + if seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 2 { + return http::Response::builder() + .status(429) + .body(r#"{"code":21,"error":"Too many concurrent writes"}"#.to_string()) + .unwrap(); + } + return accepted(); + } + let accepted_triggers = seen + .load(std::sync::atomic::Ordering::SeqCst) + .saturating_sub(2); + let left: Vec = if accepted_triggers == 0 { + vec![1] + } else { + vec![] + }; + ok_json(stats_body(&left, false)) + }); + + table + .checkpoint_lsm() + .await + .expect("contention must not abort the checkpoint"); + assert_eq!( + compacts.load(std::sync::atomic::Ordering::SeqCst), + 3, + "assert the retry count, not just the outcome" + ); + } + + /// A transient fault on the poll must not abort the checkpoint. This route + /// meets the most contention — it runs every `POLL_INTERVAL` for the + /// checkpoint's whole life, with the transport retry layer disabled — yet + /// was the one call reached with a bare `?`. + #[tokio::test(start_paused = true)] + async fn test_checkpoint_retries_a_contended_stats_poll() { + let polls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = polls.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let path = request.url().path().to_string(); + if path.contains("flush_lsm") || path.contains("compact_lsm") { + return accepted(); + } + // The opening read lands; the next two polls are latched out. + let n = seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if (1..3).contains(&n) { + return http::Response::builder() + .status(429) + .body(r#"{"code":21,"error":"Too many concurrent writes"}"#.to_string()) + .unwrap(); + } + ok_json(stats_body(if n < 4 { &[1] } else { &[] }, false)) + }); + + table + .checkpoint_lsm() + .await + .expect("a contended poll must be retried, not surfaced"); + assert_eq!( + polls.load(std::sync::atomic::Ordering::SeqCst), + 5, + "the two rejected polls must be re-issued, not skipped" + ); + } + + /// Contention and a lost claim draw on separate budgets: five straight + /// 429s on `flush`, more than `MAX_REISSUES`, must still converge. On one + /// shared counter this spent the re-issue cap and then reported a lost + /// claim nothing had ever reported. + #[tokio::test(start_paused = true)] + async fn test_contention_does_not_exhaust_the_reissue_budget() { + let flushes = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = flushes.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let path = request.url().path().to_string(); + if path.contains("flush_lsm") { + if seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < 5 { + return http::Response::builder() + .status(429) + .body(r#"{"code":21,"error":"Too many concurrent writes"}"#.to_string()) + .unwrap(); + } + return accepted(); + } + if path.contains("compact_lsm") { + return accepted(); + } + ok_json(stats_body(&[], false)) + }); + + table + .checkpoint_lsm() + .await + .expect("contention must not be reported as a lost claim"); + assert_eq!( + flushes.load(std::sync::atomic::Ordering::SeqCst), + 6, + "five retries against one seal, then it lands" + ); + } + + /// An exhausted retry budget surfaces the fault that consumed it, not a + /// message the loop invented: "429, nine times" points an operator at a + /// saturated pool, a generic runtime error points them nowhere. + #[tokio::test(start_paused = true)] + async fn test_exhausted_retries_surface_the_underlying_fault() { + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = calls.clone(); + let table = Table::new_with_handler("my_table", move |_request| { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + http::Response::builder() + .status(429) + .body(r#"{"code":21,"error":"Too many concurrent writes"}"#.to_string()) + .unwrap() + }); + + let err = table.checkpoint_lsm().await.unwrap_err(); + assert!( + matches!(&err, Error::Http { status_code: Some(s), .. } if s.as_u16() == 429), + "the fault that spent the budget must be the one reported: {err:?}" + ); + assert_eq!( + calls.load(std::sync::atomic::Ordering::SeqCst), + 9, + "one call plus MAX_RETRIES — the re-issue budget is not spent on top" + ); + } + + /// A draining node is terminal, but the client does not know that from the + /// status: draining and a proxy blip are both 503, and telling them apart + /// takes parsing the body for a namespace code. So it spends the retry + /// budget and then reports what the server said — the drain gate never + /// releases, so the answer does not change, and the operator still reads + /// "WAL node draining" in the error. + #[tokio::test(start_paused = true)] + async fn test_draining_surfaces_after_the_retry_budget() { + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = calls.clone(); + let table = Table::new_with_handler("my_table", move |_request| { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + http::Response::builder() + .status(503) + .body(r#"{"code":19,"error":"WAL node draining"}"#.to_string()) + .unwrap() + }); + + let err = table.checkpoint_lsm().await.unwrap_err(); + let message = err.to_string(); + assert!( + matches!(&err, Error::Http { status_code: Some(s), .. } if s.as_u16() == 503), + "the 503 must surface as itself: {err:?}" + ); + assert!( + message.contains("WAL node draining"), + "the server's own diagnosis must survive to the caller: {message}" + ); + assert_eq!( + calls.load(std::sync::atomic::Ordering::SeqCst), + 9, + "one call plus MAX_RETRIES, then it reports rather than spinning" + ); + } + + /// A long stall with nothing compacting must keep waiting, not fail. The + /// client cannot judge this: a checkpoint queued behind unrelated tables + /// on the pod-wide compactor pool reports exactly these numbers — flat + /// generations, an idle latch — as one whose merges are failing. The + /// deadline is the caller's. + #[tokio::test(start_paused = true)] + async fn test_checkpoint_waits_out_a_long_stall_rather_than_failing() { + let polls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = polls.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let path = request.url().path().to_string(); + if path.contains("flush_lsm") || path.contains("compact_lsm") { + return accepted(); + } + // Flat for far longer than any bound this loop ever had, with + // `compacting: false` throughout — then it drains. + let n = seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + ok_json(stats_body(if n < 40 { &[1, 2] } else { &[] }, false)) + }); + + table + .checkpoint_lsm() + .await + .expect("a stall is the server being slow, not the client's call to make"); + assert!( + polls.load(std::sync::atomic::Ordering::SeqCst) > 40, + "the loop must have kept polling well past the old ten-poll bound" + ); + } + + /// A pass already owns the latch on every outstanding bucket, so the loop + /// waits rather than piling on triggers it would only refuse. This is the + /// sole thing `compacting` is read for. + #[tokio::test(start_paused = true)] + async fn test_checkpoint_waits_while_a_pass_is_running() { + let polls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let compacts = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen_polls = polls.clone(); + let seen_compacts = compacts.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let path = request.url().path().to_string(); + if path.contains("flush_lsm") { + return accepted(); + } + if path.contains("compact_lsm") { + seen_compacts.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + return accepted(); + } + // Latched for many polls, then done. + let n = seen_polls.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + ok_json(if n > 15 { + stats_body(&[], false) + } else { + stats_body(&[1], true) + }) + }); + + table + .checkpoint_lsm() + .await + .expect("a running pass is progress, not a stall"); + assert_eq!( + compacts.load(std::sync::atomic::Ordering::SeqCst), + 0, + "never trigger against a bucket already compacting" + ); + } + + /// WAL off ⇒ `None`; WAL on ⇒ a fully populated `Some` with no field + /// defaulting to a zero it did not measure. `include_generation_rows` + /// rides in the body and is off unless asked for. + #[tokio::test] + async fn test_get_lsm_stats_round_trip() { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/get_lsm_stats/"); + let body = request.body().unwrap().as_bytes().unwrap(); + let body: serde_json::Value = serde_json::from_slice(body).unwrap(); + assert_eq!( + body["include_generation_rows"], true, + "the flag must reach the server, not be silently dropped" + ); + let response = serde_json::json!({ + "lsm_stats": { + "buckets": [{ + "shard_id": "b0", + "status": "Active", + "writer_epoch": 3, + "manifest_version": 11, + "current_generation": 9, + "replay_after_wal_entry_position": 100, + "wal_entry_position_last_seen": 140, + "generations": [{ "generation": 8, "bytes": 4096, "rows": 30 }], + "compacting": false, + "memtables": [ + { "generation": 9, "rows": 12, "bytes": 900, "batches": 2, + "indexes": ["vec_idx"] } + ], + }], + } + }); + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + }); + + let stats = table + .get_lsm_stats(true) + .await + .unwrap() + .expect("a WAL-backed table reports Some"); + let bucket = &stats.buckets[0]; + assert_eq!(bucket.replay_after_wal_entry_position, 100); + assert_eq!(bucket.wal_entry_position_last_seen, 140); + assert!(!bucket.compacting); + assert_eq!(bucket.generations[0].generation, 8); + assert_eq!(bucket.generations[0].rows, Some(30)); + // The line that answers "why is my fresh-tier vector search + // brute-force" — an absent index name is the whole explanation. + let memtables = bucket.memtables.as_ref().unwrap(); + assert_eq!(memtables[0].indexes, vec!["vec_idx".to_string()]); + } + + /// A 404 arrives as `TableNotFound`, not as a lost claim the loop + /// re-issues from flush until its cap. The two are distinguished by + /// status: 404 is "no such table", 421 is "this node holds no claim". + /// They shared 404 once, and the loop chased a name that never existed. + #[tokio::test(start_paused = true)] + async fn test_missing_table_is_not_read_as_a_lost_claim() { + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = calls.clone(); + let table = Table::new_with_handler("my_table", move |_request| { + seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + http::Response::builder() + .status(404) + .body(r#"{"code":4,"error":"Not found: Table not found: my_table"}"#.to_string()) + .unwrap() + }); + + let err = table.checkpoint_lsm().await.unwrap_err(); + assert!( + matches!(err, Error::TableNotFound { .. }), + "a missing table must say so: {err:?}" + ); + assert_eq!( + calls.load(std::sync::atomic::Ordering::SeqCst), + 1, + "no point re-claiming a table that does not exist" + ); + } + + /// A lost claim — 421, not 404 — does re-issue from flush, the call that + /// re-claims and replays. + #[tokio::test(start_paused = true)] + async fn test_registry_miss_reissues_from_flush() { + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let seen = calls.clone(); + let table = Table::new_with_handler("my_table", move |request| { + let path = request.url().path().to_string(); + let n = seen.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if path.contains("flush_lsm") { + // First flush lands; the claim is then lost, and the + // re-issued flush succeeds. + return accepted(); + } + if path.contains("compact_lsm") { + if n < 4 { + return http::Response::builder() + .status(421) + .body(r#"{"code":19,"error":"table not claimed"}"#.to_string()) + .unwrap(); + } + return accepted(); + } + ok_json(stats_body(if n < 6 { &[1] } else { &[] }, false)) + }); + + table + .checkpoint_lsm() + .await + .expect("a lost claim must be recovered by re-flushing, not surfaced"); + } + + #[tokio::test] + async fn test_get_lsm_stats_absent_when_wal_off() { + let table = Table::new_with_handler("my_table", |_request| { + http::Response::builder() + .status(200) + .body(serde_json::json!({ "lsm_stats": null }).to_string()) + .unwrap() + }); + assert!(table.get_lsm_stats(false).await.unwrap().is_none()); + } + #[tokio::test] async fn test_wait_for_index() { let table = _make_table_with_indices(0); diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 0d8a8e8b9..74ab17921 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -68,10 +68,12 @@ use self::merge::MergeInsertBuilder; pub mod add_columns; mod add_data; pub mod branch_merge; +pub mod checkpoint; mod create_index; pub mod datafusion; pub(crate) mod dataset; pub mod delete; +pub mod lsm_stats; pub mod merge; pub mod optimize; mod primary_key; @@ -95,6 +97,7 @@ pub use lance::dataset::refs::{BranchContents, Ref, TagContents, Tags as LanceTa pub use lance::dataset::scanner::DatasetRecordBatchStream; use lance::dataset::statistics::DatasetStatisticsExt; pub use lance_index::optimize::OptimizeOptions; +pub use lsm_stats::{BucketStats, GenerationStats, LsmStats, MemtableStats}; pub use optimize::{CompactionOptions, OptimizeAction, OptimizeStats}; pub use schema_evolution::{ AddColumnsResult, AlterColumnsResult, DropColumnsResult, FieldMetadataUpdate, @@ -685,6 +688,31 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "get_lsm_write_spec is not supported on this table type".into(), }) } + /// Seal every bucket's active memtable into L0. + /// + /// The default implementation returns `NotSupported`. + async fn flush_lsm(&self) -> Result<()> { + Err(Error::NotSupported { + message: "flush_lsm is not supported on this table type".into(), + }) + } + /// Trigger a background L0 → base compaction pass per bucket. + /// + /// The default implementation returns `NotSupported`. + async fn compact_lsm(&self) -> Result<()> { + Err(Error::NotSupported { + message: "compact_lsm is not supported on this table type".into(), + }) + } + /// Read live LSM state, or `None` when the LSM write path is not + /// enabled for this table. + /// + /// The default implementation returns `NotSupported`. + async fn get_lsm_stats(&self, _include_generation_rows: bool) -> Result> { + Err(Error::NotSupported { + message: "get_lsm_stats is not supported on this table type".into(), + }) + } /// Drain and close any cached MemWAL shard writers for this table. /// /// The default implementation is a no-op; table types that maintain @@ -1726,6 +1754,85 @@ impl Table { self.inner.get_lsm_write_spec().await } + /// Converge this table's LSM write path into its base table. + /// + /// One `flush` to seal every memtable into L0, then compaction triggers + /// until every generation that existed at that moment has reached base. + /// The loop runs client-side, reading progress from `get_lsm_stats`, so + /// there is no held socket and nothing to reconcile if you drop this + /// future partway through. + /// + /// **Best-effort.** Generations created *after* the opening flush are + /// deliberately not waited on — that is what lets this terminate on a + /// table taking writes. Idempotent and safe on a cadence: an + /// already-converged table costs two round trips and triggers nothing. + /// + /// **No deadline, and the caller owns that.** It returns when the target + /// generations are gone, propagates a terminal server fault, and + /// otherwise waits however long the server takes. A slow table and a + /// stuck one are the same picture from here: the compactor pool is shared + /// across every table on the node, so a checkpoint queued behind + /// unrelated work is indistinguishable from one that is merging. Wrap + /// this in `tokio::time::timeout` for a wall-clock bound; abandoning it + /// partway costs nothing. + /// + /// # Example + /// + /// ```no_run + /// # use lancedb::Table; + /// # async fn example(table: &Table) -> Result<(), Box> { + /// let before = table.get_lsm_stats(false).await?; + /// table.checkpoint_lsm().await?; + /// let after = table.get_lsm_stats(false).await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn checkpoint_lsm(&self) -> Result<()> { + checkpoint::checkpoint_lsm(self).await + } + + /// Seal every bucket's active memtable into L0 without touching the + /// base table. + /// + /// Independently useful: flushing makes memtable rows readable from L0 at + /// a lower per-query cost. On a node that has not claimed this table it + /// claims it and replays the WAL log first — reporting "nothing to flush" + /// without replaying would lie about durable data. + pub async fn flush_lsm(&self) -> Result<()> { + self.inner.flush_lsm().await + } + + /// Run one bounded L0 → base compaction pass per bucket, reporting what + /// it merged and what is left. + /// + /// One pass, not convergence: that bounds each request's cost and gives a + /// caller driving its own cadence a progress signal per round trip. + pub async fn compact_lsm(&self) -> Result<()> { + self.inner.compact_lsm().await + } + + /// Read live per-bucket LSM state. + /// + /// Answers "how far behind is my fresh tier", "which bucket is hot", and + /// "why is my fresh-tier vector search brute-force". Mutates no table + /// state, though on a node that has not claimed this table it claims it, + /// exactly as a read would. + /// + /// `include_generation_rows` reports a row count per L0 generation. Off by + /// default: each count opens an uncached Lance dataset, and + /// `checkpoint_lsm` polls this needing only generation numbers. + /// + /// `Ok(None)` only when the LSM write path is not enabled, matching + /// [`Table::get_lsm_write_spec`]. Stats is fresh-tier only, so with the + /// WAL off there is no manifest to report and a struct of zeros would + /// read as measurements. + /// + /// Do not build a checkpoint's termination on this: the completion + /// predicate lives in the `flush` and `compact` responses. + pub async fn get_lsm_stats(&self, include_generation_rows: bool) -> Result> { + self.inner.get_lsm_stats(include_generation_rows).await + } + /// Drain and close any cached MemWAL shard writers held for this table. /// /// When an [`LsmWriteSpec`] is installed, `merge_insert` opens MemWAL shard diff --git a/rust/lancedb/src/table/checkpoint.rs b/rust/lancedb/src/table/checkpoint.rs new file mode 100644 index 000000000..bb76604ed --- /dev/null +++ b/rust/lancedb/src/table/checkpoint.rs @@ -0,0 +1,315 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Converging a table's LSM write path into its base table. +//! +//! `checkpoint_lsm` seals once, then triggers compaction and watches +//! generation numbers until the L0 that existed at the start is gone. +//! +//! The loop runs in the client, not the server: `compact_lsm` dispatches a +//! pass and returns, so nothing holds a socket and a client can vanish +//! mid-operation with nothing to reconcile. Completion is read from +//! generation numbers in the shard manifest — durable state, unlike a count +//! in a compact response, which a concurrent write invalidates. +//! +//! The target set is fixed at the start, so generations created *during* the +//! checkpoint are ignored. That is what lets it terminate under write load, +//! and what makes it best-effort: it converges the fresh tier as of some +//! instant. Idempotent, abandonable at any point, safe on a cadence. +//! +//! No liveness bound — the caller owns the deadline. The compactor pool is +//! shared pod-wide, so a checkpoint queued behind unrelated tables looks +//! exactly like one that is merging. + +use std::collections::HashMap; +use std::future::Future; +use std::time::Duration; + +use crate::{Error, Result, Table}; + +/// The HTTP status a failed request carried, if it carried one. +/// +/// `None` for anything with no retry story: a `TableNotFound` that +/// `check_table_response` already translated, or a connection failure that +/// never reached the server. Both are terminal. +fn status_of(e: &Error) -> Option { + #[cfg(feature = "remote")] + { + match e { + Error::Http { + status_code: Some(status), + .. + } => Some(status.as_u16()), + _ => None, + } + } + #[cfg(not(feature = "remote"))] + { + let _ = e; + None + } +} + +/// 429 (latch held, pool saturated, or the pod replaying its WAL) and 503 (a +/// draining node, or a proxy between here and it). +/// +/// The status is the whole signal: the server deliberately keeps contention +/// off 503, so a latch collision is a 429. A draining node *is* terminal, but +/// it is also a 503 that stays a 503, so retrying spends one budget and then +/// reports the server's own message — cheaper than parsing the body for the +/// namespace code it would take to tell the two apart. +fn is_retryable(e: &Error) -> bool { + matches!(status_of(e), Some(429 | 503)) +} + +/// 421: the owning node holds no claim. Only `flush` re-claims and replays, +/// so this cannot be retried in place — the caller has to start over. +fn is_lost_claim(e: &Error) -> bool { + status_of(e) == Some(421) +} + +/// Interval between `get_lsm_stats` polls. One interval is roughly one +/// compaction pass, the granularity at which the answer can change. +/// +/// Fixed rather than configurable, matching `wait_for_index`. It costs +/// nothing on an already-converged table and at most one interval of tail +/// latency after the final pass lands. +const POLL_INTERVAL: Duration = Duration::from_secs(5); + +/// Cap on re-issues from `flush` after a 421, so a crash-looping node cannot +/// turn flush → compact → 421 → flush into a spin. +/// +/// Deliberately not shared with [`MAX_RETRIES`]: a claim that keeps +/// evaporating is a broken node, while contention is routine and wants a real +/// budget. One shared counter let a merely contended table exhaust this cap +/// and then blame a claim it never lost. +const MAX_REISSUES: usize = 3; + +/// Retryable faults tolerated on a *single* request, reset on every success — +/// scattered contention across a long checkpoint must not accumulate toward a +/// cap. Roughly 16s of retrying against the backoff below. +const MAX_RETRIES: usize = 8; + +/// Backoff between retries, doubling up to [`RETRY_BACKOFF_MAX`]. Latch +/// contention clears in about the time one pass takes, so start small; a +/// saturated pool wants the ceiling. +const RETRY_BACKOFF_BASE: Duration = Duration::from_millis(100); +const RETRY_BACKOFF_MAX: Duration = Duration::from_secs(5); + +/// Sleep before re-issuing a retryable request. +async fn backoff(attempt: usize) { + let delay = RETRY_BACKOFF_BASE + .saturating_mul(1u32 << attempt.min(8) as u32) + .min(RETRY_BACKOFF_MAX); + tokio::time::sleep(delay).await; +} + +/// Whether the drain loop finished or needs the table re-claimed first. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum CheckpointOutcome { + Done, + ReissueFromFlush, +} + +/// What one LSM request produced: its value, or word that the owning node +/// holds no claim and only `flush` can get it back. +enum Attempt { + Ok(T), + ReissueFromFlush, +} + +/// Issue one LSM request, retrying in place while the fault is retryable. +/// +/// The two recoverable faults have separate budgets: contention clears on its +/// own and retries here against [`MAX_RETRIES`], while a 421 needs `flush` to +/// re-claim, which only the caller can drive. +/// +/// An exhausted budget propagates the last error *as itself* rather than a +/// synthesized one — "429 after nine tries" beats "checkpoint failed", and a +/// draining node arrives carrying the server's own message. +async fn issue(mut call: F) -> Result> +where + F: FnMut() -> Fut, + Fut: Future>, +{ + let mut retries = 0; + loop { + let e = match call().await { + Ok(value) => return Ok(Attempt::Ok(value)), + Err(e) => e, + }; + if is_lost_claim(&e) { + return Ok(Attempt::ReissueFromFlush); + } + if !is_retryable(&e) || retries >= MAX_RETRIES { + return Err(e); + } + backoff(retries).await; + retries += 1; + } +} + +/// Drive [`Table::checkpoint_lsm`]: seal once, fix the target watermark +/// from the resulting L0, then trigger and poll until it drains. +pub(crate) async fn checkpoint_lsm(table: &Table) -> Result<()> { + for reissue in 0..=MAX_REISSUES { + // The seal turns everything written before this call into a + // generation, so the watermark has to be read after it. Idempotent: + // sealing an empty memtable is a no-op, so a re-issue does not churn + // empty generations. + match issue(|| table.flush_lsm()).await? { + Attempt::Ok(()) => {} + Attempt::ReissueFromFlush => { + backoff(reissue).await; + continue; + } + } + + let stats = match issue(|| table.get_lsm_stats(false)).await? { + Attempt::Ok(stats) => stats, + Attempt::ReissueFromFlush => { + backoff(reissue).await; + continue; + } + }; + let Some(stats) = stats else { + // Not WAL-backed; `flush_lsm` would have errored first but for a race. + return Ok(()); + }; + let targets: HashMap = stats + .buckets + .iter() + .filter_map(|b| Some((b.shard_id.clone(), b.newest_generation()?))) + .collect(); + if targets.is_empty() { + return Ok(()); + } + + match drain_to_targets(table, &targets).await? { + CheckpointOutcome::Done => return Ok(()), + CheckpointOutcome::ReissueFromFlush => { + backoff(reissue).await; + continue; + } + } + } + Err(Error::Runtime { + message: "checkpoint_lsm: the owning node kept losing its claim; \ + re-issued from flush the maximum number of times" + .into(), + }) +} + +/// Trigger and poll until no bucket holds a generation at or below its +/// target. +/// +/// No liveness bound, deliberately. The pod-wide compactor pool (a semaphore +/// of 2 by default, shared across every table on the node) is taken *inside* +/// the pass, after the bucket latch, so a checkpoint queued behind unrelated +/// tables is indistinguishable from one that is merging. An idle-poll counter +/// here could only ever have fired on a table that would have finished. +async fn drain_to_targets( + table: &Table, + targets: &HashMap, +) -> Result { + loop { + let stats = match issue(|| table.get_lsm_stats(false)).await? { + Attempt::Ok(stats) => stats, + Attempt::ReissueFromFlush => return Ok(CheckpointOutcome::ReissueFromFlush), + }; + let Some(stats) = stats else { + return Ok(CheckpointOutcome::Done); + }; + // `compacting` is the bucket's compaction latch, held from dispatch + // until the pass ends — including while it waits on the pod-wide + // permit. So it answers one question only: do not pile on. Buckets + // with nothing outstanding are skipped, not counted as idle. + let mut outstanding = 0; + let mut all_compacting = true; + for b in &stats.buckets { + let Some(target) = targets.get(&b.shard_id) else { + continue; + }; + let n = b.outstanding_generations(*target); + if n > 0 { + outstanding += n; + all_compacting &= b.compacting; + } + } + if outstanding == 0 { + return Ok(CheckpointOutcome::Done); + } + + if !all_compacting { + match table.compact_lsm().await { + Ok(()) => {} + Err(e) if is_lost_claim(&e) => return Ok(CheckpointOutcome::ReissueFromFlush), + Err(e) if !is_retryable(&e) => return Err(e), + // A 429 here means the server could latch no bucket at all, + // which the poll above already handles. Not retried in place: + // the latch it would contend for is the one doing the work, so + // fall through and re-read — `POLL_INTERVAL` is the backoff. + Err(_) => {} + } + } + tokio::time::sleep(POLL_INTERVAL).await; + } +} + +#[cfg(all(test, feature = "remote"))] +mod tests { + use super::*; + + fn http(status: u16) -> Error { + Error::Http { + source: "server said no".into(), + request_id: "rid".into(), + status_code: reqwest::StatusCode::from_u16(status).ok(), + } + } + + /// Every status the loop acts on. The two predicates are checked together + /// because their overlap is what would be wrong: a status must never be + /// both, and 421 in particular must not read as retryable — retrying it in + /// place re-issues the call that just said the node holds no claim. + #[test] + fn taxonomy_round_trips() { + for status in [429, 503] { + assert!(is_retryable(&http(status)), "{status} must retry"); + assert!( + !is_lost_claim(&http(status)), + "{status} is not a lost claim" + ); + } + assert!(is_lost_claim(&http(421)), "a lost claim must re-claim"); + assert!( + !is_retryable(&http(421)), + "retrying a lost claim in place only asks the same node again" + ); + for status in [400, 404, 409, 500] { + assert!(!is_retryable(&http(status)), "{status} is terminal"); + assert!(!is_lost_claim(&http(status)), "{status} is terminal"); + } + } + + /// An error carrying no status has no retry story and must be terminal — + /// a connection that never reached the server, or a `TableNotFound` that + /// `check_table_response` translated before the loop saw it. + #[test] + fn errors_without_a_status_are_terminal() { + let no_status = Error::Http { + source: "connection reset".into(), + request_id: "rid".into(), + status_code: None, + }; + assert!(!is_retryable(&no_status)); + assert!(!is_lost_claim(&no_status)); + + let translated = Error::TableNotFound { + name: "t".into(), + source: "gone".into(), + }; + assert!(!is_retryable(&translated)); + assert!(!is_lost_claim(&translated)); + } +} diff --git a/rust/lancedb/src/table/lsm_stats.rs b/rust/lancedb/src/table/lsm_stats.rs new file mode 100644 index 000000000..953aea90f --- /dev/null +++ b/rust/lancedb/src/table/lsm_stats.rs @@ -0,0 +1,162 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Live per-bucket LSM state — the shape [`crate::Table::get_lsm_stats`] +//! returns and [`super::checkpoint`] polls. +//! +//! Nothing here is derived: sums and differences (total L0 bytes, WAL lag) +//! are the caller's to compute. There is no "WAL is off" shape — that case is +//! `None`, because a struct of zeros would read as measurements. + +use serde::Deserialize; + +/// One flushed L0 generation. +#[derive(Debug, Clone, Deserialize)] +pub struct GenerationStats { + pub generation: u64, + pub bytes: u64, + /// Present only when `include_generation_rows` was requested. Off by + /// default because each count opens an uncached Lance dataset, and the + /// checkpoint loop polls this route needing only generation numbers. + #[serde(default)] + pub rows: Option, +} + +/// One in-memory memtable. +#[derive(Debug, Clone, Deserialize)] +pub struct MemtableStats { + pub generation: u64, + pub rows: u64, + pub bytes: u64, + pub batches: u64, + /// Names of the indexes this memtable carries. An absent name is the whole + /// answer to "why is my fresh-tier search on that column brute-force". + pub indexes: Vec, +} + +/// Live state of one bucket. A table is N buckets on one node; flattening to +/// a single number hides the one hot bucket that is usually why someone +/// opened this endpoint. +#[derive(Debug, Clone, Deserialize)] +pub struct BucketStats { + pub shard_id: String, + /// `Active` | `Sealed` (drop-table 2PC in flight). + pub status: String, + pub writer_epoch: u64, + pub manifest_version: u64, + pub current_generation: u64, + pub replay_after_wal_entry_position: u64, + pub wal_entry_position_last_seen: u64, + pub generations: Vec, + /// Whether a pass owns this bucket's compaction latch right now. Says *a* + /// driver is running, not *whose*, and the latch is held from dispatch — + /// including while the pass queues for a pod-wide compactor permit. Read + /// it as "do not pile on", never as "mine is progressing". + pub compacting: bool, + /// Oldest first, active last. Absent for a `Sealed` bucket, whose + /// in-memory state is torn down. + #[serde(default)] + pub memtables: Option>, +} + +impl BucketStats { + /// The newest flushed generation, or `None` when L0 is empty. + pub(crate) fn newest_generation(&self) -> Option { + self.generations.iter().map(|g| g.generation).max() + } + + /// How many generations at or below `target` are still in L0. + /// + /// A count, not a boolean: one pass drains a bounded prefix rather than + /// the whole target set, so a boolean would read as "no progress" for + /// every pass but the last. Compaction drains oldest-first, so this + /// decreases monotonically. + pub(crate) fn outstanding_generations(&self, target: u64) -> usize { + self.generations + .iter() + .filter(|g| g.generation <= target) + .count() + } +} + +/// Live LSM state, one entry per bucket. +#[derive(Debug, Clone, Deserialize)] +pub struct LsmStats { + pub buckets: Vec, +} + +/// Server-side JSON envelope for `get_lsm_stats`. `lsm_stats` is null when +/// the table has no LSM write path. +#[derive(Debug, Deserialize)] +pub(crate) struct GetLsmStatsResponse { + #[serde(default)] + pub lsm_stats: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + + fn bucket(shard: &str, generations: &[u64], compacting: bool) -> BucketStats { + BucketStats { + shard_id: shard.into(), + status: "Active".into(), + writer_epoch: 1, + manifest_version: 1, + current_generation: generations.iter().max().copied().unwrap_or(0) + 1, + replay_after_wal_entry_position: 0, + wal_entry_position_last_seen: 0, + generations: generations + .iter() + .map(|g| GenerationStats { + generation: *g, + bytes: 1, + rows: None, + }) + .collect(), + compacting, + memtables: None, + } + } + + /// The target watermark is the newest generation at the start, and a + /// generation created after it must not hold the loop open — that is why + /// the predicate terminates under write load. + #[test] + fn newer_generations_do_not_extend_the_target() { + let start = bucket("b0", &[7, 8], false); + let target = start.newest_generation().expect("L0 is non-empty"); + assert_eq!(target, 8); + + // Compaction drained 7 and 8; 9 and 10 arrived while it ran. + let later = bucket("b0", &[9, 10], false); + assert_eq!( + later.outstanding_generations(target), + 0, + "generations above the target are somebody else's problem" + ); + + // Still holding 8 means still outstanding. + assert_eq!( + bucket("b0", &[8, 9], false).outstanding_generations(target), + 1 + ); + } + + /// The metric counts generations, not buckets: a pass drains a bounded + /// prefix, so one bucket going 3 → 2 → 1 → 0 is three steps. + #[test] + fn progress_is_measured_in_generations() { + let target = 3; + let counts: Vec = [&[1u64, 2, 3][..], &[2, 3][..], &[3][..], &[][..]] + .iter() + .map(|gens| bucket("b0", gens, false).outstanding_generations(target)) + .collect(); + assert_eq!(counts, vec![3, 2, 1, 0]); + } + + #[test] + fn empty_l0_has_no_target() { + assert!(bucket("b0", &[], false).newest_generation().is_none()); + } +} From be290447d9fa156f17d3c1eea028bb532645f2f0 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Fri, 7 Aug 2026 11:54:32 -0700 Subject: [PATCH 018/206] chore: update lance dependency to v11.0.0-beta.3 (#3896) Updates the Rust workspace Lance dependencies and Java lance-core dependency to v11.0.0-beta.3. No compatibility fixes were required; all-features clippy and Rust formatting pass. Triggering tag: https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.3 --- Cargo.lock | 86 ++++++++++++++++++++++++++-------------------------- Cargo.toml | 28 ++++++++--------- java/pom.xml | 2 +- 3 files changed, 58 insertions(+), 58 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 93e16c06d..f6186672c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arc-swap", "arrow", @@ -4890,8 +4890,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow-array", "arrow-buffer", @@ -4913,7 +4913,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow-array", "arrow-buffer", @@ -4927,7 +4927,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow-array", "arrow-schema", @@ -4936,8 +4936,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrayref", "crunchy", @@ -4947,8 +4947,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow-array", "arrow-buffer", @@ -4988,8 +4988,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow", "arrow-array", @@ -5019,8 +5019,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow", "arrow-array", @@ -5037,8 +5037,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "proc-macro2", "quote", @@ -5047,8 +5047,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow-arith", "arrow-array", @@ -5082,8 +5082,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow-arith", "arrow-array", @@ -5114,8 +5114,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arc-swap", "arrow", @@ -5182,8 +5182,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow-array", "arrow-schema", @@ -5205,8 +5205,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow", "arrow-array", @@ -5242,8 +5242,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow-array", "arrow-buffer", @@ -5259,8 +5259,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow", "async-trait", @@ -5272,8 +5272,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow", "arrow-ipc", @@ -5303,7 +5303,6 @@ dependencies = [ "serde", "serde_json", "sha2 0.10.9", - "time", "tokio", "tower", "tower-http 0.5.2", @@ -5327,8 +5326,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow-array", "arrow-buffer", @@ -5343,8 +5342,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow", "arrow-array", @@ -5354,6 +5353,7 @@ dependencies = [ "async-trait", "aws-credential-types", "aws-sdk-dynamodb", + "blake3", "byteorder", "bytes", "chrono", @@ -5383,8 +5383,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "arrow-array", "arrow-schema", @@ -5397,8 +5397,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.2#35da5d920159b49d1b53032652f7615ab699c160" +version = "11.0.0-beta.3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 78474cd16..936660d78 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.2", default-features = false, "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.2", default-features = false, "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.2", default-features = false, "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.2", "tag" = "v11.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.3", default-features = false, "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.3", default-features = false, "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.3", default-features = false, "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } ahash = "0.8" # Note that this one does not include pyarrow arrow = { version = "58.0.0", optional = false } diff --git a/java/pom.xml b/java/pom.xml index e8f030b27..e1c39c3e2 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.2 + 11.0.0-beta.3 false 2.30.0 1.7 From 706a9c327fb324e7961620cf1e159fe8c15f7fab Mon Sep 17 00:00:00 2001 From: Dan Rammer Date: Fri, 7 Aug 2026 14:50:22 -0500 Subject: [PATCH 019/206] feat: infer maintained indexes when an LsmWriteSpec omits them (#3748) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What `LsmWriteSpec::maintained_indexes` becomes `Option>`: | value | meaning | |---|---| | `None` (new default) | every index the MemWAL supports, resolved when the spec is installed | | `Some([])` | maintain nothing — a scan/filter-only WAL table | | `Some([..])` | exactly these, taken verbatim | `with_maintained_indexes` keeps its signature; `with_no_maintained_indexes()` is new. Surfaced through the remote path (null on the wire), Python, and Node. ## Why Callers had to state the maintained set by hand every time, which is both tedious and easy to get wrong — the common case is "maintain what I already built." Resolution filters on `IndexConfig::is_memwal_maintainable`, delegating to lance's `is_maintainable_index_type`. This is load-bearing rather than cosmetic: lance does **not** skip an index type its memtable cannot build, it errors when the shard writer opens, so sweeping up a bitmap index would fail every memtable claim and leave the table unwritable. The inferred set excludes those, and an explicit list naming one is now rejected at spec time instead of at claim time. ## Behavior change A freshly constructed spec used to maintain **nothing**; it now maintains **everything supported**. This flipped because napi collapses `undefined` and `null` to `None`, so TypeScript cannot express "absent means nothing, null means all" — any other choice makes the bindings disagree with the wire. The error direction also favors it: an unwanted maintained index costs memory, while a silently unmaintained one degrades FTS to an unscored scan. Three existing tests encoded the old default and are updated rather than worked around. ## Caveat The resolved set is a snapshot, not a subscription. An index created after the spec is installed is not maintained until the spec is unset and set again. `get_lsm_write_spec` therefore always reports a concrete list — `None` never round-trips. ## Dependency Needs a lance release carrying `is_maintainable_index_type` (lance-format/lance#8095) before this builds against the pinned tag. Draft until then. ## Testing 38 Rust LSM tests and 10 Python tests pass against a local lance build, including new coverage that a bitmap index is excluded from inference and rejected when named, and that `[]` stays distinguishable from null on the wire. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5 (1M context) --- docs/src/js/classes/Table.md | 12 +- docs/src/js/interfaces/LsmWriteSpec.md | 4 +- nodejs/lancedb/table.ts | 18 +- nodejs/src/table.rs | 12 +- python/python/lancedb/_lancedb.pyi | 11 +- python/python/lancedb/table.py | 13 +- python/python/tests/test_lsm_write_spec.py | 15 +- python/python/tests/test_merge_insert_lsm.py | 4 +- python/src/table.rs | 46 +++-- rust/lancedb/src/remote/table.rs | 30 ++- rust/lancedb/src/table.rs | 202 +++++++++++++++---- rust/lancedb/src/table/merge.rs | 4 +- rust/lancedb/src/table/merge/lsm.rs | 82 +++++++- 13 files changed, 360 insertions(+), 93 deletions(-) diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 11fca32d0..3fa3b08db 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -431,9 +431,10 @@ Read the [LsmWriteSpec](../interfaces/LsmWriteSpec.md) currently installed on th Resolves to `undefined` when the MemWAL LSM write path is not enabled (no spec has been set, or it was removed with [Table#unsetLsmWriteSpec](Table.md#unsetlsmwritespec)). -The returned spec — including its `maintainedIndexes` and -`writerConfigDefaults` — mirrors what was passed to -[Table#setLsmWriteSpec](Table.md#setlsmwritespec). +The returned spec mirrors what was passed to +[Table#setLsmWriteSpec](Table.md#setlsmwritespec), except that `maintainedIndexes` always +reports the concrete list resolved when the spec was set — `undefined` +never round-trips. #### Returns @@ -806,6 +807,11 @@ All variants require the table to have an unenforced primary key ([Table#setUnenforcedPrimaryKey](Table.md#setunenforcedprimarykey)); bucket sharding additionally requires it to be the single column being bucketed. +Omitting `maintainedIndexes` maintains every index on the table, resolved +here, failing if one cannot be maintained — name them to install anyway. +Naming them pins an exact set, and a still-building index is rejected +rather than quietly omitted. + #### Parameters * **spec**: [`LsmWriteSpec`](../interfaces/LsmWriteSpec.md) diff --git a/docs/src/js/interfaces/LsmWriteSpec.md b/docs/src/js/interfaces/LsmWriteSpec.md index 8a588df6a..f2ae91186 100644 --- a/docs/src/js/interfaces/LsmWriteSpec.md +++ b/docs/src/js/interfaces/LsmWriteSpec.md @@ -34,7 +34,9 @@ Bucket and identity variants: the sharding column. optional maintainedIndexes: string[]; ``` -Names of indexes the MemWAL should keep up to date during writes. +Indexes the MemWAL keeps up to date. Omit to maintain every supported +index, resolved on install — a snapshot, so indexes created later are not +maintained. Pass `[]` for none. *** diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 3359a2643..04705475b 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -197,7 +197,11 @@ export interface LsmWriteSpec { column?: string; /** Bucket variant: the number of buckets, in `[1, 1024]`. */ numBuckets?: number; - /** Names of indexes the MemWAL should keep up to date during writes. */ + /** + * Indexes the MemWAL keeps up to date. Omit to maintain every supported + * index, resolved on install — a snapshot, so indexes created later are not + * maintained. Pass `[]` for none. + */ maintainedIndexes?: string[]; /** Default `ShardWriter` configuration recorded in the MemWAL index. */ writerConfigDefaults?: Record; @@ -595,6 +599,11 @@ export abstract class Table { * All variants require the table to have an unenforced primary key * ({@link Table#setUnenforcedPrimaryKey}); bucket sharding additionally * requires it to be the single column being bucketed. + * + * Omitting `maintainedIndexes` maintains every index on the table, resolved + * here, failing if one cannot be maintained — name them to install anyway. + * Naming them pins an exact set, and a still-building index is rejected + * rather than quietly omitted. * @param {LsmWriteSpec} spec The sharding spec to install. * @returns {Promise} * @example @@ -622,9 +631,10 @@ export abstract class Table { * * Resolves to `undefined` when the MemWAL LSM write path is not enabled (no * spec has been set, or it was removed with {@link Table#unsetLsmWriteSpec}). - * The returned spec — including its `maintainedIndexes` and - * `writerConfigDefaults` — mirrors what was passed to - * {@link Table#setLsmWriteSpec}. + * The returned spec mirrors what was passed to + * {@link Table#setLsmWriteSpec}, except that `maintainedIndexes` always + * reports the concrete list resolved when the spec was set — `undefined` + * never round-trips. * @returns {Promise} */ abstract getLsmWriteSpec(): Promise; diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 2ac2fecb2..d26a44845 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -772,7 +772,8 @@ pub struct LsmWriteSpec { pub column: Option, /// Bucket variant: the number of buckets, in `[1, 1024]`. pub num_buckets: Option, - /// Names of indexes the MemWAL should keep up to date during writes. + /// Indexes the MemWAL keeps up to date. Omitted resolves every + /// maintainable index on install; an empty array means none. pub maintained_indexes: Option>, /// Default `ShardWriter` configuration recorded in the MemWAL index. pub writer_config_defaults: Option>, @@ -782,7 +783,6 @@ impl TryFrom for lancedb::table::LsmWriteSpec { type Error = napi::Error; fn try_from(value: LsmWriteSpec) -> napi::Result { - let maintained = value.maintained_indexes.unwrap_or_default(); let writer_config_defaults = value.writer_config_defaults.unwrap_or_default(); let spec = match value.spec_type.as_str() { "bucket" => { @@ -809,7 +809,7 @@ impl TryFrom for lancedb::table::LsmWriteSpec { } }; Ok(spec - .with_maintained_indexes(maintained) + .with_maintained_indexes(value.maintained_indexes) .with_writer_config_defaults(writer_config_defaults)) } } @@ -827,7 +827,7 @@ impl From for LsmWriteSpec { spec_type: "bucket".to_string(), column: Some(column), num_buckets: Some(num_buckets), - maintained_indexes: Some(maintained_indexes), + maintained_indexes, writer_config_defaults: Some(writer_config_defaults), }, Native::Identity { @@ -838,7 +838,7 @@ impl From for LsmWriteSpec { spec_type: "identity".to_string(), column: Some(column), num_buckets: None, - maintained_indexes: Some(maintained_indexes), + maintained_indexes, writer_config_defaults: Some(writer_config_defaults), }, Native::Unsharded { @@ -848,7 +848,7 @@ impl From for LsmWriteSpec { spec_type: "unsharded".to_string(), column: None, num_buckets: None, - maintained_indexes: Some(maintained_indexes), + maintained_indexes, writer_config_defaults: Some(writer_config_defaults), }, } diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index fad2744d3..f87fd3d13 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -653,9 +653,10 @@ class LsmWriteSpec: def identity(column: str) -> "LsmWriteSpec": ... @staticmethod def unsharded() -> "LsmWriteSpec": ... - def with_maintained_indexes(self, indexes: List[str]) -> "LsmWriteSpec": - """Return a copy of this spec asking the MemWAL to keep the named - indexes up to date as rows are appended.""" + def with_maintained_indexes(self, indexes: Optional[List[str]]) -> "LsmWriteSpec": + """Set which indexes the MemWAL keeps up to date. None resolves every + index on the table at install, failing if one cannot be maintained; + a list is verbatim, empty means none.""" ... def with_writer_config_defaults(self, defaults: Dict[str, str]) -> "LsmWriteSpec": """Return a copy of this spec recording the given default @@ -670,7 +671,9 @@ class LsmWriteSpec: @property def num_buckets(self) -> Optional[int]: ... @property - def maintained_indexes(self) -> List[str]: ... + def maintained_indexes(self) -> Optional[List[str]]: + """Indexes the MemWAL keeps up to date, or None for every supported one.""" + ... @property def writer_config_defaults(self) -> Dict[str, str]: ... diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 0828f04dc..f0d7dc8c8 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -4676,6 +4676,13 @@ class AsyncTable: via [`set_unenforced_primary_key`]; bucket sharding additionally requires it to be the single column being bucketed. + By default the MemWAL maintains every index on the table, resolved + here — a snapshot, so an index created afterwards needs the spec unset + and set again. This fails if one cannot be maintained; name the set + with ``with_maintained_indexes`` to install anyway. That pins an exact + set (a still-building index is rejected, not omitted); ``[]`` maintains + none. + Parameters ---------- spec : LsmWriteSpec @@ -4702,9 +4709,9 @@ class AsyncTable: Returns ``None`` when the MemWAL LSM write path is not enabled (no spec has been set, or it was removed with `unset_lsm_write_spec`). - The returned spec — including its ``maintained_indexes`` and - ``writer_config_defaults`` — mirrors what was passed to - `set_lsm_write_spec`. + The returned spec mirrors what was passed to `set_lsm_write_spec`, + except that ``maintained_indexes`` always reports the concrete list + resolved when the spec was set — ``None`` never round-trips. """ return await self._inner.get_lsm_write_spec() diff --git a/python/python/tests/test_lsm_write_spec.py b/python/python/tests/test_lsm_write_spec.py index d38918f09..218793b89 100644 --- a/python/python/tests/test_lsm_write_spec.py +++ b/python/python/tests/test_lsm_write_spec.py @@ -83,7 +83,9 @@ def test_lsm_write_spec_repr(): assert s.spec_type == "bucket" assert s.column == "id" assert s.num_buckets == 4 - assert s.maintained_indexes == [] + # A fresh spec defers its maintained set to install time. + assert s.maintained_indexes is None + assert s.with_maintained_indexes([]).maintained_indexes == [] assert "bucket" in repr(s) assert "id" in repr(s) assert "4" in repr(s) @@ -169,18 +171,23 @@ def test_get_lsm_write_spec(tmp_path): table.unset_lsm_write_spec() assert table.get_lsm_write_spec() is None - # Identity round-trips (column recovered from the schema). + # Identity round-trips (column recovered from the schema). Leaving the + # maintained set to be inferred picks up the index on the table, so the + # spec reads back naming it rather than as "infer". table.set_lsm_write_spec(LsmWriteSpec.identity("id")) spec = table.get_lsm_write_spec() assert spec.spec_type == "identity" assert spec.column == "id" + assert spec.maintained_indexes == [idx_name] table.unset_lsm_write_spec() - # Unsharded round-trips (no routing column). - table.set_lsm_write_spec(LsmWriteSpec.unsharded()) + # Unsharded round-trips (no routing column). Opting out is distinct from + # the inferred default. + table.set_lsm_write_spec(LsmWriteSpec.unsharded().with_maintained_indexes([])) spec = table.get_lsm_write_spec() assert spec.spec_type == "unsharded" assert spec.column is None + assert spec.maintained_indexes == [] @pytest.mark.asyncio diff --git a/python/python/tests/test_merge_insert_lsm.py b/python/python/tests/test_merge_insert_lsm.py index 5674a05ab..e74c21589 100644 --- a/python/python/tests/test_merge_insert_lsm.py +++ b/python/python/tests/test_merge_insert_lsm.py @@ -544,7 +544,7 @@ def test_lsm_read_fts_unmaintained_index_errors(tmp_path): table.create_index("text", config=FTS()) # No maintained indexes: the active memtable FTS arm cannot serve un-compacted # docs, so the search would silently omit them — reject instead. - table.set_lsm_write_spec(LsmWriteSpec.unsharded()) + table.set_lsm_write_spec(LsmWriteSpec.unsharded().with_maintained_indexes([])) with pytest.raises(Exception, match="maintained"): table.search("fox", query_type="fts", fts_columns="text").to_arrow() @@ -631,7 +631,7 @@ def test_lsm_read_vector_unmaintained_index_errors(tmp_path): ) # Spec with NO maintained indexes: the base vector index's catch-up is untracked, # so the scanner rejects rather than risk dropping compacted-but-unindexed rows. - table.set_lsm_write_spec(LsmWriteSpec.unsharded()) + table.set_lsm_write_spec(LsmWriteSpec.unsharded().with_maintained_indexes([])) with pytest.raises(Exception, match="maintained"): table.search([1.0] * VECTOR_DIM).to_arrow() diff --git a/python/src/table.rs b/python/src/table.rs index 119388708..20a93556f 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -246,12 +246,22 @@ impl From for MergeResult { } } +/// Render for `__repr__`, so the default reads as Python's `None` rather than +/// Rust's `Some([..])`. +fn fmt_maintained(maintained: &Option>) -> String { + match maintained { + Some(names) => format!("{:?}", names), + None => "None".to_string(), + } +} + /// Specification selecting Lance's MemWAL LSM-style write path for /// `merge_insert`. /// /// Constructed via the `bucket(...)`, `identity(...)`, or `unsharded()` /// classmethods, then optionally chain `with_maintained_indexes(...)` and -/// `with_writer_config_defaults(...)`. +/// `with_writer_config_defaults(...)`. A fresh spec maintains every index the +/// MemWAL supports, resolved on install. #[pyclass(from_py_object)] #[derive(Clone, Debug)] pub struct LsmWriteSpec { @@ -291,11 +301,11 @@ impl LsmWriteSpec { } } - /// Replace the list of indexes the MemWAL should keep up to date as - /// rows are appended. Each name must reference an index that - /// already exists on the table at the time `set_lsm_write_spec` - /// is called. - pub fn with_maintained_indexes(&self, indexes: Vec) -> Self { + /// Set which indexes the MemWAL maintains. `None` (the default) + /// resolves every supported index on install; a list is verbatim, + /// and an empty list maintains nothing. + #[pyo3(signature = (indexes))] + pub fn with_maintained_indexes(&self, indexes: Option>) -> Self { Self { inner: self.inner.clone().with_maintained_indexes(indexes), } @@ -317,23 +327,29 @@ impl LsmWriteSpec { maintained_indexes, writer_config_defaults, } => format!( - "LsmWriteSpec.bucket(column={:?}, num_buckets={}, maintained_indexes={:?}, writer_config_defaults={:?})", - column, num_buckets, maintained_indexes, writer_config_defaults, + "LsmWriteSpec.bucket(column={:?}, num_buckets={}, maintained_indexes={}, writer_config_defaults={:?})", + column, + num_buckets, + fmt_maintained(maintained_indexes), + writer_config_defaults, ), lancedb::table::LsmWriteSpec::Identity { column, maintained_indexes, writer_config_defaults, } => format!( - "LsmWriteSpec.identity(column={:?}, maintained_indexes={:?}, writer_config_defaults={:?})", - column, maintained_indexes, writer_config_defaults, + "LsmWriteSpec.identity(column={:?}, maintained_indexes={}, writer_config_defaults={:?})", + column, + fmt_maintained(maintained_indexes), + writer_config_defaults, ), lancedb::table::LsmWriteSpec::Unsharded { maintained_indexes, writer_config_defaults, } => format!( - "LsmWriteSpec.unsharded(maintained_indexes={:?}, writer_config_defaults={:?})", - maintained_indexes, writer_config_defaults, + "LsmWriteSpec.unsharded(maintained_indexes={}, writer_config_defaults={:?})", + fmt_maintained(maintained_indexes), + writer_config_defaults, ), } } @@ -368,10 +384,10 @@ impl LsmWriteSpec { } } - /// Names of indexes the MemWAL should keep up to date during writes. + /// Indexes the MemWAL keeps up to date, or `None` for every supported one. #[getter] - pub fn maintained_indexes(&self) -> Vec { - self.inner.maintained_indexes().to_vec() + pub fn maintained_indexes(&self) -> Option> { + self.inner.maintained_indexes().map(<[String]>::to_vec) } /// Default `ShardWriter` configuration recorded by this spec. diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index f3e872cbe..0d843dd54 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2520,9 +2520,9 @@ impl BaseTable for RemoteTable { self.check_mutable().await?; // Map the spec onto the server's request DTO. `sharding` is internally - // tagged on `mode` to mirror sophon's `Sharding` enum; `maintained_indexes` - // and `writer_config_defaults` are sent verbatim (an empty list means "no - // maintained indexes", not "default to all"). + // tagged on `mode` to mirror sophon's `Sharding` enum. A null + // `maintained_indexes` asks the server to resolve every maintainable + // index at HEAD; a list is verbatim, an empty one meaning none. let sharding = match &spec { LsmWriteSpec::Bucket { column, @@ -6599,7 +6599,7 @@ mod tests { .unwrap() }); let spec = crate::table::LsmWriteSpec::unsharded() - .with_maintained_indexes(["id_idx"]) + .with_maintained_indexes(vec!["id_idx".to_string()]) .with_writer_config_defaults([("max_memtable_rows", "1000")]); table.set_lsm_write_spec(spec).await.unwrap(); } @@ -6618,7 +6618,8 @@ mod tests { body["sharding"], serde_json::json!({ "mode": "bucket", "column": "id", "num_buckets": 16 }) ); - assert_eq!(body["maintained_indexes"], serde_json::json!([])); + // An unpinned maintained set sends null: resolve server-side. + assert_eq!(body["maintained_indexes"], serde_json::Value::Null); http::Response::builder().status(200).body("{}").unwrap() }); table @@ -6627,6 +6628,23 @@ mod tests { .unwrap(); } + /// `[]` (none) must stay distinguishable on the wire from null (all). + #[tokio::test] + async fn test_set_lsm_write_spec_no_maintained_indexes() { + let table = Table::new_with_handler("my_table", |request| { + let body = request.body().unwrap().as_bytes().unwrap(); + let body: serde_json::Value = serde_json::from_slice(body).unwrap(); + assert_eq!(body["maintained_indexes"], serde_json::json!([])); + http::Response::builder().status(200).body("{}").unwrap() + }); + table + .set_lsm_write_spec( + crate::table::LsmWriteSpec::bucket("id", 16).with_maintained_indexes(Vec::new()), + ) + .await + .unwrap(); + } + #[tokio::test] async fn test_set_lsm_write_spec_identity() { let table = Table::new_with_handler("my_table", |request| { @@ -6701,7 +6719,7 @@ mod tests { } => { assert_eq!(column, "id"); assert_eq!(num_buckets, 4); - assert_eq!(maintained_indexes, vec!["id_idx".to_string()]); + assert_eq!(maintained_indexes, Some(vec!["id_idx".to_string()])); assert_eq!( writer_config_defaults .get("durable_write") diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 74ab17921..e23bb7c47 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -371,6 +371,8 @@ pub use self::merge::MergeResult; /// date) and [`LsmWriteSpec::with_writer_config_defaults`] (default /// `ShardWriter` configuration recorded in the MemWAL index). /// +/// A fresh spec maintains every index on the table, resolved on install. +/// /// Install a spec with [`Table::set_lsm_write_spec`] and remove it with /// [`Table::unset_lsm_write_spec`]. The actual `merge_insert` dispatch /// onto the MemWAL writer is a follow-up. @@ -385,9 +387,12 @@ pub enum LsmWriteSpec { Bucket { column: String, num_buckets: u32, - /// Names of indexes (already created on the table) that the - /// MemWAL should maintain in-memory as rows are appended. - maintained_indexes: Vec, + /// Indexes the MemWAL maintains in-memory as rows are appended. + /// + /// `None` means every index it can maintain, resolved on install — a + /// snapshot, so indexes created later need the spec unset and re-set. + /// `Some([])` maintains nothing. + maintained_indexes: Option>, /// Default `ShardWriter` configuration recorded in the MemWAL index. writer_config_defaults: HashMap, }, @@ -397,35 +402,41 @@ pub enum LsmWriteSpec { /// distinct value of `column` becomes its own shard. Identity { column: String, - /// Names of indexes (already created on the table) that the - /// MemWAL should maintain in-memory as rows are appended. - maintained_indexes: Vec, + /// Indexes the MemWAL maintains in-memory as rows are appended. + /// + /// `None` means every index it can maintain, resolved on install — a + /// snapshot, so indexes created later need the spec unset and re-set. + /// `Some([])` maintains nothing. + maintained_indexes: Option>, /// Default `ShardWriter` configuration recorded in the MemWAL index. writer_config_defaults: HashMap, }, /// No sharding — every `merge_insert` call writes to a single MemWAL shard. Unsharded { - /// Names of indexes (already created on the table) that the - /// MemWAL should maintain in-memory as rows are appended. - maintained_indexes: Vec, + /// Indexes the MemWAL maintains in-memory as rows are appended. + /// + /// `None` means every index it can maintain, resolved on install — a + /// snapshot, so indexes created later need the spec unset and re-set. + /// `Some([])` maintains nothing. + maintained_indexes: Option>, /// Default `ShardWriter` configuration recorded in the MemWAL index. writer_config_defaults: HashMap, }, } impl LsmWriteSpec { - /// Construct a hash-bucket sharding spec with no maintained indexes. + /// Construct a hash-bucket sharding spec maintaining every index on the table. pub fn bucket(column: impl Into, num_buckets: u32) -> Self { Self::Bucket { column: column.into(), num_buckets, - maintained_indexes: Vec::new(), + maintained_indexes: None, writer_config_defaults: HashMap::new(), } } /// Construct an identity-sharding spec (shard by the raw value of - /// `column`) with no maintained indexes. + /// `column`) maintaining every index on the table. /// /// `column` must be a deterministic function of the unenforced primary /// key: every row with a given primary key must always produce the same @@ -437,28 +448,37 @@ impl LsmWriteSpec { pub fn identity(column: impl Into) -> Self { Self::Identity { column: column.into(), - maintained_indexes: Vec::new(), + maintained_indexes: None, writer_config_defaults: HashMap::new(), } } - /// Construct an unsharded spec with no maintained indexes. + /// Construct an unsharded spec maintaining every index on the table. pub fn unsharded() -> Self { Self::Unsharded { - maintained_indexes: Vec::new(), + maintained_indexes: None, writer_config_defaults: HashMap::new(), } } - /// Replace the list of indexes the MemWAL should keep up to date as - /// rows are appended. Each name must reference an index that already - /// exists on the table at the time `set_lsm_write_spec` is called. - pub fn with_maintained_indexes(mut self, indexes: I) -> Self - where - I: IntoIterator, - S: Into, - { - let v: Vec = indexes.into_iter().map(Into::into).collect(); + /// Set which indexes the MemWAL maintains. + /// + /// `None` (the default) resolves to every index on the table at install, + /// failing if one cannot be maintained — name the set to install anyway. A + /// list is verbatim: each name must already exist and be maintainable, and + /// an empty list maintains nothing. + /// + /// ``` + /// # use lancedb::table::LsmWriteSpec; + /// // Every index the table has when the spec is installed: + /// LsmWriteSpec::unsharded().with_maintained_indexes(None); + /// // Exactly these: + /// LsmWriteSpec::unsharded().with_maintained_indexes(vec!["id_idx".to_string()]); + /// // None at all: + /// LsmWriteSpec::unsharded().with_maintained_indexes(Vec::new()); + /// ``` + pub fn with_maintained_indexes(mut self, indexes: impl Into>>) -> Self { + let indexes = indexes.into(); match &mut self { Self::Bucket { maintained_indexes, .. @@ -468,7 +488,7 @@ impl LsmWriteSpec { } | Self::Unsharded { maintained_indexes, .. - } => *maintained_indexes = v, + } => *maintained_indexes = indexes, } self } @@ -504,8 +524,9 @@ impl LsmWriteSpec { self } - /// Borrow the list of index names this spec asks MemWAL to maintain. - pub fn maintained_indexes(&self) -> &[String] { + /// Borrow the list of index names this spec asks MemWAL to maintain, or + /// `None` when it asks for every index on the table. + pub fn maintained_indexes(&self) -> Option<&[String]> { match self { Self::Bucket { maintained_indexes, .. @@ -515,7 +536,7 @@ impl LsmWriteSpec { } | Self::Unsharded { maintained_indexes, .. - } => maintained_indexes, + } => maintained_indexes.as_deref(), } } @@ -1713,7 +1734,7 @@ impl Table { /// # async fn example(table: &Table) -> Result<(), Box> { /// table /// .set_lsm_write_spec( - /// LsmWriteSpec::bucket("id", 16).with_maintained_indexes(["id_idx"]), + /// LsmWriteSpec::bucket("id", 16).with_maintained_indexes(vec!["id_idx".to_string()]), /// ) /// .await?; /// # Ok(()) @@ -1735,9 +1756,10 @@ impl Table { /// /// Returns `Ok(None)` when the MemWAL LSM write path is not enabled (no /// spec has been set, or it was removed with [`Table::unset_lsm_write_spec`]). - /// The returned spec — including its [`LsmWriteSpec::maintained_indexes`] and - /// [`LsmWriteSpec::writer_config_defaults`] — mirrors what was passed to - /// [`Table::set_lsm_write_spec`]. + /// The returned spec mirrors what was passed to + /// [`Table::set_lsm_write_spec`], except that + /// [`LsmWriteSpec::maintained_indexes`] always reports the concrete list + /// resolved when the spec was set — `None` never round-trips. /// /// # Example /// @@ -5065,7 +5087,7 @@ mod tests { // Bucket spec round-trips exactly, including the routing column (recovered // from its field id), maintained indexes, and writer config defaults. let spec = LsmWriteSpec::bucket("id", 4) - .with_maintained_indexes([idx_name]) + .with_maintained_indexes(vec![idx_name.clone()]) .with_writer_config_defaults([("durable_write", "false")]); table.set_lsm_write_spec(spec.clone()).await.unwrap(); assert_eq!(table.get_lsm_write_spec().await.unwrap(), Some(spec)); @@ -5075,15 +5097,125 @@ mod tests { assert_eq!(table.get_lsm_write_spec().await.unwrap(), None); // Identity sharding round-trips (column recovered from the schema). + // A spec left at its default maintains every index on the table, so it + // reads back naming the one on the table rather than as "infer". let spec = LsmWriteSpec::identity("region"); table.set_lsm_write_spec(spec.clone()).await.unwrap(); - assert_eq!(table.get_lsm_write_spec().await.unwrap(), Some(spec)); + assert_eq!( + table.get_lsm_write_spec().await.unwrap(), + Some(spec.with_maintained_indexes(vec![idx_name.clone()])) + ); table.unset_lsm_write_spec().await.unwrap(); // Unsharded round-trips (no routing column). let spec = LsmWriteSpec::unsharded(); table.set_lsm_write_spec(spec.clone()).await.unwrap(); - assert_eq!(table.get_lsm_write_spec().await.unwrap(), Some(spec)); + assert_eq!( + table.get_lsm_write_spec().await.unwrap(), + Some(spec.with_maintained_indexes(vec![idx_name])) + ); + } + + /// The maintained set defaults to every index on the table, resolved at + /// install. An index the memtable cannot build fails the install rather + /// than being dropped: maintaining it would take the table offline for + /// writes, dropping it would hide that from the caller. + #[tokio::test] + async fn test_set_lsm_write_spec_infers_maintained_indexes() { + let tmp_dir = tempdir().unwrap(); + let uri = tmp_dir.path().to_str().unwrap(); + + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("tag", DataType::Utf8, true), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(arrow_array::Int64Array::from(vec![1, 2, 3])), + Arc::new(StringArray::from(vec!["a", "b", "c"])), + ], + ) + .unwrap(); + let reader: Box = + Box::new(RecordBatchIterator::new(vec![Ok(batch)], schema.clone())); + let conn = ConnectBuilder::new(uri) + .read_consistency_interval(Duration::from_secs(0)) + .execute() + .await + .unwrap(); + let table = conn.create_table("t", reader).execute().await.unwrap(); + + table + .create_index(&["id"], Index::BTree(Default::default())) + .name("id_btree".to_string()) + .execute() + .await + .unwrap(); + table + .create_index(&["tag"], Index::Bitmap(Default::default())) + .name("tag_bitmap".to_string()) + .execute() + .await + .unwrap(); + + // Explicitly naming the bitmap index fails before anything commits. + let err = table + .set_lsm_write_spec( + LsmWriteSpec::unsharded().with_maintained_indexes(vec!["tag_bitmap".to_string()]), + ) + .await + .unwrap_err(); + assert!( + matches!(err, Error::InvalidInput { ref message } if message.contains("tag_bitmap")), + "expected the bitmap index to be rejected, got {err:?}" + ); + assert_eq!(table.get_lsm_write_spec().await.unwrap(), None); + + // The default covers every index, so the bitmap fails it too. + let err = table + .set_lsm_write_spec(LsmWriteSpec::unsharded()) + .await + .unwrap_err(); + assert!( + matches!(err, Error::InvalidInput { ref message } + if message.contains("tag_bitmap") && message.contains("maintained_indexes")), + "expected the inferred set to be rejected, got {err:?}" + ); + assert_eq!(table.get_lsm_write_spec().await.unwrap(), None); + + // Naming the maintainable subset installs. + table + .set_lsm_write_spec( + LsmWriteSpec::unsharded().with_maintained_indexes(vec!["id_btree".to_string()]), + ) + .await + .unwrap(); + assert_eq!( + table + .get_lsm_write_spec() + .await + .unwrap() + .unwrap() + .maintained_indexes(), + Some(["id_btree".to_string()].as_slice()) + ); + + // Opting out entirely is distinct from the default. + table.unset_lsm_write_spec().await.unwrap(); + table + .set_lsm_write_spec(LsmWriteSpec::unsharded().with_maintained_indexes(Vec::new())) + .await + .unwrap(); + assert_eq!( + table + .get_lsm_write_spec() + .await + .unwrap() + .unwrap() + .maintained_indexes(), + Some([].as_slice()) + ); } #[tokio::test] diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 82a1d1473..3a5b6882d 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -1161,7 +1161,7 @@ mod lsm_tests { .unwrap(); let fts_index = table.list_indices().await.unwrap()[0].name.clone(); table - .set_lsm_write_spec(LsmWriteSpec::unsharded().with_maintained_indexes([fts_index])) + .set_lsm_write_spec(LsmWriteSpec::unsharded().with_maintained_indexes(vec![fts_index])) .await .unwrap(); @@ -1254,7 +1254,7 @@ mod lsm_tests { .unwrap(); let vec_index = table.list_indices().await.unwrap()[0].name.clone(); table - .set_lsm_write_spec(LsmWriteSpec::unsharded().with_maintained_indexes([vec_index])) + .set_lsm_write_spec(LsmWriteSpec::unsharded().with_maintained_indexes(vec![vec_index])) .await .unwrap(); diff --git a/rust/lancedb/src/table/merge/lsm.rs b/rust/lancedb/src/table/merge/lsm.rs index 0eb7c0231..87c427b3c 100644 --- a/rust/lancedb/src/table/merge/lsm.rs +++ b/rust/lancedb/src/table/merge/lsm.rs @@ -29,6 +29,7 @@ use arrow_schema::{DataType, Schema as ArrowSchema, SchemaRef}; use lance::Dataset; use lance::dataset::mem_wal::{ DatasetMemWalExt, ShardWriter, ShardWriterConfig, evaluate_sharding_spec, + validate_maintained_indexes, }; use lance::index::DatasetIndexExt; use lance_core::datatypes::Schema as LanceSchema; @@ -37,8 +38,9 @@ use tokio::sync::RwLock; use uuid::Uuid; use crate::error::{Error, Result}; +use crate::index::IndexConfig; use crate::table::merge::{MergeInsertBuilder, MergeResult}; -use crate::table::{LsmWriteSpec, NativeTable}; +use crate::table::{BaseTable, LsmWriteSpec, NativeTable}; /// Spec id of the sole sharding spec installed by [`set_lsm_write_spec`]. /// Must match Lance's `InitializeMemWalBuilder` (`SHARDING_SPEC_ID`). @@ -80,32 +82,44 @@ pub(crate) async fn set_lsm_write_spec(table: &NativeTable, spec: LsmWriteSpec) } } + // Before the builder borrows the dataset clone. `list_indices` merges an + // index's segments into one entry, so the result needs no dedup. + let maintained_indexes = { + let dataset = table.dataset.get().await?; + resolve_maintained_indexes( + &dataset, + &table.list_indices().await?, + spec.maintained_indexes(), + ) + .await? + }; + let mut dataset = (*table.dataset.get().await?).clone(); let mut builder = dataset.initialize_mem_wal(); - let (maintained_indexes, writer_config_defaults) = match spec { + let writer_config_defaults = match spec { LsmWriteSpec::Bucket { column, num_buckets, - maintained_indexes, writer_config_defaults, + .. } => { builder = builder.bucket_sharding(column, num_buckets); - (maintained_indexes, writer_config_defaults) + writer_config_defaults } LsmWriteSpec::Identity { column, - maintained_indexes, writer_config_defaults, + .. } => { builder = builder.identity_sharding(column); - (maintained_indexes, writer_config_defaults) + writer_config_defaults } LsmWriteSpec::Unsharded { - maintained_indexes, writer_config_defaults, + .. } => { builder = builder.unsharded(); - (maintained_indexes, writer_config_defaults) + writer_config_defaults } }; builder = builder.maintained_indexes(maintained_indexes); @@ -117,6 +131,58 @@ pub(crate) async fn set_lsm_write_spec(table: &NativeTable, spec: LsmWriteSpec) Ok(()) } +/// Resolve a spec's maintained-index selection against `indices`, as reported +/// by [`Table::list_indices`](crate::Table::list_indices). +/// +/// `None` means every index on the table, snapshotted now. Lance validates +/// either selection against its shard-writer rules, so a spec that installs is +/// one the MemWAL can open. +/// +/// An unmaintainable index fails an inferred set rather than being dropped from +/// it — dropping would leave the caller believing it is maintained. +async fn resolve_maintained_indexes( + dataset: &Dataset, + indices: &[IndexConfig], + requested: Option<&[String]>, +) -> Result> { + let Some(requested) = requested else { + let all: Vec = indices.iter().map(|index| index.name.clone()).collect(); + validate_maintained_indexes(dataset, &all) + .await + .map_err(|source| Error::InvalidInput { + message: format!( + "cannot maintain every index on this table: {source}. Set \ + maintained_indexes explicitly to choose from {}", + index_name_list(indices), + ), + })?; + return Ok(all); + }; + for name in requested { + if !indices.iter().any(|index| &index.name == name) { + return Err(Error::InvalidInput { + message: format!( + "maintained index '{}' does not exist on this table; it has {}", + name, + index_name_list(indices), + ), + }); + } + } + validate_maintained_indexes(dataset, requested).await?; + Ok(requested.to_vec()) +} + +/// Index names for an error message. +fn index_name_list(indices: &[IndexConfig]) -> String { + if indices.is_empty() { + return "no indexes".to_string(); + } + let mut names: Vec<&str> = indices.iter().map(|index| index.name.as_str()).collect(); + names.sort_unstable(); + format!("[{}]", names.join(", ")) +} + // ============================================================================= // unset_lsm_write_spec // ============================================================================= From 5b347afd9925dfe9017feae5725a93230b123b30 Mon Sep 17 00:00:00 2001 From: Andrew Chen Date: Sat, 8 Aug 2026 05:05:45 +0800 Subject: [PATCH 020/206] fix: avoid AttributeError in JinaEmbeddings image input for str/Path (#3670) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## What `JinaEmbeddings._generate_image_input_dict()` crashes with `AttributeError: 'function' object has no attribute 'urlparse'` on any image given as a URL string, local path string, or `pathlib.Path` — i.e. every documented `jina-clip-v1` image-embedding use case except raw `bytes`. ## Why ```python from urllib.parse import urlparse ... parsed = urlparse.urlparse(image) ``` `urlparse` is imported as a function, then called as if it were the `urllib.parse` module (`urlparse.urlparse(...)`). The module-level `is_valid_url()` a few lines above does it correctly (`urlparse(text)`), which is why this reads as a typo rather than intentional. Fixed to `urlparse(str(image))` — `str()` is needed because `urlparse()` only accepts `str`/`bytes` and raises a different `AttributeError` on a raw `Path`. ## Testing Added `test_jina_generate_image_input_dict_local_path`, which fails with the original `AttributeError` before the fix and passes after, covering both a `str` path and a `pathlib.Path`. Verified locally (built the Rust extension, ran red→green, then the full `test_embeddings.py` file: 15 passed / 8 skipped, no regressions) and with `ruff check`/`ruff format`. --- Disclosure: this PR was drafted with AI assistance (Claude); I reviewed, tested, and take responsibility for the change. --------- Co-authored-by: Claude Opus 4.8 --- python/python/lancedb/embeddings/jinaai.py | 7 ++++--- python/python/tests/test_embeddings.py | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/python/python/lancedb/embeddings/jinaai.py b/python/python/lancedb/embeddings/jinaai.py index 9656f041f..f6ab601b3 100644 --- a/python/python/lancedb/embeddings/jinaai.py +++ b/python/python/lancedb/embeddings/jinaai.py @@ -87,12 +87,13 @@ class JinaEmbeddings(EmbeddingFunction): if isinstance(image, bytes): image_dict = {"image": base64.b64encode(image).decode("utf-8")} elif isinstance(image, (str, Path)): - parsed = urlparse.urlparse(image) - # TODO handle drive letter on windows. + parsed = urlparse(str(image)) PIL_Image = attempt_import_or_raise("PIL.Image", "pillow") if parsed.scheme == "file": pil_image = PIL_Image.open(parsed.path) - elif parsed.scheme == "": + elif parsed.scheme == "" or (os.name == "nt" and len(parsed.scheme) == 1): + # A Windows drive letter parses as a one-character scheme + # ("C:\\img.png" -> scheme="c"), so treat it as a local path. pil_image = PIL_Image.open(image if os.name == "nt" else parsed.path) elif parsed.scheme.startswith("http"): pil_image = PIL_Image.open(io.BytesIO(url_retrieve(image))) diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index 678270f19..9850669eb 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -631,3 +631,23 @@ def test_url_retrieve_downloads_image(): image_bytes = url_retrieve(image_url) img = Image.open(io.BytesIO(image_bytes)) assert img.size[0] > 0 and img.size[1] > 0 + + +def test_jina_generate_image_input_dict_local_path(tmp_path): + """ + JinaEmbeddings._generate_image_input_dict must accept a local image path + (str or Path), not just bytes. Previously it crashed with + `AttributeError: 'function' object has no attribute 'urlparse'` on any + str/Path input because it called `urlparse.urlparse(image)` instead of + `urlparse(image)` (urlparse was imported as a function, not a module). + """ + Image = pytest.importorskip("PIL.Image") + from lancedb.embeddings.jinaai import JinaEmbeddings + + image_path = tmp_path / "test.png" + Image.new("RGB", (4, 4), color="red").save(image_path, format="PNG") + + for image in (str(image_path), image_path): + image_dict = JinaEmbeddings._generate_image_input_dict(image) + assert "image" in image_dict + assert isinstance(image_dict["image"], str) and len(image_dict["image"]) > 0 From 7bb501839a18f5160bf858d6a10438630a7099ea Mon Sep 17 00:00:00 2001 From: Lance Release Date: Fri, 7 Aug 2026 21:15:20 +0000 Subject: [PATCH 021/206] =?UTF-8?q?Bump=20version:=200.37.1-beta.0=20?= =?UTF-8?q?=E2=86=92=200.37.1-beta.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package-lock.json | 4 ++-- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 601b14d3f..a015353cb 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.37.1-beta.0" +current_version = "0.37.1-beta.1" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index f6186672c..04ab7b099 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5411,7 +5411,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.37.1-beta.0" +version = "0.37.1-beta.1" dependencies = [ "ahash", "anyhow", @@ -5499,7 +5499,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.37.1-beta.0" +version = "0.37.1-beta.1" dependencies = [ "arrow-array", "arrow-buffer", @@ -5524,7 +5524,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.37.1-beta.0" +version = "0.37.1-beta.1" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 11e901ad0..091588922 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.37.1-beta.0 + 0.37.1-beta.1 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 3df2ac178..20f69e134 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.37.1-beta.0 + 0.37.1-beta.1 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index e1c39c3e2..f85b5c906 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.37.1-beta.0 + 0.37.1-beta.1 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 10e12edc8..48e5f5295 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.37.1-beta.0" +version = "0.37.1-beta.1" 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 3c93ed470..d3792f9c2 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.37.1-beta.0", + "version": "0.37.1-beta.1", "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 5ade5aaa3..44bc309ca 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.37.1-beta.0", + "version": "0.37.1-beta.1", "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 16bb0edd0..e78f0fe6a 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.37.1-beta.0", + "version": "0.37.1-beta.1", "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 6ee11e4bc..0e27c5f51 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.37.1-beta.0", + "version": "0.37.1-beta.1", "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 c2e15bb9f..7bd27ba18 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.37.1-beta.0", + "version": "0.37.1-beta.1", "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 d2820b1a1..5c76024b2 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.37.1-beta.0", + "version": "0.37.1-beta.1", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 601b51380..f8cc7d8e0 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.37.1-beta.0", + "version": "0.37.1-beta.1", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index bdbd3cf79..f7b6670e4 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lancedb/lancedb", - "version": "0.37.1-beta.0", + "version": "0.37.1-beta.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lancedb/lancedb", - "version": "0.37.1-beta.0", + "version": "0.37.1-beta.1", "cpu": [ "x64", "arm64" diff --git a/nodejs/package.json b/nodejs/package.json index 671f3f94d..0416ce81b 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.37.1-beta.0", + "version": "0.37.1-beta.1", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 5a196e27c..9d36edd5c 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.37.1-beta.0" +version = "0.37.1-beta.1" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index c2137d0b5..05251f59a 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.37.1-beta.0" +version = "0.37.1-beta.1" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 77a93fee76f091445450513dfa32252e3bda00fa Mon Sep 17 00:00:00 2001 From: Dan Tasse <105866+dantasse@users.noreply.github.com> Date: Fri, 7 Aug 2026 17:41:41 -0400 Subject: [PATCH 022/206] fix: get table size from metadata, not files (#3790) Some issues: - file_size_bytes is optional in the manifest, so if it's not there (old writer I guess) it'll under-report the table size. - it changes results a little bit from the old way by including per-file footers and metadata (probably not a big difference at real scale) --------- Co-authored-by: Will Jones --- Cargo.lock | 1 + docs/src/js/interfaces/TableStatistics.md | 5 +- nodejs/__test__/table.test.ts | 10 +- nodejs/src/table.rs | 5 +- python/python/lancedb/table.py | 4 +- python/python/tests/test_table.py | 10 +- rust/lancedb/Cargo.toml | 1 + rust/lancedb/src/table.rs | 228 +++++++++++++++++++++- 8 files changed, 253 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 04ab7b099..20f20a0ac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5480,6 +5480,7 @@ dependencies = [ "random_word", "regex", "reqwest 0.12.28", + "roaring", "rstest", "semver", "serde", diff --git a/docs/src/js/interfaces/TableStatistics.md b/docs/src/js/interfaces/TableStatistics.md index e19cba119..e2e8ef34d 100644 --- a/docs/src/js/interfaces/TableStatistics.md +++ b/docs/src/js/interfaces/TableStatistics.md @@ -44,4 +44,7 @@ The number of rows in the table totalBytes: number; ``` -The total number of bytes in the table +The total size, in bytes, of the table's data files, index files, and +overlay files + +Read from the manifest, so this excludes deletion files and manifests. diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 15d6e0804..d263d9cab 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -277,8 +277,16 @@ describe.each([arrow15, arrow16, arrow17, arrow18])( }, numIndices: 0, numRows: 3, - totalBytes: 44, + // Full on-disk size of the two data files, footers and metadata included. + totalBytes: 684, }); + + // Index files count toward totalBytes too (only deletion files and + // manifests are excluded). + await table.createIndex("id", { config: Index.btree() }); + const statsWithIndex = await table.stats(); + expect(statsWithIndex.numIndices).toBe(1); + expect(statsWithIndex.totalBytes).toBeGreaterThan(684); }); it("should overwrite data if asked", async () => { diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index d26a44845..c4ece20e2 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -1043,7 +1043,10 @@ impl From for IndexStatistics { #[napi(object)] pub struct TableStatistics { - /// The total number of bytes in the table + /// The total size, in bytes, of the table's data files, index files, and + /// overlay files + /// + /// Read from the manifest, so this excludes deletion files and manifests. pub total_bytes: i64, /// The number of rows in the table diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index f0d7dc8c8..c566fc532 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -6341,7 +6341,9 @@ class TableStatistics: Attributes ---------- total_bytes: int - The total number of bytes in the table. + The total size, in bytes, of the table's data files, index files, and + overlay files. Read from the manifest, so this excludes deletion files + and manifests. num_rows: int The total number of rows in the table. num_indices: int diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index eb6eaefaa..2a069c712 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -3713,7 +3713,8 @@ def test_stats(mem_db: DBConnection): stats = table.stats() print(f"{stats=}") assert stats == { - "total_bytes": 60, + # Full on-disk size of the data file, footer and metadata included. + "total_bytes": 633, "num_rows": 2, "num_indices": 0, "fragment_stats": { @@ -3731,6 +3732,13 @@ def test_stats(mem_db: DBConnection): }, } + # Index files count toward total_bytes too (only deletion files and + # manifests are excluded). + table.create_index("id", config=BTree()) + stats_with_index = table.stats() + assert stats_with_index["num_indices"] == 1 + assert stats_with_index["total_bytes"] > stats["total_bytes"] + def test_create_table_empty_list_with_schema(mem_db: DBConnection): """Test creating table with empty list data and schema diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 05251f59a..2dbd9d895 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -100,6 +100,7 @@ anyhow = "1" lance-testing = { workspace = true } tempfile = "3.5.0" random_word = { version = "0.4.3", features = ["en"] } +roaring = "0.11.4" tokio = { version = "1.23", features = ["io-util", "macros", "net", "rt-multi-thread", "sync", "test-util"] } uuid = { version = "1.7.0", features = ["v4"] } walkdir = "2" diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index e23bb7c47..5120c48b7 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -95,7 +95,6 @@ pub use delete::DeleteResult; use futures::future::join_all; pub use lance::dataset::refs::{BranchContents, Ref, TagContents, Tags as LanceTags}; pub use lance::dataset::scanner::DatasetRecordBatchStream; -use lance::dataset::statistics::DatasetStatisticsExt; pub use lance_index::optimize::OptimizeOptions; pub use lsm_stats::{BucketStats, GenerationStats, LsmStats, MemtableStats}; pub use optimize::{CompactionOptions, OptimizeAction, OptimizeStats}; @@ -3570,9 +3569,24 @@ impl BaseTable for NativeTable { let num_rows = self.count_rows(None).await?; let num_indices = self.list_indices().await?.len(); let ds = self.dataset.get().await?; - let ds_clone = (*ds).clone(); - let ds_stats = Arc::new(ds_clone).calculate_data_stats().await?; - let total_bytes = ds_stats.fields.iter().map(|f| f.bytes_on_disk).sum::() as usize; + // Sizes come from the manifest. Summing per-field `bytes_on_disk` instead + // would open every data file to read its column metadata, which costs one + // IO per fragment and reports 0 for legacy v1 storage. + // + // The manifest summary covers only the fragments' base data files, so + // overlay files (recorded on each fragment) and index files (recorded in + // the manifest's index section) are added separately. + let mut total_bytes = ds.manifest().summary().total_files_size as usize; + for frag in ds.manifest().fragments.iter() { + for overlay in &frag.overlays { + if let Some(size) = overlay.data_file.file_size_bytes.get() { + total_bytes += size.get() as usize; + } + } + } + for index in ds.load_indices().await?.iter() { + total_bytes += index.total_size_bytes().unwrap_or(0) as usize; + } let frags = ds.get_fragments(); let mut sorted_sizes = join_all( @@ -3644,7 +3658,12 @@ impl BaseTable for NativeTable { #[skip_serializing_none] #[derive(Debug, Deserialize, PartialEq)] pub struct TableStatistics { - /// The total number of bytes in the table + /// The total size, in bytes, of the table's data files, index files, and + /// overlay files + /// + /// Read from the manifest, so this excludes deletion files and manifests, + /// and it excludes any file whose size the manifest does not record + /// (tables and indices written before writers persisted file sizes). pub total_bytes: usize, /// The number of rows in the table @@ -3705,6 +3724,7 @@ mod tests { use super::*; use crate::connect; use crate::connection::ConnectBuilder; + use crate::io::object_store::io_tracking::IoTrackingStore; use crate::query::Select; use crate::query::{ExecutableQuery, QueryBase}; use crate::test_utils::connection::new_test_connection; @@ -5263,12 +5283,16 @@ mod tests { let res = table.stats().await.unwrap(); println!("{:#?}", res); + // `total_bytes` is the full on-disk size of the 11 data files (this table + // has no index or overlay files), so it is well above the 2000 bytes of + // column data these 250 int32 pairs hold: each file carries its own footer + // and metadata. assert_eq!( res, TableStatistics { num_rows: 250, num_indices: 0, - total_bytes: 2300, + total_bytes: 8925, fragment_stats: FragmentStatistics { num_fragments: 11, num_small_fragments: 11, @@ -5308,4 +5332,196 @@ mod tests { } ) } + + /// `total_bytes` counts more than the base data files: index files and + /// overlay files recorded in the manifest are included too. + #[tokio::test] + pub async fn test_stats_includes_index_and_overlay_files() { + use lance::dataset::WriteDestination; + use lance::dataset::transaction::{DataOverlayGroup, Operation}; + use lance_file::version::{ConcreteFileVersion, LanceFileVersion}; + use lance_file::writer::FileWriterOptions; + use lance_io::utils::CachedFileSize; + use lance_table::format::DataFile; + use lance_table::format::overlay::{DataOverlayFile, OverlayCoverage}; + use roaring::RoaringBitmap; + + 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 schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("foo", DataType::Int32, true), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from_iter_values(0..100)), + Arc::new(Int32Array::from_iter_values(0..100)), + ], + ) + .unwrap(); + let table = conn + .create_table("test_stats_extra_files", batch) + .execute() + .await + .unwrap(); + + let data_only = table.stats().await.unwrap().total_bytes; + assert!(data_only > 0); + + // A scalar index adds index files whose sizes are recorded in the + // manifest's index section. + table + .create_index(&["id"], Index::Auto) + .execute() + .await + .unwrap(); + let with_index = table.stats().await.unwrap().total_bytes; + let dataset = { + let native = table.as_native().unwrap(); + (*native.dataset.get().await.unwrap()).clone() + }; + let index_bytes: usize = dataset + .load_indices() + .await + .unwrap() + .iter() + .map(|idx| idx.total_size_bytes().unwrap_or(0) as usize) + .sum(); + assert!(index_bytes > 0); + assert_eq!(with_index, data_only + index_bytes); + + // Commit an overlay file supplying new `foo` values for the first three + // rows of fragment 0. There is no high-level API that writes overlays + // yet, so write the overlay's data file and commit the `DataOverlay` + // operation by hand. + let read_version = dataset.version().version; + let fragment_id = dataset.get_fragments()[0].id() as u64; + let foo_field_id = dataset.schema().field("foo").unwrap().id; + let overlay_schema = dataset.schema().project_by_ids(&[foo_field_id], true); + let file_version = ConcreteFileVersion::from(LanceFileVersion::Stable); + + let filename = "overlay.lance".to_string(); + let store = dataset.object_store(None).await.unwrap(); + let path = dataset.data_dir().child(filename.clone()); + let obj_writer = store.create(&path).await.unwrap(); + let mut writer = lance_file::versions::create_writer( + file_version, + obj_writer, + overlay_schema, + FileWriterOptions::default(), + ) + .unwrap(); + writer + .write_column(0, Arc::new(Int32Array::from(vec![1000, 1001, 1002])) as _) + .await + .unwrap(); + let summary = writer.finish().await.unwrap(); + let overlay_bytes = summary.size_bytes as usize; + assert!(overlay_bytes > 0); + + let mut data_file = DataFile::new_unstarted(filename, file_version); + data_file.fields = writer + .field_id_to_column_indices() + .iter() + .map(|(field_id, _)| *field_id as i32) + .collect::>() + .into(); + data_file.column_indices = writer + .field_id_to_column_indices() + .iter() + .map(|(_, column_index)| *column_index as i32) + .collect::>() + .into(); + data_file.file_size_bytes = CachedFileSize::new(summary.size_bytes); + + let overlay = DataOverlayFile { + data_file, + coverage: OverlayCoverage::dense(RoaringBitmap::from_iter(0..3)), + committed_version: 0, + }; + Dataset::commit( + WriteDestination::Dataset(Arc::new(dataset)), + Operation::DataOverlay { + groups: vec![DataOverlayGroup { + fragment_id, + overlays: vec![overlay], + }], + }, + Some(read_version), + None, + None, + Arc::new(Default::default()), + false, + ) + .await + .unwrap(); + + table.checkout_latest().await.unwrap(); + let with_overlay = table.stats().await.unwrap().total_bytes; + assert_eq!(with_overlay, with_index + overlay_bytes); + } + + /// `stats()` must stay manifest-only. Summing per-field `bytes_on_disk` + /// instead opens every data file, so cost would grow with fragment count. + #[tokio::test] + pub async fn test_stats_does_not_read_data_files() { + let tmp_dir = tempdir().unwrap(); + let uri = tmp_dir.path().to_str().unwrap(); + + let conn = ConnectBuilder::new(uri).execute().await.unwrap(); + + 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_iter_values(0..10))], + ) + .unwrap(); + + conn.create_table("test_stats_io", batch.clone()) + .execute() + .await + .unwrap(); + let table = conn.open_table("test_stats_io").execute().await.unwrap(); + const NUM_APPENDS: usize = 20; + for _ in 0..NUM_APPENDS { + table.add(batch.clone()).execute().await.unwrap(); + } + + // Reopen through a tracking store so the counters cover `stats()` alone and + // not the writes above. + let (wrapper, io_stats) = IoTrackingStore::new_wrapper(); + let table = conn + .open_table("test_stats_io") + .lance_read_params(ReadParams { + store_options: Some(ObjectStoreParams { + object_store_wrapper: Some(wrapper), + ..Default::default() + }), + ..Default::default() + }) + .execute() + .await + .unwrap(); + io_stats.lock().unwrap().read_iops = 0; + + let stats = table.stats().await.unwrap(); + let read_iops = io_stats.lock().unwrap().read_iops; + + assert_eq!(stats.fragment_stats.num_fragments, NUM_APPENDS + 1); + assert!(stats.total_bytes > 0); + // Reading the fragments' data files would take at least one IOP each. + assert!( + read_iops < stats.fragment_stats.num_fragments as u64, + "stats() issued {} read IOPs across {} fragments", + read_iops, + stats.fragment_stats.num_fragments + ); + } } From 36054be5760f54042549279333431fd8b4aaea76 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Sun, 9 Aug 2026 03:34:39 +0800 Subject: [PATCH 023/206] fix(node): preserve nested Arrow data across versions (#3900) ## Root cause When LanceDB accepted an Arrow table created by a different installed Arrow package, its compatibility sanitizer rebuilt each Data node without converting the foreign type or preserving nested children. It also dropped the separate dictionary vector payload and did not preserve identity shared by dictionary schema types, vector wrappers, or growing dictionary chunks. ## Fix Recursively sanitize nested Arrow data types and child data. Use one table-scoped sanitization context to rebuild and memoize source type objects, dictionary vectors, and Data nodes in the local Arrow realm, preserving all identities required by Arrow IPC. Add Arrow 15 through 18 regressions for list serialization, ordinary dictionaries, dictionaries shared across fields and batches, growing dictionaries, and IPC round trips. ## Validation - pnpm test __test__/arrow.test.ts --runInBand (188 passed) - pnpm lint - pnpm build - pnpm test --runInBand (706 passed, 5 skipped) - pnpm run docs Fixes #2256 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- nodejs/__test__/arrow.test.ts | 115 +++++++++++++++++++ nodejs/lancedb/sanitize.ts | 203 +++++++++++++++++++++++++++++----- 2 files changed, 289 insertions(+), 29 deletions(-) diff --git a/nodejs/__test__/arrow.test.ts b/nodejs/__test__/arrow.test.ts index c05849cb9..29030d4f8 100644 --- a/nodejs/__test__/arrow.test.ts +++ b/nodejs/__test__/arrow.test.ts @@ -6,7 +6,9 @@ import * as arrow17 from "apache-arrow-17"; import * as arrow18 from "apache-arrow-18"; import { + Vector as CurrentVector, convertToTable, + tableFromIPC as currentTableFromIPC, fromBufferToRecordBatch, fromDataToBuffer, fromRecordBatchToBuffer, @@ -19,6 +21,7 @@ import { FunctionOptions, } from "../lancedb/embedding/embedding_function"; import { EmbeddingFunctionConfig } from "../lancedb/embedding/registry"; +import { sanitizeTable } from "../lancedb/sanitize"; // biome-ignore lint/suspicious/noExplicitAny: skip function sampleRecords(): Array> { @@ -64,7 +67,11 @@ describe.each([arrow15, arrow16, arrow17, arrow18])( tableFromIPC, DataType, Dictionary, + RecordBatch: ArrowRecordBatch, + Table: ArrowTable, Uint8: ArrowUint8, + makeData: arrowMakeData, + vectorFromArray, // biome-ignore lint/suspicious/noExplicitAny: } = arrow; type Schema = ApacheArrow["Schema"]; @@ -1054,6 +1061,114 @@ describe.each([arrow15, arrow16, arrow17, arrow18])( }); describe("when using two versions of arrow", function () { + it("preserves a dictionary shared by multiple fields", async function () { + const values = ["alpha", "beta", "alpha"]; + const dictionaryVector = vectorFromArray(values); + const batch = new ArrowRecordBatch({ + first: dictionaryVector.data[0], + second: dictionaryVector.data[0], + }); + const table = new ArrowTable([batch]); + + const sanitized = sanitizeTable(table); + expect([...sanitized.getChild("first")!]).toEqual(values); + expect([...sanitized.getChild("second")!]).toEqual(values); + const firstType = sanitized.schema.fields[0].type as { + dictionary: unknown; + }; + const secondType = sanitized.schema.fields[1].type as { + dictionary: unknown; + }; + expect(secondType.dictionary).toBe(firstType.dictionary); + expect(sanitized.batches[0].data.children[1].dictionary).toBe( + sanitized.batches[0].data.children[0].dictionary, + ); + + const buf = await fromDataToBuffer(table); + const actual = currentTableFromIPC(buf); + expect([...actual.getChild("first")!]).toEqual(values); + expect([...actual.getChild("second")!]).toEqual(values); + }); + + it("preserves shared dictionary data from another Arrow version", async function () { + const values = ["alpha", "beta", "alpha"]; + const dictionaryVector = vectorFromArray(values); + const firstBatch = new ArrowRecordBatch({ + label: dictionaryVector.slice(0, 2).data[0], + }); + const secondBatch = new ArrowRecordBatch({ + label: dictionaryVector.slice(2).data[0], + }); + const table = new ArrowTable([firstBatch, secondBatch]); + + const sanitized = sanitizeTable(table); + expect([...sanitized.getChild("label")!]).toEqual(values); + + const dictionaries = sanitized.batches.map( + (batch) => batch.data.children[0].dictionary, + ); + expect(dictionaries[0]).toBeInstanceOf(CurrentVector); + expect(dictionaries[1]).toBe(dictionaries[0]); + + const buf = await fromDataToBuffer(table); + const actual = currentTableFromIPC(buf); + expect([...actual.getChild("label")!]).toEqual(values); + }); + + it("preserves shared chunks in growing dictionaries", async function () { + const type = new Dictionary(new Utf8(), new Int32(), 42, false); + const firstDictionary = vectorFromArray(["alpha", "beta"], new Utf8()); + const secondDictionary = firstDictionary.concat( + vectorFromArray(["gamma"], new Utf8()), + ); + const firstData = arrowMakeData({ + type, + data: Int32Array.from([0, 1]), + dictionary: firstDictionary, + }); + const secondData = arrowMakeData({ + type, + data: Int32Array.from([2]), + dictionary: secondDictionary, + }); + const table = new ArrowTable([ + new ArrowRecordBatch({ label: firstData }), + new ArrowRecordBatch({ label: secondData }), + ]); + + const sanitized = sanitizeTable(table); + const expected = ["alpha", "beta", "gamma"]; + expect([...sanitized.getChild("label")!]).toEqual(expected); + const firstLocalDictionary = + sanitized.batches[0].data.children[0].dictionary!; + const secondLocalDictionary = + sanitized.batches[1].data.children[0].dictionary!; + expect(secondLocalDictionary.data[0]).toBe( + firstLocalDictionary.data[0], + ); + + const buf = await fromTableToBuffer(sanitized); + const actual = currentTableFromIPC(buf); + expect([...actual.getChild("label")!]).toEqual(expected); + }); + + it("can serialize list data from another Arrow version", async function () { + const values = [["anime", "action"], [], null]; + const vector = vectorFromArray( + values, + new List(new Field("item", new Utf8(), true)), + ); + const table = new ArrowTable({ tags: vector }); + + const buf = await fromDataToBuffer(table); + const actual = currentTableFromIPC(buf); + const actualTags = actual.getChild("tags"); + + expect(actualTags?.get(0)?.toJSON()).toEqual(values[0]); + expect(actualTags?.get(1)?.toJSON()).toEqual(values[1]); + expect(actualTags?.get(2)).toBeNull(); + }); + it("can still import data", async function () { const schema = new arrow15.Schema([ new arrow15.Field("id", new arrow15.Int32()), diff --git a/nodejs/lancedb/sanitize.ts b/nodejs/lancedb/sanitize.ts index ae0bc0179..8fb2f1a0a 100644 --- a/nodejs/lancedb/sanitize.ts +++ b/nodejs/lancedb/sanitize.ts @@ -9,7 +9,7 @@ // comes from the exact same library instance. This is not always the case // and so we must sanitize the input to ensure that it is compatible. -import { BufferType, Data } from "apache-arrow"; +import { BufferType, Data, Vector } from "apache-arrow"; import type { IntBitWidth, TKeys, TimeBitWidth } from "apache-arrow/type"; import { Binary, @@ -74,6 +74,20 @@ import { Utf8, } from "./arrow"; +type SanitizationContext = { + types: WeakMap; + vectors: WeakMap; + data: WeakMap>; +}; + +function createSanitizationContext(): SanitizationContext { + return { + types: new WeakMap(), + vectors: new WeakMap(), + data: new WeakMap(), + }; +} + export function sanitizeMetadata( metadataLike?: unknown, ): Map | undefined { @@ -186,6 +200,13 @@ export function sanitizeInterval(typeLike: object) { } export function sanitizeList(typeLike: object) { + return sanitizeListWithContext(typeLike, createSanitizationContext()); +} + +function sanitizeListWithContext( + typeLike: object, + context: SanitizationContext, +) { if (!("children" in typeLike) || !Array.isArray(typeLike.children)) { throw Error( "Expected a List type to have an array-like `children` property", @@ -194,19 +215,35 @@ export function sanitizeList(typeLike: object) { if (typeLike.children.length !== 1) { throw Error("Expected a List type to have exactly one child"); } - return new List(sanitizeField(typeLike.children[0])); + return new List(sanitizeFieldWithContext(typeLike.children[0], context)); } export function sanitizeStruct(typeLike: object) { + return sanitizeStructWithContext(typeLike, createSanitizationContext()); +} + +function sanitizeStructWithContext( + typeLike: object, + context: SanitizationContext, +) { if (!("children" in typeLike) || !Array.isArray(typeLike.children)) { throw Error( "Expected a Struct type to have an array-like `children` property", ); } - return new Struct(typeLike.children.map((child) => sanitizeField(child))); + return new Struct( + typeLike.children.map((child) => sanitizeFieldWithContext(child, context)), + ); } export function sanitizeUnion(typeLike: object) { + return sanitizeUnionWithContext(typeLike, createSanitizationContext()); +} + +function sanitizeUnionWithContext( + typeLike: object, + context: SanitizationContext, +) { if ( !("typeIds" in typeLike) || !("mode" in typeLike) || @@ -226,7 +263,7 @@ export function sanitizeUnion(typeLike: object) { typeLike.mode, // biome-ignore lint/suspicious/noExplicitAny: skip typeLike.typeIds as any, - typeLike.children.map((child) => sanitizeField(child)), + typeLike.children.map((child) => sanitizeFieldWithContext(child, context)), ); } @@ -234,6 +271,19 @@ export function sanitizeTypedUnion( typeLike: object, // eslint-disable-next-line @typescript-eslint/naming-convention UnionType: typeof DenseUnion | typeof SparseUnion, +) { + return sanitizeTypedUnionWithContext( + typeLike, + UnionType, + createSanitizationContext(), + ); +} + +function sanitizeTypedUnionWithContext( + typeLike: object, + // eslint-disable-next-line @typescript-eslint/naming-convention + UnionType: typeof DenseUnion | typeof SparseUnion, + context: SanitizationContext, ) { if (!("typeIds" in typeLike)) { throw Error( @@ -248,7 +298,7 @@ export function sanitizeTypedUnion( return new UnionType( typeLike.typeIds as Int32Array | number[], - typeLike.children.map((child) => sanitizeField(child)), + typeLike.children.map((child) => sanitizeFieldWithContext(child, context)), ); } @@ -262,6 +312,16 @@ export function sanitizeFixedSizeBinary(typeLike: object) { } export function sanitizeFixedSizeList(typeLike: object) { + return sanitizeFixedSizeListWithContext( + typeLike, + createSanitizationContext(), + ); +} + +function sanitizeFixedSizeListWithContext( + typeLike: object, + context: SanitizationContext, +) { if (!("listSize" in typeLike) || typeof typeLike.listSize !== "number") { throw Error("Expected a FixedSizeList type to have a `listSize` property"); } @@ -275,11 +335,18 @@ export function sanitizeFixedSizeList(typeLike: object) { } return new FixedSizeList( typeLike.listSize, - sanitizeField(typeLike.children[0]), + sanitizeFieldWithContext(typeLike.children[0], context), ); } export function sanitizeMap(typeLike: object) { + return sanitizeMapWithContext(typeLike, createSanitizationContext()); +} + +function sanitizeMapWithContext( + typeLike: object, + context: SanitizationContext, +) { if (!("children" in typeLike) || !Array.isArray(typeLike.children)) { throw Error( "Expected a Map type to have an array-like `children` property", @@ -292,7 +359,10 @@ export function sanitizeMap(typeLike: object) { throw Error("Expected a Map type to have exactly one child"); } - return new Map_(sanitizeField(typeLike.children[0]), typeLike.keysSorted); + return new Map_( + sanitizeFieldWithContext(typeLike.children[0], context), + typeLike.keysSorted, + ); } export function sanitizeDuration(typeLike: object) { @@ -303,6 +373,13 @@ export function sanitizeDuration(typeLike: object) { } export function sanitizeDictionary(typeLike: object) { + return sanitizeDictionaryWithContext(typeLike, createSanitizationContext()); +} + +function sanitizeDictionaryWithContext( + typeLike: object, + context: SanitizationContext, +) { if (!("id" in typeLike) || typeof typeLike.id !== "number") { throw Error("Expected a Dictionary type to have an `id` property"); } @@ -316,8 +393,8 @@ export function sanitizeDictionary(typeLike: object) { throw Error("Expected a Dictionary type to have an `isOrdered` property"); } return new Dictionary( - sanitizeType(typeLike.dictionary), - sanitizeType(typeLike.indices) as TKeys, + sanitizeTypeWithContext(typeLike.dictionary, context), + sanitizeTypeWithContext(typeLike.indices, context) as TKeys, typeLike.id, typeLike.isOrdered, ); @@ -325,12 +402,23 @@ export function sanitizeDictionary(typeLike: object) { // biome-ignore lint/suspicious/noExplicitAny: skip export function sanitizeType(typeLike: unknown): DataType { + return sanitizeTypeWithContext(typeLike, createSanitizationContext()); +} + +function sanitizeTypeWithContext( + typeLike: unknown, + context: SanitizationContext, +): DataType { if (typeof typeLike === "string") { return dataTypeFromName(typeLike); } if (typeof typeLike !== "object" || typeLike === null) { throw Error("Expected a Type but object was null/undefined"); } + const cached = context.types.get(typeLike); + if (cached !== undefined) { + return cached; + } if ( !("typeId" in typeLike) || !( @@ -349,6 +437,16 @@ export function sanitizeType(typeLike: unknown): DataType { throw Error("Type's typeId property was not a function or number"); } + const type = sanitizeTypeById(typeLike, typeId, context); + context.types.set(typeLike, type); + return type; +} + +function sanitizeTypeById( + typeLike: object, + typeId: Type, + context: SanitizationContext, +): DataType { switch (typeId) { case Type.NONE: throw Error("Received a Type with a typeId of NONE"); @@ -375,21 +473,21 @@ export function sanitizeType(typeLike: unknown): DataType { case Type.Interval: return sanitizeInterval(typeLike); case Type.List: - return sanitizeList(typeLike); + return sanitizeListWithContext(typeLike, context); case Type.Struct: - return sanitizeStruct(typeLike); + return sanitizeStructWithContext(typeLike, context); case Type.Union: - return sanitizeUnion(typeLike); + return sanitizeUnionWithContext(typeLike, context); case Type.FixedSizeBinary: return sanitizeFixedSizeBinary(typeLike); case Type.FixedSizeList: - return sanitizeFixedSizeList(typeLike); + return sanitizeFixedSizeListWithContext(typeLike, context); case Type.Map: - return sanitizeMap(typeLike); + return sanitizeMapWithContext(typeLike, context); case Type.Duration: return sanitizeDuration(typeLike); case Type.Dictionary: - return sanitizeDictionary(typeLike); + return sanitizeDictionaryWithContext(typeLike, context); case Type.Int8: return new Int8(); case Type.Int16: @@ -433,9 +531,9 @@ export function sanitizeType(typeLike: unknown): DataType { case Type.TimestampSecond: return sanitizeTypedTimestamp(typeLike, TimestampSecond); case Type.DenseUnion: - return sanitizeTypedUnion(typeLike, DenseUnion); + return sanitizeTypedUnionWithContext(typeLike, DenseUnion, context); case Type.SparseUnion: - return sanitizeTypedUnion(typeLike, SparseUnion); + return sanitizeTypedUnionWithContext(typeLike, SparseUnion, context); case Type.IntervalDayTime: return new IntervalDayTime(); case Type.IntervalYearMonth: @@ -454,6 +552,13 @@ export function sanitizeType(typeLike: unknown): DataType { } export function sanitizeField(fieldLike: unknown): Field { + return sanitizeFieldWithContext(fieldLike, createSanitizationContext()); +} + +function sanitizeFieldWithContext( + fieldLike: unknown, + context: SanitizationContext, +): Field { if (fieldLike instanceof Field) { return fieldLike; } @@ -471,7 +576,7 @@ export function sanitizeField(fieldLike: unknown): Field { } let type: DataType; try { - type = sanitizeType(fieldLike.type); + type = sanitizeTypeWithContext(fieldLike.type, context); } catch (error: unknown) { throw Error( `Unable to sanitize type for field: ${fieldLike.name} due to error: ${error}`, @@ -501,6 +606,13 @@ export function sanitizeField(fieldLike: unknown): Field { * than lancedb is using. */ export function sanitizeSchema(schemaLike: SchemaLike): Schema { + return sanitizeSchemaWithContext(schemaLike, createSanitizationContext()); +} + +function sanitizeSchemaWithContext( + schemaLike: SchemaLike, + context: SanitizationContext, +): Schema { if (schemaLike instanceof Schema) { return schemaLike; } @@ -522,7 +634,7 @@ export function sanitizeSchema(schemaLike: SchemaLike): Schema { ); } const sanitizedFields = schemaLike.fields.map((field) => - sanitizeField(field), + sanitizeFieldWithContext(field, context), ); return new Schema(sanitizedFields, metadata); } @@ -544,13 +656,18 @@ export function sanitizeTable(tableLike: TableLike): Table { "The table passed in does not appear to be a table (no 'columns' property)", ); } - const schema = sanitizeSchema(tableLike.schema); - - const batches = tableLike.batches.map(sanitizeRecordBatch); + const context = createSanitizationContext(); + const schema = sanitizeSchemaWithContext(tableLike.schema, context); + const batches = tableLike.batches.map((batch) => + sanitizeRecordBatch(batch, context), + ); return new Table(schema, batches); } -function sanitizeRecordBatch(batchLike: RecordBatchLike): RecordBatch { +function sanitizeRecordBatch( + batchLike: RecordBatchLike, + context: SanitizationContext, +): RecordBatch { if (batchLike instanceof RecordBatch) { return batchLike; } @@ -567,19 +684,43 @@ function sanitizeRecordBatch(batchLike: RecordBatchLike): RecordBatch { "The record batch passed in does not appear to be a record batch (no 'data' property)", ); } - const schema = sanitizeSchema(batchLike.schema); - const data = sanitizeData(batchLike.data); + const schema = sanitizeSchemaWithContext(batchLike.schema, context); + const data = sanitizeData(batchLike.data, context) as Data; return new RecordBatch(schema, data); } + +type DictionaryVectorLike = { + data: readonly DataLike[]; +}; + +type DictionaryDataLike = DataLike & { + dictionary?: DictionaryVectorLike; +}; + function sanitizeData( dataLike: DataLike, - // biome-ignore lint/suspicious/noExplicitAny: -): import("apache-arrow").Data> { + context: SanitizationContext, +): Data { if (dataLike instanceof Data) { return dataLike; } - return new Data( - dataLike.type, + const cachedData = context.data.get(dataLike); + if (cachedData !== undefined) { + return cachedData; + } + const dictionaryLike = (dataLike as DictionaryDataLike).dictionary; + let dictionary: Vector | undefined; + if (dictionaryLike !== undefined) { + dictionary = context.vectors.get(dictionaryLike); + if (dictionary === undefined) { + dictionary = new Vector( + dictionaryLike.data.map((data) => sanitizeData(data, context)), + ); + context.vectors.set(dictionaryLike, dictionary); + } + } + const data = new Data( + sanitizeTypeWithContext(dataLike.type, context), dataLike.offset, dataLike.length, dataLike.nullCount, @@ -589,7 +730,11 @@ function sanitizeData( [BufferType.VALIDITY]: dataLike.nullBitmap, [BufferType.TYPE]: dataLike.typeIds, }, + dataLike.children.map((child) => sanitizeData(child, context)), + dictionary, ); + context.data.set(dataLike, data); + return data; } const constructorsByTypeName = { From 12405a407748fd8a445131d6747e92e9592a1dc1 Mon Sep 17 00:00:00 2001 From: ForwardXu Date: Mon, 10 Aug 2026 12:16:21 +0800 Subject: [PATCH 024/206] chore: drop explicit goosefs-sdk pin in favor of opendal 0.58.1 transitive dep (#3910) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary `opendal 0.58.1` (the version pulled in transitively via Lance) already ships `goosefs-sdk 0.1.9`, which includes the upstream fix for the 0.1.6 compile break. The explicit version pin that lancedb has been carrying since the GooseFS feature was introduced is therefore no longer necessary and is now redundant work to maintain. ## Changes - Remove the direct `goosefs-sdk` dependency from `rust/lancedb/Cargo.toml` (it was pinned to `=0.1.9` with a comment referencing the 0.1.6 compile break). - Remove the `dep:goosefs-sdk` entry from the `goosefs` cargo feature, since no source file in lancedb imports the crate directly. - Refresh `Cargo.lock`; `goosefs-sdk 0.1.9` now resolves transitively through `lance` → `opendal 0.58.1`. ## Verification - `cargo fmt --all` — clean - `cargo check --features remote,goosefs --tests --examples` — passes - `Cargo.lock` confirms `goosefs-sdk 0.1.9` is still resolved (now transitively), so the `goosefs` feature continues to enable the same set of Lance/IOPaths as before. ## Backwards compatibility No public API changes. The `goosefs` cargo feature still activates `lance/goosefs`, `lance-io/goosefs`, and `lance-namespace-impls/dir-goosefs`, and the same `goosefs-sdk 0.1.9` version is selected by the resolver. --- Cargo.lock | 1 - rust/lancedb/Cargo.toml | 3 --- 2 files changed, 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 20f20a0ac..ec6b7cbfb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5447,7 +5447,6 @@ dependencies = [ "datafusion-physical-plan", "datafusion-sql", "futures", - "goosefs-sdk", "half", "hf-hub", "http 1.5.0", diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 2dbd9d895..e33b86b12 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -49,8 +49,6 @@ lance-namespace = { workspace = true } lance-namespace-impls = { workspace = true } metrics = { workspace = true, optional = true } metrics-util = { workspace = true, optional = true } -# Pin the GooseFS SDK to the version required by Lance's OpenDAL dependency. -goosefs-sdk = { version = "=0.1.9", optional = true } moka = { workspace = true } pin-project = { workspace = true } tokio = { version = "1.23", features = ["rt-multi-thread", "sync"] } @@ -136,7 +134,6 @@ azure = [ ] cos = ["lance/tencent", "lance-io/tencent"] goosefs = [ - "dep:goosefs-sdk", "lance/goosefs", "lance-io/goosefs", "lance-namespace-impls/dir-goosefs", From 5acce6782e456f5f33a436a247290c4f796264f1 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Mon, 10 Aug 2026 15:08:36 +0800 Subject: [PATCH 025/206] ci(docs): report link checker failures through issues (#3909) --- .github/workflows/docs-link-check.yml | 119 +++++++++++++++----------- 1 file changed, 70 insertions(+), 49 deletions(-) diff --git a/.github/workflows/docs-link-check.yml b/.github/workflows/docs-link-check.yml index 0e22100eb..1286819bc 100644 --- a/.github/workflows/docs-link-check.yml +++ b/.github/workflows/docs-link-check.yml @@ -36,7 +36,9 @@ jobs: permissions: contents: read outputs: + checker_outcome: ${{ steps.lychee.outcome }} exit_code: ${{ steps.lychee.outputs.exit_code }} + status: ${{ steps.validate.outputs.status }} steps: - name: Checkout uses: actions/checkout@v6 @@ -50,6 +52,7 @@ jobs: - name: Check links id: lychee + continue-on-error: true uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0 with: # Restricted to http(s) on purpose. Much of docs/src is generated @@ -68,38 +71,50 @@ jobs: format: json output: ./lychee/out.json jobSummary: false - # The report, not a red build, is the signal for broken links. The - # validation step below still fails the run if the check itself - # breaks. + # The report issue, not a red workflow run, is the signal for link + # findings and checker failures alike. fail: false - name: Validate report + id: validate # lychee does not reserve exit code 2 for broken links: its CLI # parser also exits 2 on an invalid option, before any link was # checked or any report written. Only a parseable report whose - # counts agree with the exit code counts as a link verdict; anything - # else fails here, and the report job below is skipped entirely, so - # the tracking issue is never touched. Exit 2 covers timeouts as - # well as errors, and a timed-out host is exactly the transient - # unavailability this report exists to surface, so both count as - # findings. Requiring total > 0 also catches a glob that silently - # stopped matching any file. - if: steps.lychee.outputs.exit_code == 0 || steps.lychee.outputs.exit_code == 2 + # counts agree with a completed exit code (0 or 2) counts as a link + # verdict. Everything else becomes a checker-error report instead of + # failing the workflow. Exit 2 covers timeouts as well as errors, and a + # timed-out host is exactly the transient unavailability this report + # exists to surface, so both count as findings. Requiring total > 0 + # also catches a glob that silently stopped matching any file. + if: always() env: + CHECKER_OUTCOME: ${{ steps.lychee.outcome }} EXIT_CODE: ${{ steps.lychee.outputs.exit_code }} run: | - jq -e --argjson code "$EXIT_CODE" ' - (.total > 0) and - (if $code == 0 - then .errors == 0 and .timeouts == 0 - and (.error_map | length == 0) and (.timeout_map | length == 0) - else (.errors + .timeouts) > 0 - and ((.error_map | length) + (.timeout_map | length)) > 0 - end) - ' ./lychee/out.json + status=checker-error + if [[ "$CHECKER_OUTCOME" == success ]] && + [[ "$EXIT_CODE" == 0 || "$EXIT_CODE" == 2 ]] && + jq -e --argjson code "$EXIT_CODE" ' + (.total > 0) and + (if $code == 0 + then .errors == 0 and .timeouts == 0 + and (.error_map | length == 0) and (.timeout_map | length == 0) + else (.errors + .timeouts) > 0 + and ((.error_map | length) + (.timeout_map | length)) > 0 + end) + ' ./lychee/out.json + then + if [[ "$EXIT_CODE" == 0 ]]; then + status=healthy + else + status=findings + fi + fi + echo "status=$status" >> "$GITHUB_OUTPUT" + echo "Validated link check as $status" - name: Upload report - if: steps.lychee.outputs.exit_code == 2 + if: steps.validate.outputs.status == 'findings' uses: actions/upload-artifact@v7 with: name: link-report @@ -115,26 +130,11 @@ jobs: permissions: issues: write env: + CHECKER_OUTCOME: ${{ needs.scan.outputs.checker_outcome }} EXIT_CODE: ${{ needs.scan.outputs.exit_code }} + STATUS: ${{ needs.scan.outputs.status }} GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} steps: - - name: Classify checker result - # lychee exits 0 when every link resolves and 2 when links fail, - # both already cross-checked against the report by the scan job's - # validation step. Anything else (1 runtime, 3 bad config) means the - # check never produced a link verdict, which must surface as a failed - # run rather than be published as "broken documentation links". - run: | - case "$EXIT_CODE" in - 0|2) - echo "lychee exit code $EXIT_CODE" - ;; - *) - echo "::error::lychee exited with '$EXIT_CODE': the link check did not complete. Leaving the report issue untouched." - exit 1 - ;; - esac - - name: Find existing report issue id: report # Matched on title alone, and through search rather than a listing: @@ -144,7 +144,7 @@ jobs: # Closed issues are included because a healthy run closes the report: # an open-only lookup would forget that identity and the next failing # run would open a duplicate. The oldest match stays the canonical - # report and is reopened below when links break again. + # report and is reopened below when a problem recurs. run: | match=$(gh issue list --repo "$GITHUB_REPOSITORY" --state all \ --search "in:title \"$REPORT_TITLE\" author:app/github-actions" \ @@ -154,14 +154,14 @@ jobs: echo "state=$(jq -r '.state // empty' <<<"$match")" >> "$GITHUB_OUTPUT" - name: Download report - if: env.EXIT_CODE == 2 + if: env.STATUS == 'findings' uses: actions/download-artifact@v8 with: name: link-report path: ./lychee - name: Compose report - if: env.EXIT_CODE == 2 + if: env.STATUS == 'findings' run: | run_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" { @@ -185,22 +185,41 @@ jobs: ' ./lychee/out.json } > ./lychee/issue.md + - name: Compose checker error report + if: env.STATUS == 'checker-error' + run: | + mkdir -p ./lychee + run_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" + { + echo "The documentation link check did not complete in [the latest run]($run_url)." + echo + echo "This issue is rewritten by every scheduled run and closed automatically once a trustworthy run finds that all links resolve." + echo + echo "The checker did not produce a trustworthy link verdict. Treat the previous result, if any, as stale until a later run completes." + echo + echo "* Action outcome: \`$CHECKER_OUTCOME\`" + echo "* Exit code: \`${EXIT_CODE:-not reported}\`" + echo "* Verdict validation: \`failed\`" + } > ./lychee/issue.md + - name: Reopen report issue # A healthy run closes the report, and the issue action below only # rewrites the body of whatever number it is given. Without an - # explicit reopen, the 2 -> 0 -> 2 sequence would keep rewriting a - # closed issue while links are broken. A CLOSED state implies the - # lookup found a canonical issue, so no separate emptiness check. - if: env.EXIT_CODE == 2 && steps.report.outputs.state == 'CLOSED' + # explicit reopen, a later finding or checker error would rewrite a + # closed issue. A CLOSED state implies the lookup found a canonical + # issue, so no separate emptiness check. + if: >- + env.STATUS != 'healthy' && + steps.report.outputs.state == 'CLOSED' env: ISSUE_NUMBER: ${{ steps.report.outputs.number }} run: | run_url="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" gh issue reopen "$ISSUE_NUMBER" --repo "$GITHUB_REPOSITORY" \ - --comment "Broken documentation links found again in [the latest run]($run_url)." + --comment "The documentation link checker reported a problem again in [the latest run]($run_url)." - - name: Report broken links - if: env.EXIT_CODE == 2 + - name: Report link-check problem + if: env.STATUS != 'healthy' uses: peter-evans/create-issue-from-file@fca9117c27cdc29c6c4db3b86c48e4115a786710 # v6.0.0 with: # Empty on the first failing run, which creates the issue; afterwards @@ -213,7 +232,9 @@ jobs: - name: Close report issue once links are healthy # An OPEN state implies the lookup found a canonical issue; a report # that is already closed needs nothing. - if: env.EXIT_CODE == 0 && steps.report.outputs.state == 'OPEN' + if: >- + env.STATUS == 'healthy' && + steps.report.outputs.state == 'OPEN' env: ISSUE_NUMBER: ${{ steps.report.outputs.number }} run: | From 920fc0e455476ed054dae32a4b8e558faa8eec30 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Mon, 10 Aug 2026 21:40:31 +0800 Subject: [PATCH 026/206] fix(python): set native module metadata (#3913) PyO3 defaults native extension classes to `builtins`, so mkdocstrings/Griffe could not resolve the newly documented `lancedb.Session` alias and `Deploy docs to Pages` failed on `main`. Declare the extension module for the public native types referenced by the Python API docs so Griffe resolves them through `lancedb._lancedb` and Pages can build again. Validated with the docs toolchain used by CI (`griffe==0.49.0`, `mkdocstrings==0.25.2`, and `mkdocs==1.6.1`); `PYTHONPATH=. mkdocs build` succeeds. --- python/src/index.rs | 2 +- python/src/session.rs | 2 +- python/src/table.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/python/src/index.rs b/python/src/index.rs index 8c81dcecf..dd362373e 100644 --- a/python/src/index.rs +++ b/python/src/index.rs @@ -289,7 +289,7 @@ struct IvfHnswFlatParams { target_partition_size: Option, } -#[pyclass(get_all)] +#[pyclass(module = "lancedb._lancedb", get_all)] /// A description of an index currently configured on a column pub struct IndexConfig { /// The type of the index diff --git a/python/src/session.rs b/python/src/session.rs index 891e61e44..4d58dd269 100644 --- a/python/src/session.rs +++ b/python/src/session.rs @@ -11,7 +11,7 @@ use pyo3::{PyResult, pyclass, pymethods}; /// Sessions allow you to configure cache sizes for index and metadata caches, /// which can significantly impact memory use and performance. They can /// also be re-used across multiple connections to share the same cache state. -#[pyclass(from_py_object)] +#[pyclass(module = "lancedb._lancedb", from_py_object)] #[derive(Clone)] pub struct Session { pub(crate) inner: Arc, diff --git a/python/src/table.rs b/python/src/table.rs index 20a93556f..cae6b5d9a 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -579,7 +579,7 @@ impl PyBlobFile { } } -#[pyclass(get_all, from_py_object)] +#[pyclass(module = "lancedb._lancedb", get_all, from_py_object)] #[derive(Clone, Debug)] pub struct FtsToken { pub text: String, From a615306f39664900da9091484c6e06de4859205d Mon Sep 17 00:00:00 2001 From: Sravan Avvaru <81159574+Sravan1011@users.noreply.github.com> Date: Mon, 10 Aug 2026 21:52:06 +0530 Subject: [PATCH 027/206] feat(python): add on_transform_error fault tolerance to StreamingDataset (#3763) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #3704 ## Problem Transforms can fail on bad data (e.g. nulls/NaNs from incomplete user surveys). Today any transform exception aborts iteration, and there is no way to skip invalid rows during loading. ## Solution New `on_transform_error` parameter on `StreamingDataset`: - `"raise"` (default, matches current behavior and the convention in tf.data / WebDataset / Ray Data) - `"skip"` — drop the failing rows and continue - `"warn"` — like skip, plus a logged warning per failing batch - a WebDataset-style callable `handler(exc) -> bool`, so users can skip only expected error types Key design points: - **Row-granular skipping**: when a batch fails, the transform is re-run on single-row slices so only the rows that actually fail are dropped (avoids Ray-style whole-block loss). Skips are counted in a new `rows_skipped` property. - **No crash on uneven skips**: the round-robin loop now ends the epoch at the last cycle where every split still has a row, instead of hitting `IndexError` when a split runs dry early. - **Exact resumability under skips**: checkpoints are now position-based. `state_dict` gains `positions_consumed_per_split` (exact for owned splits), and a new `merge_state_dicts` static method combines per-rank states via elementwise max for elastic resume across topology changes. Old checkpoints without the new key still load. Positions equal sample counts when nothing is skipped, so existing behavior is unchanged. - **Guardrail**: transforms returning the wrong number of rows now raise a clear `ValueError` instead of silently corrupting split accounting. ### Answers to the issue's open questions - *Can we do this?* Yes — all transforms funnel through one guarded call in the Stage 2 pipeline. - *What do other libraries do?* tf.data `ignore_errors()`, WebDataset `handler=`, Ray `max_errored_blocks`; MosaicML StreamingDataset offers nothing (skipping conflicts with its determinism model). This design follows the common conventions: raise by default, opt-in skipping, count/log drops. - *Error handling or pre-filtering?* Both: the existing `filter=` remains the recommended tool for predictable bad data (splits are built post-filter, so all guarantees hold — now documented); `on_transform_error` covers failures not expressible as a predicate. - *Impact on splits / elastic determinism?* Per-split sample sequences stay deterministic (skips are data-dependent, not topology-dependent). With unequal bad-row counts across splits the last few global steps of an epoch can differ across topologies (bounded by the skew), which is documented on the parameter. With equal counts per split, full determinism is preserved — covered by a test. ## Testing 15 new tests in `test_elastic_dataloader.py` covering: default raise, invalid values, uniform and uneven skips (including epoch-end truncation), warn logging, selective callable handlers, wrong-row-count guardrail, determinism across runs and across world sizes (1/2/3/4) with skips, exact mid-epoch resume with skips on the same topology, elastic resume via `merge_state_dicts` (ws=2 → ws=1), merge validation, and backward-compat loading of old checkpoints. Note: relying on CI for the test run — my local machine OOMs during the final link of the native extension. The change itself is pure Python. --------- Co-authored-by: Claude Fable 5 --- python/python/lancedb/streaming.py | 342 +++++++++++++-- .../python/tests/test_elastic_dataloader.py | 402 ++++++++++++++++++ 2 files changed, 717 insertions(+), 27 deletions(-) diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py index 525ed3d63..b27e606a4 100644 --- a/python/python/lancedb/streaming.py +++ b/python/python/lancedb/streaming.py @@ -11,6 +11,11 @@ Provides StreamingDataset, a PyTorch IterableDataset that guarantees: - **Resumability**: state_dict / load_state_dict capture per-split consumption counts so training can resume from an exact mid-epoch position even when the distributed topology changes between runs. + +Transform failures on bad rows (e.g. nulls or NaNs from incomplete data) can +be tolerated with ``on_transform_error="skip"``; see the parameter +documentation on StreamingDataset for how this interacts with the guarantees +above. """ import ctypes @@ -22,7 +27,7 @@ import time from collections import deque from concurrent.futures import ThreadPoolExecutor from multiprocessing import RawArray -from typing import Any, Callable, Iterator, Optional +from typing import Any, Callable, Iterator, Optional, Union from torch.utils.data import IterableDataset, get_worker_info @@ -127,6 +132,49 @@ class StreamingDataset(IterableDataset): Maximum number of transforms to run concurrently. Must be greater than zero. When ``None`` (the default), uses ``os.cpu_count()`` or 1 when the CPU count is unavailable. + on_transform_error: + What to do when the transform raises an exception: + + - ``"raise"`` (the default): the exception propagates and iteration + aborts. + - ``"skip"``: the failing rows are dropped and iteration continues. + - ``"warn"``: like ``"skip"``, but a warning is logged for each + failing batch. + - a callable ``handler(exc) -> bool``: called with the exception; + return ``True`` to skip the failing rows or ``False`` to re-raise. + Useful to skip only expected error types (compatible with + ``webdataset.handlers`` style handlers). + + When a batch fails, the transform is re-invoked on each single-row + slice of the batch so that only the rows that actually fail are + dropped. Transforms should therefore be deterministic and accept + batches of any size (including one row). Skipped rows are counted in + ``rows_skipped``. + + Skipping weakens the elastic-determinism guarantee at the end of the + epoch: splits that lose more rows than others run dry earlier, and + each rank's iterator ends at the last cycle where every split *it + owns* still has a row. Because bad rows are not distributed evenly + across splits, this means one rank's iterator can yield noticeably + fewer or more steps than another rank's *in the same run* — there is + no cross-rank coordination that stops every rank at the same global + step. This is generally safe for asynchronous or single-rank use, + but synchronous distributed training (e.g. ranks that call + ``all_reduce`` every step) can hang or deadlock if one rank's + iterator is exhausted while others are still stepping; callers doing + synchronous multi-rank training with ``on_transform_error != "raise"`` + are responsible for their own cross-rank stopping mechanism (e.g. + broadcasting a stop signal on ``StopIteration``). The final few + global steps can also differ across topologies (bounded by the skew + in bad-row counts across splits). The sequence of samples yielded + from each split remains deterministic. Mid-epoch + checkpoints remain exact provided the transform fails + deterministically; in multi-rank training each rank must save its + own ``state_dict`` and the states must be combined with + ``merge_state_dicts`` before resuming on a different topology. + Prefer the ``filter`` parameter when bad rows can be expressed as a + SQL predicate (e.g. ``"col IS NOT NULL"``) — filtering happens before + splits are built, so every guarantee is fully preserved. worker_info_override: If set, used in place of ``torch.utils.data.get_worker_info()`` to determine the DataLoader worker assignment. Intended for unit tests @@ -152,6 +200,7 @@ class StreamingDataset(IterableDataset): filter: Optional[str] = None, transform: Optional[Callable] = None, transform_parallelism: Optional[int] = None, + on_transform_error: Union[str, Callable[[Exception], bool]] = "raise", connection_factory: Optional[Callable[[str], Any]] = None, worker_info_override=None, ): @@ -167,6 +216,13 @@ class StreamingDataset(IterableDataset): ) if transform_parallelism is not None and transform_parallelism <= 0: raise ValueError("transform_parallelism must be greater than 0") + if on_transform_error not in ("raise", "skip", "warn") and not callable( + on_transform_error + ): + raise ValueError( + "on_transform_error must be 'raise', 'skip', 'warn', or a " + f"callable, got {on_transform_error!r}" + ) self._table = table self._num_splits = num_splits @@ -182,6 +238,7 @@ class StreamingDataset(IterableDataset): self._filter = filter self._transform = transform self._transform_parallelism = transform_parallelism + self._on_transform_error = on_transform_error self._connection_factory = connection_factory self._worker_info_override = worker_info_override @@ -199,19 +256,28 @@ class StreamingDataset(IterableDataset): # in the main process. RawArray is picklable via the forkserver # reduction protocol so it survives the dataset pickle round-trip. # Layout: [unscanned_rows, raw_rows, cooked_rows, consumed_rows, - # bytes_loaded, fetch_time_us, transform_time_us] - self._worker_stats: RawArray = RawArray(ctypes.c_int64, 7) + # bytes_loaded, fetch_time_us, transform_time_us, + # rows_skipped] + self._worker_stats: RawArray = RawArray(ctypes.c_int64, 8) # Cumulative bytes of Arrow buffer data fetched across all iterations. self._bytes_loaded: int = 0 # Cumulative seconds spent in LanceDB I/O and in transform functions. self._fetch_time: float = 0.0 self._transform_time: float = 0.0 + # Cumulative rows dropped by on_transform_error across all iterations. + self._rows_skipped: int = 0 # Number of samples each split has already been consumed. At global # step boundaries all splits have consumed this many samples, so a # single scalar captures the topology-independent checkpoint state. self._resume_offset: int = 0 + # Permutation position each split has consumed through, keyed by + # global split index. Equal to _resume_offset for every split unless + # on_transform_error skipped rows, in which case skipped positions + # push the watermark of the affected splits further ahead. Splits + # this instance has never iterated have no entry. + self._resume_positions: dict[int, int] = {} # Build the permutation table once, deterministically. builder = permutation_builder(table) @@ -275,6 +341,7 @@ class StreamingDataset(IterableDataset): # Set identity transform on each Permutation so __getitems__ returns # the raw RecordBatch. Stage 2 applies the real transform. permutations: list[Permutation] = [] + initial_positions: list[int] = [] for split_idx in my_splits: perm = Permutation.from_tables( self._table, self._perm_table, split=split_idx @@ -282,14 +349,20 @@ class StreamingDataset(IterableDataset): if self._columns is not None: perm = perm.select_columns(self._columns) perm = perm.with_transform(lambda batch: batch) - if self._resume_offset > 0: - perm = perm.with_skip(self._resume_offset) + start_pos = self._resume_positions.get(split_idx, self._resume_offset) + if start_pos > 0: + perm = perm.with_skip(start_pos) + initial_positions.append(start_pos) permutations.append(perm) n = len(permutations) split_sizes = [perm.num_rows for perm in permutations] initial_offset = self._resume_offset local_consumed = [0] * n + # Permutation position each split has consumed through (absolute, + # i.e. counted from the start of the unskipped split). Runs ahead of + # initial + local_consumed when rows are skipped. + pos_consumed = list(initial_positions) batch_size = self._read_batch_size max_prefetch = self._prefetch_batches @@ -302,12 +375,14 @@ class StreamingDataset(IterableDataset): self._transform if self._transform is not None else Transforms.arrow2python ) - # Per-split pipeline state. + # Per-split pipeline state. Batches are paired with the absolute + # permutation position of their first row so that skipped rows can be + # accounted for in pos_consumed. fetch_head = [0] * n - io_pending = [deque() for _ in range(n)] # Future[RecordBatch] - raw_batches = [deque() for _ in range(n)] # RecordBatch — fetched, awaiting tx - tx_pending = [deque() for _ in range(n)] # Future[list[Any]] - cooked = [deque() for _ in range(n)] # rows ready to yield + io_pending = [deque() for _ in range(n)] # (abs_start, Future[RecordBatch]) + raw_batches = [deque() for _ in range(n)] # (abs_start, RecordBatch) + tx_pending = [deque() for _ in range(n)] # Future[list[(abs_pos, row)]] + cooked = [deque() for _ in range(n)] # (abs_pos, row) ready to yield # Limit simultaneous transforms to transform_workers across all splits. tx_semaphore = threading.Semaphore(transform_workers) @@ -330,7 +405,8 @@ class StreamingDataset(IterableDataset): fetch_head[i] += fetch perm_i = permutations[i] indices = list(range(start, start + fetch)) - io_pending[i].append(io_pool.submit(_io_call, perm_i, indices)) + abs_start = initial_positions[i] + start + io_pending[i].append((abs_start, io_pool.submit(_io_call, perm_i, indices))) def _fill_io(i: int) -> None: while len(io_pending[i]) < max_prefetch and fetch_head[i] < split_sizes[i]: @@ -338,15 +414,72 @@ class StreamingDataset(IterableDataset): def _drain_io(i: int) -> None: """Move completed I/O futures into raw_batches non-blockingly.""" - while io_pending[i] and io_pending[i][0].done(): - raw_batches[i].append(io_pending[i].popleft().result()) + while io_pending[i] and io_pending[i][0][1].done(): + abs_start, fut = io_pending[i].popleft() + raw_batches[i].append((abs_start, fut.result())) # ── Stage 2 helpers ─────────────────────────────────────────────────── - def _tx_call_guarded(batch): + on_error = self._on_transform_error + + def _should_skip(exc: Exception) -> bool: + if on_error == "raise": + return False + if callable(on_error): + return bool(on_error(exc)) + return True # "skip" or "warn" + + def _check_row_count(rows: list, num_rows: int) -> None: + if len(rows) != num_rows: + raise ValueError( + f"transform returned {len(rows)} rows for a batch of " + f"{num_rows}; transforms must return exactly one output " + "row per input row. To drop bad rows, raise inside the " + "transform and pass on_transform_error='skip'." + ) + + def _transform_isolated(abs_start, batch, batch_exc): + """Re-run the transform on single-row slices, dropping failures.""" + out = [] + skipped = 0 + first_exc = None + for j in range(batch.num_rows): + try: + rows = list(final_transform(batch.slice(j, 1))) + except Exception as exc: + if not _should_skip(exc): + raise + skipped += 1 + if first_exc is None: + first_exc = exc + continue + _check_row_count(rows, 1) + out.append((abs_start + j, rows[0])) + self._rows_skipped += skipped + if skipped and on_error == "warn": + logger.warning( + "Skipped %d of %d rows whose transform failed (first error: %r)", + skipped, + batch.num_rows, + first_exc if first_exc is not None else batch_exc, + ) + return out + + def _transform_batch(abs_start, batch): + """Apply the transform, returning [(abs_pos, row), ...].""" + try: + rows = list(final_transform(batch)) + except Exception as exc: + if not _should_skip(exc): + raise + return _transform_isolated(abs_start, batch, exc) + _check_row_count(rows, batch.num_rows) + return [(abs_start + j, row) for j, row in enumerate(rows)] + + def _tx_call_guarded(abs_start, batch): try: t0 = time.perf_counter() - result = final_transform(batch) + result = _transform_batch(abs_start, batch) self._transform_time += time.perf_counter() - t0 return result finally: @@ -355,8 +488,8 @@ class StreamingDataset(IterableDataset): def _try_submit_tx(i: int) -> None: """Submit transforms for raw_batches[i] up to available capacity.""" while raw_batches[i] and tx_semaphore.acquire(blocking=False): - batch = raw_batches[i].popleft() - tx_pending[i].append(tx_pool.submit(_tx_call_guarded, batch)) + abs_start, batch = raw_batches[i].popleft() + tx_pending[i].append(tx_pool.submit(_tx_call_guarded, abs_start, batch)) def _drain_tx(i: int) -> None: """Move completed transform futures into cooked non-blockingly.""" @@ -384,11 +517,14 @@ class StreamingDataset(IterableDataset): # Acquire a transform slot (may block briefly if all # transform_workers are busy with other splits). tx_semaphore.acquire() - batch = raw_batches[i].popleft() - tx_pending[i].append(tx_pool.submit(_tx_call_guarded, batch)) + abs_start, batch = raw_batches[i].popleft() + tx_pending[i].append( + tx_pool.submit(_tx_call_guarded, abs_start, batch) + ) elif io_pending[i]: # Block on the oldest in-flight I/O fetch. - raw_batches[i].append(io_pending[i].popleft().result()) + abs_start, fut = io_pending[i].popleft() + raw_batches[i].append((abs_start, fut.result())) _advance(i) else: break # split exhausted @@ -407,15 +543,28 @@ class StreamingDataset(IterableDataset): _fill_io(i) while True: - # Stop when any split is exhausted (all exhaust - # simultaneously: equal split sizes + round-robin). - if any(local_consumed[i] >= split_sizes[i] for i in range(n)): + # A cycle only runs if every split can still produce a + # row. Without skips all splits exhaust simultaneously + # (equal split sizes + round-robin); when + # on_transform_error drops rows a split can run dry + # early, ending the epoch at the last complete cycle. + # This check only sees splits owned by this rank/worker + # (my_splits) — there is no cross-rank coordination, so + # a different rank with fewer skipped rows keeps going; + # see the on_transform_error docstring. + exhausted = False + for i in range(n): + _ensure_cooked(i) + if not cooked[i]: + exhausted = True + break + if exhausted: break for i in range(n): - _ensure_cooked(i) - row = cooked[i].popleft() + pos, row = cooked[i].popleft() local_consumed[i] += 1 + pos_consumed[i] = pos + 1 _advance(i) # After the last split in each cycle: update the @@ -424,21 +573,39 @@ class StreamingDataset(IterableDataset): # even when __iter__ runs in a worker process. if i == n - 1: self._resume_offset = initial_offset + local_consumed[i] + for j, split_idx in enumerate(my_splits): + self._resume_positions[split_idx] = pos_consumed[j] ws = self._worker_stats ws[0] = sum( split_sizes[j] - fetch_head[j] for j in range(n) ) ws[1] = sum( - batch.num_rows for q in raw_batches for batch in q + batch.num_rows + for q in raw_batches + for _, batch in q ) ws[2] = sum(len(q) for q in cooked) ws[3] = sum(local_consumed) ws[4] = self._bytes_loaded ws[5] = int(self._fetch_time * 1_000_000) ws[6] = int(self._transform_time * 1_000_000) + ws[7] = self._rows_skipped yield row finally: + # Final stats flush: the per-cycle write above never runs + # when iteration ends mid-cycle (e.g. a split whose rows + # were all skipped before completing a single cycle), so + # counters like rows_skipped would otherwise be stale. + ws = self._worker_stats + ws[0] = sum(split_sizes[j] - fetch_head[j] for j in range(n)) + ws[1] = 0 # queue-depth properties document 0 when idle + ws[2] = 0 + ws[3] = sum(local_consumed) + ws[4] = self._bytes_loaded + ws[5] = int(self._fetch_time * 1_000_000) + ws[6] = int(self._transform_time * 1_000_000) + ws[7] = self._rows_skipped self._raw_batches_ref = None self._cooked_ref = None self._fetch_head_ref = None @@ -492,7 +659,7 @@ class StreamingDataset(IterableDataset): batches. Returns 0 when not iterating. """ if self._raw_batches_ref is not None: - return sum(batch.num_rows for q in self._raw_batches_ref for batch in q) + return sum(batch.num_rows for q in self._raw_batches_ref for _, batch in q) return int(self._worker_stats[1]) @property @@ -522,6 +689,19 @@ class StreamingDataset(IterableDataset): ) return int(self._worker_stats[0]) + @property + def rows_skipped(self) -> int: + """Number of rows dropped because their transform raised an exception. + + Only ever non-zero when ``on_transform_error`` is set to ``"skip"``, + ``"warn"``, or a callable that returned ``True``. Accumulates across + multiple iterations of the same dataset instance and is never reset + automatically. + """ + if self._raw_batches_ref is not None: + return self._rows_skipped + return int(self._worker_stats[7]) + @property def consumed_rows(self) -> int: """Number of rows already yielded to the caller across all splits. @@ -587,12 +767,27 @@ class StreamingDataset(IterableDataset): every split has been consumed the same number of times (by the round-robin design), so the per-split count is a single uniform value that is identical across all ranks and DataLoader workers. + + ``positions_consumed_per_split`` records how far into each split's + permutation iteration has advanced. It only differs from + ``samples_consumed_per_split`` when ``on_transform_error`` skipped + rows, in which case entries are exact for the splits this instance + iterated and a lower bound (the sample count) for splits owned by + other ranks or workers. Combine the state dicts from all ranks with + [merge_state_dicts][lancedb.streaming.StreamingDataset.merge_state_dicts] + to recover the exact value for every split before resuming on a + different topology. """ + positions = [ + self._resume_positions.get(split, self._resume_offset) + for split in range(self._num_splits) + ] return { "shuffle_seed": self._shuffle_seed, "num_splits": self._num_splits, "epoch": self._epoch, "samples_consumed_per_split": [self._resume_offset] * self._num_splits, + "positions_consumed_per_split": positions, } def load_state_dict(self, state: dict) -> None: @@ -618,3 +813,96 @@ class StreamingDataset(IterableDataset): self._resume_offset = consumed[0] if consumed else 0 else: self._resume_offset = int(consumed) + # Older checkpoints predate positions_consumed_per_split; without + # skipped rows positions equal sample counts, so falling back to + # _resume_offset (the .get default in __iter__) is exact. + positions = state.get("positions_consumed_per_split") + if positions is None: + self._resume_positions = {} + else: + self._resume_positions = { + split: int(pos) for split, pos in enumerate(positions) + } + + @staticmethod + def merge_state_dicts(states: list[dict]) -> dict: + """Merge state dicts saved by different ranks into one exact state. + + Only needed when ``on_transform_error`` skips rows in multi-rank + training: each rank then knows the exact permutation position only for + its own splits, and records a lower bound for the rest. Because + exactly one rank owns each split, the elementwise maximum across all + ranks' ``positions_consumed_per_split`` recovers the exact position of + every split. Without skipped rows every rank's state is already + identical and merging is a no-op. + + Raises ``ValueError`` if the states are empty or were not produced by + the same run (mismatched seed, split count, epoch, or sample counts). + + The merge is always all-to-all and topology-agnostic: collect the + ``state_dict()`` from every rank of the *previous* run into one list, + merge that whole list, and hand the identical merged result to every + rank of the *next* run — regardless of whether the rank count grew, + shrank, or stayed the same. There is no pairwise or subset merging + step, because each split's exact position is only known to whichever + rank owned that split, and the elementwise maximum needs every rank's + contribution to be correct. + + For example, checkpointing 8 ranks and resuming on 4 (the same + pattern applies when growing, e.g. 4 ranks resuming on 8):: + + states = [ds.state_dict() for ds in previous_run_datasets] # 8 + merged = StreamingDataset.merge_state_dicts(states) + for ds in resumed_datasets: # now only 4 ranks + ds.load_state_dict(merged) # same dict on every rank + + The rank count on either side never affects the merge itself, since + ``merge_state_dicts`` only cares about the list of states it is + given. Each split's position is recovered by elementwise maximum; + here rank 0 owned split 0 (and skipped two rows there) while rank 1 + owned split 1 (and skipped one row): + + >>> rank0 = { + ... "shuffle_seed": 0, "num_splits": 2, "epoch": 0, + ... "samples_consumed_per_split": [3, 3], + ... "positions_consumed_per_split": [5, 3], + ... } + >>> rank1 = { + ... "shuffle_seed": 0, "num_splits": 2, "epoch": 0, + ... "samples_consumed_per_split": [3, 3], + ... "positions_consumed_per_split": [3, 4], + ... } + >>> merged = StreamingDataset.merge_state_dicts([rank0, rank1]) + >>> merged["positions_consumed_per_split"] + [5, 4] + """ + if not states: + raise ValueError("merge_state_dicts requires at least one state dict") + first = states[0] + for state in states[1:]: + for key in ("shuffle_seed", "num_splits", "epoch"): + if state[key] != first[key]: + raise ValueError( + f"{key} mismatch across state dicts: " + f"{state[key]} != {first[key]}" + ) + if ( + state["samples_consumed_per_split"] + != first["samples_consumed_per_split"] + ): + raise ValueError( + "samples_consumed_per_split mismatch across state dicts; " + "state_dict() must be called at the same global step " + "boundary on every rank" + ) + merged = dict(first) + all_positions = [ + state.get( + "positions_consumed_per_split", state["samples_consumed_per_split"] + ) + for state in states + ] + merged["positions_consumed_per_split"] = [ + max(per_split) for per_split in zip(*all_positions) + ] + return merged diff --git a/python/python/tests/test_elastic_dataloader.py b/python/python/tests/test_elastic_dataloader.py index 22918082b..734f835c6 100644 --- a/python/python/tests/test_elastic_dataloader.py +++ b/python/python/tests/test_elastic_dataloader.py @@ -1456,6 +1456,408 @@ def test_shuffle_clump_size_yields_all_rows(lance_table): ) +# --------------------------------------------------------------------------- +# on_transform_error tests +# --------------------------------------------------------------------------- + + +class BadRowError(ValueError): + """Raised by the failing transforms below when a batch contains a bad id.""" + + +def _failing_transform(bad_ids: set): + """A transform that raises BadRowError whenever the batch has a bad id. + + Raises on the full batch and on any single-row slice containing a bad id, + so per-row isolation drops exactly the bad rows. + """ + + def transform(batch: pa.RecordBatch) -> list: + ids = batch.column("id").to_pylist() + bad = sorted(set(ids) & bad_ids) + if bad: + raise BadRowError(f"bad ids in batch: {bad}") + return [{"id": i} for i in ids] + + return transform + + +def _sequential_split_members(table) -> list[list[int]]: + """Return each split's ids in yield order for shuffle=False. + + With a single rank and no workers the round-robin yields one row per split + per cycle, so item k of a clean run belongs to split k % NUM_SPLITS. + """ + ds = StreamingDataset(table, num_splits=NUM_SPLITS, shuffle=False) + members: list[list[int]] = [[] for _ in range(NUM_SPLITS)] + for k, row in enumerate(ds): + members[k % NUM_SPLITS].append(row["id"]) + return members + + +def test_on_transform_error_default_raises(lance_table): + """By default a transform exception propagates and aborts iteration.""" + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + transform=_failing_transform({7}), + ) + with pytest.raises(BadRowError): + list(ds) + + +def test_on_transform_error_invalid_value(lance_table): + with pytest.raises(ValueError, match="on_transform_error"): + StreamingDataset(lance_table, num_splits=NUM_SPLITS, on_transform_error="bogus") + + +def test_on_transform_error_skip_drops_bad_rows(lance_table): + """With one bad row per split, 'skip' yields every good row exactly once + and counts the dropped rows in rows_skipped.""" + members = _sequential_split_members(lance_table) + bad_ids = {members[i][4] for i in range(NUM_SPLITS)} + + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle=False, + transform=_failing_transform(bad_ids), + on_transform_error="skip", + ) + assert ds.rows_skipped == 0 + + ids = [row["id"] for row in ds] + + assert sorted(ids) == sorted(set(range(NUM_ROWS)) - bad_ids) + assert ds.rows_skipped == NUM_SPLITS + + +def test_on_transform_error_skip_uneven_ends_at_last_complete_cycle(lance_table): + """When one split loses more rows than the others, the epoch ends at the + last cycle where every split still has a row — no crash, no bad rows, and + every step remains one sample per split.""" + members = _sequential_split_members(lance_table) + bad_ids = set(members[0][:3]) # all 3 bad rows in split 0 + + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle=False, + transform=_failing_transform(bad_ids), + on_transform_error="skip", + ) + items = [row["id"] for row in ds] + + rows_per_split = NUM_ROWS // NUM_SPLITS + expected_cycles = rows_per_split - len(bad_ids) + assert len(items) == expected_cycles * NUM_SPLITS + assert len(set(items)) == len(items), "duplicate samples yielded" + assert not set(items) & bad_ids, "a bad row was yielded" + # Split 0 contributed exactly its surviving rows, in order, one per cycle. + survivors = [i for i in members[0] if i not in bad_ids] + assert items[0::NUM_SPLITS] == survivors[:expected_cycles] + + +def test_on_transform_error_warn_logs(lance_table, caplog): + """'warn' skips like 'skip' but logs a warning for the failing batch.""" + members = _sequential_split_members(lance_table) + bad_ids = {members[i][3] for i in range(NUM_SPLITS)} + + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle=False, + transform=_failing_transform(bad_ids), + on_transform_error="warn", + ) + with caplog.at_level(logging.WARNING, logger="lancedb.streaming"): + items = list(ds) + + assert len(items) == NUM_ROWS - NUM_SPLITS + assert ds.rows_skipped == NUM_SPLITS + assert "Skipped" in caplog.text + assert "BadRowError" in caplog.text + + +def test_on_transform_error_callable_selective(lance_table): + """A callable handler can skip expected errors and re-raise the rest.""" + members = _sequential_split_members(lance_table) + bad_ids = {members[i][0] for i in range(NUM_SPLITS)} + + handled: list[Exception] = [] + + def handler(exc: Exception) -> bool: + handled.append(exc) + return isinstance(exc, BadRowError) + + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle=False, + transform=_failing_transform(bad_ids), + on_transform_error=handler, + ) + items = list(ds) + assert len(items) == NUM_ROWS - NUM_SPLITS + assert handled and all(isinstance(exc, BadRowError) for exc in handled) + + def broken_transform(batch: pa.RecordBatch) -> list: + raise TypeError("boom") + + ds2 = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle=False, + transform=broken_transform, + on_transform_error=handler, + ) + with pytest.raises(TypeError, match="boom"): + list(ds2) + + +def test_transform_wrong_row_count_raises(lance_table): + """A transform that returns the wrong number of rows is an error even with + on_transform_error='skip' — silent shrinkage would corrupt accounting.""" + + def drops_rows(batch: pa.RecordBatch) -> list: + return batch.column("id").to_pylist()[:-1] + + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + transform=drops_rows, + on_transform_error="skip", + ) + with pytest.raises(ValueError, match="one output row per input row"): + list(ds) + + +def test_skip_deterministic_across_runs(lance_table): + """With a fixed seed, skipping produces the identical sample sequence on + every run — skips are data-dependent, not run-dependent.""" + bad_ids = {5, 17, 46} + + def run() -> tuple[list[int], int]: + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + transform=_failing_transform(bad_ids), + on_transform_error="skip", + ) + return [row["id"] for row in ds], ds.rows_skipped + + ids_a, skipped_a = run() + ids_b, skipped_b = run() + assert ids_a == ids_b + assert skipped_a == skipped_b + assert not set(ids_a) & bad_ids + + +def test_skip_elastic_det_across_world_sizes(lance_table): + """With equal bad-row counts per split, skipping preserves the full + elastic-determinism guarantee: identical global batches at every step for + every compatible world_size.""" + members = _sequential_split_members(lance_table) + bad_ids = {members[i][6] for i in range(NUM_SPLITS)} + + def collect(world_size: int) -> list[frozenset[int]]: + micro = GLOBAL_BATCH_SIZE // world_size + iters = [ + iter( + StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle=False, + rank=rank, + world_size=world_size, + transform=_failing_transform(bad_ids), + on_transform_error="skip", + ) + ) + for rank in range(world_size) + ] + _STOP = object() + batches: list[frozenset[int]] = [] + while True: + step_samples: set[int] = set() + exhausted = 0 + for it in iters: + for _ in range(micro): + val = next(it, _STOP) + if val is _STOP: + exhausted += 1 + break + step_samples.add(val["id"]) + if exhausted == len(iters): + break + assert exhausted == 0, ( + "Rank iterators exhausted at different steps despite equal " + "bad-row counts per split" + ) + batches.append(frozenset(step_samples)) + return batches + + reference = collect(1) + assert len(reference) == NUM_ROWS // NUM_SPLITS - 1 + for ws in (2, 3, 4): + assert collect(ws) == reference, f"world_size={ws} diverged" + + +def test_resumability_with_skips_same_topology(lance_table): + """Checkpointing mid-epoch with skipped rows resumes exactly: no sample + repeated, no sample lost, skipped rows stay skipped.""" + members = _sequential_split_members(lance_table) + # Uneven skips: positions diverge across splits (2 bad in split 0, 1 in + # split 5), which only a position-based checkpoint can resume exactly. + bad_ids = {members[0][2], members[0][3], members[5][7]} + kwargs = dict( + num_splits=NUM_SPLITS, + shuffle=False, + transform=_failing_transform(bad_ids), + on_transform_error="skip", + ) + + reference = [row["id"] for row in StreamingDataset(lance_table, **kwargs)] + rows_per_split = NUM_ROWS // NUM_SPLITS + assert len(reference) == (rows_per_split - 2) * NUM_SPLITS + + steps = 3 + ds = StreamingDataset(lance_table, **kwargs) + it = iter(ds) + consumed = [next(it)["id"] for _ in range(steps * NUM_SPLITS)] + checkpoint = ds.state_dict() + it.close() + + # Split 0 skipped positions 2 and 3 within its first 3 yields; split 5's + # bad row is beyond the checkpoint. Everything else is at 3 = the sample + # count. + positions = checkpoint["positions_consumed_per_split"] + assert positions[0] == 5 + assert positions[1:] == [3] * (NUM_SPLITS - 1) + assert checkpoint["samples_consumed_per_split"] == [3] * NUM_SPLITS + + ds2 = StreamingDataset(lance_table, **kwargs) + ds2.load_state_dict(checkpoint) + resumed = [row["id"] for row in ds2] + + assert consumed == reference[: steps * NUM_SPLITS] + assert resumed == reference[steps * NUM_SPLITS :] + + +def test_resumability_with_skips_elastic_merge(lance_table): + """Elastic resume with skips: each rank's checkpoint knows exact positions + only for its own splits; merge_state_dicts recovers the global state, and + a run on a different world_size continues exactly.""" + members = _sequential_split_members(lance_table) + # Bad rows early in split 0 (rank 0) and split 6 (rank 1 of a ws=2 run) so + # both ranks' position vectors diverge before the checkpoint. + bad_ids = {members[0][0], members[0][2], members[6][1]} + kwargs = dict( + num_splits=NUM_SPLITS, + shuffle=False, + transform=_failing_transform(bad_ids), + on_transform_error="skip", + ) + + reference = [row["id"] for row in StreamingDataset(lance_table, **kwargs)] + + steps = 3 + world_size = 2 + micro = GLOBAL_BATCH_SIZE // world_size + datasets = [ + StreamingDataset(lance_table, rank=rank, world_size=world_size, **kwargs) + for rank in range(world_size) + ] + iters = [iter(ds) for ds in datasets] + seen: list[frozenset[int]] = [] + for _ in range(steps): + step_samples = set() + for it in iters: + for _ in range(micro): + step_samples.add(next(it)["id"]) + seen.append(frozenset(step_samples)) + states = [ds.state_dict() for ds in datasets] + for it in iters: + it.close() + + merged = StreamingDataset.merge_state_dicts(states) + expected_positions = [3] * NUM_SPLITS + expected_positions[0] = 5 # skipped positions 0 and 2 + expected_positions[6] = 4 # skipped position 1 + assert merged["positions_consumed_per_split"] == expected_positions + + # The first 3 global batches match the world_size=1 reference. + ref_batches = [ + frozenset(reference[s * NUM_SPLITS : (s + 1) * NUM_SPLITS]) + for s in range(len(reference) // NUM_SPLITS) + ] + assert seen == ref_batches[:steps] + + # Resume on world_size=1 from the merged state. + ds_resume = StreamingDataset(lance_table, **kwargs) + ds_resume.load_state_dict(merged) + resumed = [row["id"] for row in ds_resume] + assert resumed == reference[steps * NUM_SPLITS :] + + +def test_rows_skipped_flushed_when_split_entirely_bad(lance_table): + """A split whose rows all fail never completes a cycle, so the epoch ends + immediately — but rows_skipped must still report the drops after the + iterator exits (the shared-memory counter is flushed on exhaustion).""" + members = _sequential_split_members(lance_table) + bad_ids = set(members[0]) # every row of split 0 is bad + + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle=False, + transform=_failing_transform(bad_ids), + on_transform_error="skip", + ) + assert list(ds) == [] + assert ds.rows_skipped == len(bad_ids) + + +def test_merge_state_dicts_validates_consistency(lance_table): + ds = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED) + state = ds.state_dict() + other = dict(state, shuffle_seed=SHUFFLE_SEED + 1) + with pytest.raises(ValueError, match="shuffle_seed mismatch"): + StreamingDataset.merge_state_dicts([state, other]) + with pytest.raises(ValueError, match="at least one"): + StreamingDataset.merge_state_dicts([]) + + +def test_load_state_dict_without_positions_key(lance_table): + """Checkpoints from before positions_consumed_per_split existed still + resume exactly (positions equal sample counts when nothing is skipped).""" + reference = [ + row["id"] + for row in StreamingDataset( + lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED + ) + ] + + steps = 4 + ds = StreamingDataset(lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED) + it = iter(ds) + for _ in range(steps * NUM_SPLITS): + next(it) + checkpoint = ds.state_dict() + it.close() + del checkpoint["positions_consumed_per_split"] + + ds2 = StreamingDataset( + lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED + ) + ds2.load_state_dict(checkpoint) + resumed = [row["id"] for row in ds2] + assert resumed == reference[steps * NUM_SPLITS :] + + def test_num_splits_defaults_to_world_size(lance_table): """Omitting num_splits gives world_size splits (one per rank).""" ds = StreamingDataset( From 6fb976cf894f5b83cd24c6d7930fc6ace47e0c52 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Tue, 11 Aug 2026 23:43:44 -0700 Subject: [PATCH 028/206] chore: update lance dependency to v11.0.0-beta.6 (#3922) Updates the Rust workspace Lance dependencies and Java lance-core dependency to v11.0.0-beta.6. Includes compatibility updates for the new concrete Lance file-version API. Trigger: https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.6 --------- Co-authored-by: XYZhan --- Cargo.lock | 84 ++++++++++----------- Cargo.toml | 28 +++---- deny.toml | 7 ++ java/pom.xml | 2 +- rust/lancedb/src/blob.rs | 11 ++- rust/lancedb/src/connection/create_table.rs | 5 +- rust/lancedb/src/table.rs | 4 +- rust/lancedb/tests/blob_integration.rs | 31 ++++---- 8 files changed, 93 insertions(+), 79 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ec6b7cbfb..c5545ea8a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arc-swap", "arrow", @@ -4890,8 +4890,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow-array", "arrow-buffer", @@ -4913,7 +4913,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow-array", "arrow-buffer", @@ -4927,7 +4927,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow-array", "arrow-schema", @@ -4936,8 +4936,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrayref", "crunchy", @@ -4947,8 +4947,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow-array", "arrow-buffer", @@ -4988,8 +4988,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow", "arrow-array", @@ -5019,8 +5019,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow", "arrow-array", @@ -5037,8 +5037,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "proc-macro2", "quote", @@ -5047,8 +5047,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow-arith", "arrow-array", @@ -5082,8 +5082,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow-arith", "arrow-array", @@ -5114,8 +5114,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arc-swap", "arrow", @@ -5182,8 +5182,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow-array", "arrow-schema", @@ -5205,8 +5205,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow", "arrow-array", @@ -5242,8 +5242,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow-array", "arrow-buffer", @@ -5259,8 +5259,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow", "async-trait", @@ -5272,8 +5272,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow", "arrow-ipc", @@ -5326,8 +5326,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow-array", "arrow-buffer", @@ -5342,8 +5342,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow", "arrow-array", @@ -5383,8 +5383,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "arrow-array", "arrow-schema", @@ -5397,8 +5397,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.3#f7d475539cefbd140cc46a828f3d843e68cd10f1" +version = "11.0.0-beta.6" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 936660d78..b1eae918e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.3", default-features = false, "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.3", default-features = false, "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.3", default-features = false, "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.3", "tag" = "v11.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.6", default-features = false, "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.6", default-features = false, "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.6", default-features = false, "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } ahash = "0.8" # Note that this one does not include pyarrow arrow = { version = "58.0.0", optional = false } diff --git a/deny.toml b/deny.toml index 034b48c25..d94c9d536 100644 --- a/deny.toml +++ b/deny.toml @@ -101,6 +101,13 @@ ignore = [ # https://rustsec.org/advisories/RUSTSEC-2026-0195 { id = "RUSTSEC-2026-0194", reason = "transitive via inferno/lance/opendal; XML from trusted cloud endpoints, not attacker-controlled" }, { id = "RUSTSEC-2026-0195", reason = "transitive via inferno/lance/opendal; XML from trusted cloud endpoints, not attacker-controlled" }, + # smartstring: unmaintained — the repository was archived by its author on + # 2026-05-03. Not a vulnerability. Reached only transitively through polars + # (polars-core/-io/-ops/-time/-utils); nothing in LanceDB depends on it directly. + # The advisory states no safe upgrade is available: upstream recommends + # compact_str/smol_str, so clearing this requires polars to migrate. + # https://rustsec.org/advisories/RUSTSEC-2026-0249 + { id = "RUSTSEC-2026-0249", reason = "smartstring unmaintained via polars; no fixed upstream release" }, ] # --------------------------------------------------------------------------- diff --git a/java/pom.xml b/java/pom.xml index f85b5c906..3fec2726a 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.3 + 11.0.0-beta.6 false 2.30.0 1.7 diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index e1c18dd84..d59123ec3 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -17,7 +17,7 @@ use arrow_array::builder::LargeBinaryBuilder; use arrow_schema::{DataType, Field, Schema}; use lance::dataset::{BlobRangeRequest as LanceBlobRangeRequest, Dataset, WriteParams}; use lance_arrow::FieldExt; -use lance_file::version::LanceFileVersion; +use lance_file::version::{ConcreteFileVersion, LanceFileVersion}; use lance_io::object_store::ObjectStore; use object_store::path::Path; @@ -333,7 +333,10 @@ pub(crate) fn ensure_blob_storage_version(schema: &Schema, params: &mut WritePar .data_storage_version .unwrap_or(LanceFileVersion::Stable) .resolve(); - if resolved < LanceFileVersion::V2_2 { + if matches!( + resolved, + ConcreteFileVersion::V1 | ConcreteFileVersion::V2_0 | ConcreteFileVersion::V2_1 + ) { params.data_storage_version = Some(LanceFileVersion::V2_2); } } @@ -499,7 +502,7 @@ mod tests { ensure_blob_storage_version(&blob_schema(), &mut params); assert_eq!( params.data_storage_version.unwrap().resolve(), - LanceFileVersion::V2_2 + ConcreteFileVersion::V2_2 ); } @@ -512,7 +515,7 @@ mod tests { ensure_blob_storage_version(&blob_schema(), &mut params); assert_eq!( params.data_storage_version.unwrap().resolve(), - LanceFileVersion::V2_2 + ConcreteFileVersion::V2_2 ); } diff --git a/rust/lancedb/src/connection/create_table.rs b/rust/lancedb/src/connection/create_table.rs index b10141beb..39cc82ec0 100644 --- a/rust/lancedb/src/connection/create_table.rs +++ b/rust/lancedb/src/connection/create_table.rs @@ -438,10 +438,9 @@ mod tests { .await .unwrap() .data_storage_format - .lance_file_version() - .unwrap(); + .lance_file_format(); // Compare resolved versions since Stable/Next are aliases that resolve at storage time - assert_eq!(storage_format.resolve(), data_storage_version.resolve()); + assert_eq!(storage_format, data_storage_version.resolve()); } #[tokio::test] diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 5120c48b7..d03ac823f 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -5339,7 +5339,7 @@ mod tests { pub async fn test_stats_includes_index_and_overlay_files() { use lance::dataset::WriteDestination; use lance::dataset::transaction::{DataOverlayGroup, Operation}; - use lance_file::version::{ConcreteFileVersion, LanceFileVersion}; + use lance_file::version::stable_file_version; use lance_file::writer::FileWriterOptions; use lance_io::utils::CachedFileSize; use lance_table::format::DataFile; @@ -5405,7 +5405,7 @@ mod tests { let fragment_id = dataset.get_fragments()[0].id() as u64; let foo_field_id = dataset.schema().field("foo").unwrap().id; let overlay_schema = dataset.schema().project_by_ids(&[foo_field_id], true); - let file_version = ConcreteFileVersion::from(LanceFileVersion::Stable); + let file_version = stable_file_version(); let filename = "overlay.lance".to_string(); let store = dataset.object_store(None).await.unwrap(); diff --git a/rust/lancedb/tests/blob_integration.rs b/rust/lancedb/tests/blob_integration.rs index 77d49abd9..b92f961f4 100644 --- a/rust/lancedb/tests/blob_integration.rs +++ b/rust/lancedb/tests/blob_integration.rs @@ -10,7 +10,7 @@ use arrow_array::{ use arrow_schema::{DataType, Field, Fields, Schema}; use futures::TryStreamExt; use lance::Dataset; -use lance_file::version::LanceFileVersion; +use lance_file::version::{ConcreteFileVersion, LanceFileVersion}; use lancedb::{ Connection, Error, Result, Table, blob::{BlobRangeRequest, blob}, @@ -61,7 +61,7 @@ async fn create_inline_blob_table( Ok(table) } -async fn storage_format_version(table: &Table) -> LanceFileVersion { +async fn storage_format_version(table: &Table) -> ConcreteFileVersion { table .as_native() .unwrap() @@ -69,9 +69,14 @@ async fn storage_format_version(table: &Table) -> LanceFileVersion { .await .unwrap() .data_storage_format - .lance_file_version() - .unwrap() - .resolve() + .lance_file_format() +} + +fn supports_blob_v2(version: ConcreteFileVersion) -> bool { + matches!( + version, + ConcreteFileVersion::V2_2 | ConcreteFileVersion::V2_3 + ) } async fn uses_stable_row_ids(table: &Table) -> bool { @@ -112,7 +117,7 @@ async fn declaring_blob_column_bumps_format_and_enables_stable_row_ids() -> Resu .execute() .await?; - assert!(storage_format_version(&table).await >= LanceFileVersion::V2_2); + assert!(supports_blob_v2(storage_format_version(&table).await)); assert!(uses_stable_row_ids(&table).await); Ok(()) } @@ -127,7 +132,7 @@ async fn explicit_stable_row_id_setting_wins_over_blob_default() -> Result<()> { .execute() .await?; - assert!(storage_format_version(&table).await >= LanceFileVersion::V2_2); + assert!(supports_blob_v2(storage_format_version(&table).await)); assert!(!uses_stable_row_ids(&table).await); Ok(()) } @@ -139,7 +144,7 @@ async fn non_blob_table_keeps_default_format_and_row_id_setting() -> Result<()> let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])); let table = db.create_empty_table("t", schema).execute().await?; - assert!(storage_format_version(&table).await < LanceFileVersion::V2_2); + assert!(!supports_blob_v2(storage_format_version(&table).await)); assert!(!uses_stable_row_ids(&table).await); Ok(()) } @@ -171,7 +176,7 @@ async fn creating_with_blob_data_bumps_format() -> Result<()> { .unwrap(); let table = db.create_table("t", batch).execute().await?; - assert!(storage_format_version(&table).await >= LanceFileVersion::V2_2); + assert!(supports_blob_v2(storage_format_version(&table).await)); assert!(uses_stable_row_ids(&table).await); assert_eq!(table.count_rows(None).await?, 1); Ok(()) @@ -281,7 +286,7 @@ async fn connection_level_stable_row_id_setting_wins_over_blob_default() -> Resu .execute() .await?; - assert!(storage_format_version(&table).await >= LanceFileVersion::V2_2); + assert!(supports_blob_v2(storage_format_version(&table).await)); assert!(!uses_stable_row_ids(&table).await); Ok(()) } @@ -297,7 +302,7 @@ async fn namespace_create_applies_blob_defaults() -> Result<()> { .execute() .await?; - assert!(storage_format_version(&table).await >= LanceFileVersion::V2_2); + assert!(supports_blob_v2(storage_format_version(&table).await)); assert!(uses_stable_row_ids(&table).await); Ok(()) } @@ -474,7 +479,7 @@ async fn fetch_blobs_round_trips_nested_blob_column() -> Result<()> { let batch = RecordBatch::try_new(schema, vec![Arc::new(info_array) as ArrayRef]).unwrap(); let table = db.create_table("t", batch).execute().await?; - assert!(storage_format_version(&table).await >= LanceFileVersion::V2_2); + assert!(supports_blob_v2(storage_format_version(&table).await)); assert!(uses_stable_row_ids(&table).await); let ids = collect_row_ids(&table).await?; @@ -1305,7 +1310,7 @@ async fn optimize_preserves_blob_v2_null_and_empty_distinction() -> Result<()> { .await?; table.add(null_empty_input_batch()).execute().await?; assert!( - storage_format_version(&table).await >= LanceFileVersion::V2_2, + supports_blob_v2(storage_format_version(&table).await), "blob v2 columns require storage >= 2.2" ); From 031c3585a827c7fbe4467ef33d4be0fab63ec5f5 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Thu, 13 Aug 2026 05:37:19 -0700 Subject: [PATCH 029/206] chore: update lance dependency to v11.0.0-beta.7 (#3925) Updates the Rust workspace Lance dependencies and Java lance-core dependency to v11.0.0-beta.7. No compatibility fixes were required; full-workspace Clippy passes with warnings denied. Lance tag: https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.7 --------- Co-authored-by: Yang Cen <159225399+BubbleCal@users.noreply.github.com> --- .github/workflows/pypi-publish.yml | 10 ++++ Cargo.lock | 84 +++++++++++++++--------------- Cargo.toml | 28 +++++----- java/pom.xml | 2 +- 4 files changed, 67 insertions(+), 57 deletions(-) diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index 74b7d05e6..4f5a927dc 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -69,6 +69,16 @@ jobs: uses: actions/setup-python@v6 with: python-version: "3.10" + - name: Add swap for Arm fat LTO + if: matrix.config.platform == 'aarch64' + shell: bash + run: | + swap_file="$RUNNER_TEMP/lancedb-swap" + sudo fallocate --length 16G "$swap_file" + sudo chmod 600 "$swap_file" + sudo mkswap "$swap_file" + sudo swapon "$swap_file" + free -h - uses: ./.github/workflows/build_linux_wheel with: python-minor-version: 10 diff --git a/Cargo.lock b/Cargo.lock index c5545ea8a..04332a496 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arc-swap", "arrow", @@ -4890,8 +4890,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow-array", "arrow-buffer", @@ -4913,7 +4913,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow-array", "arrow-buffer", @@ -4927,7 +4927,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow-array", "arrow-schema", @@ -4936,8 +4936,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrayref", "crunchy", @@ -4947,8 +4947,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow-array", "arrow-buffer", @@ -4988,8 +4988,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow", "arrow-array", @@ -5019,8 +5019,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow", "arrow-array", @@ -5037,8 +5037,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "proc-macro2", "quote", @@ -5047,8 +5047,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow-arith", "arrow-array", @@ -5082,8 +5082,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow-arith", "arrow-array", @@ -5114,8 +5114,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arc-swap", "arrow", @@ -5182,8 +5182,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow-array", "arrow-schema", @@ -5205,8 +5205,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow", "arrow-array", @@ -5242,8 +5242,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow-array", "arrow-buffer", @@ -5259,8 +5259,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow", "async-trait", @@ -5272,8 +5272,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow", "arrow-ipc", @@ -5326,8 +5326,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow-array", "arrow-buffer", @@ -5342,8 +5342,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow", "arrow-array", @@ -5383,8 +5383,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "arrow-array", "arrow-schema", @@ -5397,8 +5397,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.6" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.6#5ab688688c411111d94d279bacd037d7c319dc10" +version = "11.0.0-beta.7" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index b1eae918e..33bf7e09b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.6", default-features = false, "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.6", default-features = false, "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.6", default-features = false, "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.6", "tag" = "v11.0.0-beta.6", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.7", default-features = false, "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.7", default-features = false, "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.7", default-features = false, "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } ahash = "0.8" # Note that this one does not include pyarrow arrow = { version = "58.0.0", optional = false } diff --git a/java/pom.xml b/java/pom.xml index 3fec2726a..4fdf77e81 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.6 + 11.0.0-beta.7 false 2.30.0 1.7 From 1d75638deaf2d79e8ab17e036fb63e423b1909ed Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Thu, 13 Aug 2026 21:22:42 +0800 Subject: [PATCH 030/206] fix: make table existence manifest-authoritative (#3919) ## What is the bug? #3731 tries to distinguish a missing table from a corrupt table after Lance returns `DatasetNotFound`. It does that by listing the database parent and treating a physical `.lance` entry as evidence that the table exists. That premise is not sound for a listing database. Table creation writes data before atomically committing the first manifest, so the same physical prefix can represent a live concurrent create, abandoned uncommitted data, or an old empty directory. It is not evidence of a committed table. The parent listing also makes every missing-table open, including the create-on-miss path, perform work proportional to the number of sibling tables. Cloud `list_with_delimiter` exhausts all pages before returning. ## How does this PR fix the problem? This PR makes the committed Lance manifest the sole table-existence authority for listing-database opens: - `DatasetNotFound` maps directly to `TableNotFound`; no parent or target storage probe runs. - Other Lance load errors continue to propagate unchanged. - A physical directory, object prefix, or uncommitted data file alone does not block `Create`. - Concurrent `Create` requests are arbitrated by the conditional version-1 manifest commit: one succeeds and the loser receives `TableAlreadyExists`. - `table_names` is documented as physical discovery, not an atomic table-existence check. Its snapshot can contain an entry that is still being created, has only uncommitted storage, or is concurrently dropped. This removes the need for a new Lance object-store capability. LanceDB remains on the official Lance `v11.0.0-beta.6` dependency from `main`; the merge commit for lance-format/lance#7722 is an ancestor of that tag, so the ambiguous-GCS-500 corruption-prevention fix is retained. ## Performance evidence Lower is better. The benchmark uses real `.lance` directories with marker objects on the local filesystem; fixture creation and teardown are outside the timed region. Baseline is `origin/main` at `6fb976cf`, candidate is `e1240751`. Both were built from the same lockfile on the same macOS arm64 machine with the repository's `release` profile (fat LTO), then executed in alternating baseline/candidate order for three pairs. Each run used 10 warmups and 100 distinct missing-table opens per scale. The table reports the median of the three run-level percentiles. | Scenario / metric | Baseline | This PR | Benefit | | --- | ---: | ---: | ---: | | 1,000 real sibling directories, p50 | 11.905 ms | 21.042 us | 566x speedup | | 10,000 real sibling directories, p50 | 143.630 ms | 18.375 us | 7,817x speedup | | 100,000 real sibling directories, p50 | 1.991 s | 19.917 us | 99,984x speedup | | 100,000 real sibling directories, p95 | 2.346 s | 25.792 us | 90,965x speedup | These results validate removal of the sibling-cardinality dependency in this local-filesystem workload; they are not an extrapolation to production GCS latency. A structural object-store regression test separately asserts that opening one missing table performs zero parent-scoped `list`, `list_with_offset`, or `list_with_delimiter` calls. Run with: ```bash BENCH_SIBLINGS=1000,10000,100000 BENCH_WARMUPS=10 BENCH_TRIALS=100 \ cargo run --locked --release --quiet -p lancedb --example bench_open_missing_table ``` ## Correctness and compatibility boundaries - An empty `.lance` directory or orphan data without a committed manifest now opens as `TableNotFound` and may be replaced by a successful `Create`. - Two synchronized creators sharing one object store deterministically produce one success and one conditional-manifest conflict mapped to `TableAlreadyExists`. - A readable manifest remains authoritative; non-`DatasetNotFound` corruption, external-manifest, authorization, and object-store errors are not folded into `TableNotFound`. - `TableCorrupted` remains in the public error enum for compatibility, but this listing-database fallback no longer synthesizes it from an ambiguous physical footprint. - Reliably distinguishing `Missing`, `Creating`, and `Corrupt` would require explicit authoritative lifecycle/catalog metadata (for example a leased creation record). It cannot be inferred from a directory or prefix, and is outside this incident fix. ## Validation - `cargo fmt --all -- --check` - `cargo check --quiet --locked -p lancedb --features remote --tests --examples` - `cargo clippy --quiet --locked -p lancedb --features remote --tests --examples -- -D warnings` - `cargo test --quiet --locked -p lancedb --features remote --tests` - library: 843 passed, 1 ignored - integration groups: 39 passed, 6 passed, 5 passed - focused coverage for empty directories, orphan data, physical listing snapshots, zero parent listings, and concurrent manifest arbitration --- rust/lancedb/Cargo.toml | 3 + .../examples/bench_open_missing_table.rs | 150 +++++++++ rust/lancedb/src/connection.rs | 12 +- rust/lancedb/src/database/listing.rs | 117 ++++++- rust/lancedb/src/table.rs | 299 ++++++++++++------ 5 files changed, 473 insertions(+), 108 deletions(-) create mode 100644 rust/lancedb/examples/bench_open_missing_table.rs diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index e33b86b12..23dc86e15 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -188,6 +188,9 @@ required-features = ["bedrock"] [[example]] name = "bench_streaming_dataloader" +[[example]] +name = "bench_open_missing_table" + [[example]] name = "simple" diff --git a/rust/lancedb/examples/bench_open_missing_table.rs b/rust/lancedb/examples/bench_open_missing_table.rs new file mode 100644 index 000000000..8e6b16e11 --- /dev/null +++ b/rust/lancedb/examples/bench_open_missing_table.rs @@ -0,0 +1,150 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +// Release benchmark for opening a missing table as sibling-table cardinality grows. +// +// The fixture uses real `.lance` directories and marker files. Fixture creation is +// outside the timed section. Defaults intentionally cover 1k, 10k, and 100k siblings +// with 10 warmups and 100 distinct missing-table opens per scale: +// +// ```text +// cargo run --release -p lancedb --example bench_open_missing_table +// ``` +// +// `BENCH_SIBLINGS`, `BENCH_WARMUPS`, and `BENCH_TRIALS` override those defaults. +// Reduced settings are useful only as a smoke test. Performance comparisons require +// the same machine, filesystem, fixture sizes, settings, lockfile, and alternating +// baseline/candidate execution order. + +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, bail}; +use lancedb::connection::Connection; +use lancedb::{Error, connect}; +use object_store::ObjectStoreExt as _; +use object_store::path::Path; + +const MAX_SIBLINGS: usize = 1_000_000; +const MAX_WARMUPS: usize = 10_000; +const MAX_TRIALS: usize = 100_000; + +fn env_usize(key: &str, default: usize, max: usize) -> Result { + let value = match std::env::var(key) { + Ok(value) => value + .parse() + .with_context(|| format!("invalid {key} value: {value}"))?, + Err(std::env::VarError::NotPresent) => default, + Err(error) => return Err(error).with_context(|| format!("reading {key}")), + }; + if value == 0 || value > max { + bail!("{key} must be between 1 and {max}"); + } + Ok(value) +} + +fn sibling_counts() -> Result> { + let raw = std::env::var("BENCH_SIBLINGS").unwrap_or_else(|_| "1000,10000,100000".into()); + let mut counts = raw + .split(',') + .map(|value| { + value + .trim() + .parse::() + .with_context(|| format!("invalid BENCH_SIBLINGS value: {value}")) + }) + .collect::>>()?; + counts.sort_unstable(); + counts.dedup(); + if counts.is_empty() || counts[0] == 0 || counts[counts.len() - 1] > MAX_SIBLINGS { + bail!("BENCH_SIBLINGS values must be between 1 and {MAX_SIBLINGS}"); + } + Ok(counts) +} + +async fn add_siblings( + store: &object_store::local::LocalFileSystem, + start: usize, + end: usize, +) -> Result<()> { + for index in start..end { + let marker = Path::from(format!("sibling_{index:06}.lance/_marker")); + store + .put(&marker, bytes::Bytes::new().into()) + .await + .with_context(|| format!("creating benchmark marker {marker}"))?; + } + Ok(()) +} + +async fn time_missing_open(db: &Connection, name: &str) -> Result { + let started = Instant::now(); + let result = db.open_table(name).execute().await; + let elapsed = started.elapsed(); + match result { + Err(Error::TableNotFound { .. }) => Ok(elapsed), + Err(error) => bail!("expected TableNotFound for {name}, got {error:?}"), + Ok(_) => bail!("benchmark missing-table name unexpectedly exists: {name}"), + } +} + +fn percentile(sorted: &[Duration], percentile: usize) -> Duration { + let rank = (sorted.len() * percentile).div_ceil(100).saturating_sub(1); + sorted[rank] +} + +#[tokio::main] +async fn main() -> Result<()> { + let counts = sibling_counts()?; + let warmups = env_usize("BENCH_WARMUPS", 10, MAX_WARMUPS)?; + let trials = env_usize("BENCH_TRIALS", 100, MAX_TRIALS)?; + + let fixture = tempfile::tempdir().context("creating benchmark fixture")?; + let database_path = fixture.path(); + let fixture_store = object_store::local::LocalFileSystem::new_with_prefix(database_path) + .context("creating benchmark object store")?; + let db = connect(database_path.to_str().context("non-UTF-8 fixture path")?) + .execute() + .await?; + + println!( + "config: siblings={counts:?} warmups={warmups} trials={trials} profile={} os={} arch={}", + if cfg!(debug_assertions) { + "debug" + } else { + "release" + }, + std::env::consts::OS, + std::env::consts::ARCH, + ); + println!("lower is better; fixture setup and teardown are excluded"); + println!("| siblings | samples | p50 | p95 | max |"); + println!("| ---: | ---: | ---: | ---: | ---: |"); + + let mut created = 0; + for sibling_count in counts { + add_siblings(&fixture_store, created, sibling_count).await?; + created = sibling_count; + + for index in 0..warmups { + let name = format!("__missing_warmup_{sibling_count}_{index}"); + let _ = time_missing_open(&db, &name).await?; + } + + let mut samples = Vec::with_capacity(trials); + for index in 0..trials { + let name = format!("__missing_trial_{sibling_count}_{index}"); + samples.push(time_missing_open(&db, &name).await?); + } + samples.sort_unstable(); + + println!( + "| {sibling_count} | {} | {:?} | {:?} | {:?} |", + samples.len(), + percentile(&samples, 50), + percentile(&samples, 95), + samples[samples.len() - 1], + ); + } + + Ok(()) +} diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index dd53a2d2e..1f2708d4e 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -409,6 +409,11 @@ impl Connection { /// /// The names will be returned in lexicographical order (ascending) /// + /// Listing databases discover physical `*.lance` entries without opening every + /// dataset. The result is a point-in-time discovery snapshot: an entry may still be + /// under creation, may contain only uncommitted storage, or may be concurrently + /// dropped before it is opened. + /// /// The parameters `page_token` and `limit` can be used to paginate the results pub fn table_names(&self) -> TableNamesBuilder { TableNamesBuilder::new(self.internal.clone()) @@ -456,10 +461,9 @@ impl Connection { /// /// # Returns /// Created [`TableRef`], or [`Error::TableNotFound`] if the table does not exist. - /// If the table's storage is present but holds no readable dataset (for example a - /// `.lance` directory left behind by an interrupted drop and re-create, which - /// [`Self::table_names`] still lists) this returns [`Error::TableCorrupted`] - /// instead. + /// On listing databases, a committed Lance manifest is authoritative for table + /// existence. Uncommitted files or a physical `.lance` directory alone do not + /// make a table openable. pub fn open_table(&self, name: impl Into) -> OpenTableBuilder { OpenTableBuilder::new( self.internal.clone(), diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index 0ab3614e7..f284320c6 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -1291,16 +1291,21 @@ impl Database for ListingDatabase { mod tests { use super::*; use crate::Table; + use crate::arrow::{SendableRecordBatchStream, SimpleRecordBatchStream}; use crate::connection::ConnectRequest; use crate::data::scannable::Scannable; use crate::database::{CreateTableMode, CreateTableRequest}; use crate::query::QueryRequest; use crate::table::{AnyQuery, WriteOptions}; use arrow_array::{Int32Array, RecordBatch, StringArray}; - use arrow_schema::{DataType, Field, Schema}; - use futures::TryStreamExt; + use arrow_schema::{DataType, Field, Schema, SchemaRef}; + use futures::{TryStreamExt, stream::once}; use std::path::PathBuf; + use std::sync::Arc; + use std::time::Duration; use tempfile::tempdir; + use tokio::sync::Barrier; + use tokio::time::timeout; async fn setup_database() -> (tempfile::TempDir, ListingDatabase) { let tempdir = tempdir().unwrap(); @@ -1324,6 +1329,114 @@ mod tests { (tempdir, db) } + struct BarrierScannable { + batch: RecordBatch, + barrier: Arc, + } + + impl Scannable for BarrierScannable { + fn schema(&self) -> SchemaRef { + self.batch.schema() + } + + fn scan_as_stream(&mut self) -> SendableRecordBatchStream { + let batch = self.batch.clone(); + let schema = batch.schema(); + let barrier = self.barrier.clone(); + Box::pin(SimpleRecordBatchStream { + schema, + stream: once(async move { + barrier.wait().await; + Ok(batch) + }), + }) + } + } + + fn create_request(name: &str, data: Box) -> CreateTableRequest { + CreateTableRequest { + name: name.to_string(), + namespace_path: vec![], + data, + mode: CreateTableMode::Create, + write_options: Default::default(), + location: None, + namespace_client: None, + } + } + + #[tokio::test] + async fn test_create_ignores_uncommitted_storage_without_manifest() { + let (tmp_dir, db) = setup_database().await; + let data_dir = tmp_dir.path().join("test.lance/data"); + std::fs::create_dir_all(&data_dir).unwrap(); + std::fs::write(data_dir.join("orphan.lance"), b"uncommitted").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![1]))]).unwrap(); + + let table = db + .create_table(create_request("test", Box::new(batch))) + .await + .unwrap(); + assert_eq!(table.count_rows(None).await.unwrap(), 1); + } + + #[tokio::test] + async fn test_concurrent_create_is_arbitrated_by_manifest_commit() { + let uri = format!("memory:///concurrent-create-{}", uuid::Uuid::new_v4()); + let db = crate::connect(&uri).execute().await.unwrap(); + let store: Arc = + Arc::new(object_store::memory::InMemory::new()); + let table_url = url::Url::parse("memory:///database/test.lance").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![1]))]).unwrap(); + let barrier = Arc::new(Barrier::new(2)); + + #[allow(deprecated)] + let request = |batch, barrier| { + let mut request = create_request("test", Box::new(BarrierScannable { batch, barrier })); + request.write_options = WriteOptions { + lance_write_params: Some(lance::dataset::WriteParams { + store_params: Some(ObjectStoreParams { + object_store: Some((store.clone(), table_url.clone())), + ..Default::default() + }), + commit_handler: Some(Arc::new( + lance_table::io::commit::ConditionalPutCommitHandler, + )), + ..Default::default() + }), + }; + request + }; + + let left = db + .database() + .create_table(request(batch.clone(), barrier.clone())); + let right = db.database().create_table(request(batch, barrier)); + let (left, right) = timeout(Duration::from_secs(30), async { tokio::join!(left, right) }) + .await + .expect("concurrent creates deadlocked"); + + let results = [left, right]; + assert_eq!( + results.iter().filter(|result| result.is_ok()).count(), + 1, + "expected one successful create, got {results:?}" + ); + assert_eq!( + results + .iter() + .filter(|result| matches!(result, Err(Error::TableAlreadyExists { .. }))) + .count(), + 1, + "expected one manifest conflict, got {results:?}" + ); + } + #[tokio::test] async fn test_listing_database_root_ops_do_not_create_manifest() { let tempdir = tempdir().unwrap(); diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index d03ac823f..32b6bcebc 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -50,7 +50,6 @@ use crate::DistanceType; use crate::blob::BlobRangeRequest; use crate::data::scannable::{PeekedScannable, Scannable, estimate_write_partitions}; use crate::database::Database; -use crate::database::listing::LANCE_FILE_EXTENSION; use crate::database::read_freshness::TableFreshness; use crate::embeddings::{EmbeddingDefinition, EmbeddingRegistry, MemoryRegistry}; use crate::error::{Error, Result}; @@ -152,55 +151,6 @@ pub(crate) fn map_namespace_lance_error(err: lance::Error, table_name: &str) -> } } -/// Map a `lance::Error::DatasetNotFound` for the table at `uri` into a `lancedb::Error`. -/// -/// Lance reports "there is nothing at this location" and "there is a table directory -/// here but nothing loadable inside it" with the same error. Only the first is a -/// `TableNotFound`: a `.lance` directory left behind by an interrupted drop and -/// re-create is still reported by `Connection::table_names`, so callers need to be able -/// to tell "never existed" from "exists but is broken". -/// -/// See . -async fn map_dataset_not_found( - uri: &str, - name: &str, - params: ReadParams, - err: lance::Error, -) -> Error { - let name = name.to_string(); - let source = Box::new(err); - if table_dir_exists(uri, params).await.unwrap_or(false) { - Error::TableCorrupted { name, source } - } else { - Error::TableNotFound { name, source } - } -} - -/// Whether a table directory is present at `uri`, even though no dataset could be -/// loaded from it. -/// -/// This looks for a `.lance` entry in the parent directory, which is exactly what -/// `ListingDatabase::table_names` lists, so the two APIs agree on whether a table is -/// present. Probing `uri` itself would not work: object stores have no empty -/// directories to probe, and on a local filesystem the interesting case is precisely an -/// empty directory. -async fn table_dir_exists(uri: &str, params: ReadParams) -> Result { - let (object_store, path, _) = DatasetBuilder::from_uri(uri) - .with_read_params(params) - .build_object_store() - .await?; - // Only `*.lance` entries are ever reported as tables, so nothing else can produce - // the list-then-open mismatch this guards against. - if path.extension() != Some(LANCE_FILE_EXTENSION) { - return Ok(false); - } - let (Some(parent), Some(dir_name)) = (path.parent(), path.filename()) else { - return Ok(false); - }; - let entries = object_store.read_dir(parent).await?; - Ok(entries.iter().any(|entry| entry.as_str() == dir_name)) -} - /// Defines the type of column #[derive(Debug, Clone, Serialize, Deserialize)] pub enum ColumnKind { @@ -2420,8 +2370,6 @@ impl NativeTable { None => false, }; - // Kept so that a `DatasetNotFound` can be re-checked against storage below. - let recovery_params = params.clone(); let mut builder = DatasetBuilder::from_uri(uri).with_read_params(params); // Set up commit handler when managed_versioning is enabled @@ -2440,7 +2388,12 @@ impl NativeTable { let dataset = match builder.load().await { Ok(dataset) => dataset, Err(e @ lance::Error::DatasetNotFound { .. }) => { - return Err(map_dataset_not_found(uri, name, recovery_params, e).await); + // The manifest load is the existence check. A physical prefix may be + // from a concurrent or abandoned create, so it cannot refine this error. + return Err(Error::TableNotFound { + name: name.to_string(), + source: Box::new(e), + }); } Err(e) => return Err(e.into()), }; @@ -3708,7 +3661,7 @@ pub struct FragmentSummaryStats { #[allow(deprecated)] mod tests { use std::sync::Arc; - use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::time::Duration; use arrow_array::{ @@ -3790,73 +3743,50 @@ mod tests { ); } - /// Write a table and then break it, leaving the `.lance` directory in place. - /// - /// `remove_all` reproduces an interrupted drop + re-create (the directory is left - /// empty); otherwise only the manifests are removed, leaving the data files behind. - async fn write_then_corrupt_table(dir: &std::path::Path, remove_all: bool) -> String { - let dataset_path = dir.join("test.lance"); - let uri = dataset_path.to_str().unwrap().to_string(); - - let batch = make_test_batches(); - let reader = RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema()); - Dataset::write(reader, &uri, None).await.unwrap(); - - if remove_all { - for entry in std::fs::read_dir(&dataset_path).unwrap() { - let entry = entry.unwrap(); - if entry.file_type().unwrap().is_dir() { - std::fs::remove_dir_all(entry.path()).unwrap(); - } else { - std::fs::remove_file(entry.path()).unwrap(); - } - } - assert_eq!(std::fs::read_dir(&dataset_path).unwrap().count(), 0); - } else { - let versions = dataset_path.join("_versions"); - assert!(versions.is_dir(), "expected manifests under {versions:?}"); - std::fs::remove_dir_all(&versions).unwrap(); - assert!(std::fs::read_dir(&dataset_path).unwrap().count() > 0); - } - - uri - } - #[tokio::test] - async fn test_open_corrupt_empty_dir() { + async fn test_open_not_found_when_empty_directory_exists() { let tmp_dir = tempdir().unwrap(); - let uri = write_then_corrupt_table(tmp_dir.path(), true).await; + let dataset_path = tmp_dir.path().join("test.lance"); + std::fs::create_dir(&dataset_path).unwrap(); - let err = NativeTable::open(&uri).await.unwrap_err(); + let err = NativeTable::open(dataset_path.to_str().unwrap()) + .await + .unwrap_err(); assert!( - matches!(&err, Error::TableCorrupted { name, .. } if name == "test"), + matches!(&err, Error::TableNotFound { name, .. } if name == "test"), "got {err:?}" ); } #[tokio::test] - async fn test_open_corrupt_missing_manifest() { + async fn test_open_not_found_when_only_uncommitted_storage_exists() { let tmp_dir = tempdir().unwrap(); - let uri = write_then_corrupt_table(tmp_dir.path(), false).await; + let dataset_path = tmp_dir.path().join("test.lance"); + let data_dir = dataset_path.join("data"); + std::fs::create_dir_all(&data_dir).unwrap(); + std::fs::write(data_dir.join("orphan.lance"), b"uncommitted").unwrap(); - let err = NativeTable::open(&uri).await.unwrap_err(); + let err = NativeTable::open(dataset_path.to_str().unwrap()) + .await + .unwrap_err(); assert!( - matches!(&err, Error::TableCorrupted { name, .. } if name == "test"), + matches!(&err, Error::TableNotFound { name, .. } if name == "test"), "got {err:?}" ); } - /// A table listed by `table_names()` must not be reported as missing by - /// `open_table()`. See . + /// Listing databases discover physical `*.lance` entries. That snapshot is not an + /// authoritative table-existence check: only a committed manifest makes a table + /// openable, and the entry could also be concurrently created or dropped. #[tokio::test] - async fn test_open_table_corrupt_is_still_listed() { + async fn test_table_names_may_include_uncommitted_storage() { let tmp_dir = tempdir().unwrap(); let db = connect(tmp_dir.path().to_str().unwrap()) .execute() .await .unwrap(); - write_then_corrupt_table(tmp_dir.path(), true).await; + std::fs::create_dir(tmp_dir.path().join("test.lance")).unwrap(); assert_eq!( db.table_names().execute().await.unwrap(), @@ -3864,12 +3794,177 @@ mod tests { ); let err = db.open_table("test").execute().await.unwrap_err(); assert!( - matches!(&err, Error::TableCorrupted { name, .. } if name == "test"), + matches!(&err, Error::TableNotFound { name, .. } if name == "test"), + "physical storage without a committed manifest is not a table: {err:?}" + ); + } + + #[derive(Debug)] + struct ParentListGuardStore { + inner: Arc, + parent: object_store::path::Path, + parent_list_calls: Arc, + } + + impl std::fmt::Display for ParentListGuardStore { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("ParentListGuardStore") + } + } + + #[async_trait::async_trait] + #[deny(clippy::missing_trait_methods)] + impl object_store::ObjectStore for ParentListGuardStore { + async fn put_opts( + &self, + location: &object_store::path::Path, + payload: object_store::PutPayload, + opts: object_store::PutOptions, + ) -> object_store::Result { + self.inner.put_opts(location, payload, opts).await + } + + async fn put_multipart_opts( + &self, + location: &object_store::path::Path, + opts: object_store::PutMultipartOptions, + ) -> object_store::Result> { + self.inner.put_multipart_opts(location, opts).await + } + + async fn get_opts( + &self, + location: &object_store::path::Path, + options: object_store::GetOptions, + ) -> object_store::Result { + self.inner.get_opts(location, options).await + } + + async fn get_ranges( + &self, + location: &object_store::path::Path, + ranges: &[std::ops::Range], + ) -> object_store::Result> { + self.inner.get_ranges(location, ranges).await + } + + fn delete_stream( + &self, + locations: futures::stream::BoxStream< + 'static, + object_store::Result, + >, + ) -> futures::stream::BoxStream<'static, object_store::Result> + { + self.inner.delete_stream(locations) + } + + fn list( + &self, + prefix: Option<&object_store::path::Path>, + ) -> futures::stream::BoxStream<'static, object_store::Result> + { + if prefix == Some(&self.parent) { + self.parent_list_calls.fetch_add(1, Ordering::Relaxed); + } + self.inner.list(prefix) + } + + fn list_with_offset( + &self, + prefix: Option<&object_store::path::Path>, + offset: &object_store::path::Path, + ) -> futures::stream::BoxStream<'static, object_store::Result> + { + if prefix == Some(&self.parent) { + self.parent_list_calls.fetch_add(1, Ordering::Relaxed); + } + self.inner.list_with_offset(prefix, offset) + } + + async fn list_with_delimiter( + &self, + prefix: Option<&object_store::path::Path>, + ) -> object_store::Result { + if prefix == Some(&self.parent) { + self.parent_list_calls.fetch_add(1, Ordering::Relaxed); + } + self.inner.list_with_delimiter(prefix).await + } + + async fn copy_opts( + &self, + from: &object_store::path::Path, + to: &object_store::path::Path, + options: object_store::CopyOptions, + ) -> object_store::Result<()> { + self.inner.copy_opts(from, to, options).await + } + + async fn rename_opts( + &self, + from: &object_store::path::Path, + to: &object_store::path::Path, + options: object_store::RenameOptions, + ) -> object_store::Result<()> { + self.inner.rename_opts(from, to, options).await + } + } + + #[derive(Debug)] + struct ParentListGuardWrapper { + parent_list_calls: Arc, + } + + impl WrappingObjectStore for ParentListGuardWrapper { + fn wrap( + &self, + _store_prefix: &str, + inner: Arc, + ) -> Arc { + Arc::new(ParentListGuardStore { + inner, + parent: object_store::path::Path::from("database"), + parent_list_calls: self.parent_list_calls.clone(), + }) + } + } + + #[tokio::test] + async fn test_open_missing_never_lists_database_parent() { + let parent_list_calls = Arc::new(AtomicUsize::new(0)); + let params = ReadParams { + store_options: Some(ObjectStoreParams { + object_store_wrapper: Some(Arc::new(ParentListGuardWrapper { + parent_list_calls: parent_list_calls.clone(), + })), + ..Default::default() + }), + ..Default::default() + }; + + let err = NativeTable::open_with_params( + "memory:///database/missing.lance", + "missing", + Vec::new(), + None, + Some(params), + None, + None, + HashSet::new(), + None, + ) + .await + .unwrap_err(); + + assert!( + matches!(&err, Error::TableNotFound { name, .. } if name == "missing"), "got {err:?}" ); - assert!( - err.to_string().contains("exists but could not be loaded"), - "got {err}" + assert_eq!( + parent_list_calls.load(Ordering::Relaxed), + 0, + "opening one missing table must not enumerate sibling tables" ); } From 4b7325bd745529c521faa15b7a2a76c065838203 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Thu, 13 Aug 2026 09:00:18 -0700 Subject: [PATCH 031/206] chore: update lance dependency to v11.0.0-beta.8 (#3928) Updates the Rust workspace and Java lance-core dependency to Lance v11.0.0-beta.8, with refreshed Cargo lockfile metadata. No compatibility fixes were required. Lance tag: https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.8 --- Cargo.lock | 98 +++++++++++++++++++++++----------------------------- Cargo.toml | 28 +++++++-------- java/pom.xml | 2 +- 3 files changed, 58 insertions(+), 70 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 04332a496..cf124d989 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arc-swap", "arrow", @@ -4832,7 +4832,6 @@ dependencies = [ "async-recursion", "async-trait", "async_cell", - "aws-credential-types", "aws-sdk-dynamodb", "byteorder", "bytes", @@ -4848,7 +4847,6 @@ dependencies = [ "either", "fst", "futures", - "half", "humantime", "itertools 0.14.0", "lance-arrow", @@ -4890,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow-array", "arrow-buffer", @@ -4913,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow-array", "arrow-buffer", @@ -4927,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow-array", "arrow-schema", @@ -4936,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrayref", "crunchy", @@ -4947,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow-array", "arrow-buffer", @@ -4956,12 +4954,10 @@ dependencies = [ "arrow-schema", "async-trait", "blake3", - "byteorder", "bytes", "datafusion-common", "datafusion-sql", "futures", - "itertools 0.14.0", "lance-arrow", "lance-derive", "libc", @@ -4979,7 +4975,6 @@ dependencies = [ "snafu 0.9.0", "tempfile", "tokio", - "tokio-stream", "tokio-util", "tracing", "twox-hash", @@ -4988,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow", "arrow-array", @@ -5019,8 +5014,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow", "arrow-array", @@ -5037,8 +5032,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "proc-macro2", "quote", @@ -5047,8 +5042,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow-arith", "arrow-array", @@ -5073,7 +5068,6 @@ dependencies = [ "num-traits", "prost", "prost-build", - "rand 0.9.5", "tokio", "tracing", "xxhash-rust", @@ -5082,8 +5076,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow-arith", "arrow-array", @@ -5114,8 +5108,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arc-swap", "arrow", @@ -5130,7 +5124,6 @@ dependencies = [ "async-trait", "bitvec", "bytes", - "chrono", "crossbeam-queue", "datafusion", "datafusion-common", @@ -5148,7 +5141,6 @@ dependencies = [ "lance-bitpacking", "lance-core", "lance-datafusion", - "lance-datagen", "lance-encoding", "lance-file", "lance-index-core", @@ -5177,13 +5169,12 @@ dependencies = [ "tempfile", "tokio", "tracing", - "uuid", ] [[package]] name = "lance-index-core" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow-array", "arrow-schema", @@ -5205,8 +5196,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow", "arrow-array", @@ -5220,7 +5211,6 @@ dependencies = [ "futures", "http 1.5.0", "io-uring", - "lance-arrow", "lance-core", "lance-namespace", "log", @@ -5238,29 +5228,28 @@ dependencies = [ "tokio", "tracing", "url", + "uuid", ] [[package]] name = "lance-linalg" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow-array", - "arrow-buffer", "arrow-schema", "cc", "half", "lance-arrow", "lance-core", "num-traits", - "rand 0.9.5", "rayon", ] [[package]] name = "lance-namespace" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow", "async-trait", @@ -5272,8 +5261,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow", "arrow-ipc", @@ -5326,14 +5315,13 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow-array", "arrow-buffer", "arrow-schema", "byteorder", - "bytes", "itertools 0.14.0", "lance-core", "roaring", @@ -5342,8 +5330,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow", "arrow-array", @@ -5383,8 +5371,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "arrow-array", "arrow-schema", @@ -5397,8 +5385,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.7" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.7#e581c49338bc83baf1ea50c5e235bd702f3fbeea" +version = "11.0.0-beta.8" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 33bf7e09b..107ec19f3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.7", default-features = false, "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.7", default-features = false, "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.7", default-features = false, "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.7", "tag" = "v11.0.0-beta.7", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.8", default-features = false, "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.8", default-features = false, "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.8", default-features = false, "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } ahash = "0.8" # Note that this one does not include pyarrow arrow = { version = "58.0.0", optional = false } diff --git a/java/pom.xml b/java/pom.xml index 4fdf77e81..9a4569bcf 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.7 + 11.0.0-beta.8 false 2.30.0 1.7 From 251f194696c26cab5eb5b582af23944c5f9e8421 Mon Sep 17 00:00:00 2001 From: XY Zhan Date: Thu, 13 Aug 2026 13:23:37 -0400 Subject: [PATCH 032/206] refactor(lsm): gate SSTable exclusion on every index a query relies on (#3780) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `exclusion_watermarks` resolved a single index and capped SSTable exclusion at that index's catch-up watermark. It now takes every index the query relies on and retains to the **lowest** of them, and the resolver collects arms together rather than returning at the first match. This is groundwork, not a fix for a reachable bug: `reject_unsupported` refuses hybrid search, so the vector and full-text arms are mutually exclusive and the list never holds more than one entry today. The generalisation is what the remaining work below plugs into. Unchanged: a plain scan uses the compaction watermark alone, an index with no catch-up entry contributes no cap, and a caught-up index falls back to the compaction watermark. Taking a minimum over more indexes can only lower a watermark, so the failure direction is "read an SSTable unnecessarily", never "miss rows". ## Tests Three in `lsm`: the existing lagging-index test updated for the new signature; `exclusion_watermark_takes_the_minimum_across_every_index_used` (two indexes at 7 and 4 against compaction at 9 — each alone stops at its own watermark, together the lower governs, order-independent); and `an_untracked_index_does_not_widen_a_lagging_sibling`. `cargo test -p lancedb --lib` — 45 lsm tests, 484 in the crate. `cargo fmt --check` clean. ## Follow-ups This crate pins lance to a released tag, so anything needing unreleased Lance symbols waits for a bump. 1. **Select legacy versus strict semantics from the feature bit.** On a table with `FLAG_MEM_WAL_INDEX_CATCHUP` set, a *missing* entry must mean "not caught up" and retain the SSTables, instead of leaving the compaction watermark unchanged. Needs the bit from lance-format/lance#8263. **This must land before any table is activated** — otherwise the bit is set while queries still read permissively. 2. **Collect scalar and bitmap-family prefilter indexes.** The genuinely multi-index query is a vector search with a scalar prefilter, and it is gated on the vector index alone today. Identifying the others needs the planner's chosen indexes, not the columns the filter names, so it needs a Lance-side helper. 3. **Verify a retained SSTable can actually answer.** Both base and SSTable arms use `fast_search`; a source without a compatible index contributes nothing, so retention alone does not guarantee its rows are returned. Needs a flat-search fallback or an explicit error in Lance's `LsmScanner`. 4. **Planner-level integration tests.** Current tests exercise the watermark arithmetic directly. End-to-end coverage over real queries — prefilter forms, legacy versus activated, missing index and missing shard entries — depends on 1–3. --- rust/lancedb/src/table/query/lsm.rs | 198 ++++++++++++++++++++-------- 1 file changed, 146 insertions(+), 52 deletions(-) diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index 074d13476..7ccdedf5a 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -84,9 +84,8 @@ pub(super) async fn create_lsm_plan( let pk_columns = pk_columns(&ds_ref)?; // The base index an indexed arm relies on may lag compaction; resolve it so the // snapshot retains SSTables the index has not yet caught up to. - let arm_index = arm_maintained_index_name(&ds_ref, &query, &details).await?; - let (snapshots, in_memory) = - build_read_context(table, &ds_ref, &details, arm_index.as_deref()).await?; + let arm_indexes = arm_maintained_index_names(&ds_ref, &query, &details).await?; + let (snapshots, in_memory) = build_read_context(table, &ds_ref, &details, &arm_indexes).await?; let limit = query.base.limit; let offset = query.base.offset; @@ -232,28 +231,36 @@ fn pk_columns(dataset: &Dataset) -> Result> { Ok(pk) } -/// Per-shard SSTable exclusion watermark: the generation at or below which SSTables -/// are safe to drop for this arm. A generation is droppable only once it is -/// compacted into the base table AND covered by `index_name`'s catch-up (for an -/// indexed arm); a plain scan (`index_name == None`) uses the compaction watermark -/// alone. Capping at the index catch-up keeps rows the base index has not yet -/// indexed visible through their SSTable. First occurrence per shard mirrors Lance's -/// `compacted_generation_for_shard`. +/// Per-shard SSTable exclusion watermark: the generation at or below which +/// SSTables are safe to drop for this query. +/// +/// A generation is droppable only once it is compacted into the base table AND +/// covered by the catch-up of every index the query relies on, so the watermark +/// is the minimum across `index_names`. Gating on fewer than all of them would +/// drop SSTables holding rows an uncounted index has not yet indexed, and that +/// arm would silently return fewer rows. +/// +/// See [`arm_maintained_index_names`] for which indexes are collected today: a +/// vector search with a scalar prefilter is not yet among them. +/// +/// An empty `index_names` (a plain scan) uses the compaction watermark alone. +/// First occurrence per shard mirrors Lance's `compacted_generation_for_shard`. fn exclusion_watermarks( details: &MemWalIndexDetails, - index_name: Option<&str>, + index_names: &[String], ) -> HashMap { let mut exclude: HashMap = HashMap::new(); for entry in &details.compacted_sstables { let mut watermark = entry.generation; - if let Some(name) = index_name - && let Some(caught_up) = details + for name in index_names { + if let Some(caught_up) = details .index_catchup .iter() - .find(|icp| icp.index_name == name) + .find(|icp| icp.index_name == *name) .and_then(|icp| icp.caught_up_generation_for_shard(&entry.shard_id)) - { - watermark = watermark.min(caught_up); + { + watermark = watermark.min(caught_up); + } } exclude.entry(entry.shard_id).or_insert(watermark); } @@ -271,9 +278,9 @@ async fn build_read_context( table: &NativeTable, dataset: &Dataset, details: &MemWalIndexDetails, - index_name: Option<&str>, + index_names: &[String], ) -> Result<(Vec, HashMap)> { - let exclude = exclusion_watermarks(details, index_name); + let exclude = exclusion_watermarks(details, index_names); let shard_ids = dataset.list_mem_wal_latest_shard_ids().await?; // Use the dataset's own object store (not `ObjectStore::from_uri`, which @@ -487,19 +494,33 @@ async fn index_maintained( })) } -/// The maintained base index the query's arm relies on (vector index for ANN, FTS -/// index for full-text), used to gate SSTable compaction exclusion by index catch-up. -/// `None` for a plain scan or when no maintained index covers the searched column. -async fn arm_maintained_index_name( +/// Every maintained base index this query relies on, used to gate SSTable +/// exclusion by index catch-up. +/// +/// Returns a list because the watermark must be the lowest across every index a +/// query relies on. Today it never holds more than one: `reject_unsupported` +/// refuses hybrid search, so the vector and full-text arms are mutually +/// exclusive. +/// +/// The case that is genuinely multi-index -- a vector search with a scalar or +/// bitmap prefilter -- is **not collected yet**. Identifying those needs the +/// planner's chosen indexes, not the columns the filter names, and no Lance API +/// exposes them. Until it does, such a query is gated on its vector index alone. +/// +/// Empty for a plain scan, or when no maintained index covers the searched +/// column. +async fn arm_maintained_index_names( dataset: &Dataset, query: &VectorQueryRequest, details: &MemWalIndexDetails, -) -> Result> { +) -> Result> { use lance::index::DatasetIndexExt; - // Resolve the arm's searched column, the index-detail type it relies on, and a + + // Each arm's searched column, the index-detail type it relies on, and a // label for diagnostics — catch-up is taken from the vector/FTS index // specifically, not a BTree on the same column. - let (column, type_url_suffix, arm) = if !query.query_vector.is_empty() { + let mut arms: Vec<(String, &str, &str)> = Vec::new(); + if !query.query_vector.is_empty() { let arrow_schema = ArrowSchema::from(dataset.schema()); let column = match &query.column { Some(column) => column.clone(), @@ -508,31 +529,43 @@ async fn arm_maintained_index_name( default_vector_column(&arrow_schema, dim)? } }; - (column, "VectorIndexDetails", "vector") - } else if let Some(fts) = &query.base.full_text_search { - match fts.columns().into_iter().next() { - Some(column) => (column, "InvertedIndexDetails", "full-text"), - None => return Ok(None), - } - } else { - return Ok(None); - }; - let Some(field) = dataset.schema().field(&column) else { - return Ok(None); - }; + arms.push((column, "VectorIndexDetails", "vector")); + } + if let Some(fts) = &query.base.full_text_search + && let Some(column) = fts.columns().into_iter().next() + { + arms.push((column, "InvertedIndexDetails", "full-text")); + } + if arms.is_empty() { + return Ok(Vec::new()); + } + let indices = dataset.load_indices().await?; - let segment_names: Vec = indices - .iter() - .filter(|idx| { - idx.fields.contains(&field.id) - && idx - .index_details - .as_ref() - .is_some_and(|d| d.type_url.ends_with(type_url_suffix)) - }) - .map(|idx| idx.name.clone()) - .collect(); - resolve_single_index(segment_names, &details.maintained_indexes, arm, &column) + let mut names = Vec::with_capacity(arms.len()); + for (column, type_url_suffix, arm) in arms { + let Some(field) = dataset.schema().field(&column) else { + continue; + }; + let segment_names: Vec = indices + .iter() + .filter(|idx| { + idx.fields.contains(&field.id) + && idx + .index_details + .as_ref() + .is_some_and(|d| d.type_url.ends_with(type_url_suffix)) + }) + .map(|idx| idx.name.clone()) + .collect(); + if let Some(name) = + resolve_single_index(segment_names, &details.maintained_indexes, arm, &column)? + { + names.push(name); + } + } + names.sort(); + names.dedup(); + Ok(names) } /// Resolve the single logical index from the names of its matching physical @@ -734,24 +767,85 @@ mod tests { }; // Plain scan: drop every compacted generation (through 5). - assert_eq!(exclusion_watermarks(&details, None).get(&shard), Some(&5)); + assert_eq!(exclusion_watermarks(&details, &[]).get(&shard), Some(&5)); // FTS arm with a lagging index: exclusion is capped at the index catch-up // (2), so SSTable generations 3..=5 are retained until the index covers // them — otherwise those documents would silently vanish from FTS results. assert_eq!( - exclusion_watermarks(&details, Some("fts_idx")).get(&shard), + exclusion_watermarks(&details, &["fts_idx".to_string()]).get(&shard), Some(&2) ); // A caught-up index — or one untracked in index_catchup — falls back to the // compaction watermark. assert_eq!( - exclusion_watermarks(&details, Some("caught_up_idx")).get(&shard), + exclusion_watermarks(&details, &["caught_up_idx".to_string()]).get(&shard), Some(&5) ); } + /// A hybrid search reads a vector and a full-text index, and either may lag. + /// Retaining to the lower of the two is what keeps both arms complete; + /// gating on one alone would drop SSTables the other has not indexed. + #[test] + fn exclusion_watermark_takes_the_minimum_across_every_index_used() { + let shard = Uuid::from_u128(1); + let details = MemWalIndexDetails { + compacted_sstables: vec![CompactedSsTable::new(shard, 9)], + index_catchup: vec![ + IndexCatchupProgress::new( + "vec_idx".to_string(), + vec![CompactedSsTable::new(shard, 7)], + ), + IndexCatchupProgress::new( + "fts_idx".to_string(), + vec![CompactedSsTable::new(shard, 4)], + ), + ], + maintained_indexes: vec!["vec_idx".to_string(), "fts_idx".to_string()], + ..Default::default() + }; + + // Each index alone stops at its own catch-up. + assert_eq!( + exclusion_watermarks(&details, &["vec_idx".to_string()]).get(&shard), + Some(&7) + ); + assert_eq!( + exclusion_watermarks(&details, &["fts_idx".to_string()]).get(&shard), + Some(&4) + ); + + // Used together, the lower one governs regardless of order. + let both = ["vec_idx".to_string(), "fts_idx".to_string()]; + assert_eq!(exclusion_watermarks(&details, &both).get(&shard), Some(&4)); + let reversed = ["fts_idx".to_string(), "vec_idx".to_string()]; + assert_eq!( + exclusion_watermarks(&details, &reversed).get(&shard), + Some(&4) + ); + } + + /// An index with no catch-up entry contributes no cap today, so a lagging + /// sibling must still govern rather than being widened by the untracked one. + #[test] + fn an_untracked_index_does_not_widen_a_lagging_sibling() { + let shard = Uuid::from_u128(1); + let details = MemWalIndexDetails { + compacted_sstables: vec![CompactedSsTable::new(shard, 9)], + index_catchup: vec![IndexCatchupProgress::new( + "fts_idx".to_string(), + vec![CompactedSsTable::new(shard, 4)], + )], + maintained_indexes: vec!["fts_idx".to_string(), "untracked_idx".to_string()], + ..Default::default() + }; + + let both = ["fts_idx".to_string(), "untracked_idx".to_string()]; + assert_eq!(exclusion_watermarks(&details, &both).get(&shard), Some(&4)); + } + #[test] fn resolve_single_index_dedupes_segments() { let maintained = vec!["fts_idx".to_string()]; From 790d0c684c900ae42e594601476a705c0e61f3a5 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Thu, 13 Aug 2026 11:26:58 -0700 Subject: [PATCH 033/206] docs(ci): clarify tag input on codex-update-lance-dependency (#3924) Say what resolving "latest" actually does: pick the newest release, preferring stable over pre-release, and skip the run if it is not newer than the version pinned in Cargo.toml. Co-authored-by: Claude Opus 5 (1M context) --- .github/workflows/codex-update-lance-dependency.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/codex-update-lance-dependency.yml b/.github/workflows/codex-update-lance-dependency.yml index 420daf650..79ef84364 100644 --- a/.github/workflows/codex-update-lance-dependency.yml +++ b/.github/workflows/codex-update-lance-dependency.yml @@ -4,14 +4,14 @@ on: workflow_call: inputs: tag: - description: "Tag name from Lance. If omitted, the skill will use the latest Lance release that needs an update." + description: "Tag name from Lance (e.g. `v7.2.0-beta.1`). If omitted, the newest release is resolved automatically — stable releases are preferred over pre-releases — and the run is skipped if it is not newer than the version currently pinned in Cargo.toml." required: false default: "" type: string workflow_dispatch: inputs: tag: - description: "Tag name from Lance. Leave empty to use the latest Lance release that needs an update." + description: "Tag name from Lance (e.g. `v7.2.0-beta.1`). Leave empty to resolve the newest release automatically — stable releases are preferred over pre-releases — and skip the run if it is not newer than the version currently pinned in Cargo.toml." required: false default: "" type: string From ffd35c1a8f07a05f937e59c51c4a6acb9faac7f8 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 13 Aug 2026 18:05:44 -0700 Subject: [PATCH 034/206] feat: add asynchronous drop table API (#3936) ## Summary - add `drop_table_async` and return a job handle while preserving `drop_table` - consume remote 202 responses with cleanup job IDs and retain older-server compatibility - expose the API through Python and TypeScript connection wrappers --- docs/src/js/classes/Connection.md | 23 ++++++ nodejs/__test__/connection.test.ts | 10 +++ nodejs/lancedb/connection.ts | 12 ++++ nodejs/src/connection.rs | 16 +++++ python/python/lancedb/_lancedb.pyi | 3 + python/python/lancedb/db.py | 37 ++++++++++ python/python/lancedb/namespace.py | 21 ++++++ python/python/lancedb/remote/db.py | 12 +++- python/python/tests/test_db.py | 19 ++++- python/src/connection.rs | 17 +++++ rust/lancedb/src/connection.rs | 15 ++++ rust/lancedb/src/database.rs | 12 ++++ rust/lancedb/src/remote.rs | 9 +++ rust/lancedb/src/remote/db.rs | 111 ++++++++++++++++++++++++++--- rust/lancedb/src/remote/table.rs | 10 +-- 15 files changed, 307 insertions(+), 20 deletions(-) diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index fa4e0748a..e4cbc1e96 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -386,6 +386,29 @@ Drop an existing table. *** +### dropTableAsync() + +```ts +abstract dropTableAsync(name, namespacePath?): Promise +``` + +Start dropping a table and return its cleanup job. + +The table may become unavailable before its data files are removed. Wait +on the returned job to know when cleanup has finished. + +#### Parameters + +* **name**: `string` + +* **namespacePath?**: `string`[] + +#### Returns + +`Promise`<[`Job`](Job.md)> + +*** + ### getJob() ```ts diff --git a/nodejs/__test__/connection.test.ts b/nodejs/__test__/connection.test.ts index 68180471a..af471b478 100644 --- a/nodejs/__test__/connection.test.ts +++ b/nodejs/__test__/connection.test.ts @@ -89,6 +89,16 @@ describe("given a connection", () => { await db.createTable("test4", [{ id: 1 }, { id: 2 }]); }); + it("should return a completed job when dropping a local table", async () => { + await db.createTable("async-drop", [{ id: 1 }]); + + const job = await db.dropTableAsync("async-drop"); + expect(job.id).toBeNull(); + await expect(job.status()).resolves.toBe("finished"); + await job.wait(); + await expect(db.tableNames()).resolves.toEqual([]); + }); + it("should fail if creating table twice, unless overwrite is true", async () => { let tbl = await db.createTable("test", [{ id: 1 }, { id: 2 }]); await expect(tbl.countRows()).resolves.toBe(2); diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index e63a7ae65..a81dc0442 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -327,6 +327,14 @@ export abstract class Connection { */ abstract dropTable(name: string, namespacePath?: string[]): Promise; + /** + * Start dropping a table and return its cleanup job. + * + * The table may become unavailable before its data files are removed. Wait + * on the returned job to know when cleanup has finished. + */ + abstract dropTableAsync(name: string, namespacePath?: string[]): Promise; + /** * Drop all tables in the database. * @param {string[]} namespacePath The namespace path to drop tables from (defaults to root namespace). @@ -705,6 +713,10 @@ export class LocalConnection extends Connection { return this.inner.dropTable(name, namespacePath ?? []); } + async dropTableAsync(name: string, namespacePath?: string[]): Promise { + return this.inner.dropTableAsync(name, namespacePath ?? []); + } + async dropAllTables(namespacePath?: string[]): Promise { return this.inner.dropAllTables(namespacePath ?? []); } diff --git a/nodejs/src/connection.rs b/nodejs/src/connection.rs index c45321aba..c9f5e10ea 100644 --- a/nodejs/src/connection.rs +++ b/nodejs/src/connection.rs @@ -334,6 +334,22 @@ impl Connection { .default_error() } + /// Start dropping a table and return its cleanup job. + #[napi(catch_unwind)] + pub async fn drop_table_async( + &self, + name: String, + namespace_path: Option>, + ) -> napi::Result { + let ns = namespace_path.unwrap_or_default(); + let job = self + .get_inner()? + .drop_table_async(&name, &ns) + .await + .default_error()?; + Ok(crate::job::Job::new(job)) + } + #[napi(catch_unwind)] pub async fn drop_all_tables(&self, namespace_path: Option>) -> napi::Result<()> { let ns = namespace_path.unwrap_or_default(); diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index f87fd3d13..447bcc88a 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -198,6 +198,9 @@ class Connection(object): async def drop_table( self, name: str, namespace_path: Optional[List[str]] = None ) -> None: ... + async def drop_table_async( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> Job: ... async def drop_all_tables( self, namespace_path: Optional[List[str]] = None ) -> None: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index eeae8bf50..14b6c0b0d 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -524,6 +524,12 @@ class DBConnection(EnforceOverrides): namespace_path = [] raise NotImplementedError + def drop_table_async( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> Job: + """Start dropping a table and return its cleanup job.""" + raise NotImplementedError + def rename_table( self, cur_name: str, @@ -1186,6 +1192,20 @@ class LanceDBConnection(DBConnection): ) ) + @override + def drop_table_async( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> Job: + """Start dropping a table and return its cleanup job. + + The table may become unavailable before its data files are removed. + Call :meth:`Job.wait` to wait for cleanup to finish. + """ + if namespace_path is None: + namespace_path = [] + job = LOOP.run(self._conn.drop_table_async(name, namespace_path=namespace_path)) + return Job(job if isinstance(job, AsyncJob) else AsyncJob(job)) + @override def drop_all_tables(self, namespace_path: Optional[List[str]] = None): if namespace_path is None: @@ -1963,6 +1983,23 @@ class AsyncConnection(object): if f"Table '{name}' was not found" not in str(e): raise e + async def drop_table_async( + self, + name: str, + *, + namespace_path: Optional[List[str]] = None, + ) -> AsyncJob: + """Start dropping a table and return its cleanup job. + + The table may become unavailable before its data files are removed. + Await :meth:`AsyncJob.wait` to wait for cleanup to finish. + """ + if namespace_path is None: + namespace_path = [] + return AsyncJob( + await self._inner.drop_table_async(name, namespace_path=namespace_path) + ) + async def drop_all_tables(self, namespace_path: Optional[List[str]] = None): """Drop all tables from the database. diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index b151395cc..0e60bd218 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -49,6 +49,7 @@ from lancedb._lancedb import ( ) from lancedb.background_loop import LOOP from lancedb.db import AsyncConnection, DBConnection +from lancedb.job import AsyncJob, Job from lance_namespace import ( LanceNamespace, connect as namespace_connect, @@ -624,6 +625,18 @@ class LanceNamespaceDBConnection(DBConnection): namespace_path = [] LOOP.run(self._inner.drop_table(name, namespace_path=namespace_path)) + @override + def drop_table_async( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> Job: + """Start dropping a table and return its cleanup job.""" + if namespace_path is None: + namespace_path = [] + job = LOOP.run( + self._inner.drop_table_async(name, namespace_path=namespace_path) + ) + return Job(job if isinstance(job, AsyncJob) else AsyncJob(job)) + @override def rename_table( self, @@ -1134,6 +1147,14 @@ class AsyncLanceNamespaceDBConnection: namespace_path = [] await self._inner.drop_table(name, namespace_path=namespace_path) + async def drop_table_async( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> AsyncJob: + """Start dropping a table and return its cleanup job.""" + if namespace_path is None: + namespace_path = [] + return await self._inner.drop_table_async(name, namespace_path=namespace_path) + async def rename_table( self, cur_name: str, diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 332886590..16ad65dcb 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -23,7 +23,7 @@ import pyarrow as pa from ..common import DATA from ..db import DBConnection, LOOP -from ..job import Job +from ..job import AsyncJob, Job if TYPE_CHECKING: from .._lancedb import JobDescription, JobInfo @@ -663,6 +663,16 @@ class RemoteDBConnection(DBConnection): namespace_path = [] LOOP.run(self._conn.drop_table(name, namespace_path=namespace_path)) + @override + def drop_table_async( + self, name: str, namespace_path: Optional[List[str]] = None + ) -> Job: + """Start dropping a table and return its cleanup job.""" + if namespace_path is None: + namespace_path = [] + job = LOOP.run(self._conn.drop_table_async(name, namespace_path=namespace_path)) + return Job(job if isinstance(job, AsyncJob) else AsyncJob(job)) + @override def rename_table( self, diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index 84e78fd8f..38bbb53fb 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -755,8 +755,7 @@ def test_delete_table(tmp_db: lancedb.DBConnection): assert tmp_db.table_names() == [] -@pytest.mark.asyncio -async def test_delete_table_async(tmp_db: lancedb.DBConnection): +def test_drop_table_async(tmp_db: lancedb.DBConnection): data = pd.DataFrame( { "vector": [[3.1, 4.1], [5.9, 26.5]], @@ -772,7 +771,10 @@ async def test_delete_table_async(tmp_db: lancedb.DBConnection): assert tmp_db.table_names() == ["test"] - tmp_db.drop_table("test") + job = tmp_db.drop_table_async("test") + assert job.id is None + assert job.status() == "finished" + job.wait() assert tmp_db.table_names() == [] tmp_db.create_table("test", data=data) @@ -781,6 +783,17 @@ async def test_delete_table_async(tmp_db: lancedb.DBConnection): tmp_db.drop_table("does_not_exist", ignore_missing=True) +@pytest.mark.asyncio +async def test_drop_table_async_connection(tmp_db_async: lancedb.AsyncConnection): + await tmp_db_async.create_table("test", data=pa.table({"id": [1, 2]})) + + job = await tmp_db_async.drop_table_async("test") + assert job.id is None + assert await job.status() == "finished" + await job.wait() + assert await tmp_db_async.table_names() == [] + + def test_drop_database(tmp_db: lancedb.DBConnection): data = pd.DataFrame( { diff --git a/python/src/connection.rs b/python/src/connection.rs index b97d48ad8..dbda29ba6 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -346,6 +346,23 @@ impl Connection { }) } + #[pyo3(signature = (name, namespace_path=None))] + pub fn drop_table_async( + self_: PyRef<'_, Self>, + name: String, + namespace_path: Option>, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + let ns_path = namespace_path.unwrap_or_default(); + future_into_py(self_.py(), async move { + inner + .drop_table_async(name, &ns_path) + .await + .infer_error() + .map(crate::job::Job::new) + }) + } + #[pyo3(signature = (namespace_path=None,))] pub fn drop_all_tables( self_: PyRef<'_, Self>, diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 1f2708d4e..12ca306b8 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -565,6 +565,21 @@ impl Connection { .await } + /// Start dropping a table and return a handle to the cleanup job. + /// + /// The table may become unavailable before its physical data is removed. + /// Call [`crate::job::Job::wait`] to wait for cleanup to finish. Local + /// backends may complete the drop before returning the handle. + pub async fn drop_table_async( + &self, + name: impl AsRef, + namespace_path: &[String], + ) -> Result { + self.internal + .drop_table_async(name.as_ref(), namespace_path) + .await + } + /// Drop the database /// /// This is the same as dropping all of the tables diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index f99f6e12a..f52c02439 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -323,6 +323,18 @@ pub trait Database: ) -> Result<()>; /// Drop a table in the database async fn drop_table(&self, name: &str, namespace_path: &[String]) -> Result<()>; + /// Start dropping a table and return a handle to the cleanup job. + /// + /// Backends without asynchronous cleanup complete the drop before + /// returning an already-finished job. + async fn drop_table_async( + &self, + name: &str, + namespace_path: &[String], + ) -> Result { + self.drop_table(name, namespace_path).await?; + Ok(crate::job::Job::new_done()) + } /// Drop all tables in the database async fn drop_all_tables(&self, namespace_path: &[String]) -> Result<()>; fn as_any(&self) -> &dyn std::any::Any; diff --git a/rust/lancedb/src/remote.rs b/rust/lancedb/src/remote.rs index 4b5f8832f..be9d0eef6 100644 --- a/rust/lancedb/src/remote.rs +++ b/rust/lancedb/src/remote.rs @@ -19,6 +19,15 @@ const ARROW_FILE_CONTENT_TYPE: &str = "application/vnd.apache.arrow.file"; #[cfg(test)] const JSON_CONTENT_TYPE: &str = "application/json"; +fn extract_job_id(body: &str) -> Option { + serde_json::from_str::(body) + .ok()? + .get("job_id")? + .as_str() + .filter(|job_id| !job_id.is_empty()) + .map(str::to_string) +} + pub use client::{ClientConfig, HeaderProvider, RetryConfig, TimeoutConfig, TlsConfig}; pub use db::{RemoteDatabaseOptions, RemoteDatabaseOptionsBuilder}; pub use oauth::{OAuthConfig, OAuthFlow, OAuthHeaderProvider}; diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 839cb3797..45a0bd925 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -9,6 +9,7 @@ use http::StatusCode; use lance_io::object_store::StorageOptions; use lance_namespace_impls::{DynamicContextProvider, OperationInfo}; use moka::future::Cache; +use reqwest::Response; use reqwest::header::CONTENT_TYPE; use lance_namespace::models::{ @@ -23,15 +24,17 @@ use crate::database::{ JobDescription, JobInfo, OpenTableRequest, ReadConsistency, TableNamesRequest, }; use crate::error::Result; +use crate::job::Job; +use crate::remote::job::RemoteJob; use crate::remote::util::stream_as_body; use crate::table::BaseTable; -use super::ARROW_STREAM_CONTENT_TYPE; use super::client::{ ClientConfig, HeaderProvider, HttpSend, RequestResultExt, RestfulLanceDbClient, Sender, }; use super::table::RemoteTable; use super::util::parse_server_version; +use super::{ARROW_STREAM_CONTENT_TYPE, extract_job_id}; // Request structure for the remote clone table API #[derive(serde::Serialize)] @@ -326,6 +329,22 @@ impl RemoteDatabase { } } +impl RemoteDatabase { + async fn submit_drop_table( + &self, + name: &str, + namespace_path: &[String], + ) -> Result<(String, Response)> { + let identifier = build_table_identifier(name, namespace_path, &self.client.id_delimiter); + let cache_key = build_cache_key(name, namespace_path); + let req = self.client.post(&format!("/v1/table/{}/drop/", identifier)); + let (request_id, resp) = self.client.send(req).await?; + let resp = self.client.check_response(&request_id, resp).await?; + self.table_cache.remove(&cache_key).await; + Ok((request_id, resp)) + } +} + #[cfg(all(test, feature = "remote"))] mod test_utils { use super::*; @@ -894,13 +913,28 @@ impl Database for RemoteDatabase { } async fn drop_table(&self, name: &str, namespace_path: &[String]) -> Result<()> { - let identifier = build_table_identifier(name, namespace_path, &self.client.id_delimiter); - let cache_key = build_cache_key(name, namespace_path); - let req = self.client.post(&format!("/v1/table/{}/drop/", identifier)); - let (request_id, resp) = self.client.send(req).await?; - self.client.check_response(&request_id, resp).await?; - self.table_cache.remove(&cache_key).await; - Ok(()) + self.submit_drop_table(name, namespace_path) + .await + .map(|_| ()) + } + + async fn drop_table_async(&self, name: &str, namespace_path: &[String]) -> Result { + let (request_id, response) = self.submit_drop_table(name, namespace_path).await?; + let status = response.status(); + let body = response.text().await.err_to_http(request_id.clone())?; + let job_id = extract_job_id(&body); + Ok(match job_id { + Some(job_id) => Job::new(Box::new(RemoteJob::new(self.client.clone(), job_id))), + None if status == StatusCode::ACCEPTED => { + return Err(Error::Http { + source: "asynchronous drop-table response did not contain a valid job_id" + .into(), + request_id, + status_code: Some(status), + }); + } + None => Job::new_done(), + }) } async fn drop_all_tables(&self, namespace_path: &[String]) -> Result<()> { @@ -1492,6 +1526,67 @@ mod tests { // NOTE: the API will return 200 even if the table does not exist. So we shouldn't expect 404. } + #[tokio::test] + async fn test_drop_table_does_not_read_response_body() { + let conn = Connection::new_with_handler(|_| { + http::Response::builder() + .status(200) + .body(vec![0xff]) + .unwrap() + }); + + conn.drop_table("table1", &[]).await.unwrap(); + } + + #[tokio::test] + async fn test_drop_table_async_returns_job() { + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::POST); + assert_eq!(request.url().path(), "/v1/table/table1/drop/"); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"drop-job-123"}"#) + .unwrap() + }); + + let job = conn.drop_table_async("table1", &[]).await.unwrap(); + assert_eq!(job.id(), Some("drop-job-123")); + } + + #[tokio::test] + async fn test_drop_table_async_old_server_returns_done_job() { + let conn = Connection::new_with_handler(|_| { + http::Response::builder().status(200).body("").unwrap() + }); + + let job = conn.drop_table_async("table1", &[]).await.unwrap(); + assert_eq!(job.id(), None); + assert_eq!(job.status().await.unwrap(), "finished"); + } + + #[tokio::test] + async fn test_drop_table_async_rejects_accepted_response_without_job_id() { + let conn = Connection::new_with_handler(|_| { + http::Response::builder().status(202).body("{}").unwrap() + }); + + let error = conn.drop_table_async("table1", &[]).await.err().unwrap(); + assert!(error.to_string().contains("valid job_id")); + } + + #[tokio::test] + async fn test_drop_table_async_rejects_empty_job_id() { + let conn = Connection::new_with_handler(|_| { + http::Response::builder() + .status(202) + .body(r#"{"job_id":""}"#) + .unwrap() + }); + + let error = conn.drop_table_async("table1", &[]).await.err().unwrap(); + assert!(error.to_string().contains("valid job_id")); + } + #[tokio::test] async fn test_rename_table() { let conn = Connection::new_with_handler(|request| { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 0d843dd54..3816a3a86 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -8,7 +8,7 @@ use self::insert::{RemoteWriteExec, WriteOp}; use super::client::RequestResultExt; use super::client::{HttpSend, RestfulLanceDbClient, Sender}; use super::db::ServerVersion; -use super::{ARROW_FILE_CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE}; +use super::{ARROW_FILE_CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE, extract_job_id}; use crate::blob::BlobFile; use crate::data::scannable::{PeekedScannable, Scannable, estimate_write_partitions}; use crate::expr::expr_to_sql_string; @@ -392,13 +392,7 @@ impl RemoteTable { .text() .await .ok() - .and_then(|body| serde_json::from_str::(&body).ok()) - .and_then(|value| { - value - .get("job_id") - .and_then(|id| id.as_str()) - .map(str::to_string) - }); + .and_then(|body| extract_job_id(&body)); if let Some(wait_timeout) = index.wait_timeout { let index_name = index.name.unwrap_or_else(|| format!("{}_idx", column)); From 91c5f344d283f255ce1fddb59a7394747936a6a3 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Fri, 14 Aug 2026 01:09:15 +0000 Subject: [PATCH 035/206] =?UTF-8?q?Bump=20version:=200.37.1-beta.1=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package-lock.json | 4 ++-- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index a015353cb..cab6bb104 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.37.1-beta.1" +current_version = "0.38.0-beta.0" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index cf124d989..58c63ba26 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5399,7 +5399,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.37.1-beta.1" +version = "0.38.0-beta.0" dependencies = [ "ahash", "anyhow", @@ -5487,7 +5487,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.37.1-beta.1" +version = "0.38.0-beta.0" dependencies = [ "arrow-array", "arrow-buffer", @@ -5512,7 +5512,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.37.1-beta.1" +version = "0.38.0-beta.0" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 091588922..f9a0ea053 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.37.1-beta.1 + 0.38.0-beta.0 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 20f69e134..09b088e46 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.37.1-beta.1 + 0.38.0-beta.0 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 9a4569bcf..c580cf070 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.37.1-beta.1 + 0.38.0-beta.0 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 48e5f5295..2e9373b9b 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.37.1-beta.1" +version = "0.38.0-beta.0" 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 d3792f9c2..e0fd7426d 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.37.1-beta.1", + "version": "0.38.0-beta.0", "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 44bc309ca..ef281de3d 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.37.1-beta.1", + "version": "0.38.0-beta.0", "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 e78f0fe6a..d535820fa 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.37.1-beta.1", + "version": "0.38.0-beta.0", "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 0e27c5f51..7aa21301e 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.37.1-beta.1", + "version": "0.38.0-beta.0", "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 7bd27ba18..d220991f7 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.37.1-beta.1", + "version": "0.38.0-beta.0", "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 5c76024b2..519d7376a 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.37.1-beta.1", + "version": "0.38.0-beta.0", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index f8cc7d8e0..9f608d6d0 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.37.1-beta.1", + "version": "0.38.0-beta.0", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index f7b6670e4..9222bf582 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lancedb/lancedb", - "version": "0.37.1-beta.1", + "version": "0.38.0-beta.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lancedb/lancedb", - "version": "0.37.1-beta.1", + "version": "0.38.0-beta.0", "cpu": [ "x64", "arm64" diff --git a/nodejs/package.json b/nodejs/package.json index 0416ce81b..c87af926b 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.37.1-beta.1", + "version": "0.38.0-beta.0", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 9d36edd5c..bede2bc37 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.37.1-beta.1" +version = "0.38.0-beta.0" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 23dc86e15..23c0dcfd0 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.37.1-beta.1" +version = "0.38.0-beta.0" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 0ac70a8b9f44346524dc8068075d65271110aed1 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Fri, 14 Aug 2026 03:46:46 -0700 Subject: [PATCH 036/206] chore: update lance dependency to v11.0.0-beta.10 (#3944) Updates the Rust workspace Lance dependencies and Java lance-core dependency to v11.0.0-beta.10. No compatibility fixes were required; workspace clippy with all features and Rust formatting pass. Lance tag: https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.10 --- Cargo.lock | 85 ++++++++++++++++++++++++++-------------------------- Cargo.toml | 28 ++++++++--------- java/pom.xml | 2 +- 3 files changed, 57 insertions(+), 58 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 58c63ba26..f9e1566a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow", "arrow-array", @@ -5003,7 +5003,6 @@ dependencies = [ "jsonb", "lance-arrow", "lance-core", - "lance-datagen", "log", "pin-project", "prost", @@ -5014,8 +5013,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow", "arrow-array", @@ -5032,8 +5031,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "proc-macro2", "quote", @@ -5042,8 +5041,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow-arith", "arrow-array", @@ -5076,8 +5075,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow-arith", "arrow-array", @@ -5108,8 +5107,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arc-swap", "arrow", @@ -5173,8 +5172,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow-array", "arrow-schema", @@ -5196,8 +5195,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow", "arrow-array", @@ -5233,8 +5232,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow-array", "arrow-schema", @@ -5248,8 +5247,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow", "async-trait", @@ -5261,8 +5260,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow", "arrow-ipc", @@ -5315,8 +5314,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow-array", "arrow-buffer", @@ -5330,8 +5329,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow", "arrow-array", @@ -5371,8 +5370,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "arrow-array", "arrow-schema", @@ -5385,8 +5384,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.8" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.8#9acbac748e8a7d616146dac8b06da42d8e7c6b62" +version = "11.0.0-beta.10" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 107ec19f3..aa1f01f57 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.8", default-features = false, "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.8", default-features = false, "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.8", default-features = false, "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.8", "tag" = "v11.0.0-beta.8", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.10", default-features = false, "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.10", default-features = false, "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.10", default-features = false, "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } ahash = "0.8" # Note that this one does not include pyarrow arrow = { version = "58.0.0", optional = false } diff --git a/java/pom.xml b/java/pom.xml index c580cf070..e9c04bc26 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.8 + 11.0.0-beta.10 false 2.30.0 1.7 From 4148dfef723cdb4a77e8f19eabef8e43cfbcfd30 Mon Sep 17 00:00:00 2001 From: XY Zhan Date: Fri, 14 Aug 2026 09:32:02 -0400 Subject: [PATCH 037/206] feat(lsm): require recorded index catch-up, as an explicit activation (#3911) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > Stacked on #3780. Blocked only on #3922 (`lance` → `v11.0.0-beta.6`), so CI > stays red until that lands. ## Missing coverage must mean "not known to be covered" #3780 caps the SSTable exclusion watermark at an index's recorded catch-up when there is one, and silently ignores the case where there is none. On a table that requires catch-up, an absent entry means the index is *not* known to hold the compacted rows — and the LSM base arm reads base through the index (`fast_search`, no brute-force tail), so dropping that SSTable loses those rows for that query. ```rust Some(caught_up) => watermark = watermark.min(caught_up), None if catchup_required => watermark = 0, // retain everything None => {} ``` `catchup_required` reads the manifest feature bit directly, and requires both words: a half-set manifest is treated as legacy, which is the conservative side. Without the bit the field is not maintained at all, so absence carries no information and behaviour is unchanged. ## Activation, as a table-level entry point `Table::require_mem_wal_index_catchup()` performs the one-way switch, separate from `set_lsm_write_spec`: a table carrying the bit retains every generation until something records catch-up, so it has to follow the deployment of whatever repairs coverage, not the creation of the table. This is a convenience, not the only path — a writer holding the dataset calls the equivalent on `DatasetMemWalExt`, which is what the WAL pod does. Lance enforces the preconditions either way: the MemWAL index must exist, and the table must not already carry `compacted_sstables` from before this protocol, since those numbers cannot be validated. ## Still correct after the Lance rework lance-format/lance#8481 replaced the transmitted `IndexCatchupAdvance` with a position derived at commit time from the version a transaction read. That changed how a writer earns coverage; it did not change what a reader may conclude from its absence. The rule here, and the field it reads, are unchanged. ## Tests Existing `exclusion_watermarks` unit tests carry the new argument. Coverage against a real dataset follows once #3922 lands and this can build. --- rust/lancedb/src/table.rs | 27 ++++++++++ rust/lancedb/src/table/merge/lsm.rs | 30 +++++++++++ rust/lancedb/src/table/query/lsm.rs | 78 +++++++++++++++++++++++++---- 3 files changed, 124 insertions(+), 11 deletions(-) diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 32b6bcebc..10822cafa 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -637,6 +637,15 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "set_lsm_write_spec is not supported on this table type".into(), }) } + /// Switch this table to required index catch-up, one way. + /// + /// The default implementation returns `NotSupported`. Implementations + /// that support the MemWAL LSM write path must override this. + async fn require_mem_wal_index_catchup(&self) -> Result<()> { + Err(Error::NotSupported { + message: "require_mem_wal_index_catchup is not supported on this table type".into(), + }) + } /// Remove the [`LsmWriteSpec`] from this table. /// /// This is a no-op if no spec is currently set. @@ -1693,6 +1702,20 @@ impl Table { self.inner.set_lsm_write_spec(spec).await } + /// Switch this table to required index catch-up, one way. + /// + /// Separate from [`Self::set_lsm_write_spec`] on purpose: a table carrying + /// the bit retains its SSTables until an index records that it holds the + /// compacted rows, so turn it on only once something can repair coverage. + /// A writer that already holds the dataset can call the equivalent on + /// `DatasetMemWalExt` instead; this is the table-level entry point. + /// + /// Errors if no spec is set, or if the table already records SSTable + /// compaction progress from before this protocol. + pub async fn require_mem_wal_index_catchup(&self) -> Result<()> { + self.inner.require_mem_wal_index_catchup().await + } + /// Remove the [`LsmWriteSpec`] from this table, reverting to the standard /// `merge_insert` write path. /// @@ -3226,6 +3249,10 @@ impl BaseTable for NativeTable { merge::lsm::set_lsm_write_spec(self, spec).await } + async fn require_mem_wal_index_catchup(&self) -> Result<()> { + merge::lsm::require_mem_wal_index_catchup(self).await + } + async fn unset_lsm_write_spec(&self) -> Result<()> { merge::lsm::unset_lsm_write_spec(self).await } diff --git a/rust/lancedb/src/table/merge/lsm.rs b/rust/lancedb/src/table/merge/lsm.rs index 87c427b3c..eb2feacbd 100644 --- a/rust/lancedb/src/table/merge/lsm.rs +++ b/rust/lancedb/src/table/merge/lsm.rs @@ -183,6 +183,36 @@ fn index_name_list(indices: &[IndexConfig]) -> String { format!("[{}]", names.join(", ")) } +// ============================================================================= +// require_mem_wal_index_catchup +// ============================================================================= + +/// Switch this table to required index catch-up, one way. +/// +/// Deliberately **not** part of installing the write spec. Until something can +/// actually repair coverage, a table carrying the bit reports every index as +/// not known to hold the compacted rows, so its SSTables are retained +/// indefinitely -- and the WAL pod trims on the legacy rule meanwhile, leaving +/// readers pointed at files that are gone. Turn this on only once remote +/// maintenance owns the merge and the repair for the table. +/// +/// Lance refuses the activation if the table already records SSTable +/// compaction progress: those numbers predate this protocol and cannot be +/// validated, so such a table must be drained rather than activated. +#[allow(clippy::redundant_pub_crate)] +pub(crate) async fn require_mem_wal_index_catchup(table: &NativeTable) -> Result<()> { + table.dataset.ensure_mutable()?; + let mut dataset = (*table.dataset.get().await?).clone(); + if dataset.mem_wal_index_details().await?.is_none() { + return Err(Error::InvalidInput { + message: "require_mem_wal_index_catchup: no LSM write spec is set on this table".into(), + }); + } + dataset.require_mem_wal_index_catchup().await?; + table.dataset.update(dataset); + Ok(()) +} + // ============================================================================= // unset_lsm_write_spec // ============================================================================= diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index 7ccdedf5a..6155ec095 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -36,6 +36,7 @@ use lance::dataset::mem_wal::{ DatasetMemWalExt, LsmScanner, ShardManifestStore, ShardSnapshot, ShardWriterConfig, }; use lance_index::mem_wal::{MemWalIndexDetails, ShardManifest}; +use lance_table::feature_flags::FLAG_MEM_WAL_INDEX_CATCHUP; use uuid::Uuid; use super::NativeTable; @@ -248,18 +249,26 @@ fn pk_columns(dataset: &Dataset) -> Result> { fn exclusion_watermarks( details: &MemWalIndexDetails, index_names: &[String], + catchup_required: bool, ) -> HashMap { let mut exclude: HashMap = HashMap::new(); for entry in &details.compacted_sstables { let mut watermark = entry.generation; for name in index_names { - if let Some(caught_up) = details + match details .index_catchup .iter() .find(|icp| icp.index_name == *name) .and_then(|icp| icp.caught_up_generation_for_shard(&entry.shard_id)) { - watermark = watermark.min(caught_up); + Some(caught_up) => watermark = watermark.min(caught_up), + // No entry. On a table that requires catch-up this means the + // index is *not* known to hold these rows, and the base arm is + // index-only -- so every generation stays readable from its + // SSTable. Without the bit the field is not maintained at all, + // and absence carries no information. + None if catchup_required => watermark = 0, + None => {} } } exclude.entry(entry.shard_id).or_insert(watermark); @@ -274,13 +283,26 @@ fn exclusion_watermarks( /// with a live cached `ShardWriter` (this session's in-flight writes) the /// writer's authoritative in-memory manifest and memtables override the /// on-disk view so a read sees data not yet flushed. +/// Whether this table reads a missing `index_catchup` entry as "not caught up". +/// +/// Both words must be set. A reader honouring the bit while a writer does not +/// would retain SSTables the writer had already trimmed, and the reverse would +/// serve rows from files the writer still expects to be excluded -- so a +/// half-set manifest is treated as legacy, which is the conservative side. +fn requires_index_catchup(dataset: &Dataset) -> bool { + let manifest = dataset.manifest(); + manifest.reader_feature_flags & FLAG_MEM_WAL_INDEX_CATCHUP != 0 + && manifest.writer_feature_flags & FLAG_MEM_WAL_INDEX_CATCHUP != 0 +} + async fn build_read_context( table: &NativeTable, dataset: &Dataset, details: &MemWalIndexDetails, index_names: &[String], ) -> Result<(Vec, HashMap)> { - let exclude = exclusion_watermarks(details, index_names); + let catchup_required = requires_index_catchup(dataset); + let exclude = exclusion_watermarks(details, index_names, catchup_required); let shard_ids = dataset.list_mem_wal_latest_shard_ids().await?; // Use the dataset's own object store (not `ObjectStore::from_uri`, which @@ -767,22 +789,50 @@ mod tests { }; // Plain scan: drop every compacted generation (through 5). - assert_eq!(exclusion_watermarks(&details, &[]).get(&shard), Some(&5)); + assert_eq!( + exclusion_watermarks(&details, &[], false).get(&shard), + Some(&5) + ); // FTS arm with a lagging index: exclusion is capped at the index catch-up // (2), so SSTable generations 3..=5 are retained until the index covers // them — otherwise those documents would silently vanish from FTS results. assert_eq!( - exclusion_watermarks(&details, &["fts_idx".to_string()]).get(&shard), + exclusion_watermarks(&details, &["fts_idx".to_string()], false).get(&shard), Some(&2) ); // A caught-up index — or one untracked in index_catchup — falls back to the // compaction watermark. assert_eq!( - exclusion_watermarks(&details, &["caught_up_idx".to_string()]).get(&shard), + exclusion_watermarks(&details, &["caught_up_idx".to_string()], false).get(&shard), Some(&5) ); + + // The same missing entry, once the table requires catch-up: absence now + // means "not known to hold these rows", so nothing may be excluded and + // every generation stays readable from its SSTable. This is the whole + // point of the protocol -- an indexed query against a table whose index + // has not caught up must not silently lose rows. + assert_eq!( + exclusion_watermarks(&details, &["untracked_idx".to_string()], true).get(&shard), + Some(&0) + ); + + // A tracked index is unaffected by the mode: the recorded position is + // information either way, and it still caps the exclusion. + assert_eq!( + exclusion_watermarks(&details, &["fts_idx".to_string()], true).get(&shard), + Some(&2) + ); + + // One missing entry is enough to hold everything back, even alongside an + // index that has caught up. + let mixed = vec!["fts_idx".to_string(), "untracked_idx".to_string()]; + assert_eq!( + exclusion_watermarks(&details, &mixed, true).get(&shard), + Some(&0) + ); } /// A hybrid search reads a vector and a full-text index, and either may lag. @@ -809,20 +859,23 @@ mod tests { // Each index alone stops at its own catch-up. assert_eq!( - exclusion_watermarks(&details, &["vec_idx".to_string()]).get(&shard), + exclusion_watermarks(&details, &["vec_idx".to_string()], false).get(&shard), Some(&7) ); assert_eq!( - exclusion_watermarks(&details, &["fts_idx".to_string()]).get(&shard), + exclusion_watermarks(&details, &["fts_idx".to_string()], false).get(&shard), Some(&4) ); // Used together, the lower one governs regardless of order. let both = ["vec_idx".to_string(), "fts_idx".to_string()]; - assert_eq!(exclusion_watermarks(&details, &both).get(&shard), Some(&4)); + assert_eq!( + exclusion_watermarks(&details, &both, false).get(&shard), + Some(&4) + ); let reversed = ["fts_idx".to_string(), "vec_idx".to_string()]; assert_eq!( - exclusion_watermarks(&details, &reversed).get(&shard), + exclusion_watermarks(&details, &reversed, false).get(&shard), Some(&4) ); } @@ -843,7 +896,10 @@ mod tests { }; let both = ["fts_idx".to_string(), "untracked_idx".to_string()]; - assert_eq!(exclusion_watermarks(&details, &both).get(&shard), Some(&4)); + assert_eq!( + exclusion_watermarks(&details, &both, false).get(&shard), + Some(&4) + ); } #[test] From 9e4d8bd1c7ff782c4653ecea8f701d1d58a2fb03 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Fri, 14 Aug 2026 08:31:58 -0700 Subject: [PATCH 038/206] chore: update lance dependency to v11.0.0-beta.11 (#3946) Updates the Rust workspace Lance crates and Java lance-core dependency to v11.0.0-beta.11. No compatibility fixes were required; formatting and full-workspace clippy validation pass. Lance tag: https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.11 --- Cargo.lock | 84 ++++++++++++++++++++++++++-------------------------- Cargo.toml | 28 +++++++++--------- java/pom.xml | 2 +- 3 files changed, 57 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f9e1566a4..b4f11fb65 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow", "arrow-array", @@ -5013,8 +5013,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow", "arrow-array", @@ -5031,8 +5031,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "proc-macro2", "quote", @@ -5041,8 +5041,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow-arith", "arrow-array", @@ -5075,8 +5075,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow-arith", "arrow-array", @@ -5107,8 +5107,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arc-swap", "arrow", @@ -5172,8 +5172,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow-array", "arrow-schema", @@ -5195,8 +5195,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow", "arrow-array", @@ -5232,8 +5232,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow-array", "arrow-schema", @@ -5247,8 +5247,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow", "async-trait", @@ -5260,8 +5260,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow", "arrow-ipc", @@ -5314,8 +5314,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow-array", "arrow-buffer", @@ -5329,8 +5329,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow", "arrow-array", @@ -5370,8 +5370,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "arrow-array", "arrow-schema", @@ -5384,8 +5384,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.10" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.10#6ff89857202accce53670dcee6069b1dddfea4dd" +version = "11.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index aa1f01f57..3e332adfc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.10", default-features = false, "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.10", default-features = false, "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.10", default-features = false, "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.10", "tag" = "v11.0.0-beta.10", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.11", default-features = false, "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.11", default-features = false, "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.11", default-features = false, "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } ahash = "0.8" # Note that this one does not include pyarrow arrow = { version = "58.0.0", optional = false } diff --git a/java/pom.xml b/java/pom.xml index e9c04bc26..9d9fe1f87 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.10 + 11.0.0-beta.11 false 2.30.0 1.7 From def869bb7815ce29ca7cf671a5b17010dee48b15 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Fri, 14 Aug 2026 14:17:41 -0700 Subject: [PATCH 039/206] feat: declare computed columns by SQL expression (#3937) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit add_columns().computed("doubled", "x * 2") stores the expression in field metadata and commits the column empty; a later refresh fills it. Type and inputs are derived from the expression. The declaration stays authoritative for its lifetime: writes that would give the column a value (append, update, merge, SQL insert), schema changes that would break the stored expression or reshape its output, metadata edits, volatile expressions, declaration metadata arriving through any path but the validated declare call, and LSM write specs in either order against latest committed state are all refused. The LSM check also refuses on the mem-wal catch-up feature flag, which outlives unset and marks retained SSTable rows. Simultaneous declare/install interleavings conflict at commit via lance's mem-wal rule (lance#8539). Local tables only. --- Stack created with GitHub Stacks CLIGive Feedback 💬 --- docs/src/js/classes/Table.md | 27 +- nodejs/__test__/table.test.ts | 19 + nodejs/lancedb/table.ts | 41 +- nodejs/src/table.rs | 14 + python/python/lancedb/_lancedb.pyi | 3 + python/python/lancedb/remote/table.py | 11 +- python/python/lancedb/table.py | 78 +- python/python/tests/test_table.py | 19 + python/src/table.rs | 15 + rust/lancedb/src/error.rs | 8 + rust/lancedb/src/remote/table.rs | 32 + rust/lancedb/src/table.rs | 32 + rust/lancedb/src/table/add_columns.rs | 137 +- rust/lancedb/src/table/computed_columns.rs | 1329 +++++++++++++++++++ rust/lancedb/src/table/datafusion/insert.rs | 17 +- rust/lancedb/src/table/merge/lsm.rs | 9 + rust/lancedb/src/table/schema_evolution.rs | 105 +- rust/lancedb/src/table/update.rs | 4 + 18 files changed, 1865 insertions(+), 35 deletions(-) create mode 100644 rust/lancedb/src/table/computed_columns.rs diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 3fa3b08db..97bdea628 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -69,14 +69,33 @@ abstract addColumns(newColumnTransforms): Promise Add new columns with defined values. +The `{ computed }` form stores the expression rather than evaluating it +now: the column is committed with no values, and a later refresh fills +the rows. Declaring one therefore costs the same on a large table as on +an empty one. + +A refresh does not revisit rows it has already filled, so mutating an +input leaves the value computed at fill time; recomputing means dropping +the column and declaring it again. While a declaration reads a column, +that column cannot be renamed, retyped or dropped. + +Computed columns are local-only: LanceDB Cloud and Enterprise reject a +declaration. + #### Parameters -* **newColumnTransforms**: `Field`<`any`> \| `Field`<`any`>[] \| `Schema`<`any`> \| [`AddColumnsSql`](../interfaces/AddColumnsSql.md)[] +* **newColumnTransforms**: + \| `Field`<`any`> + \| `Field`<`any`>[] + \| `Schema`<`any`> + \| [`AddColumnsSql`](../interfaces/AddColumnsSql.md)[] + \| `object` Either: - An array of objects with column names and SQL expressions to calculate values - A single Arrow Field defining one column with its data type (column will be initialized with null values) - An array of Arrow Fields defining columns with their data types (columns will be initialized with null values) - An Arrow Schema defining columns with their data types (columns will be initialized with null values) + - `{ computed }`, declaring columns defined by a SQL expression whose type and inputs are derived from it #### Returns @@ -85,6 +104,12 @@ Add new columns with defined values. A promise that resolves to an object containing the new version number of the table after adding the columns. +#### Example + +```ts +await table.addColumns({ computed: [{ name: "doubled", valueSql: "x * 2" }] }); +``` + *** ### alterColumns() diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index d263d9cab..5ff18da3e 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -3340,3 +3340,22 @@ describe("LSM merge insert", () => { await expect(table.query().useLsm(true).toArray()).rejects.toThrow(); }); }); + +describe("computed columns", () => { + let tmpDir: tmp.DirResult; + beforeEach(() => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + }); + afterEach(() => tmpDir.removeCallback()); + + it("declares a column with no values", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("computed", [{ x: 1 }, { x: 2 }]); + + await table.addColumns({ + computed: [{ name: "doubled", valueSql: "x * 2" }], + }); + const rows = await table.query().toArray(); + expect(rows.map((r) => r.doubled)).toEqual([null, null]); + }); +}); diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 04705475b..6234b8fbf 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -525,16 +525,39 @@ export abstract class Table { abstract vectorSearch(vector: IntoVector | MultiVector): VectorQuery; /** * Add new columns with defined values. + * + * The `{ computed }` form stores the expression rather than evaluating it + * now: the column is committed with no values, and a later refresh fills + * the rows. Declaring one therefore costs the same on a large table as on + * an empty one. + * + * A refresh does not revisit rows it has already filled, so mutating an + * input leaves the value computed at fill time; recomputing means dropping + * the column and declaring it again. While a declaration reads a column, + * that column cannot be renamed, retyped or dropped. + * + * Computed columns are local-only: LanceDB Cloud and Enterprise reject a + * declaration. * @param {AddColumnsSql[] | Field | Field[] | Schema} newColumnTransforms Either: * - An array of objects with column names and SQL expressions to calculate values * - A single Arrow Field defining one column with its data type (column will be initialized with null values) * - An array of Arrow Fields defining columns with their data types (columns will be initialized with null values) * - An Arrow Schema defining columns with their data types (columns will be initialized with null values) + * - `{ computed }`, declaring columns defined by a SQL expression whose type and inputs are derived from it * @returns {Promise} A promise that resolves to an object * containing the new version number of the table after adding the columns. + * @example + * ```ts + * await table.addColumns({ computed: [{ name: "doubled", valueSql: "x * 2" }] }); + * ``` */ abstract addColumns( - newColumnTransforms: AddColumnsSql[] | Field | Field[] | Schema, + newColumnTransforms: + | AddColumnsSql[] + | Field + | Field[] + | Schema + | { computed: AddColumnsSql[] }, ): Promise; /** @@ -1088,8 +1111,22 @@ export class LocalTable extends Table { // TODO: Support BatchUDF async addColumns( - newColumnTransforms: AddColumnsSql[] | Field | Field[] | Schema, + newColumnTransforms: + | AddColumnsSql[] + | Field + | Field[] + | Schema + | { computed: AddColumnsSql[] }, ): Promise { + // Columns defined by an expression are declared, not materialized here. + if ( + typeof newColumnTransforms === "object" && + !Array.isArray(newColumnTransforms) && + "computed" in newColumnTransforms + ) { + return await this.inner.addComputedColumns(newColumnTransforms.computed); + } + // Handle single Field -> convert to array of Fields if (newColumnTransforms instanceof Field) { newColumnTransforms = [newColumnTransforms]; diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index c4ece20e2..16ca387e6 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -347,6 +347,20 @@ impl Table { Ok(res.into()) } + #[napi(catch_unwind)] + pub async fn add_computed_columns( + &self, + columns: Vec, + ) -> napi::Result { + let table = self.inner_ref()?; + let mut builder = table.add_columns(); + for column in columns { + builder = builder.computed(column.name, column.value_sql); + } + let res = builder.execute().await.default_error()?; + Ok(res.into()) + } + #[napi(catch_unwind)] pub async fn add_columns_with_schema( &self, diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 447bcc88a..84455d74b 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -338,6 +338,9 @@ class Table: ) -> list[FtsToken]: ... async def delete(self, filter: Union[str, PyExpr]) -> DeleteResult: ... async def add_columns(self, columns: list[tuple[str, str]]) -> AddColumnsResult: ... + async def add_computed_columns( + self, columns: list[tuple[str, str]] + ) -> AddColumnsResult: ... async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ... async def alter_columns( self, columns: list[dict[str, Any]] diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index acc2f4c9d..5c98a64f1 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -958,7 +958,16 @@ class RemoteTable(Table): def count_rows(self, filter: Optional[str] = None) -> int: return LOOP.run(self._table.count_rows(filter)) - def add_columns(self, transforms: Dict[str, str]) -> AddColumnsResult: + def add_columns( + self, + transforms: Dict[str, str] | None = None, + *, + computed: Dict[str, str] | None = None, + ) -> AddColumnsResult: + if computed: + raise NotImplementedError( + "computed columns are supported only on local tables" + ) return LOOP.run(self._table.add_columns(transforms)) def alter_columns( diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index c566fc532..5c9104699 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1916,7 +1916,14 @@ class Table(ABC): @abstractmethod def add_columns( - self, transforms: Dict[str, str] | pa.Field | List[pa.Field] | pa.Schema + self, + transforms: Dict[str, str] + | pa.Field + | List[pa.Field] + | pa.Schema + | None = None, + *, + computed: Dict[str, str] | None = None, ): """ Add new columns with defined values. @@ -1930,11 +1937,38 @@ class Table(ABC): Alternatively, a pyarrow Field or Schema can be provided to add new columns with the specified data types. The new columns will be initialized with null values. + computed: Dict[str, str], optional + A map of column name to a SQL expression defining the column. The + column's type and inputs are derived from the expression, so no + data type is supplied. + + Unlike ``transforms``, the expression is stored rather than + evaluated now: the column is committed with no values, and a + later refresh fills the rows. Declaring one therefore costs the + same on a large table as on an empty one. + + A refresh does not revisit rows it has already filled, so mutating + an input leaves the value computed at fill time; recomputing means + dropping the column and declaring it again. While a declaration + reads a column, that column cannot be renamed, retyped or dropped. + + Local tables only; LanceDB Cloud and Enterprise raise + ``NotImplementedError``. Cannot be combined with ``transforms``. Returns ------- AddColumnsResult version: the new version number of the table after adding columns. + + Examples + -------- + >>> import lancedb + >>> db = lancedb.connect("./.lancedb") + >>> table = db.create_table("computed_demo", [{"x": 1}, {"x": 2}]) + >>> table.add_columns(computed={"doubled": "x * 2"}) + AddColumnsResult(version=2) + >>> table.to_arrow()["doubled"].to_pylist() + [None, None] """ @abstractmethod @@ -3939,9 +3973,16 @@ class LanceTable(Table): return LOOP.run(self._table.index_stats(index_name)) def add_columns( - self, transforms: Dict[str, str] | pa.field | List[pa.field] | pa.Schema + self, + transforms: Dict[str, str] + | pa.field + | List[pa.field] + | pa.Schema + | None = None, + *, + computed: Dict[str, str] | None = None, ) -> AddColumnsResult: - return LOOP.run(self._table.add_columns(transforms)) + return LOOP.run(self._table.add_columns(transforms, computed=computed)) def alter_columns( self, *alterations: Iterable[Dict[str, str]] @@ -5856,7 +5897,14 @@ class AsyncTable: return await self._inner.update(updates_sql, where) async def add_columns( - self, transforms: dict[str, str] | pa.field | List[pa.field] | pa.Schema + self, + transforms: dict[str, str] + | pa.field + | List[pa.field] + | pa.Schema + | None = None, + *, + computed: dict[str, str] | None = None, ) -> AddColumnsResult: """ Add new columns with defined values. @@ -5869,6 +5917,20 @@ class AsyncTable: each row in the table, and can reference existing columns. Alternatively, you can pass a pyarrow field or schema to add new columns with NULLs. + computed: Dict[str, str], optional + A map of column name to a SQL expression defining the column. The + column's type and inputs are derived from the expression. + + Unlike ``transforms``, the expression is stored rather than + evaluated now: the column is committed with no values, and a + later refresh fills the rows. + + A refresh does not revisit rows it has already filled, so mutating + an input leaves the value computed at fill time. While a + declaration reads a column, that column cannot be renamed, retyped + or dropped. + + Local tables only. Cannot be combined with ``transforms``. Returns ------- @@ -5882,6 +5944,14 @@ class AsyncTable: {isinstance(f, pa.Field) for f in transforms} ): transforms = pa.schema(transforms) + if computed: + if transforms: + raise ValueError( + "add_columns cannot take both transforms and computed columns" + ) + return await self._inner.add_computed_columns(list(computed.items())) + if transforms is None: + raise ValueError("add_columns requires transforms or computed columns") if isinstance(transforms, pa.Schema): return await self._inner.add_columns_with_schema(transforms) else: diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 2a069c712..6393cd42a 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -3854,3 +3854,22 @@ async def test_async_search_runs_embedding_on_dedicated_executor( assert all(name.startswith("lancedb-embedding") for name in captured_threads), ( f"embedding ran off the dedicated executor: {captured_threads}" ) + + +def test_computed_column_declares_all_null(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("computed", [{"x": 1}, {"x": 2}]) + + table.add_columns(computed={"doubled": "x * 2"}) + assert table.to_arrow()["doubled"].to_pylist() == [None, None] + + # The declaration is durable field metadata. + field = table.schema.field("doubled") + assert field.metadata[b"computed_column.expression"] == b"x * 2" + + +def test_computed_column_rejects_transforms_and_computed_together(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("computed_mixed", [{"x": 1}]) + with pytest.raises(ValueError): + table.add_columns({"a": "x + 1"}, computed={"b": "x * 2"}) diff --git a/python/src/table.rs b/python/src/table.rs index cae6b5d9a..a9ff70ad6 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1510,6 +1510,21 @@ impl Table { }) } + pub fn add_computed_columns( + self_: PyRef<'_, Self>, + columns: Vec<(String, String)>, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let mut builder = inner.add_columns(); + for (name, expression) in columns { + builder = builder.computed(name, expression); + } + let result = builder.execute().await.infer_error()?; + Ok(AddColumnsResult::from(result)) + }) + } + pub fn add_columns_with_schema( self_: PyRef<'_, Self>, schema: PyArrowType, diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 4a6e6d8d9..6bd1ffa2b 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -71,6 +71,14 @@ pub enum Error { IndexNotFound { name: String }, #[snafu(display("Embedding function '{name}' was not found. : {reason}"))] EmbeddingFunctionNotFound { name: String, reason: String }, + #[snafu(display("Column '{name}' was not found"))] + ColumnNotFound { name: String }, + #[snafu(display("Column '{name}' already exists"))] + ColumnAlreadyExists { name: String }, + #[snafu(display("Column '{name}' is not a computed column"))] + NotAComputedColumn { name: String }, + #[snafu(display("Invalid expression for column '{column}': {message}"))] + InvalidExpression { column: String, message: String }, #[snafu(display("Table '{name}' already exists"))] TableAlreadyExists { name: String }, diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 3816a3a86..3e467b674 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2700,6 +2700,13 @@ impl BaseTable for RemoteTable { Ok(result) } + // A declaration reaches here as AllNulls, which the remote protocol + // has no representation for. + NewColumnTransform::AllNulls(_) => { + return Err(Error::NotSupported { + message: "computed columns are supported only on local tables".into(), + }); + } _ => { return Err(Error::NotSupported { message: "Only SQL expressions are supported for adding columns".into(), @@ -6449,6 +6456,31 @@ mod tests { assert_eq!(result.version, if old_server { 0 } else { 43 }); } + /// Computed columns are local-only. Both halves say so here rather than + /// reaching the wire and failing somewhere less legible. + #[tokio::test] + async fn test_computed_columns_are_refused() { + let table = Table::new_with_handler("my_table", |request| -> http::Response { + panic!("unexpected request: {}", request.url().path()) + }); + + let declared = Arc::new(Schema::new(vec![Field::new( + "doubled", + DataType::Int32, + true, + )])); + let err = table + .add_columns() + .transform(NewColumnTransform::AllNulls(declared)) + .execute() + .await + .unwrap_err(); + assert!( + matches!(&err, Error::NotSupported { message } if message.contains("local tables")), + "{err:?}" + ); + } + #[tokio::test] async fn test_prewarm_index() { let table = Table::new_with_handler("my_table", |request| { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 10822cafa..00a51058c 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -68,6 +68,7 @@ pub mod add_columns; mod add_data; pub mod branch_merge; pub mod checkpoint; +pub mod computed_columns; mod create_index; pub mod datafusion; pub(crate) mod dataset; @@ -90,6 +91,9 @@ pub use branch_merge::{ MergeBranchResult, MergeBranchStatus, MergePreview, RowCountSummary, }; pub use chrono::Duration; +pub use computed_columns::{ + ComputedColumn, ComputedColumnKind, computed_column_from_field, computed_columns, +}; pub use delete::DeleteResult; use futures::future::join_all; pub use lance::dataset::refs::{BranchContents, Ref, TagContents, Tags as LanceTags}; @@ -741,6 +745,15 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { transforms: NewColumnTransform, read_columns: Option>, ) -> Result; + /// Declare computed columns, each defined by a SQL expression. + async fn add_computed_columns( + &self, + _columns: &[(String, String)], + ) -> Result { + Err(Error::NotSupported { + message: "computed columns are not supported on this table type".into(), + }) + } /// Alter columns in the table. async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result; /// Drop columns from the table. @@ -2628,6 +2641,7 @@ impl NativeTable { namespace_client: Option>, pushdown_operations: HashSet, ) -> Result { + computed_columns::ensure_no_foreign_declarations(batches.arrow_schema().fields())?; // Default params uses format v1. let params = params.unwrap_or(WriteParams { ..Default::default() @@ -3076,6 +3090,13 @@ impl BaseTable for NativeTable { let ds = self.dataset.get().await?; let table_schema = Schema::from(&ds.schema().clone()); + computed_columns::ensure_not_written( + &table_schema, + add.data.schema().fields().iter().map(|f| f.name().as_str()), + )?; + if matches!(add.mode, AddDataMode::Overwrite) { + computed_columns::ensure_no_foreign_declarations(add.data.schema().fields())?; + } let num_partitions = if let Some(parallelism) = add.write_parallelism { parallelism @@ -3236,6 +3257,11 @@ impl BaseTable for NativeTable { params: MergeInsertBuilder, new_data: Box, ) -> Result { + let source_schema = arrow_array::RecordBatchReader::schema(&new_data); + computed_columns::ensure_not_written( + &Schema::from(self.dataset.get().await?.schema()), + source_schema.fields().iter().map(|f| f.name().as_str()), + )?; let result = merge::execute_merge_insert(self, params, new_data).await?; self.bump_freshness(); Ok(result) @@ -3321,6 +3347,12 @@ impl BaseTable for NativeTable { Ok(result) } + async fn add_computed_columns(&self, columns: &[(String, String)]) -> Result { + let result = schema_evolution::execute_declare(self, columns).await?; + self.bump_freshness(); + Ok(result) + } + async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result { let result = schema_evolution::execute_alter_columns(self, alterations).await?; self.bump_freshness(); diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index 0d410cd04..e5c4ef8d1 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -15,6 +15,7 @@ use crate::{Error, Result}; pub struct AddColumnsBuilder { parent: Arc, transform: Option, + computed: Vec<(String, String)>, read_columns: Option>, } @@ -23,6 +24,7 @@ impl std::fmt::Debug for AddColumnsBuilder { f.debug_struct("AddColumnsBuilder") .field("parent", &self.parent) .field("has_transform", &self.transform.is_some()) + .field("computed", &self.computed) .field("read_columns", &self.read_columns) .finish() } @@ -33,19 +35,54 @@ impl AddColumnsBuilder { Self { parent, transform: None, + computed: Vec::new(), read_columns: None, } } - /// Set how the new columns' values are produced. Required. + /// Set how the new columns' values are produced. pub fn transform(mut self, transform: NewColumnTransform) -> Self { self.transform = Some(transform); self } + /// Add a column defined by `expression`, evaluated by a later refresh + /// rather than by this commit. Its type and inputs are derived from the + /// expression. + /// + /// The column is committed with no values, so declaring one costs the same + /// on an empty table as on a large one. Rows get values from a later + /// refresh, which fills every fragment that has none -- including + /// fragments appended since the last refresh. + /// + /// Refresh does not revisit a fragment it has filled, so mutating an input + /// leaves the value computed at fill time; recomputing means dropping the + /// column and declaring it again. An input cannot be renamed, retyped or + /// dropped while a declaration reads it, since the expression names it. + /// + /// Local tables only: LanceDB Cloud and Enterprise reject a declaration + /// with `NotSupported`. + /// + /// ``` + /// # use lancedb::Table; + /// # async fn declare(table: &Table) -> Result<(), Box> { + /// table + /// .add_columns() + /// .computed("doubled", "x * 2") + /// .execute() + /// .await?; + /// # Ok(()) + /// # } + /// ``` + pub fn computed(mut self, name: impl Into, expression: impl Into) -> Self { + self.computed.push((name.into(), expression.into())); + self + } + /// Limit which existing columns a [`NewColumnTransform::BatchUDF`] mapper - /// receives. Every other transform determines what it reads, so setting - /// this alongside one is an error rather than a silent no-op. + /// receives. Every other transform, and a computed column, determines what + /// it reads, so setting this alongside one is an error rather than a silent + /// no-op. pub fn read_columns(mut self, columns: impl IntoIterator>) -> Self { self.read_columns = Some(columns.into_iter().map(Into::into).collect()); self @@ -56,24 +93,42 @@ impl AddColumnsBuilder { let Self { parent, transform, + computed, read_columns, } = self; - let Some(transform) = transform else { - return Err(Error::InvalidInput { - message: "add_columns requires a transform".into(), - }); - }; - - if read_columns.is_some() && !matches!(transform, NewColumnTransform::BatchUDF(_)) { - return Err(Error::InvalidInput { - message: "read_columns applies only to a BatchUDF transform; \ - every other transform determines what it reads" + match (transform, computed.is_empty()) { + (None, true) => Err(Error::InvalidInput { + message: "add_columns requires a transform or a computed column".into(), + }), + // The two commit through different transforms, so one call covering + // both would be two commits and could half-apply. + (Some(_), false) => Err(Error::InvalidInput { + message: "add_columns cannot mix a transform with computed columns; \ + they cannot be added atomically in one call" .into(), - }); + }), + (Some(transform), true) => { + if read_columns.is_some() && !matches!(transform, NewColumnTransform::BatchUDF(_)) { + return Err(Error::InvalidInput { + message: "read_columns applies only to a BatchUDF transform; \ + every other transform determines what it reads" + .into(), + }); + } + parent.add_columns(transform, read_columns).await + } + (None, false) => { + if read_columns.is_some() { + return Err(Error::InvalidInput { + message: "read_columns applies only to a BatchUDF transform; \ + a computed column's inputs come from its expression" + .into(), + }); + } + parent.add_computed_columns(&computed).await + } } - - parent.add_columns(transform, read_columns).await } } @@ -85,8 +140,8 @@ mod tests { use arrow_schema::{DataType, Field, Schema}; use lance::dataset::{BatchUDF, NewColumnTransform}; - use crate::Table; use crate::connect; + use crate::{Error, Table}; async fn table_with_two_columns(name: &str) -> Table { let conn = connect("memory://").execute().await.unwrap(); @@ -98,10 +153,7 @@ mod tests { async fn test_requires_a_transform() { let table = table_with_two_columns("no_transform").await; let err = table.add_columns().execute().await.unwrap_err(); - assert!( - err.to_string().contains("requires a transform"), - "got: {err}" - ); + assert!(matches!(err, Error::InvalidInput { .. })); } #[tokio::test] @@ -117,7 +169,7 @@ mod tests { .execute() .await .unwrap_err(); - assert!(err.to_string().contains("BatchUDF"), "got: {err}"); + assert!(matches!(err, Error::InvalidInput { .. })); let schema = table.schema().await.unwrap(); assert!( @@ -126,6 +178,47 @@ mod tests { ); } + #[tokio::test] + async fn test_mixing_transform_and_computed_is_rejected() { + let table = table_with_two_columns("mixed_add").await; + let err = table + .add_columns() + .transform(NewColumnTransform::SqlExpressions(vec![( + "eager".into(), + "x * 2".into(), + )])) + .computed("lazy", "x * 3") + .execute() + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidInput { .. })); + + let schema = table.schema().await.unwrap(); + assert!(schema.field_with_name("eager").is_err()); + assert!(schema.field_with_name("lazy").is_err()); + } + + #[tokio::test] + async fn test_read_columns_with_computed_is_rejected() { + let table = table_with_two_columns("read_cols_computed").await; + let err = table + .add_columns() + .computed("doubled", "x * 2") + .read_columns(["x"]) + .execute() + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidInput { .. })); + assert!( + table + .schema() + .await + .unwrap() + .field_with_name("doubled") + .is_err() + ); + } + #[tokio::test] async fn test_read_columns_limits_what_a_batch_udf_sees() { let table = table_with_two_columns("read_cols_udf").await; diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs new file mode 100644 index 000000000..4787b420f --- /dev/null +++ b/rust/lancedb/src/table/computed_columns.rs @@ -0,0 +1,1329 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Computed columns. +//! +//! A computed column is defined by a rule rather than by values supplied at +//! write time. Declaring one commits the column carrying that rule in field +//! metadata but no data, so the cost does not scale with the table; a later +//! refresh fills the rows. +//! +//! The rule is tagged by kind ([`ComputedColumnKind`]) because kinds differ in +//! where the column's type and inputs come from. A SQL expression is +//! self-describing -- both are derived from the expression, so a caller writes +//! neither -- while a kind resolved through a registry cannot be typed without +//! consulting it. Only SQL exists today; the tag is what lets another kind be +//! added without a second reading of the same key. +//! +//! [`computed_columns`] and [`computed_column_from_field`] read declarations +//! back off a schema. + +use std::collections::HashMap; +use std::sync::Arc; + +use arrow_schema::{DataType, Field as ArrowField, Schema as ArrowSchema, SchemaRef}; +use datafusion_common::tree_node::TreeNode; +use lance::dataset::NewColumnTransform; +use lance_datafusion::planner::Planner; + +use crate::{Error, Result}; + +/// Field metadata key marking a column as computed. The value is `"true"`. +pub const COMPUTED_COLUMN_META_KEY: &str = "computed_column"; + +/// Field metadata key naming the kind of rule that defines the column. +pub const KIND_META_KEY: &str = "computed_column.kind"; + +/// Field metadata key holding the SQL expression that defines the column. +pub const EXPRESSION_META_KEY: &str = "computed_column.expression"; + +/// Field metadata key holding the column's inputs, as a JSON array of names. +pub const INPUTS_META_KEY: &str = "computed_column.inputs"; + +/// Value of [`KIND_META_KEY`] for a column defined by a SQL expression. +pub const SQL_KIND: &str = "sql"; + +/// The rule that defines a computed column's values. +/// +/// Non-exhaustive: a kind added later is an additive change, and a caller that +/// only handles the kinds it knows keeps compiling. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum ComputedColumnKind { + /// A SQL expression evaluated by DataFusion. It is the whole definition: + /// the column's type and its inputs are both derived from it. + Sql { + /// The expression. + expression: String, + }, + /// A kind this version does not understand, written by a newer one. + /// + /// Reported rather than hidden so a caller can tell a column it cannot + /// refresh apart from one that was never computed. Nothing produces this. + Unrecognized { + /// The kind as it was found in the metadata. + kind: String, + }, +} + +/// A computed column's declaration, as read back from field metadata. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ComputedColumn { + /// Name of the computed column. + pub name: String, + /// The rule that defines it. + pub kind: ComputedColumnKind, + /// Columns the rule reads, recorded at declaration time. + /// + /// Outside the kind because every kind has inputs and the consumers that + /// use them -- refresh planning, dependency ordering -- do not care which + /// kind produced them. Where they come from does differ, and that is + /// settled at declaration: derived from a SQL expression, supplied by the + /// caller for a kind that cannot be parsed. + pub inputs: Vec, +} + +/// Build the field metadata recording a SQL binding. +fn computed_column_metadata(expression: &str, inputs: &[String]) -> HashMap { + HashMap::from([ + (COMPUTED_COLUMN_META_KEY.to_string(), "true".to_string()), + (KIND_META_KEY.to_string(), SQL_KIND.to_string()), + (EXPRESSION_META_KEY.to_string(), expression.to_string()), + ( + INPUTS_META_KEY.to_string(), + serde_json::to_string(inputs).unwrap_or_else(|_| "[]".to_string()), + ), + ]) +} + +/// Read a field's computed-column declaration, if it carries one. +/// +/// A field flagged computed but carrying no kind, or a SQL one missing its +/// expression, is not a computed column here: without the rule there is +/// nothing to refresh from, so it is reported as absent rather than as a +/// half-formed declaration. An unrecognized kind is different -- the rule is +/// there and intact, this version just cannot act on it -- and comes back as +/// [`ComputedColumnKind::Unrecognized`]. +pub fn computed_column_from_field(field: &ArrowField) -> Option { + let metadata = field.metadata(); + if metadata.get(COMPUTED_COLUMN_META_KEY).map(String::as_str) != Some("true") { + return None; + } + let kind = match metadata.get(KIND_META_KEY)?.as_str() { + SQL_KIND => ComputedColumnKind::Sql { + expression: metadata.get(EXPRESSION_META_KEY)?.clone(), + }, + other => ComputedColumnKind::Unrecognized { + kind: other.to_string(), + }, + }; + let inputs = metadata + .get(INPUTS_META_KEY) + .and_then(|raw| serde_json::from_str::>(raw).ok()) + .unwrap_or_default(); + Some(ComputedColumn { + name: field.name().clone(), + kind, + inputs, + }) +} + +/// Read every computed-column declaration carried by `schema`, in field order. +/// +/// Introspection is a pure read of the schema the caller already holds, the +/// way a SQL catalog reports a generation expression as another column of +/// `information_schema.columns`. +pub fn computed_columns(schema: &ArrowSchema) -> Vec { + schema + .fields() + .iter() + .filter_map(|field| computed_column_from_field(field)) + .collect() +} + +/// Reject a schema change to a column some declaration reads. +/// +/// A binding is SQL text naming its inputs, so renaming, retyping or dropping +/// one leaves an expression that no longer resolves. Refusing the change keeps +/// a declaration that survived [`plan`] evaluable for as long as it exists. +/// +/// 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<()> { + for declaration in computed_columns(schema) { + // 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()) + .parse_expr(expression) + .map(|parsed| Planner::column_names_in_expr(&parsed)) + .map_err(|e| Error::InvalidInput { + message: format!( + "computed column '{}' has an unevaluable expression ({e}); drop it \ + before changing the schema", + declaration.name + ), + })?, + _ => declaration.inputs.clone(), + }; + for path in paths { + // Exact target only: the binding travels with the whole column, + // not with a nested field the expression still shapes. + if declaration.name == *path { + continue; + } + if declaration.name == root(path) { + return Err(Error::InvalidInput { + message: format!( + "'{}' is part of computed column '{}'; drop the column and declare \ + it again", + path, declaration.name + ), + }); + } + if inputs.iter().any(|input| root(input) == root(path)) { + return Err(Error::InvalidInput { + message: format!( + "column '{}' is read by computed column '{}'; drop that column first", + path, declaration.name + ), + }); + } + } + } + Ok(()) +} + +/// Reject a write that supplies values for a computed column directly: +/// only refresh materializes one, and refresh never revisits a filled row. +pub(crate) fn ensure_not_written<'a>( + schema: &ArrowSchema, + written: impl IntoIterator, +) -> Result<()> { + let declared: Vec = computed_columns(schema) + .into_iter() + .map(|declaration| declaration.name) + .collect(); + for name in written { + if declared.iter().any(|declared| declared == root(name)) { + return Err(Error::InvalidInput { + message: format!( + "column '{}' is computed; its values come from refresh and cannot be \ + written directly", + root(name) + ), + }); + } + } + Ok(()) +} + +/// Reject a batch holding values for a computed column. Null slots are the +/// declared state, so planner-padded placeholders pass. +pub(crate) fn ensure_batch_writes_no_computed_values( + declared: &[String], + batch: &arrow_array::RecordBatch, +) -> Result<()> { + for name in declared { + if let Some(column) = batch.column_by_name(name) + && column.null_count() != column.len() + { + return Err(Error::InvalidInput { + message: format!( + "column '{name}' is computed; its values come from refresh and cannot \ + be written directly" + ), + }); + } + } + Ok(()) +} + +/// Reject fields carrying declaration metadata that did not come through +/// [`plan`]. One authority for creation, overwrite and raw transforms. +pub(crate) fn ensure_no_foreign_declarations<'a>( + fields: impl IntoIterator>, +) -> Result<()> { + for field in fields { + if field.metadata().keys().any(|k| is_declaration_key(k)) { + return Err(Error::InvalidInput { + message: format!( + "field '{}' carries computed-column metadata; declare computed columns \ + with add_columns().computed()", + field.name() + ), + }); + } + } + Ok(()) +} + +/// True for field-metadata keys that belong to a computed-column declaration. +/// +/// A declaration is immutable through metadata edits: it is validated as a +/// whole at declare time, and rewriting any piece of it -- the flag, the +/// kind, the expression, the inputs -- would bypass that validation or move +/// a binding out from under a refresh. Drop the column and declare it again. +pub(crate) fn is_declaration_key(key: &str) -> bool { + key == COMPUTED_COLUMN_META_KEY || key.starts_with("computed_column.") +} + +/// Reject retyping a computed column itself. +/// +/// A cast keeps the stored expression while changing the type it must yield +/// -- and lance's cast rewrites the field without its metadata, so the +/// declaration silently stops being one. Dropping and redeclaring is the +/// coherent way to change a computed column's type. +pub(crate) fn ensure_not_retyped(schema: &ArrowSchema, paths: &[&str]) -> Result<()> { + for declaration in computed_columns(schema) { + for path in paths { + if declaration.name == root(path) { + return Err(Error::InvalidInput { + message: format!( + "column '{}' is computed; drop it and declare it again to change \ + its type", + declaration.name + ), + }); + } + } + } + Ok(()) +} + +/// The top-level column a possibly nested input path reads. +pub(crate) fn root(path: &str) -> &str { + path.split('.').next().unwrap_or(path) +} + +/// A declaration's expression bound to a schema. +pub(crate) struct BoundExpression { + /// The columns the expression names, as written; nested inputs keep + /// their dotted path. + pub inputs: Vec, + /// The type the expression yields. + pub data_type: DataType, +} + +/// Parse, resolve and compile `expression` against `schema`. +/// +/// Inputs come from the expression as written, before optimization: the +/// simplifier can fold a referenced column out entirely (`true OR x > 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 { + let invalid = |message: String| Error::InvalidExpression { + column: column.to_string(), + message, + }; + + let planner = Planner::new(schema.clone()); + let parsed = planner + .parse_expr(expression) + .map_err(|e| invalid(e.to_string()))?; + + // A declaration is evaluated more than once -- staging and writing are + // separate passes, and a refresh years later replays the same text -- so + // a function that can answer differently each time has no coherent value + // to declare. + let mut volatile = None; + parsed + .apply(|expr| { + use datafusion_common::tree_node::TreeNodeRecursion; + if let datafusion_expr::Expr::ScalarFunction(function) = expr + && function.func.signature().volatility != datafusion_expr::Volatility::Immutable + { + volatile = Some(function.func.name().to_string()); + return Ok(TreeNodeRecursion::Stop); + } + Ok(TreeNodeRecursion::Continue) + }) + .map_err(|e| invalid(e.to_string()))?; + if let Some(function) = volatile { + return Err(invalid(format!( + "'{function}' is not deterministic; a computed column's expression must \ + yield the same value every time it is evaluated" + ))); + } + + let mut inputs = Planner::column_names_in_expr(&parsed); + inputs.sort(); + inputs.dedup(); + + // A nested input is recorded by its path but read through its root + // column; Schema::index_of resolves top-level names only. Resolved here + // rather than left to the planner so an unknown column names itself in + // the error instead of surfacing as a plan failure. + let mut indices = Vec::with_capacity(inputs.len()); + for input in &inputs { + let index = schema + .index_of(root(input)) + .map_err(|_| invalid(format!("unknown column '{input}'")))?; + if !indices.contains(&index) { + indices.push(index); + } + } + indices.sort_unstable(); + + // Physical expressions address columns by position, so the planner that + // compiles the expression has to be built on the projected schema + // evaluation will actually read. + let read_schema = Arc::new( + schema + .project(&indices) + .map_err(|e| invalid(e.to_string()))?, + ); + let optimized = planner + .optimize_expr(parsed) + .map_err(|e| invalid(e.to_string()))?; + let physical = Planner::new(read_schema.clone()) + .create_physical_expr(&optimized) + .map_err(|e| invalid(e.to_string()))?; + let data_type = physical + .data_type(read_schema.as_ref()) + .map_err(|e| invalid(e.to_string()))?; + + Ok(BoundExpression { inputs, data_type }) +} + +/// Resolve `(name, expression)` pairs against `schema` into fields carrying +/// their bindings. +/// +/// Everything that can be known statically is checked here rather than at +/// refresh time: that the expression parses, that every column it reads +/// exists, and that the target name is free. A declaration that survives this +/// is one a refresh can always act on. +pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result> { + if columns.is_empty() { + return Err(Error::InvalidInput { + message: "at least one computed column is required".into(), + }); + } + + let mut fields = Vec::with_capacity(columns.len()); + let mut declared: Vec<&str> = Vec::with_capacity(columns.len()); + + for (name, expression) in columns { + if schema.field_with_name(name).is_ok() || declared.contains(&name.as_str()) { + return Err(Error::ColumnAlreadyExists { name: name.clone() }); + } + + let bound = bind(schema.clone(), name, expression)?; + + // Declared columns start entirely null, so nullability is a property + // of the declaration rather than of what the expression yields. + fields.push( + ArrowField::new(name, bound.data_type, true) + .with_metadata(computed_column_metadata(expression, &bound.inputs)), + ); + declared.push(name); + } + + Ok(fields) +} + +/// Build the transform that declares `columns` against `schema`. +/// +/// An all-null column is how a binding with no values yet is carried into a +/// commit; that it is spelled `AllNulls` is a detail of the commit, not of the +/// column, which is why this is internal and +/// [`AddColumnsBuilder::computed`](super::AddColumnsBuilder::computed) is the +/// public way in. +pub(crate) fn declare( + schema: SchemaRef, + columns: &[(String, String)], +) -> Result { + let fields = plan(schema, columns)?; + Ok(NewColumnTransform::AllNulls(Arc::new(ArrowSchema::new( + fields, + )))) +} + +/// Commit a declaration of a kind this version does not produce, the way a +/// newer lancedb would leave one behind. Bypasses admission, which exists to +/// stop exactly this through the public API. +#[cfg(test)] +pub(super) async fn add_foreign_kind(table: &crate::Table, name: &str, kind: &str) { + let field = ArrowField::new(name, DataType::Int32, true).with_metadata(HashMap::from([ + (COMPUTED_COLUMN_META_KEY.to_string(), "true".to_string()), + (KIND_META_KEY.to_string(), kind.to_string()), + (INPUTS_META_KEY.to_string(), r#"["x"]"#.to_string()), + ])); + super::schema_evolution::commit_add_columns( + table.as_native().unwrap(), + NewColumnTransform::AllNulls(Arc::new(ArrowSchema::new(vec![field]))), + None, + ) + .await + .unwrap(); +} + +#[cfg(test)] +mod tests { + use arrow_array::record_batch; + use arrow_schema::DataType; + use futures::TryStreamExt; + use lance::dataset::ColumnAlteration; + + use super::*; + use crate::connect; + use crate::query::{ExecutableQuery, QueryBase, Select}; + use crate::{Error, Table}; + + async fn table_with_ints(name: &str) -> Table { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!(("x", Int32, [1, 2, 3])).unwrap(); + conn.create_table(name, batch).execute().await.unwrap() + } + + /// Declare `columns` the way a caller would: plan the expressions, then + /// add them through the ordinary column API. + async fn add_computed(table: &Table, columns: &[(String, String)]) -> Result { + let mut builder = table.add_columns(); + for (name, expression) in columns { + builder = builder.computed(name, expression); + } + Ok(builder.execute().await?.version) + } + + async fn declared(table: &Table) -> Vec { + computed_columns(table.schema().await.unwrap().as_ref()) + } + + #[tokio::test] + async fn test_declare_infers_type_and_inputs() { + let table = table_with_ints("declare_infers").await; + let initial = table.version().await.unwrap(); + + let version = add_computed(&table, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap(); + assert!(version > initial); + + let schema = table.schema().await.unwrap(); + let field = schema.field_with_name("doubled").unwrap(); + assert_eq!(field.data_type(), &DataType::Int32); + assert!(field.is_nullable()); + + assert_eq!( + declared(&table).await, + vec![ComputedColumn { + name: "doubled".into(), + kind: ComputedColumnKind::Sql { + expression: "x * 2".into() + }, + inputs: vec!["x".into()], + }] + ); + } + + /// The binding reaches the schema only if `AllNulls` carries per-field + /// metadata through the commit. The whole representation rests on it. + #[tokio::test] + async fn test_all_nulls_preserves_field_metadata() { + let table = table_with_ints("metadata_survives").await; + add_computed(&table, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap(); + + let schema = table.schema().await.unwrap(); + let metadata = schema.field_with_name("doubled").unwrap().metadata(); + assert_eq!( + metadata.get(COMPUTED_COLUMN_META_KEY).map(String::as_str), + Some("true") + ); + assert_eq!(metadata.get(KIND_META_KEY).map(String::as_str), Some("sql")); + assert_eq!( + metadata.get(EXPRESSION_META_KEY).map(String::as_str), + Some("x * 2") + ); + assert_eq!( + metadata.get(INPUTS_META_KEY).map(String::as_str), + Some(r#"["x"]"#) + ); + } + + #[tokio::test] + async fn test_declared_column_is_all_null() { + let table = table_with_ints("declare_is_null").await; + add_computed(&table, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap(); + + let batches = table + .query() + .select(Select::columns(&["doubled"])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + + let total: usize = batches.iter().map(|b| b.num_rows()).sum(); + assert_eq!(total, 3); + for batch in &batches { + assert_eq!(batch["doubled"].null_count(), batch.num_rows()); + } + } + + #[tokio::test] + async fn test_unknown_column_fails_at_declare_time() { + let table = table_with_ints("unknown_input").await; + let err = add_computed(&table, &[("bad".into(), "missing + 1".into())]) + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidExpression { column, .. } if column == "bad")); + + let schema = table.schema().await.unwrap(); + assert!(schema.field_with_name("bad").is_err()); + } + + #[tokio::test] + async fn test_unparsable_expression_fails_at_declare_time() { + let table = table_with_ints("bad_syntax").await; + let err = add_computed(&table, &[("bad".into(), "x *".into())]) + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidExpression { column, .. } if column == "bad")); + assert!( + table + .schema() + .await + .unwrap() + .field_with_name("bad") + .is_err() + ); + } + + /// A user-defined function is an expression like any other; only its + /// resolution is missing. When a registry-aware planner exists this + /// becomes a supported declaration rather than a new API. + #[tokio::test] + async fn test_unregistered_function_is_rejected_for_now() { + let table = table_with_ints("udf_not_yet").await; + let err = add_computed(&table, &[("vec".into(), "embed(x)".into())]) + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidExpression { column, .. } if column == "vec")); + assert!( + table + .schema() + .await + .unwrap() + .field_with_name("vec") + .is_err() + ); + } + + #[tokio::test] + async fn test_existing_column_name_is_rejected() { + let table = table_with_ints("name_taken").await; + let err = add_computed(&table, &[("x".into(), "x * 2".into())]) + .await + .unwrap_err(); + assert!(matches!(err, Error::ColumnAlreadyExists { name } if name == "x")); + assert!(declared(&table).await.is_empty()); + } + + #[tokio::test] + async fn test_constant_expression_needs_no_inputs() { + let table = table_with_ints("constant").await; + add_computed(&table, &[("answer".into(), "42".into())]) + .await + .unwrap(); + + let declared = declared(&table).await; + assert_eq!(declared.len(), 1); + assert!(declared[0].inputs.is_empty()); + } + + #[tokio::test] + async fn test_multiple_columns_in_one_commit() { + let table = table_with_ints("multi").await; + let initial = table.version().await.unwrap(); + + add_computed( + &table, + &[ + ("plus".into(), "x + 1".into()), + ("squared".into(), "x * x".into()), + ], + ) + .await + .unwrap(); + + assert_eq!(table.version().await.unwrap(), initial + 1); + let declared = declared(&table).await; + assert_eq!(declared.len(), 2); + assert_eq!(declared[0].name, "plus"); + assert_eq!(declared[1].name, "squared"); + } + + #[tokio::test] + async fn test_duplicate_declaration_in_one_call_is_rejected() { + let table = table_with_ints("dupe").await; + let err = add_computed( + &table, + &[ + ("dup".into(), "x + 1".into()), + ("dup".into(), "x + 2".into()), + ], + ) + .await + .unwrap_err(); + assert!(matches!(err, Error::ColumnAlreadyExists { name } if name == "dup")); + assert!(declared(&table).await.is_empty()); + } + + /// A column added by an ordinary transform is materialized, not bound, so + /// it carries no declaration to report. + #[tokio::test] + async fn test_ordinary_columns_are_not_reported_as_computed() { + let table = table_with_ints("plain").await; + assert!(declared(&table).await.is_empty()); + + table + .add_columns() + .transform(NewColumnTransform::SqlExpressions(vec![( + "eager".into(), + "x * 2".into(), + )])) + .execute() + .await + .unwrap(); + assert!(declared(&table).await.is_empty()); + } + + /// Built-in functions type the column the same way an operator does. + #[tokio::test] + async fn test_builtin_function_inference() { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!(("name", Utf8, ["ada", "grace"]), ("n", Int32, [-1, 2])).unwrap(); + let table = conn + .create_table("builtins", batch) + .execute() + .await + .unwrap(); + + add_computed( + &table, + &[ + ("shout".into(), "upper(name)".into()), + ("width".into(), "length(name)".into()), + ("magnitude".into(), "abs(n)".into()), + ], + ) + .await + .unwrap(); + + let schema = table.schema().await.unwrap(); + assert_eq!( + schema.field_with_name("shout").unwrap().data_type(), + &DataType::Utf8 + ); + assert_eq!( + schema.field_with_name("magnitude").unwrap().data_type(), + &DataType::Int32 + ); + // length() returns a width-dependent integer type; assert it is one + // rather than pinning which. + assert!( + schema + .field_with_name("width") + .unwrap() + .data_type() + .is_integer() + ); + + let declared = declared(&table).await; + assert_eq!(declared.len(), 3); + assert_eq!(declared[0].inputs, vec!["name".to_string()]); + assert_eq!(declared[2].inputs, vec!["n".to_string()]); + } + + /// The reason the kind is tagged: a declaration written by a newer version + /// has to read back as a computed column this one cannot evaluate, not as + /// an ordinary column. Reported as absent it would be refreshable by + /// nothing and redeclarable over, silently. + #[tokio::test] + async fn test_unrecognized_kind_is_reported_rather_than_hidden() { + let table = table_with_ints("foreign_kind").await; + super::add_foreign_kind(&table, "embedding", "udf").await; + + assert_eq!( + declared(&table).await, + vec![ComputedColumn { + name: "embedding".into(), + kind: ComputedColumnKind::Unrecognized { kind: "udf".into() }, + inputs: vec!["x".into()], + }] + ); + + let err = add_computed(&table, &[("embedding".into(), "x * 2".into())]) + .await + .unwrap_err(); + assert!(matches!(err, Error::ColumnAlreadyExists { name } if name == "embedding")); + } + + /// A kind is what makes a declaration readable at all, so the flag alone + /// is half-formed in the same way a missing expression is. + #[test] + fn test_flag_without_a_kind_is_not_a_declaration() { + let field = + ArrowField::new("half", DataType::Int32, true).with_metadata(HashMap::from([( + COMPUTED_COLUMN_META_KEY.to_string(), + "true".to_string(), + )])); + assert_eq!(computed_column_from_field(&field), None); + } + + /// A SQL declaration is its expression; without one there is nothing to + /// refresh from. + #[test] + fn test_sql_kind_without_an_expression_is_not_a_declaration() { + let field = ArrowField::new("half", DataType::Int32, true).with_metadata(HashMap::from([ + (COMPUTED_COLUMN_META_KEY.to_string(), "true".to_string()), + (KIND_META_KEY.to_string(), SQL_KIND.to_string()), + ])); + assert_eq!(computed_column_from_field(&field), None); + } + + #[tokio::test] + async fn test_inputs_are_deduplicated_and_sorted() { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!(("b", Int32, [1, 2]), ("a", Int32, [3, 4])).unwrap(); + let table = conn.create_table("dedupe", batch).execute().await.unwrap(); + + add_computed(&table, &[("total".into(), "b + a + b".into())]) + .await + .unwrap(); + + assert_eq!( + declared(&table).await[0].inputs, + vec!["a".to_string(), "b".to_string()] + ); + } + + #[tokio::test] + async fn test_dropping_an_input_is_refused() { + let table = table_with_ints("drop_input").await; + add_computed(&table, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap(); + + let err = table.drop_columns(&["x"]).await.unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("doubled")), + "{err:?}" + ); + } + + #[tokio::test] + async fn test_renaming_an_input_is_refused() { + let table = table_with_ints("rename_input").await; + add_computed(&table, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap(); + + let err = table + .alter_columns(&[ColumnAlteration::new("x".into()).rename("y".into())]) + .await + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("doubled")), + "{err:?}" + ); + } + + /// Nothing resolves against nullability, so it is not a rebinding. + #[tokio::test] + async fn test_altering_an_input_nullability_is_allowed() { + let table = table_with_ints("nullable_input").await; + add_computed(&table, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap(); + + table + .alter_columns(&[ColumnAlteration::new("x".into()).set_nullable(true)]) + .await + .unwrap(); + } + + /// The gate's reproducer: a volatile function evaluates differently in + /// the counting and writing passes, so the declared value is incoherent. + /// Refused at declare time. + #[tokio::test] + async fn test_a_volatile_expression_is_refused() { + let table = table_with_ints("volatile_expr").await; + let err = add_computed(&table, &[("maybe".into(), "random() < 0.5".into())]) + .await + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidExpression { message, .. } + if message.contains("random") && message.contains("deterministic")), + "{err:?}" + ); + } + + /// The gate's reproducer: the simplifier folds `true OR x > 0` to a + /// constant, but the stored SQL still names `x`, so the recorded inputs + /// must too -- otherwise dropping `x` is allowed and refresh breaks. + #[tokio::test] + async fn test_inputs_survive_expression_optimization() { + let table = table_with_ints("optimized_inputs").await; + add_computed(&table, &[("flag".into(), "true OR x > 0".into())]) + .await + .unwrap(); + + assert_eq!(declared(&table).await[0].inputs, vec!["x".to_string()]); + let err = table.drop_columns(&["x"]).await.unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("flag")), + "{err:?}" + ); + } + + /// The gate's reproducer: casting a computed column rewrites the field + /// without its metadata, silently destroying the declaration. + #[tokio::test] + async fn test_retyping_the_computed_column_is_refused() { + use arrow_schema::DataType as ArrowDataType; + + let table = table_with_ints("retype_computed").await; + add_computed(&table, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap(); + + let err = table + .alter_columns(&[ColumnAlteration::new("doubled".into()).cast_to(ArrowDataType::Int64)]) + .await + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("computed")), + "{err:?}" + ); + + // The declaration survives the refused change. + assert_eq!(declared(&table).await.len(), 1); + } + + /// A declaration cannot be edited, fabricated or erased through field + /// metadata: it is validated as a whole at declare time. + #[tokio::test] + async fn test_declaration_metadata_is_immutable() { + use crate::table::FieldMetadataUpdate; + + let table = table_with_ints("metadata_tamper").await; + add_computed(&table, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap(); + + // Moving the binding. + let err = table + .update_field_metadata(&[ + FieldMetadataUpdate::new("doubled").set(EXPRESSION_META_KEY, "x * 3") + ]) + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidInput { .. }), "{err:?}"); + + // Fabricating a declaration on a plain column. + let err = table + .update_field_metadata(&[FieldMetadataUpdate::new("x") + .set(COMPUTED_COLUMN_META_KEY, "true") + .set(KIND_META_KEY, SQL_KIND) + .set(EXPRESSION_META_KEY, "x")]) + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidInput { .. }), "{err:?}"); + + // Erasing the declaration wholesale. + let err = table + .update_field_metadata(&[FieldMetadataUpdate::new("doubled") + .set("note", "hi") + .replace()]) + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidInput { .. }), "{err:?}"); + + // Ordinary metadata on a computed column still merges, leaving the + // declaration intact. + table + .update_field_metadata(&[FieldMetadataUpdate::new("doubled").set("note", "hi")]) + .await + .unwrap(); + assert_eq!(declared(&table).await.len(), 1); + } + + /// The gate's reproducer: only refresh materializes a declared column; + /// a direct write would store an arbitrary durable value. + #[tokio::test] + async fn test_a_computed_column_cannot_be_written_directly() { + let table = table_with_ints("direct_write").await; + add_computed(&table, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap(); + + let batch = record_batch!(("x", Int32, [4]), ("doubled", Int32, [999])).unwrap(); + let err = table.add(batch.clone()).execute().await.unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("refresh")), + "{err:?}" + ); + + let err = table + .update() + .column("doubled", "999") + .execute() + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidInput { .. })); + + let mut merge = table.merge_insert(&["x"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + let err = merge + .execute(Box::new(arrow_array::RecordBatchIterator::new( + vec![Ok(batch.clone())], + batch.schema(), + ))) + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidInput { .. })); + + // The append that omits the column still works. + let plain = record_batch!(("x", Int32, [4])).unwrap(); + table.add(plain).execute().await.unwrap(); + } + + /// The gate's reproducer: the reciprocal of the declare-under-spec check. + #[tokio::test] + async fn test_installing_an_lsm_spec_over_computed_columns_is_refused() { + use crate::table::LsmWriteSpec; + + let tmp_dir = tempfile::tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(arrow_schema::Schema::new(vec![arrow_schema::Field::new( + "x", + DataType::Int32, + false, + )])); + let batch = arrow_array::RecordBatch::try_new( + schema, + vec![Arc::new(arrow_array::Int32Array::from(vec![1, 2])) as _], + ) + .unwrap(); + let table = conn + .create_table("lsm_after", batch) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["x"]).await.unwrap(); + add_computed(&table, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap(); + + let err = table + .set_lsm_write_spec(LsmWriteSpec::unsharded()) + .await + .unwrap_err(); + assert!( + matches!(&err, Error::NotSupported { message } if message.contains("computed")), + "{err:?}" + ); + assert!(table.get_lsm_write_spec().await.unwrap().is_none()); + } + + /// The gate's reproducer: declaration metadata is admitted only through + /// the validated declare path, never smuggled through a raw transform. + #[tokio::test] + async fn test_forged_declaration_metadata_is_rejected() { + let table = table_with_ints("forged_metadata").await; + let field = + ArrowField::new("doubled", DataType::Int32, true).with_metadata(HashMap::from([ + (COMPUTED_COLUMN_META_KEY.to_string(), "true".to_string()), + (KIND_META_KEY.to_string(), SQL_KIND.to_string()), + (EXPRESSION_META_KEY.to_string(), "x * 2".to_string()), + (INPUTS_META_KEY.to_string(), "[]".to_string()), + ])); + let err = table + .add_columns() + .transform(NewColumnTransform::AllNulls(Arc::new(ArrowSchema::new( + vec![field], + )))) + .execute() + .await + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("computed()")), + "{err:?}" + ); + assert!(declared(&table).await.is_empty()); + } + + /// The gate's reproducer: SQL INSERT is a write path too. + #[tokio::test] + async fn test_sql_insert_cannot_write_a_computed_column() { + use datafusion::prelude::SessionContext; + + let table = table_with_ints("sql_insert").await; + add_computed(&table, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap(); + + let ctx = SessionContext::new(); + let provider = + crate::table::datafusion::BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(); + ctx.register_table("t", Arc::new(provider)).unwrap(); + + let result = async { + ctx.sql("INSERT INTO t (x, doubled) VALUES (4, 999)") + .await? + .collect() + .await + } + .await; + let err = result.unwrap_err().to_string(); + assert!(err.contains("refresh"), "{err}"); + } + + /// The gate's reproducer: an overwrite must not smuggle in a filled + /// declaration. + #[tokio::test] + async fn test_overwrite_cannot_inject_a_declaration() { + use crate::table::AddDataMode; + + let table = table_with_ints("overwrite_inject").await; + let field = + ArrowField::new("doubled", DataType::Int32, true).with_metadata(HashMap::from([ + (COMPUTED_COLUMN_META_KEY.to_string(), "true".to_string()), + (KIND_META_KEY.to_string(), SQL_KIND.to_string()), + (EXPRESSION_META_KEY.to_string(), "x * 2".to_string()), + ])); + let schema = Arc::new(ArrowSchema::new(vec![ + ArrowField::new("x", DataType::Int32, true), + field, + ])); + let batch = arrow_array::RecordBatch::try_new( + schema, + vec![ + Arc::new(arrow_array::Int32Array::from(vec![1])) as _, + Arc::new(arrow_array::Int32Array::from(vec![999])) as _, + ], + ) + .unwrap(); + + let err = table + .add(batch) + .mode(AddDataMode::Overwrite) + .execute() + .await + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("declare")), + "{err:?}" + ); + } + + #[tokio::test] + async fn test_create_table_cannot_inject_a_declaration() { + let conn = connect("memory://").execute().await.unwrap(); + let field = + ArrowField::new("doubled", DataType::Int32, true).with_metadata(HashMap::from([ + (COMPUTED_COLUMN_META_KEY.to_string(), "true".to_string()), + (KIND_META_KEY.to_string(), SQL_KIND.to_string()), + (EXPRESSION_META_KEY.to_string(), "x * 2".to_string()), + ])); + let schema = Arc::new(ArrowSchema::new(vec![ + ArrowField::new("x", DataType::Int32, true), + field, + ])); + let batch = arrow_array::RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(arrow_array::Int32Array::from(vec![1])) as _, + Arc::new(arrow_array::Int32Array::from(vec![999])) as _, + ], + ) + .unwrap(); + let err = conn + .create_table("forged_create", batch) + .execute() + .await + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("computed()")), + "{err:?}" + ); + } + + #[tokio::test] + async fn test_sql_insert_omitting_computed_is_allowed() { + use datafusion::prelude::SessionContext; + + let table = table_with_ints("sql_insert_omitted").await; + add_computed(&table, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap(); + + let ctx = SessionContext::new(); + let provider = + crate::table::datafusion::BaseTableAdapter::try_new(table.base_table().clone()) + .await + .unwrap(); + ctx.register_table("t", Arc::new(provider)).unwrap(); + ctx.sql("INSERT INTO t (x) VALUES (4)") + .await + .unwrap() + .collect() + .await + .unwrap(); + + table.checkout_latest().await.unwrap(); + assert_eq!(table.count_rows(None).await.unwrap(), 4); + } + + #[tokio::test] + async fn test_a_nested_computed_field_cannot_be_renamed() { + let table = table_with_ints("computed_struct_rename").await; + add_computed(&table, &[("payload".into(), "named_struct('a', x)".into())]) + .await + .unwrap(); + + let err = table + .alter_columns(&[ColumnAlteration::new("payload.a".into()).rename("b".into())]) + .await + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("payload")), + "{err:?}" + ); + } + + /// Stale handles must not commit the computed/LSM state in either order. + #[tokio::test] + async fn test_stale_handles_cannot_mix_computed_and_lsm() { + use crate::table::LsmWriteSpec; + + let tmp_dir = tempfile::tempdir().unwrap(); + let uri = tmp_dir.path().to_str().unwrap(); + let schema = Arc::new(ArrowSchema::new(vec![ArrowField::new( + "x", + DataType::Int32, + false, + )])); + let batch = arrow_array::RecordBatch::try_new( + schema.clone(), + vec![Arc::new(arrow_array::Int32Array::from(vec![1])) as _], + ) + .unwrap(); + let conn = connect(uri).execute().await.unwrap(); + let table = conn.create_table("mix", batch).execute().await.unwrap(); + table.set_unenforced_primary_key(["x"]).await.unwrap(); + let stale = conn.open_table("mix").execute().await.unwrap(); + + // Declare on one handle; the stale handle must not install a spec. + add_computed(&table, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap(); + let err = stale + .set_lsm_write_spec(LsmWriteSpec::unsharded()) + .await + .unwrap_err(); + assert!(matches!(err, Error::NotSupported { .. }), "install won"); + + // Reverse order on fresh tables. + let batch = arrow_array::RecordBatch::try_new( + schema, + vec![Arc::new(arrow_array::Int32Array::from(vec![1])) as _], + ) + .unwrap(); + let table = conn.create_table("mix2", batch).execute().await.unwrap(); + table.set_unenforced_primary_key(["x"]).await.unwrap(); + let stale = conn.open_table("mix2").execute().await.unwrap(); + table + .set_lsm_write_spec(LsmWriteSpec::unsharded()) + .await + .unwrap(); + let err = add_computed(&stale, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap_err(); + assert!(matches!(err, Error::NotSupported { .. }), "declare won"); + } + + /// The gate's reproducer: after catch-up activation, an LSM write, and + /// unset, retained SSTable rows survive without a live spec. The catch-up + /// flag is the durable marker; declaration refuses on it. + #[tokio::test] + async fn test_unset_with_retained_lsm_rows_cannot_admit_a_declaration() { + use crate::table::LsmWriteSpec; + use arrow_array::{Int64Array, RecordBatchIterator}; + + let tmp_dir = tempfile::tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(ArrowSchema::new(vec![ + ArrowField::new("id", DataType::Int64, false), + ArrowField::new("value", DataType::Int64, false), + ])); + let batch = arrow_array::RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int64Array::from(vec![1, 2])) as _, + Arc::new(Int64Array::from(vec![10, 20])) as _, + ], + ) + .unwrap(); + let table = conn + .create_table("t", batch.clone()) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["id"]).await.unwrap(); + table + .set_lsm_write_spec(LsmWriteSpec::unsharded()) + .await + .unwrap(); + table.require_mem_wal_index_catchup().await.unwrap(); + + let mut merge = table.merge_insert(&["id"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all() + .use_lsm(true); + merge + .execute(Box::new(RecordBatchIterator::new(vec![Ok(batch)], schema))) + .await + .unwrap(); + table.unset_lsm_write_spec().await.unwrap(); + + let err = add_computed(&table, &[("doubled".into(), "value * 2".into())]) + .await + .unwrap_err(); + assert!( + matches!(&err, Error::NotSupported { message } if message.contains("LSM")), + "{err:?}" + ); + } + + /// A declaration does not read itself, so it travels with its binding. + #[tokio::test] + async fn test_dropping_the_computed_column_is_allowed() { + let table = table_with_ints("drop_computed").await; + add_computed(&table, &[("doubled".into(), "x * 2".into())]) + .await + .unwrap(); + + table.drop_columns(&["doubled"]).await.unwrap(); + assert!(declared(&table).await.is_empty()); + } +} diff --git a/rust/lancedb/src/table/datafusion/insert.rs b/rust/lancedb/src/table/datafusion/insert.rs index e176c228b..b9bd2396e 100644 --- a/rust/lancedb/src/table/datafusion/insert.rs +++ b/rust/lancedb/src/table/datafusion/insert.rs @@ -17,7 +17,7 @@ use datafusion_physical_plan::stream::RecordBatchStreamAdapter; use datafusion_physical_plan::{ DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, }; -use futures::TryStreamExt; +use futures::StreamExt; use lance::Dataset; use lance::dataset::transaction::{Operation, Transaction}; use lance::dataset::{CommitBuilder, InsertBuilder, WriteParams, WriteProgressFn}; @@ -194,12 +194,23 @@ impl ExecutionPlan for InsertExec { let output_bytes = MetricBuilder::new(&self.metrics).output_bytes(partition); let input_schema = input_stream.schema(); + let declared: Vec = crate::table::computed_columns::computed_columns( + &arrow_schema::Schema::from(self.dataset.schema()), + ) + .into_iter() + .map(|declaration| declaration.name) + .collect(); let input_stream: SendableRecordBatchStream = Box::pin(InstrumentedRecordBatchStreamAdapter::new( input_schema, - input_stream.map_ok(move |batch| { + input_stream.map(move |batch| { + let batch = batch?; + crate::table::computed_columns::ensure_batch_writes_no_computed_values( + &declared, &batch, + ) + .map_err(|e| datafusion::error::DataFusionError::External(Box::new(e)))?; output_bytes.add(batch.get_array_memory_size()); - batch + Ok(batch) }), partition, &self.metrics, diff --git a/rust/lancedb/src/table/merge/lsm.rs b/rust/lancedb/src/table/merge/lsm.rs index eb2feacbd..5751cd916 100644 --- a/rust/lancedb/src/table/merge/lsm.rs +++ b/rust/lancedb/src/table/merge/lsm.rs @@ -94,7 +94,16 @@ pub(crate) async fn set_lsm_write_spec(table: &NativeTable, spec: LsmWriteSpec) .await? }; + table.checkout_latest().await?; let mut dataset = (*table.dataset.get().await?).clone(); + let schema = arrow_schema::Schema::from(dataset.schema()); + if !crate::table::computed_columns::computed_columns(&schema).is_empty() { + return Err(Error::NotSupported { + message: "an LSM write spec cannot be installed on a table with computed \ + columns: rows in un-compacted tiers are invisible to refresh" + .into(), + }); + } let mut builder = dataset.initialize_mem_wal(); let writer_config_defaults = match spec { LsmWriteSpec::Bucket { diff --git a/rust/lancedb/src/table/schema_evolution.rs b/rust/lancedb/src/table/schema_evolution.rs index ce208111a..7503fd790 100644 --- a/rust/lancedb/src/table/schema_evolution.rs +++ b/rust/lancedb/src/table/schema_evolution.rs @@ -8,12 +8,14 @@ //! - [`alter_columns`](execute_alter_columns): Rename columns, change types, or modify nullability //! - [`drop_columns`](execute_drop_columns): Remove columns from the table +use arrow_schema::Schema as ArrowSchema; use lance::dataset::{ColumnAlteration, NewColumnTransform}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; -use super::NativeTable; -use crate::Result; +use super::computed_columns; +use super::{BaseTable, NativeTable}; +use crate::{Error, Result}; /// The result of an add columns operation. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -98,6 +100,48 @@ pub(crate) async fn execute_add_columns( table: &NativeTable, transforms: NewColumnTransform, read_columns: Option>, +) -> Result { + // Declarations are admitted only through [`execute_declare`]. + match &transforms { + NewColumnTransform::AllNulls(schema) => { + computed_columns::ensure_no_foreign_declarations(schema.fields())? + } + NewColumnTransform::BatchUDF(udf) => { + computed_columns::ensure_no_foreign_declarations(udf.output_schema.fields())? + } + _ => {} + } + commit_add_columns(table, transforms, read_columns).await +} + +/// Declare validated computed columns. The only admission path for +/// declaration metadata. +pub(crate) async fn execute_declare( + table: &NativeTable, + columns: &[(String, String)], +) -> Result { + // An LSM write spec keeps visible rows in tiers refresh cannot reach; + // checked against latest committed state, not this handle's snapshot. + // The catch-up flag outlives unset and marks retained SSTable rows. + table.checkout_latest().await?; + let catchup = table.dataset.get().await?.manifest().reader_feature_flags + & lance_table::feature_flags::FLAG_MEM_WAL_INDEX_CATCHUP + != 0; + if catchup || table.get_lsm_write_spec().await?.is_some() { + return Err(Error::NotSupported { + message: "computed columns are not supported on a table with an LSM write \ + spec: rows in un-compacted tiers are invisible to refresh" + .into(), + }); + } + let transform = computed_columns::declare(table.schema().await?, columns)?; + commit_add_columns(table, transform, None).await +} + +pub(crate) async fn commit_add_columns( + table: &NativeTable, + transforms: NewColumnTransform, + read_columns: Option>, ) -> Result { table.dataset.ensure_mutable()?; let mut dataset = (*table.dataset.get().await?).clone(); @@ -116,6 +160,21 @@ pub(crate) async fn execute_alter_columns( ) -> Result { table.dataset.ensure_mutable()?; let mut dataset = (*table.dataset.get().await?).clone(); + // Nullability is not part of what an expression resolves against, so only + // a rename or a retype can invalidate a binding. + let schema = std::sync::Arc::new(ArrowSchema::from(dataset.schema())); + let rebinding = alterations + .iter() + .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)?; + let retyped = alterations + .iter() + .filter(|alteration| alteration.data_type.is_some()) + .map(|alteration| alteration.path.as_str()) + .collect::>(); + computed_columns::ensure_not_retyped(schema.as_ref(), &retyped)?; dataset.alter_columns(alterations).await?; let version = dataset.version().version; table.dataset.update(dataset); @@ -131,6 +190,10 @@ pub(crate) async fn execute_drop_columns( ) -> Result { table.dataset.ensure_mutable()?; let mut dataset = (*table.dataset.get().await?).clone(); + computed_columns::ensure_not_an_input( + &std::sync::Arc::new(ArrowSchema::from(dataset.schema())), + columns, + )?; dataset.drop_columns(columns).await?; let version = dataset.version().version; table.dataset.update(dataset); @@ -147,6 +210,44 @@ pub(crate) async fn execute_update_field_metadata( table.dataset.ensure_mutable()?; let mut dataset = (*table.dataset.get().await?).clone(); + // A declaration is validated as a whole at declare time; editing its keys + // here would bypass that, fabricate one on a plain column, or move a + // binding out from under a refresh. A replace on a declared column would + // silently erase it. + let schema = ArrowSchema::from(dataset.schema()); + let declared: Vec = computed_columns::computed_columns(&schema) + .into_iter() + .map(|declaration| declaration.name) + .collect(); + for update in updates { + if update + .metadata + .keys() + .any(|key| computed_columns::is_declaration_key(key)) + { + return Err(Error::InvalidInput { + message: format!( + "metadata keys of a computed-column declaration cannot be edited \ + (path '{}'); drop the column and declare it again", + update.path + ), + }); + } + if update.replace + && declared + .iter() + .any(|name| name == computed_columns::root(&update.path)) + { + return Err(Error::InvalidInput { + message: format!( + "replacing all metadata of computed column '{}' would erase its \ + declaration; drop the column and declare it again", + update.path + ), + }); + } + } + let mut builder = dataset.update_field_metadata(); for update in updates { let entries = update.metadata.iter().map(|(k, v)| (k.clone(), v.clone())); diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index 61eb93992..fd9fa6828 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -82,6 +82,10 @@ pub(crate) async fn execute_update( // 1. Snapshot the current dataset let dataset = table.dataset.get().await?; + super::computed_columns::ensure_not_written( + &arrow_schema::Schema::from(dataset.schema()), + update.columns.iter().map(|(name, _)| name.as_str()), + )?; // 2. Initialize the Lance Core builder let mut builder = LanceUpdateBuilder::new(dataset); From fc0d917d32da9c600cdba9d0efa5f8bdacecfdcf Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Fri, 14 Aug 2026 14:43:41 -0700 Subject: [PATCH 040/206] feat: refresh computed columns (#3938) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit table.refresh_column("doubled") fills the rows of a declared column that hold no value, in two passes per fragment: the first scans only the unfilled live rows to count exact gains and decide staging, the second streams the fragment's physical rows into a standalone column file published in one DataReplacement -- committed under the dataset's own session -- so peak memory is bounded by a scan batch. A row that holds a value keeps it; deleted and already-filled rows never reach the expression, so a poison value in them cannot fail the refresh. Refresh refuses under an LSM write spec, including the mem-wal catch-up flag that outlives unset and marks retained SSTable rows. --- Stack created with GitHub Stacks CLIGive Feedback 💬 --- docs/src/js/classes/Table.md | 33 +- docs/src/js/globals.md | 1 + docs/src/js/interfaces/RefreshColumnResult.md | 23 + nodejs/__test__/table.test.ts | 27 +- nodejs/lancedb/index.ts | 1 + nodejs/lancedb/table.ts | 24 +- nodejs/src/table.rs | 25 + python/python/lancedb/_lancedb.pyi | 5 + python/python/lancedb/remote/table.py | 3 + python/python/lancedb/table.py | 75 +- python/python/tests/test_table.py | 23 +- python/src/lib.rs | 4 +- python/src/table.rs | 34 + rust/lancedb/src/remote/table.rs | 6 + rust/lancedb/src/table.rs | 39 + rust/lancedb/src/table/add_columns.rs | 9 +- rust/lancedb/src/table/computed_columns.rs | 31 +- rust/lancedb/src/table/refresh.rs | 708 ++++++++++++++++++ 18 files changed, 1042 insertions(+), 29 deletions(-) create mode 100644 docs/src/js/interfaces/RefreshColumnResult.md create mode 100644 rust/lancedb/src/table/refresh.rs diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 97bdea628..278559cc4 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -70,9 +70,9 @@ abstract addColumns(newColumnTransforms): Promise Add new columns with defined values. The `{ computed }` form stores the expression rather than evaluating it -now: the column is committed with no values, and a later refresh fills -the rows. Declaring one therefore costs the same on a large table as on -an empty one. +now: the column is committed with no values, and rows get them from +[Table#refreshColumn](Table.md#refreshcolumn). Declaring one therefore costs the same on a +large table as on an empty one. A refresh does not revisit rows it has already filled, so mutating an input leaves the value computed at fill time; recomputing means dropping @@ -108,6 +108,7 @@ containing the new version number of the table after adding the columns. ```ts await table.addColumns({ computed: [{ name: "doubled", valueSql: "x * 2" }] }); +const { rowsFilled } = await table.refreshColumn("doubled"); ``` *** @@ -743,6 +744,32 @@ for await (const batch of table.query()) { *** +### refreshColumn() + +```ts +abstract refreshColumn(column): Promise +``` + +Fill the rows of a computed column that hold no value yet. + +Rows appended since the last refresh are filled by the next one; rows +already filled are left as they are, so the call is idempotent and does +not observe a mutated input. Local tables only. + +#### Parameters + +* **column**: `string` + The name of the computed column to fill. + +#### Returns + +`Promise`<[`RefreshColumnResult`](../interfaces/RefreshColumnResult.md)> + +A promise that resolves to the +number of rows filled and the new version number of the table. + +*** + ### restore() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 7455a81ce..bd2ca54b5 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -105,6 +105,7 @@ - [OptimizeOptions](interfaces/OptimizeOptions.md) - [OptimizeStats](interfaces/OptimizeStats.md) - [QueryExecutionOptions](interfaces/QueryExecutionOptions.md) +- [RefreshColumnResult](interfaces/RefreshColumnResult.md) - [RemovalStats](interfaces/RemovalStats.md) - [RenameTableOptions](interfaces/RenameTableOptions.md) - [RestNamespaceConfig](interfaces/RestNamespaceConfig.md) diff --git a/docs/src/js/interfaces/RefreshColumnResult.md b/docs/src/js/interfaces/RefreshColumnResult.md new file mode 100644 index 000000000..d2854fda6 --- /dev/null +++ b/docs/src/js/interfaces/RefreshColumnResult.md @@ -0,0 +1,23 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / RefreshColumnResult + +# Interface: RefreshColumnResult + +## Properties + +### rowsFilled + +```ts +rowsFilled: number; +``` + +*** + +### version + +```ts +version: number; +``` diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 5ff18da3e..bc495d24b 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -3348,14 +3348,37 @@ describe("computed columns", () => { }); afterEach(() => tmpDir.removeCallback()); - it("declares a column with no values", async () => { + it("declares a column and fills it on refresh", async () => { const db = await connect(tmpDir.name); const table = await db.createTable("computed", [{ x: 1 }, { x: 2 }]); await table.addColumns({ computed: [{ name: "doubled", valueSql: "x * 2" }], }); - const rows = await table.query().toArray(); + let rows = await table.query().toArray(); expect(rows.map((r) => r.doubled)).toEqual([null, null]); + + const result = await table.refreshColumn("doubled"); + expect(result.rowsFilled).toBe(2); + + rows = await table.query().toArray(); + expect(rows.map((r) => r.doubled).sort()).toEqual([2, 4]); + }); + + it("fills rows added since the last refresh", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("computed_append", [{ x: 1 }]); + + await table.addColumns({ + computed: [{ name: "doubled", valueSql: "x * 2" }], + }); + await table.refreshColumn("doubled"); + await table.add([{ x: 5 }]); + + const result = await table.refreshColumn("doubled"); + expect(result.rowsFilled).toBe(1); + + const rows = await table.query().toArray(); + expect(rows.map((r) => r.doubled).sort()).toEqual([10, 2]); }); }); diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 319222421..9f2e97989 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -50,6 +50,7 @@ export { MergeResult, AddResult, AddColumnsResult, + RefreshColumnResult, AlterColumnsResult, UpdateFieldMetadataResult, DeleteResult, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 6234b8fbf..5b8d00076 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -33,6 +33,7 @@ import { Job, Branches as NativeBranches, OptimizeStats, + RefreshColumnResult, TableStatistics, Tags, UpdateFieldMetadataResult, @@ -527,9 +528,9 @@ export abstract class Table { * Add new columns with defined values. * * The `{ computed }` form stores the expression rather than evaluating it - * now: the column is committed with no values, and a later refresh fills - * the rows. Declaring one therefore costs the same on a large table as on - * an empty one. + * now: the column is committed with no values, and rows get them from + * {@link Table#refreshColumn}. Declaring one therefore costs the same on a + * large table as on an empty one. * * A refresh does not revisit rows it has already filled, so mutating an * input leaves the value computed at fill time; recomputing means dropping @@ -549,6 +550,7 @@ export abstract class Table { * @example * ```ts * await table.addColumns({ computed: [{ name: "doubled", valueSql: "x * 2" }] }); + * const { rowsFilled } = await table.refreshColumn("doubled"); * ``` */ abstract addColumns( @@ -560,6 +562,18 @@ export abstract class Table { | { computed: AddColumnsSql[] }, ): Promise; + /** + * Fill the rows of a computed column that hold no value yet. + * + * Rows appended since the last refresh are filled by the next one; rows + * already filled are left as they are, so the call is idempotent and does + * not observe a mutated input. Local tables only. + * @param {string} column The name of the computed column to fill. + * @returns {Promise} A promise that resolves to the + * number of rows filled and the new version number of the table. + */ + abstract refreshColumn(column: string): Promise; + /** * Alter the name or nullability of columns. * @param {ColumnAlteration[]} columnAlterations One or more alterations to @@ -1161,6 +1175,10 @@ 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 alterColumns( columnAlterations: ColumnAlteration[], ): Promise { diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 16ca387e6..40ed7d9f0 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -361,6 +361,16 @@ impl Table { Ok(res.into()) } + #[napi(catch_unwind)] + pub async fn refresh_column(&self, column: String) -> napi::Result { + let res = self + .inner_ref()? + .refresh_column(column) + .await + .default_error()?; + Ok(res.into()) + } + #[napi(catch_unwind)] pub async fn add_columns_with_schema( &self, @@ -1210,6 +1220,21 @@ pub struct AddColumnsResult { pub version: i64, } +#[napi(object)] +pub struct RefreshColumnResult { + pub rows_filled: i64, + pub version: i64, +} + +impl From for RefreshColumnResult { + fn from(value: lancedb::table::RefreshColumnResult) -> Self { + Self { + rows_filled: value.rows_filled as i64, + version: value.version as i64, + } + } +} + impl From for AddColumnsResult { fn from(value: lancedb::table::AddColumnsResult) -> Self { Self { diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 84455d74b..96bbecad8 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -341,6 +341,7 @@ class Table: async def add_computed_columns( self, columns: list[tuple[str, str]] ) -> AddColumnsResult: ... + async def refresh_column(self, column: str) -> RefreshColumnResult: ... async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ... async def alter_columns( self, columns: list[dict[str, Any]] @@ -686,6 +687,10 @@ class LsmWriteSpec: class AddColumnsResult: version: int +class RefreshColumnResult: + rows_filled: int + version: int + class AlterColumnsResult: version: int diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 5c98a64f1..5bd446775 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -970,6 +970,9 @@ class RemoteTable(Table): ) return LOOP.run(self._table.add_columns(transforms)) + def refresh_column(self, column: str): + raise NotImplementedError("computed columns are supported only on local tables") + 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 5c9104699..db25c4ebc 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -176,6 +176,7 @@ if TYPE_CHECKING: CompactionStats, Tag, AddColumnsResult, + RefreshColumnResult, AddResult, AlterColumnsResult, UpdateFieldMetadataResult, @@ -1943,9 +1944,10 @@ class Table(ABC): data type is supplied. Unlike ``transforms``, the expression is stored rather than - evaluated now: the column is committed with no values, and a - later refresh fills the rows. Declaring one therefore costs the - same on a large table as on an empty one. + evaluated now: the column is committed with no values, and rows get + them from [`refresh_column`][lancedb.table.Table.refresh_column]. + Declaring one therefore costs the same on a large table as on an + empty one. A refresh does not revisit rows it has already filled, so mutating an input leaves the value computed at fill time; recomputing means @@ -1967,8 +1969,37 @@ class Table(ABC): >>> table = db.create_table("computed_demo", [{"x": 1}, {"x": 2}]) >>> table.add_columns(computed={"doubled": "x * 2"}) AddColumnsResult(version=2) - >>> table.to_arrow()["doubled"].to_pylist() - [None, None] + >>> table.refresh_column("doubled") + RefreshColumnResult(rows_filled=2, version=3) + >>> table.to_arrow().sort_by("x").to_pandas() + x doubled + 0 1 2 + 1 2 4 + """ + + @abstractmethod + def refresh_column(self, column: str) -> "RefreshColumnResult": + """ + Fill the rows of a computed column that hold no value yet. + + Declared with ``add_columns(computed=...)``, a column starts empty and + gets its values here. Rows appended since the last refresh are filled + by the next one; rows already filled are left as they are, so the call + is idempotent and does not observe a mutated input. + + Local tables only; LanceDB Cloud and Enterprise raise + ``NotImplementedError``. + + Parameters + ---------- + column: str + The name of the computed column to fill. + + Returns + ------- + RefreshColumnResult + rows_filled: the number of rows given a value. + version: the new version number of the table. """ @abstractmethod @@ -3984,6 +4015,11 @@ class LanceTable(Table): ) -> AddColumnsResult: return LOOP.run(self._table.add_columns(transforms, computed=computed)) + def refresh_column(self, column: str) -> "RefreshColumnResult": + """Fill a computed column's unfilled rows. See + [`AsyncTable.refresh_column`][lancedb.AsyncTable.refresh_column].""" + return LOOP.run(self._table.refresh_column(column)) + def alter_columns( self, *alterations: Iterable[Dict[str, str]] ) -> AlterColumnsResult: @@ -5922,8 +5958,9 @@ class AsyncTable: column's type and inputs are derived from the expression. Unlike ``transforms``, the expression is stored rather than - evaluated now: the column is committed with no values, and a - later refresh fills the rows. + evaluated now: the column is committed with no values, and rows get + them from + [`refresh_column`][lancedb.table.AsyncTable.refresh_column]. A refresh does not revisit rows it has already filled, so mutating an input leaves the value computed at fill time. While a @@ -5957,6 +5994,30 @@ class AsyncTable: else: return await self._inner.add_columns(list(transforms.items())) + async def refresh_column(self, column: str) -> RefreshColumnResult: + """ + Fill the rows of a computed column that hold no value yet. + + Declared with ``add_columns(computed=...)``, a column starts empty and + gets its values here. Rows appended since the last refresh are filled + by the next one; rows already filled are left as they are, so the call + is idempotent and does not observe a mutated input. + + Local tables only; LanceDB Cloud and Enterprise raise + ``NotImplementedError``. + + Parameters + ---------- + column: str + The name of the computed column to fill. + + Returns + ------- + RefreshColumnResult + The number of rows filled and the new version of the table. + """ + return await self._inner.refresh_column(column) + async def alter_columns( self, *alterations: Iterable[dict[str, Any]] ) -> AlterColumnsResult: diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 6393cd42a..ddc1f450f 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -3856,16 +3856,20 @@ async def test_async_search_runs_embedding_on_dedicated_executor( ) -def test_computed_column_declares_all_null(tmp_path): +def test_computed_column_declare_and_refresh(tmp_path): db = lancedb.connect(tmp_path) table = db.create_table("computed", [{"x": 1}, {"x": 2}]) table.add_columns(computed={"doubled": "x * 2"}) assert table.to_arrow()["doubled"].to_pylist() == [None, None] - # The declaration is durable field metadata. - field = table.schema.field("doubled") - assert field.metadata[b"computed_column.expression"] == b"x * 2" + result = table.refresh_column("doubled") + assert result.rows_filled == 2 + assert sorted(table.to_arrow()["doubled"].to_pylist()) == [2, 4] + + table.add([{"x": 5}]) + assert table.refresh_column("doubled").rows_filled == 1 + assert sorted(table.to_arrow()["doubled"].to_pylist()) == [2, 4, 10] def test_computed_column_rejects_transforms_and_computed_together(tmp_path): @@ -3873,3 +3877,14 @@ def test_computed_column_rejects_transforms_and_computed_together(tmp_path): table = db.create_table("computed_mixed", [{"x": 1}]) with pytest.raises(ValueError): table.add_columns({"a": "x + 1"}, computed={"b": "x * 2"}) + + +@pytest.mark.asyncio +async def test_computed_column_async(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("computed_async", [{"x": 3}]) + + await table.add_columns(computed={"tripled": "x * 3"}) + await table.refresh_column("tripled") + + assert (await table.to_arrow())["tripled"].to_pylist() == [9] diff --git a/python/src/lib.rs b/python/src/lib.rs index 6b0c0cf97..a19bf172d 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -16,7 +16,8 @@ use query::{FTSQuery, HybridQuery, Query, VectorQuery}; use session::Session; use table::{ AddColumnsResult, AddResult, AlterColumnsResult, DeleteResult, DropColumnsResult, FtsToken, - LsmWriteSpec, MergeResult, PyBlobFile, Table, UpdateFieldMetadataResult, UpdateResult, + LsmWriteSpec, MergeResult, PyBlobFile, RefreshColumnResult, Table, UpdateFieldMetadataResult, + UpdateResult, }; pub mod arrow; @@ -57,6 +58,7 @@ 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::()?; diff --git a/python/src/table.rs b/python/src/table.rs index a9ff70ad6..a4c3c307a 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -415,6 +415,32 @@ pub struct AddColumnsResult { pub version: u64, } +#[pyclass(get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct RefreshColumnResult { + pub rows_filled: u64, + pub version: u64, +} + +#[pymethods] +impl RefreshColumnResult { + pub fn __repr__(&self) -> String { + format!( + "RefreshColumnResult(rows_filled={}, version={})", + self.rows_filled, self.version + ) + } +} + +impl From for RefreshColumnResult { + fn from(result: lancedb::table::RefreshColumnResult) -> Self { + Self { + rows_filled: result.rows_filled, + version: result.version, + } + } +} + #[pymethods] impl AddColumnsResult { pub fn __repr__(&self) -> String { @@ -1525,6 +1551,14 @@ impl Table { }) } + pub fn refresh_column(self_: PyRef<'_, Self>, column: String) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let result = inner.refresh_column(column).await.infer_error()?; + Ok(RefreshColumnResult::from(result)) + }) + } + pub fn add_columns_with_schema( self_: PyRef<'_, Self>, schema: PyArrowType, diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 3e467b674..8ca84a520 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -6479,6 +6479,12 @@ mod tests { matches!(&err, Error::NotSupported { message } if message.contains("local tables")), "{err:?}" ); + + let err = table.refresh_column("doubled").await.unwrap_err(); + assert!( + matches!(&err, Error::NotSupported { message } if message.contains("local tables")), + "{err:?}" + ); } #[tokio::test] diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 00a51058c..bfa060638 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -78,6 +78,7 @@ pub mod merge; pub mod optimize; mod primary_key; pub mod query; +pub mod refresh; pub mod schema_evolution; pub mod update; pub mod write_progress; @@ -101,6 +102,7 @@ pub use lance::dataset::scanner::DatasetRecordBatchStream; pub use lance_index::optimize::OptimizeOptions; pub use lsm_stats::{BucketStats, GenerationStats, LsmStats, MemtableStats}; pub use optimize::{CompactionOptions, OptimizeAction, OptimizeStats}; +pub use refresh::RefreshColumnResult; pub use schema_evolution::{ AddColumnsResult, AlterColumnsResult, DropColumnsResult, FieldMetadataUpdate, UpdateFieldMetadataResult, @@ -754,6 +756,14 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "computed columns are not supported on this table type".into(), }) } + /// Fill a computed column's unfilled rows. + /// + /// The default returns `NotSupported`; Lance-backed tables override it. + async fn refresh_column(&self, _column: &str) -> Result { + Err(Error::NotSupported { + message: "computed columns are supported only on local tables".into(), + }) + } /// Alter columns in the table. async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result; /// Drop columns from the table. @@ -1646,6 +1656,29 @@ impl Table { AddColumnsBuilder::new(self.inner.clone()) } + /// Fill the fragments of a computed column that hold no values yet. + /// + /// Declared with + /// [`AddColumnsBuilder::computed`](add_columns::AddColumnsBuilder::computed), + /// a column starts empty and gets its values here. Fragments appended + /// since the last refresh are filled by the next one; fragments already + /// filled are left as they are, so the call is idempotent and does not + /// observe a mutated input. + /// + /// Local tables only. + /// + /// ``` + /// # use lancedb::Table; + /// # async fn refresh(table: &Table) -> Result<(), Box> { + /// let result = table.refresh_column("doubled").await?; + /// println!("filled {} rows at version {}", result.rows_filled, result.version); + /// # Ok(()) + /// # } + /// ``` + pub async fn refresh_column(&self, column: impl AsRef) -> Result { + self.inner.refresh_column(column.as_ref()).await + } + /// Change a column's name or nullability. pub async fn alter_columns( &self, @@ -3353,6 +3386,12 @@ impl BaseTable for NativeTable { Ok(result) } + async fn refresh_column(&self, column: &str) -> Result { + let result = refresh::execute_refresh_column(self, column).await?; + self.bump_freshness(); + Ok(result) + } + async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result { let result = schema_evolution::execute_alter_columns(self, alterations).await?; self.bump_freshness(); diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index e5c4ef8d1..6aa2ce86a 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -51,9 +51,10 @@ impl AddColumnsBuilder { /// expression. /// /// The column is committed with no values, so declaring one costs the same - /// on an empty table as on a large one. Rows get values from a later - /// refresh, which fills every fragment that has none -- including - /// fragments appended since the last refresh. + /// on an empty table as on a large one. Rows get values from + /// [`Table::refresh_column`](super::Table::refresh_column), which fills + /// every fragment that has none -- including fragments appended since the + /// last refresh. /// /// Refresh does not revisit a fragment it has filled, so mutating an input /// leaves the value computed at fill time; recomputing means dropping the @@ -71,6 +72,8 @@ impl AddColumnsBuilder { /// .computed("doubled", "x * 2") /// .execute() /// .await?; + /// let filled = table.refresh_column("doubled").await?; + /// println!("filled {} rows", filled.rows_filled); /// # Ok(()) /// # } /// ``` diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 4787b420f..9a6a2585d 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -23,6 +23,7 @@ use std::sync::Arc; use arrow_schema::{DataType, Field as ArrowField, Schema as ArrowSchema, SchemaRef}; use datafusion_common::tree_node::TreeNode; +use datafusion_physical_plan::PhysicalExpr; use lance::dataset::NewColumnTransform; use lance_datafusion::planner::Planner; @@ -296,11 +297,18 @@ pub(crate) fn root(path: &str) -> &str { path.split('.').next().unwrap_or(path) } -/// A declaration's expression bound to a schema. +/// A declaration's expression bound to a schema, ready to evaluate. pub(crate) struct BoundExpression { /// The columns the expression names, as written; nested inputs keep /// their dotted path. pub inputs: Vec, + /// The top-level columns evaluation reads, in [`Self::read_schema`] + /// order. A nested input appears through its root. + pub roots: Vec, + /// The projected schema evaluation runs against. + pub read_schema: SchemaRef, + /// The compiled expression. + pub physical: Arc, /// The type the expression yields. pub data_type: DataType, } @@ -373,6 +381,12 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< .project(&indices) .map_err(|e| invalid(e.to_string()))?, ); + let roots = read_schema + .fields() + .iter() + .map(|field| field.name().clone()) + .collect(); + let optimized = planner .optimize_expr(parsed) .map_err(|e| invalid(e.to_string()))?; @@ -383,7 +397,13 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< .data_type(read_schema.as_ref()) .map_err(|e| invalid(e.to_string()))?; - Ok(BoundExpression { inputs, data_type }) + Ok(BoundExpression { + inputs, + roots, + read_schema, + physical, + data_type, + }) } /// Resolve `(name, expression)` pairs against `schema` into fields carrying @@ -905,7 +925,7 @@ mod tests { ); // The declaration survives the refused change. - assert_eq!(declared(&table).await.len(), 1); + table.refresh_column("doubled").await.unwrap(); } /// A declaration cannot be edited, fabricated or erased through field @@ -947,13 +967,12 @@ mod tests { .unwrap_err(); assert!(matches!(err, Error::InvalidInput { .. }), "{err:?}"); - // Ordinary metadata on a computed column still merges, leaving the - // declaration intact. + // Ordinary metadata on a computed column still merges. table .update_field_metadata(&[FieldMetadataUpdate::new("doubled").set("note", "hi")]) .await .unwrap(); - assert_eq!(declared(&table).await.len(), 1); + table.refresh_column("doubled").await.unwrap(); } /// The gate's reproducer: only refresh materializes a declared column; diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs new file mode 100644 index 000000000..ab4f8e452 --- /dev/null +++ b/rust/lancedb/src/table/refresh.rs @@ -0,0 +1,708 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Filling computed columns. +//! +//! A row without a value gets one; a row that has one keeps it. Refresh is +//! therefore idempotent and does not observe input mutation -- once a row is +//! filled, changing what the expression reads leaves the stored result alone. +//! +//! Two passes per fragment. The first scans only the unfilled live rows and +//! evaluates the expression over them, which yields the exact fill count and +//! decides whether the fragment is staged at all -- a fragment where nothing +//! would change stages nothing, which is what lets an expression yielding +//! null settle instead of restaging forever. The second streams the +//! fragment's physical rows into `write_column` a batch at a time, so peak +//! memory is bounded by a scan batch. The expression is evaluated by this +//! module, never through a projection alias, and only over rows being +//! filled: every other row -- deleted, or already holding a value -- has its +//! inputs masked to null first, so a poison value in a row nobody is filling +//! cannot fail the refresh. + +use std::sync::Arc; + +use arrow_array::{ArrayRef, BooleanArray, RecordBatch, RecordBatchOptions}; +use arrow_schema::Schema as ArrowSchema; +use datafusion_expr::ColumnarValue; +use futures::{Stream, StreamExt, TryStreamExt}; +use lance::Dataset; +use lance::dataset::WriteDestination; +use lance::dataset::fragment::FileFragment; +use lance::dataset::transaction::Operation; +use lance_core::ROW_ID; +use lance_core::datatypes::Schema as LanceSchema; +use serde::{Deserialize, Serialize}; + +use super::computed_columns::{BoundExpression, ComputedColumnKind, computed_column_from_field}; +use super::{BaseTable, NativeTable}; +use crate::{Error, Result}; + +/// The result of refreshing a computed column. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +pub struct RefreshColumnResult { + /// Rows that had a value computed. + #[serde(default)] + pub rows_filled: u64, + /// The commit version associated with the operation. + #[serde(default)] + pub version: u64, +} + +/// Internal implementation of the refresh logic. +pub(crate) async fn execute_refresh_column( + table: &NativeTable, + column: &str, +) -> Result { + table.dataset.ensure_mutable()?; + ensure_no_lsm_write_spec(table).await?; + let dataset = table.dataset.get().await?; + + let expression = declared_expression(&dataset, column)?; + let schema = Arc::new(ArrowSchema::from(dataset.schema())); + let bound = Arc::new(super::computed_columns::bind(schema, column, &expression)?); + let field = dataset + .schema() + .field(column) + .ok_or_else(|| Error::ColumnNotFound { + name: column.to_string(), + })?; + // The dataset's own field, so the identity write_column checks against the + // manifest holds by construction. + let column_schema = LanceSchema { + fields: vec![field.clone()], + metadata: Default::default(), + }; + + let mut rows_filled = 0u64; + let mut replacements = Vec::new(); + for fragment in dataset.get_fragments() { + let gained = count_fragment_gains(&dataset, &fragment, &bound, column).await?; + if gained == 0 { + continue; + } + rows_filled += gained; + let values = fill_stream(&dataset, &fragment, bound.clone(), column).await?; + replacements.push(fragment.write_column(values, &column_schema).await?); + } + + if replacements.is_empty() { + return Ok(RefreshColumnResult { + rows_filled: 0, + version: dataset.version().version, + }); + } + + let read_version = dataset.version().version; + // The dataset's own session, so registrations and caches survive the + // commit being installed on the handle. + let session = dataset.session(); + let new_dataset = Dataset::commit( + WriteDestination::Dataset(dataset.clone()), + Operation::DataReplacement { replacements }, + Some(read_version), + None, + None, + session, + false, + ) + .await?; + + let version = new_dataset.version().version; + table.dataset.update(new_dataset); + Ok(RefreshColumnResult { + rows_filled, + version, + }) +} + +/// Refuse to refresh under an LSM write spec. +/// +/// Refresh enumerates base fragments, and a write spec keeps visible rows in +/// un-compacted MemWAL tiers it cannot reach -- success would silently omit +/// readable rows. +async fn ensure_no_lsm_write_spec(table: &NativeTable) -> Result<()> { + // The catch-up flag outlives unset and marks retained SSTable rows. + let catchup = table.dataset.get().await?.manifest().reader_feature_flags + & lance_table::feature_flags::FLAG_MEM_WAL_INDEX_CATCHUP + != 0; + if catchup || table.get_lsm_write_spec().await?.is_some() { + return Err(Error::NotSupported { + message: "refresh_column is not supported on a table with an LSM write \ + spec: rows in un-compacted tiers are invisible to refresh" + .into(), + }); + } + Ok(()) +} + +/// The SQL expression `column` is declared with. +fn declared_expression(dataset: &Dataset, column: &str) -> Result { + let schema = ArrowSchema::from(dataset.schema()); + let field = schema + .field_with_name(column) + .map_err(|_| Error::ColumnNotFound { + name: column.to_string(), + })?; + let declaration = + computed_column_from_field(field).ok_or_else(|| Error::NotAComputedColumn { + name: column.to_string(), + })?; + match declaration.kind { + ComputedColumnKind::Sql { expression } => Ok(expression), + ComputedColumnKind::Unrecognized { kind } => Err(Error::NotSupported { + message: format!( + "computed column '{column}' is defined by '{kind}', which this version of \ + lancedb cannot evaluate" + ), + }), + } +} + +/// Quote `name` as a lance SQL identifier. +/// +/// Lance's dialect delimits with backticks, so a double-quoted name would +/// parse as a string literal rather than a column. +fn quote_identifier(name: &str) -> String { + format!("`{}`", name.replace('`', "``")) +} + +/// Assemble the batch evaluation runs against: the bound roots, in read-schema +/// order. Built by name so scan-side column order never matters. +fn evaluation_batch( + batch: &RecordBatch, + bound: &BoundExpression, + mask_out: Option<&BooleanArray>, +) -> lance_core::Result { + let mut columns = Vec::with_capacity(bound.roots.len()); + for name in &bound.roots { + let column = batch.column_by_name(name).ok_or_else(|| { + lance_core::Error::invalid_input(format!( + "refreshing a computed column read no {name} column" + )) + })?; + // Rows outside the mask must not reach the expression: a value in a + // deleted or already-filled row can be one it would choke on. + columns.push(match mask_out { + Some(mask) => arrow::compute::nullif(column, mask)?, + None => column.clone(), + }); + } + Ok(RecordBatch::try_new_with_options( + bound.read_schema.clone(), + columns, + &RecordBatchOptions::new().with_row_count(Some(batch.num_rows())), + )?) +} + +/// Evaluate the expression over `batch`, materializing a constant result to +/// the batch's length. +fn evaluate(bound: &BoundExpression, batch: &RecordBatch) -> lance_core::Result { + let value = bound + .physical + .evaluate(batch) + .map_err(lance_core::Error::from)?; + match value { + ColumnarValue::Array(array) => Ok(array), + scalar => scalar + .into_array(batch.num_rows()) + .map_err(lance_core::Error::from), + } +} + +/// How many rows of one fragment would gain a value. +/// +/// Scans only the unfilled live rows -- deleted rows never reach the +/// expression here, the filter having already excluded them -- and counts the +/// non-null results. Exact, so it is both the staging decision and the +/// fragment's contribution to `rows_filled`. +async fn count_fragment_gains( + dataset: &Dataset, + fragment: &FileFragment, + bound: &BoundExpression, + column: &str, +) -> Result { + let mut scanner = dataset.scan(); + scanner + .with_fragments(vec![fragment.metadata().clone()]) + .with_row_id() + .filter(&format!("{} IS NULL", quote_identifier(column)))? + .project(&bound.roots)?; + + let mut gained = 0u64; + let mut batches = scanner.try_into_stream().await?; + while let Some(batch) = batches.try_next().await? { + let evaluated = evaluate(bound, &evaluation_batch(&batch, bound, None)?)?; + gained += (batch.num_rows() - evaluated.null_count()) as u64; + } + Ok(gained) +} + +/// Stream one fragment's column in physical order, filling the unfilled live +/// rows and keeping every other value. +/// +/// Deleted rows are carried through so the values line up positionally with +/// the fragment's data files; they are never read back, but the column file +/// has to cover them. +async fn fill_stream( + dataset: &Dataset, + fragment: &FileFragment, + bound: Arc, + column: &str, +) -> Result> + Send + use<>> { + let mut projection: Vec = bound.roots.clone(); + projection.push(column.to_string()); + let mut scanner = dataset.scan(); + scanner + .with_fragments(vec![fragment.metadata().clone()]) + .with_row_id() + .include_deleted_rows() + .project(&projection)?; + + let projected = Arc::new(ArrowSchema::new(vec![ + ArrowSchema::from(dataset.schema()) + .field_with_name(column) + .map_err(|_| Error::ColumnNotFound { + name: column.to_string(), + })? + .clone(), + ])); + + let column = column.to_string(); + let batches = scanner.try_into_stream().await?; + Ok(batches.map(move |batch| { + let batch = batch?; + let missing = |name: &str| { + lance_core::Error::invalid_input(format!( + "refreshing a computed column read no {name} column" + )) + }; + let existing = batch + .column_by_name(&column) + .ok_or_else(|| missing(&column))?; + let row_ids = batch + .column_by_name(ROW_ID) + .ok_or_else(|| missing(ROW_ID))?; + + // Only an unfilled live row gains a value; a deleted row has a null + // row id and keeps its (null) slot. + let unfilled = arrow::compute::is_null(existing.as_ref())?; + let live = arrow::compute::is_not_null(row_ids.as_ref())?; + let fill = arrow::compute::and(&unfilled, &live)?; + let keep = arrow::compute::not(&fill)?; + + let computed = evaluate(&bound, &evaluation_batch(&batch, &bound, Some(&keep))?)?; + let merged = arrow_select::zip::zip(&fill, &computed, existing)?; + Ok(RecordBatch::try_new(projected.clone(), vec![merged])?) + })) +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use arrow_array::{Int32Array, record_batch}; + use futures::TryStreamExt; + + use crate::connect; + use crate::query::{ExecutableQuery, QueryBase, Select}; + use crate::{Error, Result, Table}; + + async fn table_with(name: &str, values: Vec) -> Table { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!(("x", Int32, values)).unwrap(); + conn.create_table(name, batch).execute().await.unwrap() + } + + async fn declare_doubled(table: &Table) -> Result { + Ok(table + .add_columns() + .computed("doubled", "x * 2") + .execute() + .await? + .version) + } + + async fn read(table: &Table, column: &str) -> Vec> { + let batches = table + .query() + .select(Select::columns(&[column])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let mut values: Vec> = batches + .iter() + .flat_map(|batch| { + batch[column] + .as_any() + .downcast_ref::() + .unwrap() + .iter() + .collect::>() + }) + .collect(); + values.sort(); + values + } + + async fn append(table: &Table, values: Vec) { + let batch = record_batch!(("x", Int32, values)).unwrap(); + table.add(batch).execute().await.unwrap(); + } + + #[tokio::test] + async fn test_refresh_fills_a_declared_column() { + let table = table_with("refresh_fills", vec![1, 2, 3]).await; + let declared = declare_doubled(&table).await.unwrap(); + assert_eq!(read(&table, "doubled").await, vec![None, None, None]); + + let result = table.refresh_column("doubled").await.unwrap(); + assert!(result.version > declared); + assert_eq!(result.rows_filled, 3); + assert_eq!( + read(&table, "doubled").await, + vec![Some(2), Some(4), Some(6)] + ); + } + + /// Values written after the last refresh must be reachable by another one. + #[tokio::test] + async fn test_refresh_fills_rows_appended_since_the_last_refresh() { + let table = table_with("refresh_appended", vec![1, 2]).await; + declare_doubled(&table).await.unwrap(); + table.refresh_column("doubled").await.unwrap(); + + append(&table, vec![5, 6]).await; + assert_eq!( + read(&table, "doubled").await, + vec![None, None, Some(2), Some(4)] + ); + + let result = table.refresh_column("doubled").await.unwrap(); + assert_eq!(result.rows_filled, 2); + assert_eq!( + read(&table, "doubled").await, + vec![Some(2), Some(4), Some(10), Some(12)] + ); + } + + #[tokio::test] + async fn test_refresh_with_nothing_to_fill() { + let table = table_with("refresh_noop", vec![1, 2, 3]).await; + declare_doubled(&table).await.unwrap(); + table.refresh_column("doubled").await.unwrap(); + + let again = table.refresh_column("doubled").await.unwrap(); + assert_eq!(again.rows_filled, 0); + assert_eq!( + read(&table, "doubled").await, + vec![Some(2), Some(4), Some(6)] + ); + } + + /// A row is filled only by gaining a value, so an expression yielding null + /// settles at once instead of re-selecting the same rows forever. Nothing + /// is staged, so the version does not move either. + #[tokio::test] + async fn test_refresh_converges_on_a_null_result() { + let table = table_with("refresh_null_result", vec![1, 2, 3]).await; + let declared = table + .add_columns() + .computed("maybe", "nullif(x, x)") + .execute() + .await + .unwrap() + .version; + + let first = table.refresh_column("maybe").await.unwrap(); + assert_eq!(first.rows_filled, 0); + assert_eq!(first.version, declared); + assert_eq!(read(&table, "maybe").await, vec![None, None, None]); + + let again = table.refresh_column("maybe").await.unwrap(); + assert_eq!(again.rows_filled, 0); + assert_eq!(again.version, declared); + } + + /// The contract's boundary: a filled fragment is not revisited, so + /// mutating an input leaves the value computed at fill time. + #[tokio::test] + async fn test_refresh_does_not_observe_input_mutation() { + let table = table_with("refresh_mutation", vec![1]).await; + declare_doubled(&table).await.unwrap(); + table.refresh_column("doubled").await.unwrap(); + assert_eq!(read(&table, "doubled").await, vec![Some(2)]); + + table.update().column("x", "3").execute().await.unwrap(); + + let again = table.refresh_column("doubled").await.unwrap(); + assert_eq!(again.rows_filled, 0); + assert_eq!(read(&table, "doubled").await, vec![Some(2)]); + } + + /// A row rewrite before the first refresh materializes the declared + /// column as null behind a covering data file. Those rows are still + /// unfilled and a later refresh has to reach them. + #[tokio::test] + async fn test_update_before_the_first_refresh() { + let table = table_with("refresh_update_first", vec![1]).await; + declare_doubled(&table).await.unwrap(); + + table.update().column("x", "3").execute().await.unwrap(); + + let result = table.refresh_column("doubled").await.unwrap(); + assert_eq!(result.rows_filled, 1); + assert_eq!(read(&table, "doubled").await, vec![Some(6)]); + } + + /// The contract holds row by row, not fragment by fragment: revisiting a + /// fragment to fill one row must not recompute a filled row sitting beside + /// it, even where the input behind it has since changed. + #[tokio::test] + async fn test_refresh_does_not_recompute_a_filled_row_beside_an_unfilled_one() { + let table = table_with("refresh_mixed", vec![1, 2]).await; + declare_doubled(&table).await.unwrap(); + table.refresh_column("doubled").await.unwrap(); + + append(&table, vec![5]).await; + table + .update() + .column("x", "100") + .only_if("x = 1") + .execute() + .await + .unwrap(); + table + .optimize(crate::table::OptimizeAction::Compact { + options: crate::table::CompactionOptions::default(), + remap_options: None, + }) + .await + .unwrap(); + + let result = table.refresh_column("doubled").await.unwrap(); + assert_eq!(result.rows_filled, 1); + // 2 is the mutated row keeping the value it was filled with, not 200. + assert_eq!( + read(&table, "doubled").await, + vec![Some(2), Some(4), Some(10)] + ); + } + + /// Filling a fragment must not disturb the values it already holds, which + /// is what makes a compaction-mixed fragment safe to revisit. + #[tokio::test] + async fn test_refresh_preserves_already_filled_rows() { + let table = table_with("refresh_preserves", vec![1, 2]).await; + declare_doubled(&table).await.unwrap(); + table.refresh_column("doubled").await.unwrap(); + + append(&table, vec![5]).await; + table + .optimize(crate::table::OptimizeAction::Compact { + options: crate::table::CompactionOptions::default(), + remap_options: None, + }) + .await + .unwrap(); + + let result = table.refresh_column("doubled").await.unwrap(); + assert_eq!(result.rows_filled, 1); + assert_eq!( + read(&table, "doubled").await, + vec![Some(2), Some(4), Some(10)] + ); + } + + #[tokio::test] + async fn test_refresh_leaves_deleted_rows_alone() { + let table = table_with("refresh_deleted", vec![1, 2, 3, 4]).await; + declare_doubled(&table).await.unwrap(); + table.delete("x = 2").await.unwrap(); + + let result = table.refresh_column("doubled").await.unwrap(); + assert_eq!(result.rows_filled, 3); + assert_eq!( + read(&table, "doubled").await, + vec![Some(2), Some(6), Some(8)] + ); + } + + #[tokio::test] + async fn test_refresh_a_constant_expression() { + let table = table_with("refresh_constant", vec![1, 2, 3]).await; + table + .add_columns() + .computed("answer", "42") + .execute() + .await + .unwrap(); + + let result = table.refresh_column("answer").await.unwrap(); + assert_eq!(result.rows_filled, 3); + } + + /// A name needing quotes reaches the evaluator intact: it is carried as a + /// projection alias, never spliced into SQL text. + #[tokio::test] + async fn test_refresh_a_column_whose_name_needs_quoting() { + let table = table_with("refresh_quoted", vec![1, 2, 3]).await; + table + .add_columns() + .computed("double value", "x * 2") + .execute() + .await + .unwrap(); + + let result = table.refresh_column("double value").await.unwrap(); + assert_eq!(result.rows_filled, 3); + assert_eq!( + read(&table, "double value").await, + vec![Some(2), Some(4), Some(6)] + ); + } + + /// A fragment spanning several scan batches exercises the streamed fill: + /// the probe buffers only until the first gained value and the rest flows + /// through write_column a batch at a time. + #[tokio::test] + async fn test_refresh_streams_a_multi_batch_fragment() { + let values: Vec = (0..20_000).collect(); + let table = table_with("refresh_multi_batch", values.clone()).await; + declare_doubled(&table).await.unwrap(); + + let result = table.refresh_column("doubled").await.unwrap(); + assert_eq!(result.rows_filled, 20_000); + + let read_back = read(&table, "doubled").await; + assert_eq!(read_back.len(), 20_000); + let mut expected: Vec> = values.iter().map(|v| Some(v * 2)).collect(); + expected.sort(); + assert_eq!(read_back, expected); + } + + /// The gate's reproducer: the commit must reuse the configured session, + /// or registrations and caches vanish from the handle after a refresh. + #[tokio::test] + async fn test_refresh_preserves_the_configured_session() { + let session = Arc::new(lance::session::Session::default()); + let conn = crate::connect("memory://") + .session(session.clone()) + .execute() + .await + .unwrap(); + let batch = record_batch!(("x", Int32, [1, 2])).unwrap(); + let table = conn + .create_table("session_kept", batch) + .execute() + .await + .unwrap(); + declare_doubled(&table).await.unwrap(); + table.refresh_column("doubled").await.unwrap(); + + let dataset = table.as_native().unwrap().dataset.get().await.unwrap(); + assert!(Arc::ptr_eq(&dataset.session(), &session)); + } + + /// Both orders of declare+spec are refused at the source (see the + /// schema_evolution tests); refresh's own check covers a dataset another + /// writer left in that state. + #[tokio::test] + async fn test_refresh_refuses_a_foreign_lsm_state() { + use crate::table::LsmWriteSpec; + + let tmp_dir = tempfile::tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(arrow_schema::Schema::new(vec![arrow_schema::Field::new( + "x", + arrow_schema::DataType::Int32, + false, + )])); + let batch = + arrow_array::RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![1]))]) + .unwrap(); + let table = conn.create_table("lsm", batch).execute().await.unwrap(); + table.set_unenforced_primary_key(["x"]).await.unwrap(); + table + .set_lsm_write_spec(LsmWriteSpec::unsharded()) + .await + .unwrap(); + super::super::computed_columns::add_foreign_kind(&table, "doubled", "sql").await; + + let err = table.refresh_column("doubled").await.unwrap_err(); + assert!( + matches!(&err, Error::NotSupported { message } if message.contains("LSM")), + "{err:?}" + ); + } + + /// After catch-up activation and unset, no spec remains but the catch-up + /// flag still marks retained SSTable rows; refresh refuses on the flag. + #[tokio::test] + async fn test_refresh_refuses_retained_catchup_state() { + use crate::table::LsmWriteSpec; + + let tmp_dir = tempfile::tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(arrow_schema::Schema::new(vec![arrow_schema::Field::new( + "x", + arrow_schema::DataType::Int32, + false, + )])); + let batch = arrow_array::RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(vec![1]))], + ) + .unwrap(); + let table = conn + .create_table("catchup", batch.clone()) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["x"]).await.unwrap(); + table + .set_lsm_write_spec(LsmWriteSpec::unsharded()) + .await + .unwrap(); + table.require_mem_wal_index_catchup().await.unwrap(); + let mut merge = table.merge_insert(&["x"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all() + .use_lsm(true); + merge + .execute(Box::new(arrow_array::RecordBatchIterator::new( + vec![Ok(batch)], + schema, + ))) + .await + .unwrap(); + table.unset_lsm_write_spec().await.unwrap(); + super::super::computed_columns::add_foreign_kind(&table, "doubled", "sql").await; + + let err = table.refresh_column("doubled").await.unwrap_err(); + assert!( + matches!(&err, Error::NotSupported { message } if message.contains("LSM")), + "{err:?}" + ); + } + + /// A declaration of a kind this version cannot evaluate is refused by + /// name, rather than mistaken for a plain column or fed to the SQL path. + #[tokio::test] + async fn test_refresh_rejects_a_kind_it_cannot_evaluate() { + let table = table_with("refresh_foreign", vec![1, 2, 3]).await; + super::super::computed_columns::add_foreign_kind(&table, "embedding", "udf").await; + + let err = table.refresh_column("embedding").await.unwrap_err(); + assert!(matches!(err, Error::NotSupported { message } if message.contains("udf"))); + } +} From c429863122489cc19a47aabc187fad1f37ef9bfc Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Fri, 14 Aug 2026 16:05:04 -0700 Subject: [PATCH 041/206] feat: refresh_column_async returns a job handle (#3939) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Mirrors create_index's dual surface: the blocking refresh_column keeps returning {rows_filled, version}, and refresh_column_async returns the same Job handle create_index uses, running the refresh as an in-process task. Invalid input is reported by the submitting call rather than by the job. --- Stack created with GitHub Stacks CLIGive Feedback 💬 --- docs/src/js/classes/Table.md | 33 ++++ nodejs/__test__/table.test.ts | 22 +++ nodejs/lancedb/table.ts | 22 +++ nodejs/src/table.rs | 10 ++ python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/remote/table.py | 3 + python/python/lancedb/table.py | 59 ++++++ python/python/tests/test_table.py | 28 +++ python/src/table.rs | 11 ++ rust/lancedb/src/job.rs | 2 +- rust/lancedb/src/table.rs | 33 ++++ rust/lancedb/src/table/refresh.rs | 246 ++++++++++++++++++++++++++ 12 files changed, 469 insertions(+), 1 deletion(-) diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 278559cc4..712c15ad0 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -770,6 +770,39 @@ number of rows filled and the new version number of the table. *** +### refreshColumnAsync() + +```ts +abstract refreshColumnAsync(column): Promise +``` + +Like [Table#refreshColumn](Table.md#refreshcolumn), but returns a handle to the refresh +job instead of blocking until it completes. + +The job may already be complete when returned; callers must not assume +the column is filled until [Job.wait](Job.md#wait) resolves. Invalid input -- +an unknown column, or one that is not computed -- rejects here rather +than failing the job. Local tables only. + +#### Parameters + +* **column**: `string` + The name of the computed column to fill. + +#### Returns + +`Promise`<[`Job`](Job.md)> + +#### Example + +```ts +const job = await table.refreshColumnAsync("doubled"); +await job.wait(); +console.log(await job.status()); // "finished" +``` + +*** + ### restore() ```ts diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index bc495d24b..5396a251a 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -3365,6 +3365,28 @@ describe("computed columns", () => { expect(rows.map((r) => r.doubled).sort()).toEqual([2, 4]); }); + it("returns a job handle from refreshColumnAsync", async () => { + const db = await connect(tmpDir.name); + const table = await db.createTable("computed_job", [{ x: 1 }, { x: 2 }]); + + await table.addColumns({ + computed: [{ name: "doubled", valueSql: "x * 2" }], + }); + + const job = await table.refreshColumnAsync("doubled"); + expect(job.id).toBeNull(); + await job.wait(); + expect(await job.status()).toBe("finished"); + + const rows = await table.query().toArray(); + expect(rows.map((r) => r.doubled).sort()).toEqual([2, 4]); + + // Bad input rejects at the call, not through the job. + await expect(table.refreshColumnAsync("x")).rejects.toThrow( + "not a computed column", + ); + }); + it("fills rows added since the last refresh", async () => { const db = await connect(tmpDir.name); const table = await db.createTable("computed_append", [{ x: 1 }]); diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 5b8d00076..4469e41a0 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -574,6 +574,24 @@ export abstract class Table { */ abstract refreshColumn(column: string): Promise; + /** + * Like {@link Table#refreshColumn}, but returns a handle to the refresh + * job instead of blocking until it completes. + * + * The job may already be complete when returned; callers must not assume + * the column is filled until {@link Job.wait} resolves. Invalid input -- + * an unknown column, or one that is not computed -- rejects here rather + * than failing the job. Local tables only. + * @param {string} column The name of the computed column to fill. + * @example + * ```ts + * const job = await table.refreshColumnAsync("doubled"); + * await job.wait(); + * console.log(await job.status()); // "finished" + * ``` + */ + abstract refreshColumnAsync(column: string): Promise; + /** * Alter the name or nullability of columns. * @param {ColumnAlteration[]} columnAlterations One or more alterations to @@ -1179,6 +1197,10 @@ export class LocalTable extends Table { return await this.inner.refreshColumn(column); } + async refreshColumnAsync(column: string): Promise { + return await this.inner.refreshColumnAsync(column); + } + async alterColumns( columnAlterations: ColumnAlteration[], ): Promise { diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 40ed7d9f0..4c45be668 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -371,6 +371,16 @@ impl Table { Ok(res.into()) } + #[napi(catch_unwind)] + pub async fn refresh_column_async(&self, column: String) -> napi::Result { + let job = self + .inner_ref()? + .refresh_column_async(column) + .await + .default_error()?; + Ok(crate::job::Job::new(job)) + } + #[napi(catch_unwind)] pub async fn add_columns_with_schema( &self, diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 96bbecad8..22878fd85 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -342,6 +342,7 @@ class Table: self, columns: list[tuple[str, str]] ) -> AddColumnsResult: ... async def refresh_column(self, column: str) -> RefreshColumnResult: ... + async def refresh_column_async(self, column: str) -> Job: ... async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ... async def alter_columns( self, columns: list[dict[str, Any]] diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 5bd446775..b1bc5bded 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -973,6 +973,9 @@ class RemoteTable(Table): def refresh_column(self, column: str): raise NotImplementedError("computed columns are supported only on local tables") + def refresh_column_async(self, column: str) -> Job: + raise NotImplementedError("computed columns are supported only on local tables") + 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 db25c4ebc..9c5925cb7 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2002,6 +2002,31 @@ class Table(ABC): version: the new version number of the table. """ + @abstractmethod + def refresh_column_async(self, column: str) -> Job: + """ + Like :meth:`refresh_column`, but returns a handle to the refresh job + instead of blocking until it completes. + + The job may already be complete when returned; callers must not assume + the column is filled until :meth:`Job.wait` returns. Invalid input -- + an unknown column, or one that is not computed -- raises here rather + than failing the job. Local tables only; LanceDB Cloud and Enterprise + raise ``NotImplementedError``. + + Examples + -------- + >>> import lancedb + >>> db = lancedb.connect("./.lancedb") + >>> table = db.create_table("computed_job_demo", [{"x": 1}, {"x": 2}]) + >>> table.add_columns(computed={"doubled": "x * 2"}) + AddColumnsResult(version=2) + >>> job = table.refresh_column_async("doubled") + >>> job.wait() + >>> job.status() + 'finished' + """ + @abstractmethod def alter_columns(self, *alterations: Iterable[Dict[str, str]]): """ @@ -4020,6 +4045,13 @@ class LanceTable(Table): [`AsyncTable.refresh_column`][lancedb.AsyncTable.refresh_column].""" return LOOP.run(self._table.refresh_column(column)) + def refresh_column_async(self, column: str) -> Job: + """Fill a computed column's unfilled rows, returning a handle to the + refresh job. See + [`Table.refresh_column_async`][lancedb.table.Table.refresh_column_async]. + """ + return Job(LOOP.run(self._table.refresh_column_async(column))) + def alter_columns( self, *alterations: Iterable[Dict[str, str]] ) -> AlterColumnsResult: @@ -6018,6 +6050,33 @@ class AsyncTable: """ return await self._inner.refresh_column(column) + async def refresh_column_async(self, column: str) -> AsyncJob: + """ + Like :meth:`refresh_column`, but returns a handle to the refresh job + instead of blocking until it completes. + + The job may already be complete when returned; callers must not assume + the column is filled until :meth:`AsyncJob.wait` resolves. Invalid + input -- an unknown column, or one that is not computed -- raises here + rather than failing the job. Local tables only; LanceDB Cloud and + Enterprise raise ``NotImplementedError``. + + Examples + -------- + >>> import asyncio + >>> import lancedb + >>> async def refresh_in_background(): + ... db = await lancedb.connect_async("./.lancedb") + ... table = await db.create_table("computed_job_async_demo", [{"x": 1}]) + ... await table.add_columns(computed={"doubled": "x * 2"}) + ... job = await table.refresh_column_async("doubled") + ... await job.wait() + ... return await job.status() + >>> asyncio.run(refresh_in_background()) + 'finished' + """ + return AsyncJob(await self._inner.refresh_column_async(column)) + async def alter_columns( self, *alterations: Iterable[dict[str, Any]] ) -> AlterColumnsResult: diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index ddc1f450f..bb011f8c0 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -3888,3 +3888,31 @@ async def test_computed_column_async(tmp_path): await table.refresh_column("tripled") assert (await table.to_arrow())["tripled"].to_pylist() == [9] + + +def test_refresh_column_async_returns_job(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("computed_job", [{"x": 1}, {"x": 2}]) + table.add_columns(computed={"doubled": "x * 2"}) + + job = table.refresh_column_async("doubled") + assert job.id is None # in-process jobs have no server id + job.wait() + assert job.status() == "finished" + assert sorted(table.to_arrow()["doubled"].to_pylist()) == [2, 4] + + # Bad input raises at the call, not through the job. + with pytest.raises(Exception, match="not a computed column"): + table.refresh_column_async("x") + + +@pytest.mark.asyncio +async def test_refresh_column_async_job_async_table(tmp_path): + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("computed_job_async", [{"x": 3}]) + await table.add_columns(computed={"tripled": "x * 3"}) + + job = await table.refresh_column_async("tripled") + await job.wait() + assert await job.status() == "finished" + assert (await table.to_arrow())["tripled"].to_pylist() == [9] diff --git a/python/src/table.rs b/python/src/table.rs index a4c3c307a..35ee92dc4 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1559,6 +1559,17 @@ impl Table { }) } + pub fn refresh_column_async( + self_: PyRef<'_, Self>, + column: String, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let job = inner.refresh_column_async(column).await.infer_error()?; + Ok(crate::job::Job::new(job)) + }) + } + pub fn add_columns_with_schema( self_: PyRef<'_, Self>, schema: PyArrowType, diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 789ce8312..d77dd6974 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -141,7 +141,7 @@ impl SpawnedJob { Ok(Err(err)) => Outcome::Failed(Arc::new(err)), Err(err) if err.is_cancelled() => Outcome::Cancelled, Err(err) => Outcome::Failed(Arc::new(Error::Runtime { - message: format!("index job task failed: {err}"), + message: format!("job task failed: {err}"), })), }; let _ = tx.send(Some(outcome)); diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index bfa060638..093d63438 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -764,6 +764,13 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "computed columns are supported only on local tables".into(), }) } + /// Fill a computed column's unfilled rows, returning a [`Job`] tracking + /// the operation. + async fn refresh_column_async(&self, _column: &str) -> Result { + Err(Error::NotSupported { + message: "computed columns are supported only on local tables".into(), + }) + } /// Alter columns in the table. async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result; /// Drop columns from the table. @@ -1679,6 +1686,28 @@ impl Table { self.inner.refresh_column(column.as_ref()).await } + /// Like [`Table::refresh_column`], but returns a [`Job`] tracking the + /// operation instead of blocking until it completes. + /// + /// The job may already be complete when returned, and callers must not + /// assume the column is filled until [`Job::wait`] returns. Invalid input + /// -- an unknown column, or one that is not computed -- is reported by + /// this call rather than by the job. Local tables only: LanceDB Cloud and + /// Enterprise reject with `NotSupported`. + /// + /// ``` + /// # use lancedb::Table; + /// # async fn refresh_in_background(table: &Table) -> Result<(), Box> { + /// let job = table.refresh_column_async("doubled").await?; + /// println!("refresh running: {:?}", job.status().await?); + /// job.wait().await?; + /// # Ok(()) + /// # } + /// ``` + pub async fn refresh_column_async(&self, column: impl AsRef) -> Result { + self.inner.refresh_column_async(column.as_ref()).await + } + /// Change a column's name or nullability. pub async fn alter_columns( &self, @@ -3392,6 +3421,10 @@ impl BaseTable for NativeTable { Ok(result) } + async fn refresh_column_async(&self, column: &str) -> Result { + refresh::execute_refresh_column_async(self, column).await + } + async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result { let result = schema_evolution::execute_alter_columns(self, alterations).await?; self.bump_freshness(); diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index ab4f8e452..edc78387e 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -35,6 +35,7 @@ use serde::{Deserialize, Serialize}; use super::computed_columns::{BoundExpression, ComputedColumnKind, computed_column_from_field}; use super::{BaseTable, NativeTable}; +use crate::job::Job; use crate::{Error, Result}; /// The result of refreshing a computed column. @@ -115,6 +116,25 @@ pub(crate) async fn execute_refresh_column( }) } +/// Run the refresh as a [`Job`] in this process. +pub(crate) async fn execute_refresh_column_async(table: &NativeTable, column: &str) -> Result { + // Validate before spawning so bad input is reported by this call rather + // than only by the job. + table.dataset.ensure_mutable()?; + ensure_no_lsm_write_spec(table).await?; + let dataset = table.dataset.get().await?; + declared_expression(&dataset, column)?; + drop(dataset); + + let table = table.clone(); + let column = column.to_string(); + Ok(Job::spawned(tokio::spawn(async move { + execute_refresh_column(&table, &column).await?; + table.bump_freshness(); + Ok(()) + }))) +} + /// Refuse to refresh under an LSM write spec. /// /// Refresh enumerates base fragments, and a write spec keeps visible rows in @@ -606,6 +626,230 @@ mod tests { assert!(Arc::ptr_eq(&dataset.session(), &session)); } + /// The async form's job settles with the fill visible, like + /// create_index's execute_async. + #[tokio::test] + async fn test_refresh_async_job_waits_for_the_fill() { + let table = table_with("refresh_async", vec![1, 2, 3]).await; + declare_doubled(&table).await.unwrap(); + + let job = table.refresh_column_async("doubled").await.unwrap(); + assert!(job.id().is_none(), "in-process jobs have no server id"); + job.wait().await.unwrap(); + assert_eq!(job.status().await.unwrap(), "finished"); + assert_eq!( + read(&table, "doubled").await, + vec![Some(2), Some(4), Some(6)] + ); + } + + /// Bad input is reported by the call, not by the job. + #[tokio::test] + async fn test_refresh_async_rejects_bad_input_before_spawning() { + let table = table_with("refresh_async_bad", vec![1, 2, 3]).await; + + let err = table.refresh_column_async("x").await.unwrap_err(); + assert!(matches!(err, Error::NotAComputedColumn { name } if name == "x")); + + let err = table.refresh_column_async("nope").await.unwrap_err(); + assert!(matches!(err, Error::ColumnNotFound { name } if name == "nope")); + } + + #[tokio::test] + async fn test_refresh_async_job_reports_success_to_every_waiter() { + let table = table_with("refresh_async_waiters", vec![1, 2]).await; + declare_doubled(&table).await.unwrap(); + + let job = table.refresh_column_async("doubled").await.unwrap(); + job.wait().await.unwrap(); + // A second wait after completion observes the same outcome. + job.wait().await.unwrap(); + assert_eq!(job.status().await.unwrap(), "finished"); + } + + #[tokio::test] + async fn test_refresh_rejects_a_plain_column() { + let table = table_with("refresh_plain", vec![1, 2, 3]).await; + let err = table.refresh_column("x").await.unwrap_err(); + assert!(matches!(err, Error::NotAComputedColumn { name } if name == "x")); + } + + #[tokio::test] + async fn test_refresh_rejects_an_unknown_column() { + let table = table_with("refresh_missing", vec![1, 2, 3]).await; + let err = table.refresh_column("nope").await.unwrap_err(); + assert!(matches!(err, Error::ColumnNotFound { name } if name == "nope")); + } + + /// The gate's reproducer: a poison value in a deleted row must not + /// abort filling the live rows, since nobody can read it. + #[tokio::test] + async fn test_a_deleted_rows_value_is_never_evaluated() { + let table = table_with("refresh_deleted_poison", vec![1, 0]).await; + table + .add_columns() + .computed("quotient", "10 / x") + .execute() + .await + .unwrap(); + table.delete("x = 0").await.unwrap(); + + let result = table.refresh_column("quotient").await.unwrap(); + assert_eq!(result.rows_filled, 1); + assert_eq!(read(&table, "quotient").await, vec![Some(10)]); + } + + /// The gate's reproducer: an already-filled row's value must not be + /// re-evaluated either -- its input may have mutated into one the + /// expression chokes on. + #[tokio::test] + async fn test_a_filled_rows_value_is_never_evaluated() { + let table = table_with("refresh_filled_poison", vec![1, 2]).await; + table + .add_columns() + .computed("quotient", "10 / x") + .execute() + .await + .unwrap(); + table.refresh_column("quotient").await.unwrap(); + + table + .update() + .column("x", "0") + .only_if("x = 1") + .execute() + .await + .unwrap(); + append(&table, vec![5]).await; + + let result = table.refresh_column("quotient").await.unwrap(); + assert_eq!(result.rows_filled, 1); + assert_eq!( + read(&table, "quotient").await, + vec![Some(2), Some(5), Some(10)] + ); + } + + /// The gate's reproducer: the old internal projection alias is an + /// ordinary column name; a computed column may use it. + #[tokio::test] + async fn test_refresh_a_column_named_like_the_old_alias() { + let table = table_with("refresh_alias_name", vec![1, 2]).await; + table + .add_columns() + .computed("__lancedb_computed", "x * 2") + .execute() + .await + .unwrap(); + + let result = table.refresh_column("__lancedb_computed").await.unwrap(); + assert_eq!(result.rows_filled, 2); + assert_eq!( + read(&table, "__lancedb_computed").await, + vec![Some(2), Some(4)] + ); + } + + /// The gate's reproducer: a late-gain fragment (filled, then one null row + /// compacted onto the end) fills without the old probe's buffering, which + /// this pins behaviorally; the memory bound is structural -- the fill + /// stream retains no batches at all. + #[tokio::test] + async fn test_refresh_fills_a_late_gain_fragment() { + let values: Vec = (0..20_000).collect(); + let table = table_with("refresh_late_gain", values).await; + declare_doubled(&table).await.unwrap(); + table.refresh_column("doubled").await.unwrap(); + + append(&table, vec![2_000_000]).await; + table + .optimize(crate::table::OptimizeAction::Compact { + options: crate::table::CompactionOptions::default(), + remap_options: None, + }) + .await + .unwrap(); + + let result = table.refresh_column("doubled").await.unwrap(); + assert_eq!(result.rows_filled, 1); + let read_back = read(&table, "doubled").await; + assert_eq!(read_back.len(), 20_001); + assert_eq!(read_back.last().unwrap(), &Some(4_000_000)); + } + + /// The gate's reproducer: a nested input declares, refreshes, and guards + /// its root against invalidating schema changes. + #[tokio::test] + async fn test_a_nested_input_declares_and_refreshes() { + use arrow_array::{Int32Array, StructArray}; + use arrow_schema::{DataType, Field, Fields}; + + let conn = connect("memory://").execute().await.unwrap(); + let age = Arc::new(Int32Array::from(vec![30, 40])); + let fields = Fields::from(vec![Field::new("age", DataType::Int32, true)]); + let metadata = StructArray::new(fields.clone(), vec![age as _], None); + let schema = Arc::new(arrow_schema::Schema::new(vec![Field::new( + "metadata", + DataType::Struct(fields), + true, + )])); + let batch = + arrow_array::RecordBatch::try_new(schema, vec![Arc::new(metadata) as _]).unwrap(); + let table = conn + .create_table("refresh_nested", batch) + .execute() + .await + .unwrap(); + + table + .add_columns() + .computed("next_age", "metadata.age + 1") + .execute() + .await + .unwrap(); + let declaration = + &crate::table::computed_columns(table.schema().await.unwrap().as_ref())[0]; + assert_eq!(declaration.inputs, vec!["metadata.age".to_string()]); + + let result = table.refresh_column("next_age").await.unwrap(); + assert_eq!(result.rows_filled, 2); + assert_eq!(read(&table, "next_age").await, vec![Some(31), Some(41)]); + + // The dotted input guards its root. + let err = table.drop_columns(&["metadata"]).await.unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("next_age")), + "{err:?}" + ); + + // Masking a struct input for a deleted row goes through the same + // nullif path as a primitive; a nested input plus deletions must not + // be the combination that breaks it. + table.delete("next_age = 31").await.unwrap(); + append_struct_row(&table, 50).await; + let result = table.refresh_column("next_age").await.unwrap(); + assert_eq!(result.rows_filled, 1); + assert_eq!(read(&table, "next_age").await, vec![Some(41), Some(51)]); + } + + /// Append one `metadata: {age}` row to the nested-input table. + async fn append_struct_row(table: &Table, age: i32) { + use arrow_array::{Int32Array, StructArray}; + use arrow_schema::{DataType, Field, Fields}; + + let ages = Arc::new(Int32Array::from(vec![age])); + let fields = Fields::from(vec![Field::new("age", DataType::Int32, true)]); + let metadata = StructArray::new(fields.clone(), vec![ages as _], None); + let schema = Arc::new(arrow_schema::Schema::new(vec![Field::new( + "metadata", + DataType::Struct(fields), + true, + )])); + let batch = + arrow_array::RecordBatch::try_new(schema, vec![Arc::new(metadata) as _]).unwrap(); + table.add(batch).execute().await.unwrap(); + } + /// Both orders of declare+spec are refused at the source (see the /// schema_evolution tests); refresh's own check covers a dataset another /// writer left in that state. @@ -639,6 +883,8 @@ mod tests { matches!(&err, Error::NotSupported { message } if message.contains("LSM")), "{err:?}" ); + let err = table.refresh_column_async("doubled").await.unwrap_err(); + assert!(matches!(err, Error::NotSupported { .. })); } /// After catch-up activation and unset, no spec remains but the catch-up From 980818df2659233df0b9500ca3a1bbc4857cc227 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Fri, 14 Aug 2026 16:20:39 -0700 Subject: [PATCH 042/206] chore: update lance dependency to v11.0.0-beta.13 (#3947) Updates the Lance Rust workspace dependencies and Java lance-core dependency to [v11.0.0-beta.13](https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.13). Adds the required `ListTablesResponse.context` compatibility field and validates the workspace with Clippy warnings denied. --- Cargo.lock | 88 ++++++++++++++-------------- Cargo.toml | 28 ++++----- java/pom.xml | 2 +- rust/lancedb/src/database/listing.rs | 1 + 4 files changed, 60 insertions(+), 59 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b4f11fb65..f0a213459 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow", "arrow-array", @@ -5013,8 +5013,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow", "arrow-array", @@ -5031,8 +5031,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "proc-macro2", "quote", @@ -5041,8 +5041,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow-arith", "arrow-array", @@ -5075,8 +5075,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow-arith", "arrow-array", @@ -5107,8 +5107,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arc-swap", "arrow", @@ -5172,8 +5172,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow-array", "arrow-schema", @@ -5195,8 +5195,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow", "arrow-array", @@ -5232,8 +5232,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow-array", "arrow-schema", @@ -5247,8 +5247,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow", "async-trait", @@ -5260,8 +5260,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow", "arrow-ipc", @@ -5300,9 +5300,9 @@ dependencies = [ [[package]] name = "lance-namespace-reqwest-client" -version = "0.8.6" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3f0a235e3ed5f8805205649ccc7d7d0f3df23ce1294242c9265ad488d7f19d" +checksum = "0a030196da1c994b63a96a4f0bf5b0cfa459fe6dadc9e962320246ca328da22a" dependencies = [ "reqwest 0.12.28", "serde", @@ -5314,8 +5314,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow-array", "arrow-buffer", @@ -5329,8 +5329,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow", "arrow-array", @@ -5370,8 +5370,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "arrow-array", "arrow-schema", @@ -5384,8 +5384,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.11#5ef1e969030b79fe8c6d31fff9e40d18b24ebbd3" +version = "11.0.0-beta.13" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 3e332adfc..2a19cbb00 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.11", default-features = false, "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.11", default-features = false, "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.11", default-features = false, "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.11", "tag" = "v11.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.13", default-features = false, "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.13", default-features = false, "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.13", default-features = false, "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } ahash = "0.8" # Note that this one does not include pyarrow arrow = { version = "58.0.0", optional = false } diff --git a/java/pom.xml b/java/pom.xml index 9d9fe1f87..3d0682c46 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.11 + 11.0.0-beta.13 false 2.30.0 1.7 diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index f284320c6..5ebbe6c5c 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -1032,6 +1032,7 @@ impl Database for ListingDatabase { }; Ok(ListTablesResponse { + context: None, tables: f, page_token: next_page_token, }) From 928c3dde2dd94173931632bde06062e786e495be Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Fri, 14 Aug 2026 17:21:55 -0700 Subject: [PATCH 043/206] feat: computed columns on remote tables (#3941) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit LanceDB Cloud and Enterprise support computed columns through the REST API, so declaration dispatches per backend: local tables plan the expression themselves, remote ones send {name, computed} entries for the server to plan. A remote refresh is the server's backfill job -- refresh_column_async submits it and returns a handle whose successful wait establishes a read-freshness baseline on the submitting handle, unless a checkout has pinned the handle by the time the job completes; the blocking form refuses rather than invent a fill count the server does not report. Declaration entries are built from the namespace client's AddColumnsEntry model (lance-namespace 0.11.0, via the lance beta.13 pin), so the payload shape is compile-checked against the published contract. --- Stack created with GitHub Stacks CLIGive Feedback 💬 --- docs/src/js/classes/Table.md | 11 +- nodejs/lancedb/table.ts | 11 +- python/python/lancedb/remote/table.py | 10 +- python/python/lancedb/table.py | 26 +- rust/lancedb/src/remote/table.rs | 494 ++++++++++++++++++++++++-- rust/lancedb/src/table.rs | 12 +- rust/lancedb/src/table/add_columns.rs | 5 +- 7 files changed, 500 insertions(+), 69 deletions(-) diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 712c15ad0..4479bf4e4 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -79,8 +79,9 @@ input leaves the value computed at fill time; recomputing means dropping the column and declaring it again. While a declaration reads a column, that column cannot be renamed, retyped or dropped. -Computed columns are local-only: LanceDB Cloud and Enterprise reject a -declaration. +On LanceDB Cloud and Enterprise the expression is planned by the +server, and the refresh runs as a server job -- see +[Table#refreshColumnAsync](Table.md#refreshcolumnasync). #### Parameters @@ -754,7 +755,8 @@ Fill the rows of a computed column that hold no value yet. Rows appended since the last refresh are filled by the next one; rows already filled are left as they are, so the call is idempotent and does -not observe a mutated input. Local tables only. +not observe a mutated input. Local tables only: a remote refresh runs +as a server job, through [Table#refreshColumnAsync](Table.md#refreshcolumnasync). #### Parameters @@ -782,7 +784,8 @@ job instead of blocking until it completes. The job may already be complete when returned; callers must not assume the column is filled until [Job.wait](Job.md#wait) resolves. Invalid input -- an unknown column, or one that is not computed -- rejects here rather -than failing the job. Local tables only. +than failing the job. On local tables the job runs in-process; on +LanceDB Cloud and Enterprise it is the server's backfill job. #### Parameters diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 4469e41a0..a7dc8def1 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -537,8 +537,9 @@ export abstract class Table { * the column and declaring it again. While a declaration reads a column, * that column cannot be renamed, retyped or dropped. * - * Computed columns are local-only: LanceDB Cloud and Enterprise reject a - * declaration. + * On LanceDB Cloud and Enterprise the expression is planned by the + * server, and the refresh runs as a server job -- see + * {@link Table#refreshColumnAsync}. * @param {AddColumnsSql[] | Field | Field[] | Schema} newColumnTransforms Either: * - An array of objects with column names and SQL expressions to calculate values * - A single Arrow Field defining one column with its data type (column will be initialized with null values) @@ -567,7 +568,8 @@ export abstract class Table { * * Rows appended since the last refresh are filled by the next one; rows * already filled are left as they are, so the call is idempotent and does - * not observe a mutated input. Local tables only. + * not observe a mutated input. Local tables only: a remote refresh runs + * as a server job, through {@link Table#refreshColumnAsync}. * @param {string} column The name of the computed column to fill. * @returns {Promise} A promise that resolves to the * number of rows filled and the new version number of the table. @@ -581,7 +583,8 @@ export abstract class Table { * The job may already be complete when returned; callers must not assume * the column is filled until {@link Job.wait} resolves. Invalid input -- * an unknown column, or one that is not computed -- rejects here rather - * than failing the job. Local tables only. + * than failing the job. On local tables the job runs in-process; on + * LanceDB Cloud and Enterprise it is the server's backfill job. * @param {string} column The name of the computed column to fill. * @example * ```ts diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index b1bc5bded..aa822b913 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -964,17 +964,13 @@ class RemoteTable(Table): *, computed: Dict[str, str] | None = None, ) -> AddColumnsResult: - if computed: - raise NotImplementedError( - "computed columns are supported only on local tables" - ) - return LOOP.run(self._table.add_columns(transforms)) + return LOOP.run(self._table.add_columns(transforms, computed=computed)) def refresh_column(self, column: str): - raise NotImplementedError("computed columns are supported only on local tables") + return LOOP.run(self._table.refresh_column(column)) def refresh_column_async(self, column: str) -> Job: - raise NotImplementedError("computed columns are supported only on local tables") + return Job(LOOP.run(self._table.refresh_column_async(column))) def alter_columns( self, *alterations: Iterable[Dict[str, str]] diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 9c5925cb7..4ecf6e836 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1954,8 +1954,10 @@ class Table(ABC): dropping the column and declaring it again. While a declaration reads a column, that column cannot be renamed, retyped or dropped. - Local tables only; LanceDB Cloud and Enterprise raise - ``NotImplementedError``. Cannot be combined with ``transforms``. + On LanceDB Cloud and Enterprise the expression is planned by the + server, and the refresh runs as a server job -- see + [`refresh_column_async`][lancedb.table.Table.refresh_column_async]. + Cannot be combined with ``transforms``. Returns ------- @@ -1987,8 +1989,8 @@ class Table(ABC): by the next one; rows already filled are left as they are, so the call is idempotent and does not observe a mutated input. - Local tables only; LanceDB Cloud and Enterprise raise - ``NotImplementedError``. + Local tables only: a remote refresh runs as a server job, through + [`refresh_column_async`][lancedb.table.Table.refresh_column_async]. Parameters ---------- @@ -2011,8 +2013,8 @@ class Table(ABC): The job may already be complete when returned; callers must not assume the column is filled until :meth:`Job.wait` returns. Invalid input -- an unknown column, or one that is not computed -- raises here rather - than failing the job. Local tables only; LanceDB Cloud and Enterprise - raise ``NotImplementedError``. + than failing the job. On local tables the job runs in-process; on + LanceDB Cloud and Enterprise it is the server's backfill job. Examples -------- @@ -5999,7 +6001,8 @@ class AsyncTable: declaration reads a column, that column cannot be renamed, retyped or dropped. - Local tables only. Cannot be combined with ``transforms``. + On LanceDB Cloud and Enterprise the expression is planned by + the server. Cannot be combined with ``transforms``. Returns ------- @@ -6035,8 +6038,8 @@ class AsyncTable: by the next one; rows already filled are left as they are, so the call is idempotent and does not observe a mutated input. - Local tables only; LanceDB Cloud and Enterprise raise - ``NotImplementedError``. + Local tables only: a remote refresh runs as a server job, through + [`refresh_column_async`][lancedb.table.Table.refresh_column_async]. Parameters ---------- @@ -6058,8 +6061,9 @@ class AsyncTable: The job may already be complete when returned; callers must not assume the column is filled until :meth:`AsyncJob.wait` resolves. Invalid input -- an unknown column, or one that is not computed -- raises here - rather than failing the job. Local tables only; LanceDB Cloud and - Enterprise raise ``NotImplementedError``. + rather than failing the job. On local tables the job runs + in-process; on LanceDB Cloud and Enterprise it is the server's + backfill job. Examples -------- diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 8ca84a520..a0a4cebc2 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -33,7 +33,9 @@ use crate::table::lsm_stats::GetLsmStatsResponse; use crate::table::merge::MergeFilter; use crate::table::query::create_multi_vector_plan; use crate::table::write_progress::FinishOnDrop; -use crate::table::{AlterColumnsResult, FieldMetadataUpdate, UpdateFieldMetadataResult}; +use crate::table::{ + AlterColumnsResult, FieldMetadataUpdate, RefreshColumnResult, UpdateFieldMetadataResult, +}; use crate::table::{AnyQuery, Filter, Predicate, PreprocessingOutput, TableStatistics}; use crate::utils::background_cache::BackgroundCache; use crate::utils::{ @@ -140,6 +142,40 @@ impl FreshnessHeaders { } } +/// A backfill job whose successful wait establishes a read-freshness +/// baseline on the submitting handle, so a later read cannot be served +/// from a cache older than the completed fill. A handle pinned by checkout +/// at completion keeps its time-travel view instead. +struct FreshnessJob { + inner: RemoteJob, + freshness: Arc>, + version: Arc>>, +} + +#[async_trait] +impl crate::job::JobHandle for FreshnessJob { + fn id(&self) -> Option<&str> { + crate::job::JobHandle::id(&self.inner) + } + + async fn status(&self) -> Result { + crate::job::JobHandle::status(&self.inner).await + } + + async fn wait(&self) -> Result<()> { + crate::job::JobHandle::wait(&self.inner).await?; + let version = self.version.read().await; + if version.is_none() { + self.freshness.lock().unwrap().checkout_baseline = Some(SystemTime::now()); + } + Ok(()) + } + + async fn cancel(&self) -> Result<()> { + crate::job::JobHandle::cancel(&self.inner).await + } +} + fn compute_min_timestamp( state: &FreshnessState, interval: Option, @@ -274,10 +310,10 @@ pub struct RemoteTable { identifier: String, server_version: ServerVersion, - version: RwLock>, + version: Arc>>, location: RwLock>, schema_cache: BackgroundCache, - freshness: Mutex, + freshness: Arc>, /// The branch this handle is scoped to, or `None` for the main branch. /// Stamped onto every branch-accepting request so reads and writes resolve /// on the branch's own version chain rather than main's. @@ -415,10 +451,10 @@ impl RemoteTable { namespace, identifier, server_version, - version: RwLock::new(None), + version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), - freshness: Mutex::new(FreshnessState::default()), + freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, } } @@ -447,10 +483,10 @@ impl RemoteTable { namespace: self.namespace.clone(), identifier: self.identifier.clone(), server_version: self.server_version.clone(), - version: RwLock::new(None), + version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), - freshness: Mutex::new(FreshnessState::default()), + freshness: Arc::new(Mutex::new(FreshnessState::default())), branch, } } @@ -1268,10 +1304,10 @@ mod test_utils { namespace: vec![], identifier: name, server_version: version.map(ServerVersion).unwrap_or_default(), - version: RwLock::new(None), + version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), - freshness: Mutex::new(FreshnessState::default()), + freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, } } @@ -1292,10 +1328,10 @@ mod test_utils { namespace: vec![], identifier: name, server_version: ServerVersion::default(), - version: RwLock::new(None), + version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), - freshness: Mutex::new(FreshnessState::default()), + freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, } } @@ -1325,10 +1361,10 @@ mod test_utils { namespace: vec![], identifier: name, server_version: version.map(ServerVersion).unwrap_or_default(), - version: RwLock::new(None), + version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), - freshness: Mutex::new(FreshnessState::default()), + freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, } } @@ -2700,13 +2736,6 @@ impl BaseTable for RemoteTable { Ok(result) } - // A declaration reaches here as AllNulls, which the remote protocol - // has no representation for. - NewColumnTransform::AllNulls(_) => { - return Err(Error::NotSupported { - message: "computed columns are supported only on local tables".into(), - }); - } _ => { return Err(Error::NotSupported { message: "Only SQL expressions are supported for adding columns".into(), @@ -2715,6 +2744,86 @@ impl BaseTable for RemoteTable { } } + async fn add_computed_columns(&self, columns: &[(String, String)]) -> Result { + self.check_mutable().await?; + // The server plans the declaration: expression validation, type + // inference and the persisted binding all happen there. + let entries = columns + .iter() + .map( + |(name, expression)| lance_namespace::models::AddColumnsEntry { + name: name.clone(), + computed: Some(Some(expression.clone())), + ..Default::default() + }, + ) + .collect::>(); + let mut body = serde_json::json!({ "new_columns": entries }); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/add_columns/", 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())?; + + if body.trim().is_empty() { + // Backward compatible with old servers + return Ok(AddColumnsResult { version: 0 }); + } + + let result: AddColumnsResult = serde_json::from_str(&body).map_err(|e| Error::Http { + source: format!("Failed to parse add_columns response: {}", e).into(), + request_id, + status_code: None, + })?; + + self.invalidate_schema_cache(); + self.track_write_version(result.version); + + Ok(result) + } + + async fn refresh_column(&self, _column: &str) -> Result { + // The server runs a refresh as a job and does not report a fill + // count, so the blocking form has no honest result to return. + Err(Error::NotSupported { + message: "a remote refresh runs as a server job; use refresh_column_async and \ + wait on the returned handle" + .into(), + }) + } + + async fn refresh_column_async(&self, column: &str) -> Result { + self.check_mutable().await?; + let mut body = serde_json::json!({ "column": column }); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/backfill_column", 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())?; + + #[derive(serde::Deserialize)] + struct BackfillResponse { + job_id: String, + } + let response: BackfillResponse = serde_json::from_str(&body).map_err(|e| Error::Http { + source: format!("Failed to parse backfill_column response: {}", e).into(), + request_id, + status_code: None, + })?; + + Ok(Job::new(Box::new(FreshnessJob { + inner: RemoteJob::new(self.client.clone(), response.job_id), + freshness: self.freshness.clone(), + version: self.version.clone(), + }))) + } + async fn alter_columns(&self, alterations: &[ColumnAlteration]) -> Result { self.check_mutable().await?; let body = alterations @@ -6456,37 +6565,346 @@ mod tests { assert_eq!(result.version, if old_server { 0 } else { 43 }); } - /// Computed columns are local-only. Both halves say so here rather than - /// reaching the wire and failing somewhere less legible. + /// A declaration is sent as `{name, computed}` entries for the server to + /// plan; the client never types the expression itself. #[tokio::test] - async fn test_computed_columns_are_refused() { - let table = Table::new_with_handler("my_table", |request| -> http::Response { - panic!("unexpected request: {}", request.url().path()) + async fn test_add_computed_columns_sends_the_expression() { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.method(), "POST"); + assert_eq!(request.url().path(), "/v1/table/my_table/add_columns/"); + let body = request.body().unwrap().as_bytes().unwrap(); + let value: serde_json::Value = serde_json::from_slice(body).unwrap(); + assert_eq!( + value["new_columns"], + serde_json::json!([{"name": "doubled", "computed": "x * 2"}]) + ); + http::Response::builder() + .status(200) + .body(r#"{"version": 7}"#) + .unwrap() }); - let declared = Arc::new(Schema::new(vec![Field::new( - "doubled", - DataType::Int32, - true, - )])); - let err = table + let result = table .add_columns() - .transform(NewColumnTransform::AllNulls(declared)) + .computed("doubled", "x * 2") .execute() .await - .unwrap_err(); - assert!( - matches!(&err, Error::NotSupported { message } if message.contains("local tables")), - "{err:?}" - ); + .unwrap(); + assert_eq!(result.version, 7); + } + + /// A remote refresh is a server job: the async form returns its handle, + /// and the blocking form refuses rather than invent a fill count. + #[tokio::test] + async fn test_refresh_column_async_submits_a_backfill_job() { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.method(), "POST"); + assert_eq!(request.url().path(), "/v1/table/my_table/backfill_column"); + let body = request.body().unwrap().as_bytes().unwrap(); + let value: serde_json::Value = serde_json::from_slice(body).unwrap(); + assert_eq!(value["column"], "doubled"); + http::Response::builder() + .status(202) + .body(r#"{"job_id": "j-42"}"#) + .unwrap() + }); + + let job = table.refresh_column_async("doubled").await.unwrap(); + assert_eq!(job.id(), Some("j-42")); let err = table.refresh_column("doubled").await.unwrap_err(); assert!( - matches!(&err, Error::NotSupported { message } if message.contains("local tables")), + matches!(&err, Error::NotSupported { message } + if message.contains("refresh_column_async")), "{err:?}" ); } + /// The gate's reproducer: after a successful wait, a same-handle read + /// must carry a freshness baseline so a stale server cache cannot serve + /// the pre-backfill snapshot. + #[tokio::test] + async fn test_backfill_wait_establishes_read_freshness() { + let saw_min_timestamp = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let saw = saw_min_timestamp.clone(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/backfill_column" => http::Response::builder() + .status(202) + .body(r#"{"job_id": "j-7"}"#.to_string()) + .unwrap(), + "/v1/jobs/describe" => http::Response::builder() + .status(200) + .body(r#"{"job_id": "j-7", "job_state": "DONE"}"#.to_string()) + .unwrap(), + "/v1/table/my_table/count_rows/" => { + saw.store( + request.headers().contains_key("x-lancedb-min-timestamp"), + std::sync::atomic::Ordering::SeqCst, + ); + http::Response::builder() + .status(200) + .body("1".to_string()) + .unwrap() + } + path => panic!("unexpected request: {path}"), + }); + + let job = table.refresh_column_async("doubled").await.unwrap(); + job.wait().await.unwrap(); + table.count_rows(None).await.unwrap(); + assert!( + saw_min_timestamp.load(std::sync::atomic::Ordering::SeqCst), + "read after wait carried no freshness baseline" + ); + } + + /// A checkout after submission wins over the completion fence: the + /// pinned view must not regain a timestamp floor from the job. + #[tokio::test] + async fn test_checkout_after_submit_beats_the_completion_fence() { + let saw_min_timestamp = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let saw = saw_min_timestamp.clone(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/backfill_column" => http::Response::builder() + .status(202) + .body(r#"{"job_id": "j-8"}"#.to_string()) + .unwrap(), + "/v1/jobs/describe" => http::Response::builder() + .status(200) + .body(r#"{"job_id": "j-8", "job_state": "DONE"}"#.to_string()) + .unwrap(), + "/v1/table/my_table/describe/" => { + let schema = Schema::new(vec![Field::new("x", DataType::Int32, true)]); + http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap() + } + "/v1/table/my_table/count_rows/" => { + saw.store( + request.headers().contains_key("x-lancedb-min-timestamp"), + std::sync::atomic::Ordering::SeqCst, + ); + http::Response::builder() + .status(200) + .body("1".to_string()) + .unwrap() + } + path => panic!("unexpected request: {path}"), + }); + + let job = table.refresh_column_async("doubled").await.unwrap(); + table.checkout(3).await.unwrap(); + job.wait().await.unwrap(); + table.count_rows(None).await.unwrap(); + assert!( + !saw_min_timestamp.load(std::sync::atomic::Ordering::SeqCst), + "completion fence overrode an explicit checkout" + ); + } + + /// Tag checkout resets freshness state wholesale; the fence must not + /// survive it. + #[tokio::test] + async fn test_tag_checkout_after_submit_beats_the_completion_fence() { + let saw_min_timestamp = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let saw = saw_min_timestamp.clone(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/backfill_column" => http::Response::builder() + .status(202) + .body(r#"{"job_id": "j-9"}"#.to_string()) + .unwrap(), + "/v1/jobs/describe" => http::Response::builder() + .status(200) + .body(r#"{"job_id": "j-9", "job_state": "DONE"}"#.to_string()) + .unwrap(), + "/v1/table/my_table/tags/version/" => http::Response::builder() + .status(200) + .body(r#"{"version": 5}"#.to_string()) + .unwrap(), + "/v1/table/my_table/describe/" => { + let schema = Schema::new(vec![Field::new("x", DataType::Int32, true)]); + http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap() + } + "/v1/table/my_table/count_rows/" => { + saw.store( + request.headers().contains_key("x-lancedb-min-timestamp"), + std::sync::atomic::Ordering::SeqCst, + ); + http::Response::builder() + .status(200) + .body("1".to_string()) + .unwrap() + } + path => panic!("unexpected request: {path}"), + }); + + let job = table.refresh_column_async("doubled").await.unwrap(); + table.checkout_tag("v1").await.unwrap(); + job.wait().await.unwrap(); + table.count_rows(None).await.unwrap(); + assert!( + !saw_min_timestamp.load(std::sync::atomic::Ordering::SeqCst), + "completion fence overrode a tag checkout" + ); + } + + /// A checkout landing while the submission request is in flight advances + /// the epoch past the token captured at submit. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_checkout_during_submission_beats_the_completion_fence() { + let saw_min_timestamp = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let saw = saw_min_timestamp.clone(); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let release_rx = Arc::new(std::sync::Mutex::new(release_rx)); + let (arrived_tx, arrived_rx) = std::sync::mpsc::channel::<()>(); + let arrived_tx = Arc::new(std::sync::Mutex::new(arrived_tx)); + let table = Table::new_with_handler("my_table", move |request| { + match request.url().path() { + "/v1/table/my_table/backfill_column" => { + // Signal arrival, then hold the response until the + // test's checkout completes. + arrived_tx.lock().unwrap().send(()).unwrap(); + release_rx + .lock() + .unwrap() + .recv_timeout(std::time::Duration::from_secs(10)) + .unwrap(); + http::Response::builder() + .status(202) + .body(r#"{"job_id": "j-10"}"#.to_string()) + .unwrap() + } + "/v1/jobs/describe" => http::Response::builder() + .status(200) + .body(r#"{"job_id": "j-10", "job_state": "DONE"}"#.to_string()) + .unwrap(), + "/v1/table/my_table/describe/" => { + let schema = Schema::new(vec![Field::new("x", DataType::Int32, true)]); + http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap() + } + "/v1/table/my_table/count_rows/" => { + saw.store( + request.headers().contains_key("x-lancedb-min-timestamp"), + std::sync::atomic::Ordering::SeqCst, + ); + http::Response::builder() + .status(200) + .body("1".to_string()) + .unwrap() + } + path => panic!("unexpected request: {path}"), + } + }); + + let submit = tokio::spawn({ + let table = table.clone(); + async move { table.refresh_column_async("doubled").await } + }); + tokio::task::spawn_blocking(move || { + arrived_rx + .recv_timeout(std::time::Duration::from_secs(10)) + .unwrap() + }) + .await + .unwrap(); + table.checkout(7).await.unwrap(); + release_tx.send(()).unwrap(); + + let job = submit.await.unwrap().unwrap(); + job.wait().await.unwrap(); + table.count_rows(None).await.unwrap(); + assert!( + !saw_min_timestamp.load(std::sync::atomic::Ordering::SeqCst), + "completion fence overrode a checkout that landed mid-submission" + ); + } + + /// checkout_latest keeps the handle on latest, so a completed backfill + /// must still establish its post-fill baseline -- strictly later than the + /// checkout's own, or a pre-fill cache could still serve. + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_checkout_latest_during_submission_keeps_the_fence() { + let seen_min_timestamp = Arc::new(std::sync::Mutex::new(None::)); + let saw = seen_min_timestamp.clone(); + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let release_rx = Arc::new(std::sync::Mutex::new(release_rx)); + let (arrived_tx, arrived_rx) = std::sync::mpsc::channel::<()>(); + let arrived_tx = Arc::new(std::sync::Mutex::new(arrived_tx)); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/backfill_column" => { + arrived_tx.lock().unwrap().send(()).unwrap(); + release_rx + .lock() + .unwrap() + .recv_timeout(std::time::Duration::from_secs(10)) + .unwrap(); + http::Response::builder() + .status(202) + .body(r#"{"job_id": "j-11"}"#.to_string()) + .unwrap() + } + "/v1/jobs/describe" => http::Response::builder() + .status(200) + .body(r#"{"job_id": "j-11", "job_state": "DONE"}"#.to_string()) + .unwrap(), + "/v1/table/my_table/count_rows/" => { + *saw.lock().unwrap() = request + .headers() + .get("x-lancedb-min-timestamp") + .map(|v| v.to_str().unwrap().to_string()); + http::Response::builder() + .status(200) + .body("1".to_string()) + .unwrap() + } + path => panic!("unexpected request: {path}"), + }); + + let submit = tokio::spawn({ + let table = table.clone(); + async move { table.refresh_column_async("doubled").await } + }); + tokio::task::spawn_blocking(move || { + arrived_rx + .recv_timeout(std::time::Duration::from_secs(10)) + .unwrap() + }) + .await + .unwrap(); + table.checkout_latest().await.unwrap(); + let after_checkout = SystemTime::now(); + // Real separation between the checkout baseline and completion. + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + release_tx.send(()).unwrap(); + + let job = submit.await.unwrap().unwrap(); + job.wait().await.unwrap(); + table.count_rows(None).await.unwrap(); + let header = seen_min_timestamp + .lock() + .unwrap() + .clone() + .expect("no baseline"); + let sent: SystemTime = chrono::DateTime::parse_from_rfc3339(&header) + .unwrap() + .into(); + assert!( + sent > after_checkout, + "baseline {header} did not advance past the checkout" + ); + } + #[tokio::test] async fn test_prewarm_index() { let table = Table::new_with_handler("my_table", |request| { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 093d63438..2e16b0940 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -748,6 +748,10 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { read_columns: Option>, ) -> Result; /// Declare computed columns, each defined by a SQL expression. + /// + /// Where the declaration is planned depends on the backend: a local table + /// validates and types the expression itself, a remote one sends the text + /// for the server to plan. async fn add_computed_columns( &self, _columns: &[(String, String)], @@ -1672,7 +1676,8 @@ impl Table { /// filled are left as they are, so the call is idempotent and does not /// observe a mutated input. /// - /// Local tables only. + /// Local tables only: a remote refresh runs as a server job, through + /// [`Table::refresh_column_async`]. /// /// ``` /// # use lancedb::Table; @@ -1692,8 +1697,9 @@ impl Table { /// The job may already be complete when returned, and callers must not /// assume the column is filled until [`Job::wait`] returns. Invalid input /// -- an unknown column, or one that is not computed -- is reported by - /// this call rather than by the job. Local tables only: LanceDB Cloud and - /// Enterprise reject with `NotSupported`. + /// this call rather than by the job. On local tables the job runs as an + /// in-process task; on LanceDB Cloud and Enterprise it is the server's + /// backfill job. /// /// ``` /// # use lancedb::Table; diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index 6aa2ce86a..67764c346 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -61,8 +61,9 @@ impl AddColumnsBuilder { /// column and declaring it again. An input cannot be renamed, retyped or /// dropped while a declaration reads it, since the expression names it. /// - /// Local tables only: LanceDB Cloud and Enterprise reject a declaration - /// with `NotSupported`. + /// On LanceDB Cloud and Enterprise the expression is planned by the + /// server, and the refresh runs as a server job -- see + /// [`Table::refresh_column_async`](super::Table::refresh_column_async). /// /// ``` /// # use lancedb::Table; From 040a4120c876dc105df18afc34c075a36fc64cb6 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Mon, 17 Aug 2026 16:56:20 +0000 Subject: [PATCH 044/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.0=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package-lock.json | 4 ++-- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index cab6bb104..e2e693549 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.0" +current_version = "0.38.0-beta.1" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index f0a213459..2f7499e91 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5398,7 +5398,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.0" +version = "0.38.0-beta.1" dependencies = [ "ahash", "anyhow", @@ -5486,7 +5486,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.0" +version = "0.38.0-beta.1" dependencies = [ "arrow-array", "arrow-buffer", @@ -5511,7 +5511,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.0" +version = "0.38.0-beta.1" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index f9a0ea053..42bc06b9d 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.38.0-beta.0 + 0.38.0-beta.1 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 09b088e46..94c72b326 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.0 + 0.38.0-beta.1 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 3d0682c46..90ad2f7f8 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.0 + 0.38.0-beta.1 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 2e9373b9b..3496e2839 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.0" +version = "0.38.0-beta.1" 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 e0fd7426d..ad1503090 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.38.0-beta.0", + "version": "0.38.0-beta.1", "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 ef281de3d..e7455832d 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.38.0-beta.0", + "version": "0.38.0-beta.1", "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 d535820fa..8269bc4ce 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.38.0-beta.0", + "version": "0.38.0-beta.1", "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 7aa21301e..7a7d0a097 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.38.0-beta.0", + "version": "0.38.0-beta.1", "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 d220991f7..ce95c0174 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.38.0-beta.0", + "version": "0.38.0-beta.1", "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 519d7376a..2ae43e763 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.38.0-beta.0", + "version": "0.38.0-beta.1", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 9f608d6d0..1030609fa 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.38.0-beta.0", + "version": "0.38.0-beta.1", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index 9222bf582..26091b118 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.0", + "version": "0.38.0-beta.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.0", + "version": "0.38.0-beta.1", "cpu": [ "x64", "arm64" diff --git a/nodejs/package.json b/nodejs/package.json index c87af926b..cfdc851ef 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.0", + "version": "0.38.0-beta.1", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index bede2bc37..745ca4ea2 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.0" +version = "0.38.0-beta.1" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 23c0dcfd0..92f020956 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.0" +version = "0.38.0-beta.1" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From a075aa62f8cdd87ef666eea2f3d7555507e8d773 Mon Sep 17 00:00:00 2001 From: Igor Ganapolsky Date: Mon, 17 Aug 2026 10:48:02 -0700 Subject: [PATCH 045/206] fix(python): treat naive lit(datetime) as UTC wall clock (#3262) (#3775) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Fixes naive `lit(datetime)` equality filters against table timestamp columns on non-UTC hosts, and adds the integration matrix from #3262. ## Failure (before) On a machine in US Eastern (UTC−4 / EDT), with PyPI `lancedb==0.36.0`: ```python from datetime import datetime import lancedb from lancedb.expr import col, lit db = lancedb.connect("memory://") ts = datetime(2024, 7, 1, 10, 0, 0) # naive table = db.create_table("t", [{"id": 1, "ts": ts}]) rows = table.search().where(col("ts") == lit(ts)).to_list() # actual: [] (0 rows) # expected: 1 row ``` ### Root cause In `python/src/expr.rs`, `expr_lit` converted every `datetime` via Python's `.timestamp()`: - **naive** `.timestamp()` = local wall → UTC epoch (shifted by host offset) - **PyArrow naive** storage = UTC wall-clock microseconds (no local shift) So `lit(naive)` became `CAST('2024-07-01 14:00:00' AS TIMESTAMP)` on EDT while the table held `10:00:00`. ## After Naive datetimes are interpreted as UTC wall clock (`replace(tzinfo=timezone.utc).timestamp()`), matching Arrow storage. Aware datetimes still use `.timestamp()` (correct epoch). Same repro on this branch: **1 matching row**. ## Tests Added `TestExprDatetimeTimezoneIntegration` covering: | Case | Result | |------|--------| | both naive | match | | both same TZ (UTC) | match | | different TZs, same instant | match | | table TZ + naive lit | match (wall clock) | | table naive + aware lit | match | | naive lit SQL is wall clock, not local-shifted | asserts `10:00:00` in SQL | ### Verification ```bash cd python maturin develop pytest python/tests/test_expr.py -v ``` **102 passed** (full `test_expr.py`, including the 6 new cases). Closes #3262 --------- Co-authored-by: Will Jones Co-authored-by: Claude Opus 5 (1M context) --- python/python/tests/test_expr.py | 98 ++++++++++++++++++++++++++++++++ python/src/expr.rs | 21 ++++++- 2 files changed, 118 insertions(+), 1 deletion(-) diff --git a/python/python/tests/test_expr.py b/python/python/tests/test_expr.py index 6aa78943e..0eb6f8929 100644 --- a/python/python/tests/test_expr.py +++ b/python/python/tests/test_expr.py @@ -632,3 +632,101 @@ class TestExprBytesIntegration: .to_arrow() ) assert result.num_rows == 2 + + +# ── datetime / timezone integration for lit() (issue #3262) ────────────────── + + +class TestExprDatetimeTimezoneIntegration: + """Integration coverage for lit(datetime) against table timestamp columns. + + PyArrow stores naive timestamps as UTC wall-clock microseconds. Python's + datetime.timestamp() treats naive values as *local* time, which used to + shift lit(naive) by the host UTC offset and break equality filters on + non-UTC machines. These cases lock the expected semantics. + """ + + def test_both_naive_match(self, tmp_path): + """Table naive + lit naive with the same wall clock must match.""" + db = lancedb.connect(str(tmp_path / "naive")) + ts = datetime(2024, 7, 1, 10, 0, 0) + table = db.create_table( + "t", [{"id": 1, "ts": ts}, {"id": 2, "ts": datetime(2024, 7, 2, 10, 0, 0)}] + ) + result = table.search().where(col("ts") == lit(ts)).to_list() + assert len(result) == 1 + assert result[0]["id"] == 1 + + def test_both_same_timezone_match(self, tmp_path): + """Table UTC + lit UTC for the same instant must match.""" + db = lancedb.connect(str(tmp_path / "utc")) + ts = datetime(2024, 7, 1, 10, 0, 0, tzinfo=timezone.utc) + table = db.create_table( + "t", + pa.table( + { + "id": [1, 2], + "ts": pa.array( + [ts, datetime(2024, 7, 2, 10, 0, 0, tzinfo=timezone.utc)], + type=pa.timestamp("us", tz="UTC"), + ), + } + ), + ) + result = table.search().where(col("ts") == lit(ts)).to_list() + assert len(result) == 1 + assert result[0]["id"] == 1 + + def test_different_timezones_same_instant(self, tmp_path): + """UTC table row equals lit of the same instant in a different zone.""" + db = lancedb.connect(str(tmp_path / "diff_tz")) + ts_utc = datetime(2024, 7, 1, 10, 0, 0, tzinfo=timezone.utc) + # Same instant as 06:00 in UTC-4 + ts_est = datetime(2024, 7, 1, 6, 0, 0, tzinfo=timezone(timedelta(hours=-4))) + table = db.create_table( + "t", + pa.table( + { + "id": [1], + "ts": pa.array([ts_utc], type=pa.timestamp("us", tz="UTC")), + } + ), + ) + result = table.search().where(col("ts") == lit(ts_est)).to_list() + assert len(result) == 1 + assert result[0]["id"] == 1 + + def test_table_tz_literal_naive(self, tmp_path): + """UTC table + naive lit uses wall-clock equality (10:00 == 10:00 UTC).""" + db = lancedb.connect(str(tmp_path / "tz_naive")) + ts_utc = datetime(2024, 7, 1, 10, 0, 0, tzinfo=timezone.utc) + ts_naive = datetime(2024, 7, 1, 10, 0, 0) + table = db.create_table( + "t", + pa.table( + { + "id": [1], + "ts": pa.array([ts_utc], type=pa.timestamp("us", tz="UTC")), + } + ), + ) + result = table.search().where(col("ts") == lit(ts_naive)).to_list() + assert len(result) == 1 + assert result[0]["id"] == 1 + + def test_table_naive_literal_aware(self, tmp_path): + """Naive table + UTC lit with the same wall clock must match.""" + db = lancedb.connect(str(tmp_path / "naive_aware")) + ts_naive = datetime(2024, 7, 1, 10, 0, 0) + ts_utc = datetime(2024, 7, 1, 10, 0, 0, tzinfo=timezone.utc) + table = db.create_table("t", [{"id": 1, "ts": ts_naive}]) + result = table.search().where(col("ts") == lit(ts_utc)).to_list() + assert len(result) == 1 + assert result[0]["id"] == 1 + + def test_naive_lit_sql_is_wall_clock_not_local_shifted(self): + """Regression: naive lit must not apply the host local UTC offset.""" + ts = datetime(2024, 7, 1, 10, 0, 0) + sql = lit(ts).to_sql() + # Must encode 10:00 wall clock, not 10:00+local_offset. + assert "2024-07-01 10:00:00" in sql diff --git a/python/src/expr.rs b/python/src/expr.rs index 242e88b05..eae1d96ec 100644 --- a/python/src/expr.rs +++ b/python/src/expr.rs @@ -191,8 +191,27 @@ pub fn expr_lit(value: Bound<'_, PyAny>) -> PyResult { } // datetime.datetime is a subclass of datetime.date, so it must be checked first. + // + // Python's datetime.timestamp() treats *naive* datetimes as local wall time. + // PyArrow (and therefore Lance table storage) encodes naive timestamps as + // UTC wall-clock microseconds. Using .timestamp() for naive values therefore + // shifts the literal by the local UTC offset on non-UTC machines, so + // `col("ts") == lit(naive_dt)` fails against a table that holds the same + // naive value. Fix: treat naive datetimes as UTC wall clock (match Arrow); + // keep aware datetimes on the real .timestamp() path (correct epoch). if let Ok(dt) = value.cast::() { - let ts: f64 = dt.call_method0("timestamp")?.extract()?; + let ts: f64 = if dt.getattr("tzinfo")?.is_none() { + // Force UTC interpretation of the naive wall clock. + let utc = pyo3::types::PyModule::import(value.py(), "datetime")? + .getattr("timezone")? + .getattr("utc")?; + let kwargs = pyo3::types::PyDict::new(value.py()); + kwargs.set_item("tzinfo", utc)?; + let aware = dt.call_method("replace", (), Some(&kwargs))?; + aware.call_method0("timestamp")?.extract()? + } else { + dt.call_method0("timestamp")?.extract()? + }; let micros = (ts * 1_000_000.0).round() as i64; return Ok(PyExpr(df_lit(ScalarValue::TimestampMicrosecond( Some(micros), From d742b174c4d5c10086694213e17f26bbee4c2dd2 Mon Sep 17 00:00:00 2001 From: Adityaj0 <93090622+Adityaj0@users.noreply.github.com> Date: Mon, 17 Aug 2026 11:38:38 -0700 Subject: [PATCH 046/206] fix: hybrid search silently ignores .offset() (#3769) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary `LanceHybridQueryBuilder` (sync hybrid search, `table.search(query_type="hybrid")`) silently ignored `.offset()`. `self._offset` was never forwarded to the vector/FTS sub-queries and never applied when slicing the final combined/reranked result, so `.offset(N)` behaved identically to `.offset(0)` — no error, just wrong pagination. Fixes #3765 ## Changes - `_create_query_builders()`: each sub-query now fetches `limit + offset` rows so there's enough data to slice the correct window out of after combining/reranking. - `_combine_hybrid_results()` / `to_arrow()`: the final table is sliced with `offset=self._offset` instead of always starting at 0. ## Test plan - [x] New regression test `test_hybrid_query_offset` in `python/python/tests/test_hybrid_query.py` - [x] `uv run --extra tests pytest python/tests/test_hybrid_query.py -vv` — 13 passed - [x] `uv run --extra dev ruff format` / `ruff check` — clean Co-authored-by: Claude Sonnet 5 Co-authored-by: Will Jones --- python/python/lancedb/query.py | 12 +++++++++--- python/python/tests/test_hybrid_query.py | 25 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 095a7b5ff..e2bb491ea 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -2235,6 +2235,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): reranker=self._reranker, limit=self._limit, with_row_ids=True, + offset=self._offset, ) return self._finish_hybrid_results(results) @@ -2256,6 +2257,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): reranker, limit: int, with_row_ids: bool, + offset: Optional[int] = None, ) -> pa.Table: if norm == "rank": vector_results = LanceHybridQueryBuilder._rank(vector_results, "_distance") @@ -2332,7 +2334,7 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): score_i = results.column_names.index("_score") results = results.set_column(score_i, "_score", original_scores) - results = results.slice(length=limit) + results = results.slice(offset=offset or 0, length=limit) if not with_row_ids: results = results.drop(["_rowid"]) @@ -2679,8 +2681,12 @@ class LanceHybridQueryBuilder(LanceQueryBuilder): # Apply common configurations if self._limit: - self._vector_query.limit(self._limit) - self._fts_query.limit(self._limit) + # The final offset/limit window is sliced out of the combined, + # reranked results, so each sub-query must fetch enough rows to + # cover the skipped prefix as well as the window itself. + sub_query_limit = self._limit + (self._offset or 0) + self._vector_query.limit(sub_query_limit) + self._fts_query.limit(sub_query_limit) if self._columns: self._vector_query.select(self._columns) self._fts_query.select(self._columns) diff --git a/python/python/tests/test_hybrid_query.py b/python/python/tests/test_hybrid_query.py index 72dcaaa49..5e9b45ecb 100644 --- a/python/python/tests/test_hybrid_query.py +++ b/python/python/tests/test_hybrid_query.py @@ -203,6 +203,31 @@ async def test_async_hybrid_query_default_limit(table: AsyncTable): assert texts.count("a") == 1 +def test_hybrid_query_offset(sync_table: Table): + # The offset window of a hybrid query must be a suffix of the same query + # run without an offset -- it must not be silently ignored. + full = ( + sync_table.search(query_type="hybrid") + .vector([0.0, 0.4]) + .text("dog") + .limit(4) + .with_row_id(True) + .to_arrow() + ) + assert len(full) == 4 + + offset_result = ( + sync_table.search(query_type="hybrid") + .vector([0.0, 0.4]) + .text("dog") + .offset(2) + .limit(2) + .with_row_id(True) + .to_arrow() + ) + assert offset_result["_rowid"].to_pylist() == full["_rowid"].to_pylist()[2:] + + def test_hybrid_query_minimum_nprobes_zero_raises(sync_table: Table): # minimum_nprobes(0) must raise the same validation error a plain vector # query raises, not silently no-op because 0 is falsy. From 76942306b796b329f67a162beffc3e04c28acd1f Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 18 Aug 2026 20:03:20 +0800 Subject: [PATCH 047/206] docs(java): add vended credentials example (#3958) ## Context Java users opening catalog-backed tables with vended credentials currently lack a documented workflow. Opening the catalog-returned URI directly drops the namespace-provided storage options and automatic credential refresh. Document the namespace-backed `Dataset.open()` path so temporary object store credentials are applied and refreshed transparently. --- docs/src/java/java.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 42bc06b9d..df8f4a119 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -55,6 +55,38 @@ LanceNamespace namespaceClient = LanceDbNamespaceClientBuilder.newBuilder() | `region(String)` | AWS region (default: "us-east-1") | No | | `config(String, String)` | Additional configuration parameters | No | +### Opening a Table with Vended Credentials + +When the catalog vends temporary object store credentials, open the table through the +namespace client. The Lance dataset builder fetches the table location and storage options +from the catalog and refreshes the credentials when they expire. + +```java +import com.lancedb.LanceDbNamespaceClientBuilder; +import org.lance.Dataset; +import org.lance.namespace.LanceNamespace; + +import java.util.Arrays; + +LanceNamespace namespaceClient = LanceDbNamespaceClientBuilder.newBuilder() + .apiKey(System.getenv("LANCEDB_API_KEY")) + .database(System.getenv("LANCEDB_DATABASE")) + // Set the endpoint for a LanceDB Enterprise deployment. + // .endpoint("https://your-enterprise-endpoint") + .build(); + +try (Dataset dataset = Dataset.open() + .namespaceClient(namespaceClient) + .tableId(Arrays.asList("my_namespace", "my_table")) + .build()) { + System.out.println("Rows: " + dataset.countRows()); +} +``` + +Do not call `describeTable()` and then open the returned location with `Dataset.open(uri)`. +Opening through `namespaceClient()` is what applies the vended storage options and enables +automatic credential refresh. No object store credentials need to be passed by the application. + ## Metadata Operations ### Creating a Namespace Path From cdebea118d43e0bcc7ef3a31a959bda3c9956acf Mon Sep 17 00:00:00 2001 From: Dan Rammer Date: Tue, 18 Aug 2026 17:25:08 -0500 Subject: [PATCH 048/206] feat(python): expose LSM checkpoint and stats on sync RemoteTable (#3961) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary The sync `RemoteTable` carried `set_lsm_write_spec`, `unset_lsm_write_spec`, `get_lsm_write_spec`, and `close_lsm_writers`, but not `checkpoint_lsm`, `flush_lsm`, `compact_lsm`, or `get_lsm_stats`. That left the four LSM control methods reachable from `AsyncTable` only. They are also the four that *only* work against a remote table — `NativeTable` does not override the `BaseTable` defaults, so on a local table they return `NotSupported` (`rust/lancedb/src/table.rs:679-701`). The net effect for sync users: | | `checkpoint_lsm` / `get_lsm_stats` | |---|---| | `LanceTable` (sync, local) | present, but always `NotSupported` | | `RemoteTable` (sync, remote) | `AttributeError` — method absent | | `AsyncTable` (remote) | works | So there was no working sync path at all, despite the Rust `RemoteTable` implementing every one of these against real endpoints. ## Changes * Add `checkpoint_lsm`, `flush_lsm`, `compact_lsm`, and `get_lsm_stats` to `lancedb.remote.table.RemoteTable`, mirroring the delegation style of their neighbours. * Correct the docstrings on `set_lsm_write_spec` / `unset_lsm_write_spec`, which read `"""Not supported on LanceDB Cloud."""` although `rust/lancedb/src/remote/table.rs:2549-2601` implements both against `/v1/table/{}/set_lsm_write_spec/` and `/unset_lsm_write_spec/`. They appear to have been copy-pasted from `set_unenforced_primary_key` directly above. No Rust or PyO3 changes — the bindings and the `AsyncTable` methods already existed. The `Table` ABC is left alone, matching how the existing `*_lsm_write_spec` methods are declared on the concrete classes only. ## Tests Four new tests in `python/python/tests/test_remote_db.py`, against the existing mock HTTP server: * `test_get_lsm_stats_sync` — the server payload round-trips into the dict, and `include_generation_rows` defaults to `False` and is forwarded when set. * `test_get_lsm_stats_sync_returns_none_when_lsm_disabled` — a `{"lsm_stats": null}` envelope yields `None` rather than an error. * `test_flush_and_compact_lsm_sync` — both are one-shot POSTs answered `202` with no body. * `test_checkpoint_lsm_sync` — pins the binding to the endpoints it drives (`flush_lsm` then `get_lsm_stats`); the convergence loop itself is already covered in Rust. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5 (1M context) --- python/python/lancedb/remote/table.py | 26 +++++- python/python/lancedb/table.py | 6 +- python/python/tests/test_remote_db.py | 125 ++++++++++++++++++++++++++ 3 files changed, 152 insertions(+), 5 deletions(-) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index aa822b913..25363cf8f 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -990,17 +990,39 @@ class RemoteTable(Table): return LOOP.run(self._table.set_unenforced_primary_key(columns)) def set_lsm_write_spec(self, spec: "LsmWriteSpec") -> None: - """Not supported on LanceDB Cloud.""" + """Install an LsmWriteSpec.""" return LOOP.run(self._table.set_lsm_write_spec(spec)) def unset_lsm_write_spec(self) -> None: - """Not supported on LanceDB Cloud.""" + """Remove the LsmWriteSpec.""" return LOOP.run(self._table.unset_lsm_write_spec()) def get_lsm_write_spec(self) -> Optional["LsmWriteSpec"]: """Read the installed LsmWriteSpec, or ``None``.""" return LOOP.run(self._table.get_lsm_write_spec()) + def checkpoint_lsm(self) -> None: + """Synchronous version of + [`AsyncTable.checkpoint_lsm`][lancedb.AsyncTable.checkpoint_lsm].""" + return LOOP.run(self._table.checkpoint_lsm()) + + def flush_lsm(self) -> None: + """Synchronous version of + [`AsyncTable.flush_lsm`][lancedb.AsyncTable.flush_lsm].""" + return LOOP.run(self._table.flush_lsm()) + + def compact_lsm(self) -> None: + """Synchronous version of + [`AsyncTable.compact_lsm`][lancedb.AsyncTable.compact_lsm].""" + return LOOP.run(self._table.compact_lsm()) + + def get_lsm_stats(self, *, include_generation_rows: bool = False) -> Optional[dict]: + """Synchronous version of + [`AsyncTable.get_lsm_stats`][lancedb.AsyncTable.get_lsm_stats].""" + return LOOP.run( + self._table.get_lsm_stats(include_generation_rows=include_generation_rows) + ) + def close_lsm_writers(self) -> None: """No-op on LanceDB Cloud (no local shard writers).""" return LOOP.run(self._table.close_lsm_writers()) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 4ecf6e836..f97d0331c 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -4846,7 +4846,7 @@ class AsyncTable: ``asyncio.wait_for`` for a wall-clock bound; abandoning it partway costs nothing. """ - return await self._inner.checkpoint_lsm() + await self._inner.checkpoint_lsm() async def flush_lsm(self) -> None: """Seal every bucket's active memtable into L0. @@ -4855,7 +4855,7 @@ class AsyncTable: `compact_lsm`. On a node that has not claimed this table, this claims it and replays its WAL log first. """ - return await self._inner.flush_lsm() + await self._inner.flush_lsm() async def compact_lsm(self) -> None: """Trigger a background L0 to base compaction pass per bucket. @@ -4864,7 +4864,7 @@ class AsyncTable: ``get_lsm_stats`` for progress, or use ``checkpoint_lsm`` to loop until the current L0 has reached base. """ - return await self._inner.compact_lsm() + await self._inner.compact_lsm() async def get_lsm_stats( self, *, include_generation_rows: bool = False diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index ce8d5bd6e..13ffc4415 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1133,6 +1133,131 @@ def test_stats(): assert res == stats +@contextlib.contextmanager +def lsm_test_table(lsm_handler): + """A remote table whose LSM routes are served by ``lsm_handler``. + + ``lsm_handler(request, route)`` is called for ``/v1/table/test//`` + where route is one of flush_lsm, compact_lsm, get_lsm_stats, and is + responsible for writing the response. + """ + routes = ("flush_lsm", "compact_lsm", "get_lsm_stats") + + def handler(request): + match = re.fullmatch(r"/v1/table/test/(\w+)/", request.path) + route = match.group(1) if match else None + if route in routes: + lsm_handler(request, route) + elif route == "describe": + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b'{"version": 1, "schema": {"fields": []}}') + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + yield db.open_table("test") + + +def read_json_body(request): + content_len = int(request.headers.get("Content-Length")) + return json.loads(request.rfile.read(content_len)) + + +def send_json(request, payload, status=200): + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(payload).encode()) + + +def test_get_lsm_stats_sync(): + """The sync wrapper round-trips the server payload into a dict.""" + bucket = { + "shard_id": "b0", + "status": "Active", + "writer_epoch": 3, + "manifest_version": 12, + "current_generation": 6, + "replay_after_wal_entry_position": 40, + "wal_entry_position_last_seen": 42, + "generations": [{"generation": 5, "bytes": 1024, "rows": 7}], + "compacting": False, + "memtables": [ + { + "generation": 6, + "rows": 2, + "bytes": 64, + "batches": 1, + "indexes": ["vec_idx"], + } + ], + } + seen_bodies = [] + + def lsm_handler(request, route): + assert route == "get_lsm_stats" + seen_bodies.append(read_json_body(request)) + send_json(request, {"lsm_stats": {"buckets": [bucket]}}) + + with lsm_test_table(lsm_handler) as table: + assert table.get_lsm_stats() == {"buckets": [bucket]} + # Off by default, and forwarded when asked for. + assert seen_bodies == [{"include_generation_rows": False}] + table.get_lsm_stats(include_generation_rows=True) + assert seen_bodies[-1] == {"include_generation_rows": True} + + +def test_get_lsm_stats_sync_returns_none_when_lsm_disabled(): + """A null envelope means the LSM write path is not enabled, not an error.""" + + def lsm_handler(request, route): + send_json(request, {"lsm_stats": None}) + + with lsm_test_table(lsm_handler) as table: + assert table.get_lsm_stats() is None + + +def test_flush_and_compact_lsm_sync(): + """Both are one-shot POSTs answered 202 with no body.""" + called = [] + + def lsm_handler(request, route): + called.append(route) + request.send_response(202) + request.end_headers() + + with lsm_test_table(lsm_handler) as table: + assert table.flush_lsm() is None + assert table.compact_lsm() is None + assert called == ["flush_lsm", "compact_lsm"] + + +def test_checkpoint_lsm_sync(): + """Seal, read the watermark, and return once L0 holds nothing. + + The convergence loop itself is covered in Rust; this pins the sync + binding to the endpoints it drives. + """ + called = [] + + def lsm_handler(request, route): + called.append(route) + if route == "get_lsm_stats": + # An empty L0 yields no target watermark, so the loop is done + # after the seal without ever polling compaction. + send_json(request, {"lsm_stats": {"buckets": []}}) + else: + request.send_response(202) + request.end_headers() + + with lsm_test_table(lsm_handler) as table: + assert table.checkpoint_lsm() is None + assert called == ["flush_lsm", "get_lsm_stats"] + + @contextlib.contextmanager def query_test_table(query_handler, *, server_version=Version("0.1.0")): def handler(request): From f6efdc9e9f2c705c4102db78b55cddddb50173bd Mon Sep 17 00:00:00 2001 From: Lance Release Date: Wed, 19 Aug 2026 01:58:48 +0000 Subject: [PATCH 049/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.1=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package-lock.json | 4 ++-- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index e2e693549..b0be7dc82 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.1" +current_version = "0.38.0-beta.2" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 2f7499e91..5bd5479fd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5398,7 +5398,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.1" +version = "0.38.0-beta.2" dependencies = [ "ahash", "anyhow", @@ -5486,7 +5486,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.1" +version = "0.38.0-beta.2" dependencies = [ "arrow-array", "arrow-buffer", @@ -5511,7 +5511,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.1" +version = "0.38.0-beta.2" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index df8f4a119..452bd54f4 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.38.0-beta.1 + 0.38.0-beta.2 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 94c72b326..fb0d2618f 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.1 + 0.38.0-beta.2 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 90ad2f7f8..5f47d6f19 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.1 + 0.38.0-beta.2 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 3496e2839..9b9b56f7e 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.1" +version = "0.38.0-beta.2" 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 ad1503090..c2be3aeac 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.38.0-beta.1", + "version": "0.38.0-beta.2", "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 e7455832d..901405fe4 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.38.0-beta.1", + "version": "0.38.0-beta.2", "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 8269bc4ce..415e60c78 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.38.0-beta.1", + "version": "0.38.0-beta.2", "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 7a7d0a097..22416dbcb 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.38.0-beta.1", + "version": "0.38.0-beta.2", "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 ce95c0174..77d6a5dd5 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.38.0-beta.1", + "version": "0.38.0-beta.2", "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 2ae43e763..0dea90f81 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.38.0-beta.1", + "version": "0.38.0-beta.2", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 1030609fa..0be0b457b 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.38.0-beta.1", + "version": "0.38.0-beta.2", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index 26091b118..999b3f16f 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.1", + "version": "0.38.0-beta.2", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.1", + "version": "0.38.0-beta.2", "cpu": [ "x64", "arm64" diff --git a/nodejs/package.json b/nodejs/package.json index cfdc851ef..8291d3dc8 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.1", + "version": "0.38.0-beta.2", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 745ca4ea2..e41563266 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.1" +version = "0.38.0-beta.2" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 92f020956..69d07b2d8 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.1" +version = "0.38.0-beta.2" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 11c1d816389cfbba78eaad42a464aed454d133bf Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Wed, 19 Aug 2026 06:04:45 -0700 Subject: [PATCH 050/206] chore: update lance dependency to v11.0.0-beta.14 (#3965) Updates the Rust workspace Lance dependencies and Java lance-core dependency to v11.0.0-beta.14. No compatibility fixes were required; full workspace clippy with all features passes. Trigger: https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.14 --------- Co-authored-by: Yang Cen --- Cargo.lock | 96 ++++++++++++++++++++++++++-------------------------- Cargo.toml | 28 +++++++-------- deny.toml | 6 ++++ java/pom.xml | 2 +- 4 files changed, 69 insertions(+), 63 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5bd5479fd..3f4d6682c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -959,7 +959,7 @@ dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", "h2 0.3.27", - "h2 0.4.14", + "h2 0.4.16", "http 0.2.12", "http 1.5.0", "http-body 0.4.6", @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow-array", "rand 0.9.5", @@ -3877,9 +3877,9 @@ dependencies = [ [[package]] name = "h2" -version = "0.4.14" +version = "0.4.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "171fefbc92fe4a4de27e0698d6a5b392d6a0e333506bc49133760b3bcf948733" +checksum = "a9f37a958b41b3b19ee2707c06439c0e9e547e847223eb791ecb0cb821c65e27" dependencies = [ "atomic-waker", "bytes", @@ -4188,7 +4188,7 @@ dependencies = [ "bytes", "futures-channel", "futures-core", - "h2 0.4.14", + "h2 0.4.16", "http 1.5.0", "http-body 1.1.0", "httparse", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow", "arrow-array", @@ -5013,8 +5013,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow", "arrow-array", @@ -5031,8 +5031,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "proc-macro2", "quote", @@ -5041,8 +5041,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow-arith", "arrow-array", @@ -5075,8 +5075,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow-arith", "arrow-array", @@ -5107,8 +5107,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arc-swap", "arrow", @@ -5172,8 +5172,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow-array", "arrow-schema", @@ -5195,8 +5195,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow", "arrow-array", @@ -5232,8 +5232,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow-array", "arrow-schema", @@ -5247,8 +5247,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow", "async-trait", @@ -5260,8 +5260,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow", "arrow-ipc", @@ -5314,8 +5314,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow-array", "arrow-buffer", @@ -5329,8 +5329,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow", "arrow-array", @@ -5370,8 +5370,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "arrow-array", "arrow-schema", @@ -5384,8 +5384,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.13" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.13#ee41152ceb9a78e5df4d2456fdbdb98542eb2059" +version = "11.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" dependencies = [ "frostem", "icu_segmenter", @@ -8426,7 +8426,7 @@ dependencies = [ "encoding_rs", "futures-core", "futures-util", - "h2 0.4.14", + "h2 0.4.16", "http 1.5.0", "http-body 1.1.0", "http-body-util", @@ -10082,7 +10082,7 @@ dependencies = [ "async-trait", "base64 0.22.1", "bytes", - "h2 0.4.14", + "h2 0.4.16", "http 1.5.0", "http-body 1.1.0", "http-body-util", diff --git a/Cargo.toml b/Cargo.toml index 2a19cbb00..c90fb81d8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.13", default-features = false, "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.13", default-features = false, "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.13", default-features = false, "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.13", "tag" = "v11.0.0-beta.13", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.14", default-features = false, "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.14", default-features = false, "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.14", default-features = false, "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } ahash = "0.8" # Note that this one does not include pyarrow arrow = { version = "58.0.0", optional = false } diff --git a/deny.toml b/deny.toml index d94c9d536..cea2522fd 100644 --- a/deny.toml +++ b/deny.toml @@ -108,6 +108,12 @@ ignore = [ # compact_str/smol_str, so clearing this requires polars to migrate. # https://rustsec.org/advisories/RUSTSEC-2026-0249 { id = "RUSTSEC-2026-0249", reason = "smartstring unmaintained via polars; no fixed upstream release" }, + + # h2 0.3: empty DATA frames can be queued without limit. The patched + # h2 0.4 line is locked to 0.4.16, but no patched 0.3 release exists. + # The old copy is pulled in by aws-smithy's legacy hyper 0.14 client. + # https://rustsec.org/advisories/RUSTSEC-2026-0258 + { id = "RUSTSEC-2026-0258", reason = "h2 0.3 via legacy aws-smithy/hyper 0.14; no patched 0.3 release" }, ] # --------------------------------------------------------------------------- diff --git a/java/pom.xml b/java/pom.xml index 5f47d6f19..63711d0c9 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.13 + 11.0.0-beta.14 false 2.30.0 1.7 From f1c4967eebf2c9a08e9bcce7a12fd10fd64a8740 Mon Sep 17 00:00:00 2001 From: Dan Rammer Date: Wed, 19 Aug 2026 11:44:46 -0500 Subject: [PATCH 051/206] feat: bring the MemWAL LSM surface to parity across the SDKs (#3962) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Why Four of the eight LSM methods are **remote-only in the core**. `impl BaseTable for NativeTable` implements only `set`/`unset`/`get_lsm_write_spec` and `close_lsm_writers`; `flush_lsm`, `compact_lsm` and `get_lsm_stats` fall through to trait defaults returning `NotSupported` (`rust/lancedb/src/table.rs:679,687,696`), and `checkpoint_lsm` is built on all three. That explains the state of the bindings: Node had bound the four that work against a local table and stopped, so a Cloud user could install an LSM write spec but had no way to observe fresh-tier state or drive a checkpoint. Java had none of it at all. | SDK | set/unset/get spec | closeWriters | flush | compact | getStats | checkpoint | |---|---|---|---|---|---|---| | Rust core | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Python | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Node *(before)* | ✅ | ✅ | — | — | — | — | | **Node (after)** | ✅ | ✅ | **new** | **new** | **new** | **new** | | Java *(before)* | — | — | — | — | — | — | | **Java (after)** | **new** | n/a | **new** | **new** | **new** | **new** | Go and C are separate repos and are out of scope here. `closeLsmWriters` drains cached in-process shard writers, so it has no meaning for Java, which is a pure REST client. ## Node Adds napi bindings for `flushLsm`, `compactLsm`, `checkpointLsm` and `getLsmStats`, plus typed `LsmStats` / `BucketStats` / `GenerationStats` / `MemtableStats` objects — typed rather than a JSON blob, matching the existing `LsmWriteSpec` object in the same file, with `u64` cast to `i64` per that file's convention. Because these four are remote-only, the new tests assert each binding reaches the core and surfaces `NotSupported` against a local table. That covers the wiring; behavior against a real endpoint stays covered by the mocked-endpoint tests in `rust/lancedb/src/remote/table.rs`. ## Python No new methods. All eight are on `LanceTable`, `AsyncTable` and `RemoteTable` — the last four landed on the sync `RemoteTable` in #3961, which is merged into this branch. What was missing here was reachability. `LsmWriteSpec` was importable only from the private `lancedb._lancedb`, appearing in `table.py` solely under `if TYPE_CHECKING:`, and `docs/src/python/python.md` had no mention of it, which per the repo's docs guidance means it rendered nowhere in the API reference. It is now `lancedb.LsmWriteSpec`, in `__all__`, and documented. ## Java Java reaches LanceDB purely over REST through the generated Lance Namespace client, and these routes are not in that spec, so they are issued through a small dedicated client rather than added to the spec. That call is revisitable — LSM is one of four unspecified route families alongside `multipart_write`, `page_cache/prewarm` and `branches/diff|merge`. If those are ever regularized into the spec as a group, `LanceDbTableLsm` is one file that gets deleted. `LsmWriteSpec` here is deliberately **not** `org.lance.memwal.InitializeMemWalParams`. That type defaults to maintaining *no* indexes where a spec here defaults to maintaining *every* index, and it cannot express the `null` that asks the server to resolve the set: | Value | On the wire | Meaning | |---|---|---| | unset (null) | `null` | Server resolves **every** maintainable index | | `Collections.emptyList()` | `[]` | Maintain **none** | | `Arrays.asList("id_idx")` | `["id_idx"]` | Exactly those | A dedicated test pins null and `[]` as distinct on the wire, since collapsing them is the failure mode that motivated a LanceDB-owned type. `checkpointLsm` is ported from `rust/lancedb/src/table/checkpoint.rs` with its constants and status semantics intact: 429/503 retried in place against an 8-budget, 421 restarting from flush against a 3-budget, 5s poll, and a target watermark fixed after the seal so it terminates under write load. `getLsmStats` returns typed `LsmStats` / `BucketStats` / `GenerationStats` / `MemtableStats`, mirroring the Rust structs in `rust/lancedb/src/table/lsm_stats.rs` and the objects Node exposes. Decoding is strict — see below. ## Review feedback Both gatekeeper findings were real. Each was reproduced against the scripted test server first, and each fix ships with the reproducer as a regression test. **The transport was doubling every checkpoint retry budget.** `HttpClients.createDefault()` installs Apache's default response retry strategy, whose retryable-status list is exactly 429 and 503 — the two statuses `isRetryable` owns. A 429 held against `flush_lsm` issued **18** wire requests where the loop intends 9, and `compact_lsm` was retried in place despite the loop being built to fall through to a fresh stats poll instead. Timing confirmed the mechanism: that run took 25.4s ≈ 16.3s of the loop's own backoff plus 9 × the transport's 1s retry interval. Automatic retries are now disabled, so the checkpoint loop is the sole owner of the 421/429/503 transitions. A side effect worth noting: `testCheckpointRetriesRetryableStatusInPlace` was passing on a transport-absorbed 429 and never reaching `issue()`'s retry branch at all. It now exercises the real path. **Stats decoding failed open.** `getLsmStats` read the response with Jackson's `path()`, which yields a missing node that iterates as an empty array — making "malformed" indistinguishable from "no buckets", which is indistinguishable from "drained". Four separate payloads made `checkpointLsm()` report convergence for a checkpoint that never ran: | Response | Before | Now | |---|---|---| | `{"lsm_stats": null}` or absent key | disabled ✓ | disabled ✓ | | `{"lsm_stats": {}}` | **reported success** | `IllegalStateException` | | empty response body | **reported success** | `IllegalStateException` | | bucket missing required fields | **reported success** | `IllegalStateException` | The empty-body row is the one to weight: a proxy 200 with no body is a realistic production event, and it silently reported a checkpoint that never happened. Decoding is now strict and fails closed, matching the serde contract on the Rust side exactly. One deliberate deviation from the review comment, which asked that *only* explicit JSON `null` count as disabled: Rust has `#[serde(default)]` on `lsm_stats`, so an **absent key** decodes to `None` there too. Java now matches that. It is an absent-or-malformed **`buckets`** that fails closed, which is the case the comment was actually protecting. ## Testing - Java: **33 passing** (8 existing + 25 LSM) against a scripted `com.sun.net.httpserver.HttpServer` — no new test dependency. Wire assertions mirror `rust/lancedb/src/remote/table.rs:6581-6748`; checkpoint tests cover convergence, not piling onto a latched bucket, 421 restart-from-flush, 429 retry-in-place, terminal-status propagation, reissue exhaustion, the exact wire-request count against the retry budget, and five malformed stats payloads. - Node: **19 LSM tests passing**; `cargo check`, `npm run build`, `npm run tsc`, `npm run lint`, `npm run docs` all clean. - Python: `ruff format --check` and `ruff check` clean. - Java formatting: `./mvnw -pl lancedb-core spotless:apply` and `spotless:check` both clean under a JDK 11 toolchain. ## Note: spotless needs a pre-16 JDK `./mvnw spotless:apply` fails on JDK 16+ with `JCTree$JCImport.getQualifiedIdentifier()` — google-java-format 1.7, pinned at `java/pom.xml:34`, predates JDK 16's compiler API change. **This is pre-existing** and reproduces on a pristine `main` checkout. It is not a blocker, just a toolchain requirement. Spotless was run against these sources under JDK 11 and both `spotless:apply` and `spotless:check` pass on the whole module: ```shell JAVA_HOME=/path/to/jdk11 ./mvnw -pl lancedb-core spotless:apply ``` Bumping the plugin so it works on modern JDKs is still worth doing, but separately from this PR. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5 (1M context) --- docs/src/js/classes/Table.md | 93 +++ docs/src/js/globals.md | 4 + docs/src/js/interfaces/BucketStats.md | 116 ++++ docs/src/js/interfaces/GenerationStats.md | 40 ++ docs/src/js/interfaces/LsmStats.md | 22 + docs/src/js/interfaces/MemtableStats.md | 60 ++ docs/src/python/python.md | 2 + java/README.md | 42 ++ java/lancedb-core/pom.xml | 14 + .../main/java/com/lancedb/BucketStats.java | 194 ++++++ .../java/com/lancedb/GenerationStats.java | 64 ++ .../src/main/java/com/lancedb/JsonFields.java | 109 ++++ .../LanceDbNamespaceClientBuilder.java | 49 +- .../java/com/lancedb/LanceDbRestClient.java | 119 ++++ .../java/com/lancedb/LanceDbTableLsm.java | 394 ++++++++++++ .../src/main/java/com/lancedb/LsmStats.java | 56 ++ .../main/java/com/lancedb/LsmWriteSpec.java | 260 ++++++++ .../main/java/com/lancedb/MemtableStats.java | 99 +++ .../java/com/lancedb/LanceDbTableLsmTest.java | 570 ++++++++++++++++++ nodejs/__test__/table.test.ts | 53 ++ nodejs/lancedb/index.ts | 4 + nodejs/lancedb/table.ts | 78 +++ nodejs/src/table.rs | 151 +++++ python/python/lancedb/__init__.py | 2 + python/python/lancedb/table.py | 2 +- 25 files changed, 2581 insertions(+), 16 deletions(-) create mode 100644 docs/src/js/interfaces/BucketStats.md create mode 100644 docs/src/js/interfaces/GenerationStats.md create mode 100644 docs/src/js/interfaces/LsmStats.md create mode 100644 docs/src/js/interfaces/MemtableStats.md create mode 100644 java/lancedb-core/src/main/java/com/lancedb/BucketStats.java create mode 100644 java/lancedb-core/src/main/java/com/lancedb/GenerationStats.java create mode 100644 java/lancedb-core/src/main/java/com/lancedb/JsonFields.java create mode 100644 java/lancedb-core/src/main/java/com/lancedb/LanceDbRestClient.java create mode 100644 java/lancedb-core/src/main/java/com/lancedb/LanceDbTableLsm.java create mode 100644 java/lancedb-core/src/main/java/com/lancedb/LsmStats.java create mode 100644 java/lancedb-core/src/main/java/com/lancedb/LsmWriteSpec.java create mode 100644 java/lancedb-core/src/main/java/com/lancedb/MemtableStats.java create mode 100644 java/lancedb-core/src/test/java/com/lancedb/LanceDbTableLsmTest.java diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 4479bf4e4..06dc8479e 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -213,6 +213,39 @@ version of the table. *** +### checkpointLsm() + +```ts +abstract checkpointLsm(): Promise +``` + +Converge this table's LSM write path into its base table. + +Seals once, then triggers compaction and polls until the L0 that existed +at the start is gone. The target set is fixed at the start, so +generations created *during* the checkpoint are ignored — that is what +lets it terminate under write load, and what makes it best-effort: it +converges the fresh tier as of some instant. Idempotent, abandonable at +any point, and safe to run on a cadence. + +There is no liveness bound — the compactor pool is shared across tables, +so a checkpoint queued behind unrelated work looks exactly like one that +is merging. The caller owns the deadline. + +#### Returns + +`Promise`<`void`> + +#### Example + +```ts +const before = await table.getLsmStats(); +await table.checkpointLsm(); +const after = await table.getLsmStats(); +``` + +*** + ### close() ```ts @@ -250,6 +283,24 @@ It is a no-op when no writers are cached. *** +### compactLsm() + +```ts +abstract compactLsm(): Promise +``` + +Trigger a background L0 → base compaction pass per bucket. + +Returns once the passes are *dispatched*, not once they finish — watch +[Table#getLsmStats](Table.md#getlsmstats) for progress, or use +[Table#checkpointLsm](Table.md#checkpointlsm) to wait for convergence. + +#### Returns + +`Promise`<`void`> + +*** + ### countRows() ```ts @@ -448,6 +499,48 @@ Drop an index from the table. *** +### flushLsm() + +```ts +abstract flushLsm(): Promise +``` + +Seal every bucket's active memtable into a new L0 generation. + +Returns once the seal is committed. Sealing an empty memtable is a no-op, +so this is safe to call repeatedly. + +#### Returns + +`Promise`<`void`> + +*** + +### getLsmStats() + +```ts +abstract getLsmStats(includeGenerationRows?): Promise +``` + +Read live per-bucket LSM state. + +Answers "how far behind is my fresh tier", "which bucket is hot", and +"why is my fresh-tier vector search brute-force". Mutates no table state. + +Resolves to `undefined` only when the LSM write path is not enabled. + +#### Parameters + +* **includeGenerationRows?**: `boolean` + Also count rows per L0 generation. + Off by default because each count opens an uncached Lance dataset. + +#### Returns + +`Promise`<`undefined` \| [`LsmStats`](../interfaces/LsmStats.md)> + +*** + ### getLsmWriteSpec() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index bd2ca54b5..462907cfd 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -58,6 +58,7 @@ - [BranchDiff](interfaces/BranchDiff.md) - [BranchIndexSummary](interfaces/BranchIndexSummary.md) - [BranchRowCountSummary](interfaces/BranchRowCountSummary.md) +- [BucketStats](interfaces/BucketStats.md) - [ClientConfig](interfaces/ClientConfig.md) - [ColumnAlteration](interfaces/ColumnAlteration.md) - [ColumnOrdering](interfaces/ColumnOrdering.md) @@ -81,6 +82,7 @@ - [FtsToken](interfaces/FtsToken.md) - [FullTextQuery](interfaces/FullTextQuery.md) - [FullTextSearchOptions](interfaces/FullTextSearchOptions.md) +- [GenerationStats](interfaces/GenerationStats.md) - [HnswPqOptions](interfaces/HnswPqOptions.md) - [HnswSqOptions](interfaces/HnswSqOptions.md) - [IndexConfig](interfaces/IndexConfig.md) @@ -94,7 +96,9 @@ - [JobInfo](interfaces/JobInfo.md) - [ListNamespacesOptions](interfaces/ListNamespacesOptions.md) - [ListNamespacesResponse](interfaces/ListNamespacesResponse.md) +- [LsmStats](interfaces/LsmStats.md) - [LsmWriteSpec](interfaces/LsmWriteSpec.md) +- [MemtableStats](interfaces/MemtableStats.md) - [MergeBlocker](interfaces/MergeBlocker.md) - [MergeBranchResult](interfaces/MergeBranchResult.md) - [MergePreview](interfaces/MergePreview.md) diff --git a/docs/src/js/interfaces/BucketStats.md b/docs/src/js/interfaces/BucketStats.md new file mode 100644 index 000000000..3f5095672 --- /dev/null +++ b/docs/src/js/interfaces/BucketStats.md @@ -0,0 +1,116 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / BucketStats + +# Interface: BucketStats + +Live state of one bucket. A table is N buckets on one node; flattening to a +single number hides the one hot bucket that is usually why someone opened +this endpoint. + +## Properties + +### compacting + +```ts +compacting: boolean; +``` + +Whether a pass owns this bucket's compaction latch right now. Says *a* +driver is running, not *whose*, and the latch is held from dispatch — +including while the pass queues for a pod-wide compactor permit. Read it +as "do not pile on", never as "mine is progressing". + +*** + +### currentGeneration + +```ts +currentGeneration: number; +``` + +The generation the active memtable will become. + +*** + +### generations + +```ts +generations: GenerationStats[]; +``` + +Flushed L0 generations not yet merged into the base table. + +*** + +### manifestVersion + +```ts +manifestVersion: number; +``` + +Version of the shard manifest these numbers were read from. + +*** + +### memtables? + +```ts +optional memtables: MemtableStats[]; +``` + +Oldest first, active last. Absent for a `"Sealed"` bucket, whose +in-memory state is torn down. + +*** + +### replayAfterWalEntryPosition + +```ts +replayAfterWalEntryPosition: number; +``` + +WAL position replay resumes from. + +*** + +### shardId + +```ts +shardId: string; +``` + +The shard this bucket writes. + +*** + +### status + +```ts +status: string; +``` + +`"Active"` or `"Sealed"` (drop-table 2PC in flight). + +*** + +### walEntryPositionLastSeen + +```ts +walEntryPositionLastSeen: number; +``` + +Highest WAL position the writer has seen. The difference against +`replayAfterWalEntryPosition` is the WAL lag. + +*** + +### writerEpoch + +```ts +writerEpoch: number; +``` + +Epoch of the writer that currently owns the shard. diff --git a/docs/src/js/interfaces/GenerationStats.md b/docs/src/js/interfaces/GenerationStats.md new file mode 100644 index 000000000..19dd2afda --- /dev/null +++ b/docs/src/js/interfaces/GenerationStats.md @@ -0,0 +1,40 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / GenerationStats + +# Interface: GenerationStats + +One flushed L0 generation. + +## Properties + +### bytes + +```ts +bytes: number; +``` + +On-disk size of the generation. + +*** + +### generation + +```ts +generation: number; +``` + +The generation number. Increases as memtables are sealed into L0. + +*** + +### rows? + +```ts +optional rows: number; +``` + +Present only when `includeGenerationRows` was requested. Off by default +because each count opens an uncached Lance dataset. diff --git a/docs/src/js/interfaces/LsmStats.md b/docs/src/js/interfaces/LsmStats.md new file mode 100644 index 000000000..76a2f50db --- /dev/null +++ b/docs/src/js/interfaces/LsmStats.md @@ -0,0 +1,22 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / LsmStats + +# Interface: LsmStats + +Live per-bucket LSM state, as returned by `Table#getLsmStats`. + +Nothing here is derived: sums and differences (total L0 bytes, WAL lag) are +the caller's to compute. + +## Properties + +### buckets + +```ts +buckets: BucketStats[]; +``` + +One entry per bucket backing this table. diff --git a/docs/src/js/interfaces/MemtableStats.md b/docs/src/js/interfaces/MemtableStats.md new file mode 100644 index 000000000..fdc1e4467 --- /dev/null +++ b/docs/src/js/interfaces/MemtableStats.md @@ -0,0 +1,60 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / MemtableStats + +# Interface: MemtableStats + +One in-memory memtable. + +## Properties + +### batches + +```ts +batches: number; +``` + +Record batches currently buffered. + +*** + +### bytes + +```ts +bytes: number; +``` + +Estimated in-memory size. + +*** + +### generation + +```ts +generation: number; +``` + +The generation this memtable will become once sealed. + +*** + +### indexes + +```ts +indexes: string[]; +``` + +Names of the indexes this memtable carries. An absent name is the whole +answer to "why is my fresh-tier search on that column brute-force". + +*** + +### rows + +```ts +rows: number; +``` + +Rows currently buffered. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 3dd6f59f4..1d5975dee 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -52,6 +52,8 @@ listing a storage directory. ::: lancedb.table.Branches +::: lancedb.LsmWriteSpec + ## Expressions Type-safe expression builder for filters and projections. Use these instead diff --git a/java/README.md b/java/README.md index d3560ba4d..c46c8174b 100644 --- a/java/README.md +++ b/java/README.md @@ -29,6 +29,48 @@ LanceNamespace namespaceClient = LanceDbNamespaceClientBuilder.newBuilder() .build(); ``` +## MemWAL LSM write path + +Most table operations reach LanceDB through the `LanceNamespace` above, which is +generated from the Lance Namespace specification. The MemWAL LSM routes are not part +of that specification, so they are issued through a separate client: + +```java +import com.lancedb.LanceDbRestClient; +import com.lancedb.LanceDbTableLsm; +import com.lancedb.LsmWriteSpec; + +LanceDbRestClient client = LanceDbNamespaceClientBuilder.newBuilder() + .apiKey("your_lancedb_cloud_api_key") + .database("your_database_name") + .buildRestClient(); + +LanceDbTableLsm lsm = new LanceDbTableLsm(client, "my_table"); + +// Route future merge_insert upserts through the MemWAL, hash-bucketed by `id`. +lsm.setLsmWriteSpec(LsmWriteSpec.bucket("id", 16)); + +// ... merge_insert traffic ... + +// Converge the fresh tier into the base table. +lsm.checkpointLsm(); + +// Inspect live per-bucket state. +lsm.getLsmStats().ifPresent(stats -> stats.buckets().forEach(bucket -> + System.out.println(bucket.shardId() + ": " + bucket.generations().size() + " L0 generations"))); + +client.close(); +``` + +`maintainedIndexes` is tri-state, and the null default is the opposite of what a Java +reader usually expects: + +| Value | Meaning | +| --- | --- | +| unset (null) | Maintain **every** index the MemWAL can, resolved on install | +| `Collections.emptyList()` | Maintain **none** | +| `Arrays.asList("id_idx")` | Maintain exactly those | + ## Development Build: diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index fb0d2618f..60c1549e3 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -33,6 +33,20 @@ arrow-memory-netty + + + org.apache.httpcomponents.client5 + httpclient5 + 5.2.1 + + + + com.fasterxml.jackson.core + jackson-databind + 2.17.1 + + org.junit.jupiter junit-jupiter diff --git a/java/lancedb-core/src/main/java/com/lancedb/BucketStats.java b/java/lancedb-core/src/main/java/com/lancedb/BucketStats.java new file mode 100644 index 000000000..2a8060c5d --- /dev/null +++ b/java/lancedb-core/src/main/java/com/lancedb/BucketStats.java @@ -0,0 +1,194 @@ +/* + * 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. + */ +package com.lancedb; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.OptionalLong; + +/** + * Live state of one bucket. A table is N buckets on one node; flattening to a single number hides + * the one hot bucket that is usually why someone opened this endpoint. + */ +public class BucketStats { + private static final String CONTEXT = "bucket stats"; + + private final String shardId; + private final String status; + private final long writerEpoch; + private final long manifestVersion; + private final long currentGeneration; + private final long replayAfterWalEntryPosition; + private final long walEntryPositionLastSeen; + private final List generations; + private final boolean compacting; + private final List memtables; + + BucketStats( + String shardId, + String status, + long writerEpoch, + long manifestVersion, + long currentGeneration, + long replayAfterWalEntryPosition, + long walEntryPositionLastSeen, + List generations, + boolean compacting, + List memtables) { + this.shardId = shardId; + this.status = status; + this.writerEpoch = writerEpoch; + this.manifestVersion = manifestVersion; + this.currentGeneration = currentGeneration; + this.replayAfterWalEntryPosition = replayAfterWalEntryPosition; + this.walEntryPositionLastSeen = walEntryPositionLastSeen; + this.generations = Collections.unmodifiableList(generations); + this.compacting = compacting; + this.memtables = memtables == null ? null : Collections.unmodifiableList(memtables); + } + + /** The shard this bucket writes. */ + public String shardId() { + return shardId; + } + + /** {@code "Active"} or {@code "Sealed"} (drop-table 2PC in flight). */ + public String status() { + return status; + } + + /** Epoch of the writer that currently owns the shard. */ + public long writerEpoch() { + return writerEpoch; + } + + /** Version of the shard manifest these numbers were read from. */ + public long manifestVersion() { + return manifestVersion; + } + + /** The generation the active memtable will become. */ + public long currentGeneration() { + return currentGeneration; + } + + /** WAL position replay resumes from. */ + public long replayAfterWalEntryPosition() { + return replayAfterWalEntryPosition; + } + + /** + * Highest WAL position the writer has seen. The difference against {@link + * #replayAfterWalEntryPosition()} is the WAL lag. + */ + public long walEntryPositionLastSeen() { + return walEntryPositionLastSeen; + } + + /** Flushed L0 generations not yet merged into the base table. */ + public List generations() { + return generations; + } + + /** + * Whether a pass owns this bucket's compaction latch right now. Says a driver is + * running, not whose, and the latch is held from dispatch — including while the pass + * queues for a pod-wide compactor permit. Read it as "do not pile on", never as "mine is + * progressing". + */ + public boolean compacting() { + return compacting; + } + + /** Oldest first, active last. Empty for a {@code "Sealed"} bucket, whose state is torn down. */ + public Optional> memtables() { + return Optional.ofNullable(memtables); + } + + /** The newest flushed generation, or empty when L0 is empty. */ + OptionalLong newestGeneration() { + OptionalLong newest = OptionalLong.empty(); + for (GenerationStats generation : generations) { + if (!newest.isPresent() || generation.generation() > newest.getAsLong()) { + newest = OptionalLong.of(generation.generation()); + } + } + return newest; + } + + /** + * How many generations at or below {@code target} are still in L0. + * + *

A count, not a boolean: one pass drains a bounded prefix rather than the whole target set, + * so a boolean would read as "no progress" for every pass but the last. Compaction drains + * oldest-first, so this decreases monotonically. + */ + long outstandingGenerations(long target) { + long count = 0; + for (GenerationStats generation : generations) { + if (generation.generation() <= target) { + count++; + } + } + return count; + } + + static BucketStats fromJson(JsonNode node) { + JsonFields.requiredObject(node, CONTEXT); + List generations = new ArrayList(); + for (JsonNode generation : JsonFields.requiredArray(node, "generations", CONTEXT)) { + generations.add(GenerationStats.fromJson(generation)); + } + + JsonNode memtablesNode = JsonFields.optionalArray(node, "memtables", CONTEXT); + List memtables = null; + if (memtablesNode != null) { + memtables = new ArrayList(); + for (JsonNode memtable : memtablesNode) { + memtables.add(MemtableStats.fromJson(memtable)); + } + } + + return new BucketStats( + JsonFields.requiredText(node, "shard_id", CONTEXT), + JsonFields.requiredText(node, "status", CONTEXT), + JsonFields.requiredLong(node, "writer_epoch", CONTEXT), + JsonFields.requiredLong(node, "manifest_version", CONTEXT), + JsonFields.requiredLong(node, "current_generation", CONTEXT), + JsonFields.requiredLong(node, "replay_after_wal_entry_position", CONTEXT), + JsonFields.requiredLong(node, "wal_entry_position_last_seen", CONTEXT), + generations, + JsonFields.requiredBoolean(node, "compacting", CONTEXT), + memtables); + } + + @Override + public String toString() { + return "BucketStats{shardId=" + + shardId + + ", status=" + + status + + ", currentGeneration=" + + currentGeneration + + ", generations=" + + generations + + ", compacting=" + + compacting + + "}"; + } +} diff --git a/java/lancedb-core/src/main/java/com/lancedb/GenerationStats.java b/java/lancedb-core/src/main/java/com/lancedb/GenerationStats.java new file mode 100644 index 000000000..12222407c --- /dev/null +++ b/java/lancedb-core/src/main/java/com/lancedb/GenerationStats.java @@ -0,0 +1,64 @@ +/* + * 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. + */ +package com.lancedb; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.OptionalLong; + +/** One flushed L0 generation. */ +public class GenerationStats { + private static final String CONTEXT = "generation stats"; + + private final long generation; + private final long bytes; + private final Long rows; + + GenerationStats(long generation, long bytes, Long rows) { + this.generation = generation; + this.bytes = bytes; + this.rows = rows; + } + + /** The generation number. Increases as memtables are sealed into L0. */ + public long generation() { + return generation; + } + + /** On-disk size of the generation. */ + public long bytes() { + return bytes; + } + + /** + * Rows in this generation, present only when {@code includeGenerationRows} was requested. Off by + * default because each count opens an uncached Lance dataset. + */ + public OptionalLong rows() { + return rows == null ? OptionalLong.empty() : OptionalLong.of(rows); + } + + static GenerationStats fromJson(JsonNode node) { + JsonFields.requiredObject(node, CONTEXT); + return new GenerationStats( + JsonFields.requiredLong(node, "generation", CONTEXT), + JsonFields.requiredLong(node, "bytes", CONTEXT), + JsonFields.optionalLong(node, "rows", CONTEXT)); + } + + @Override + public String toString() { + return "GenerationStats{generation=" + generation + ", bytes=" + bytes + ", rows=" + rows + "}"; + } +} diff --git a/java/lancedb-core/src/main/java/com/lancedb/JsonFields.java b/java/lancedb-core/src/main/java/com/lancedb/JsonFields.java new file mode 100644 index 000000000..b78e2411a --- /dev/null +++ b/java/lancedb-core/src/main/java/com/lancedb/JsonFields.java @@ -0,0 +1,109 @@ +/* + * 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. + */ +package com.lancedb; + +import com.fasterxml.jackson.databind.JsonNode; + +/** + * Strict readers for decoding LanceDB JSON responses. + * + *

Every reader fails closed: a missing, null, or wrong-typed field throws rather than + * defaulting. That mirrors the serde decoding the Rust client applies to the same payloads in + * {@code rust/lancedb/src/table/lsm_stats.rs}, where a required field has no default and a + * malformed response is an error rather than a zero. + * + *

The alternative — Jackson's {@code path()}, which yields a missing node that reads as an empty + * array or a zero — is unsafe here because {@link LanceDbTableLsm#checkpointLsm()} decides + * convergence from these numbers. A defaulted {@code generations} array is indistinguishable from a + * drained one, so a malformed response would report a checkpoint that never happened. + */ +final class JsonFields { + private JsonFields() {} + + /** The node itself, once confirmed to be a JSON object. */ + static JsonNode requiredObject(JsonNode node, String context) { + if (node == null || !node.isObject()) { + throw new IllegalStateException(context + " is not a JSON object: " + node); + } + return node; + } + + static String requiredText(JsonNode owner, String field, String context) { + JsonNode value = required(owner, field, context); + if (!value.isTextual()) { + throw new IllegalStateException(fieldIs(context, field, "a string", value)); + } + return value.asText(); + } + + static long requiredLong(JsonNode owner, String field, String context) { + JsonNode value = required(owner, field, context); + if (!value.isIntegralNumber()) { + throw new IllegalStateException(fieldIs(context, field, "an integer", value)); + } + return value.asLong(); + } + + static boolean requiredBoolean(JsonNode owner, String field, String context) { + JsonNode value = required(owner, field, context); + if (!value.isBoolean()) { + throw new IllegalStateException(fieldIs(context, field, "a boolean", value)); + } + return value.asBoolean(); + } + + static JsonNode requiredArray(JsonNode owner, String field, String context) { + JsonNode value = required(owner, field, context); + if (!value.isArray()) { + throw new IllegalStateException(fieldIs(context, field, "an array", value)); + } + return value; + } + + /** Null when the field is absent or JSON null, mirroring a serde {@code Option}. */ + static Long optionalLong(JsonNode owner, String field, String context) { + JsonNode value = owner.get(field); + if (value == null || value.isNull()) { + return null; + } + if (!value.isIntegralNumber()) { + throw new IllegalStateException(fieldIs(context, field, "an integer", value)); + } + return value.asLong(); + } + + /** Null when the field is absent or JSON null, mirroring a serde {@code Option}. */ + static JsonNode optionalArray(JsonNode owner, String field, String context) { + JsonNode value = owner.get(field); + if (value == null || value.isNull()) { + return null; + } + if (!value.isArray()) { + throw new IllegalStateException(fieldIs(context, field, "an array", value)); + } + return value; + } + + private static JsonNode required(JsonNode owner, String field, String context) { + JsonNode value = owner.get(field); + if (value == null || value.isNull()) { + throw new IllegalStateException(context + " is missing required field '" + field + "'"); + } + return value; + } + + private static String fieldIs(String context, String field, String expected, JsonNode value) { + return context + " field '" + field + "' is not " + expected + ": " + value; + } +} diff --git a/java/lancedb-core/src/main/java/com/lancedb/LanceDbNamespaceClientBuilder.java b/java/lancedb-core/src/main/java/com/lancedb/LanceDbNamespaceClientBuilder.java index 5e31aaaa1..da241dfd5 100644 --- a/java/lancedb-core/src/main/java/com/lancedb/LanceDbNamespaceClientBuilder.java +++ b/java/lancedb-core/src/main/java/com/lancedb/LanceDbNamespaceClientBuilder.java @@ -136,29 +136,48 @@ public class LanceDbNamespaceClientBuilder { * @throws IllegalStateException if required parameters are missing */ public LanceNamespace build() { - // Validate required fields + validate(); + + // Build configuration map + Map config = new HashMap<>(additionalConfig); + config.put("header.x-lancedb-database", database); + config.put("header.x-api-key", apiKey); + config.put("uri", resolveUri()); + + return LanceNamespace.connect("rest", config, null); + } + + /** + * Build a {@link LanceDbRestClient} for the same endpoint. + * + *

Needed only for LanceDB routes that the Lance Namespace specification does not cover — the + * MemWAL LSM write path, reached through {@link LanceDbTableLsm}. Every other table operation + * belongs on the {@link LanceNamespace} from {@link #build()}. + * + *

The returned client owns an HTTP connection pool; close it when you are done with it. + * + * @return A configured LanceDbRestClient + * @throws IllegalStateException if required parameters are missing + */ + public LanceDbRestClient buildRestClient() { + validate(); + return new LanceDbRestClient(resolveUri(), apiKey, database); + } + + private void validate() { if (apiKey == null) { throw new IllegalStateException("API key is required"); } if (database == null) { throw new IllegalStateException("Database is required"); } + } - // Build configuration map - Map config = new HashMap<>(additionalConfig); - config.put("header.x-lancedb-database", database); - config.put("header.x-api-key", apiKey); - - // Determine base URL - String uri; + /** The custom endpoint when set, else the LanceDB Cloud URL for this database and region. */ + private String resolveUri() { if (endpoint.isPresent()) { - uri = endpoint.get(); - } else { - String effectiveRegion = region.orElse(DEFAULT_REGION); - uri = String.format(CLOUD_URL_PATTERN, database, effectiveRegion); + return endpoint.get(); } - config.put("uri", uri); - - return LanceNamespace.connect("rest", config, null); + return String.format(CLOUD_URL_PATTERN, database, region.orElse(DEFAULT_REGION)); } } diff --git a/java/lancedb-core/src/main/java/com/lancedb/LanceDbRestClient.java b/java/lancedb-core/src/main/java/com/lancedb/LanceDbRestClient.java new file mode 100644 index 000000000..baafbb9df --- /dev/null +++ b/java/lancedb-core/src/main/java/com/lancedb/LanceDbRestClient.java @@ -0,0 +1,119 @@ +/* + * 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. + */ +package com.lancedb; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.hc.client5.http.classic.methods.HttpPost; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.core5.http.ContentType; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.http.io.entity.StringEntity; + +import java.io.Closeable; +import java.io.IOException; +import java.io.UncheckedIOException; + +/** + * Minimal HTTP client for LanceDB Cloud and Enterprise routes that the Lance Namespace + * specification does not cover. + * + *

Most table operations reach LanceDB through {@link org.lance.namespace.LanceNamespace}, which + * is generated from the namespace spec. A handful of routes — the MemWAL LSM write path in + * particular — are served by the same endpoint but are not part of that spec, so they are issued + * directly here. See {@link LanceDbTableLsm}. + * + *

Obtain one from {@link LanceDbNamespaceClientBuilder#buildRestClient()}. + */ +public class LanceDbRestClient implements Closeable { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private final String baseUri; + private final String apiKey; + private final String database; + private final CloseableHttpClient http; + + LanceDbRestClient(String baseUri, String apiKey, String database) { + this.baseUri = baseUri.endsWith("/") ? baseUri.substring(0, baseUri.length() - 1) : baseUri; + this.apiKey = apiKey; + this.database = database; + // Automatic retries off, deliberately. The default strategy retries 429 and 503 — + // exactly the two statuses LanceDbTableLsm.checkpointLsm() acts on — which would + // silently double its explicit retry budget and would also retry compact_lsm in + // place, where the loop is designed to fall through to a fresh stats poll instead. + // The checkpoint loop owns the 421/429/503 transitions; the transport must not. + this.http = HttpClients.custom().disableAutomaticRetries().build(); + } + + /** + * POST {@code path}, sending {@code body} as JSON when it is non-null. + * + * @param path Absolute request path, beginning with {@code /}. + * @param body Object to serialize as the request body, or null to send no body. + * @return The parsed response body, or null when the response carried no content. + * @throws HttpException if the server returned a non-2xx status. + */ + public JsonNode post(String path, Object body) { + HttpPost request = new HttpPost(baseUri + path); + request.setHeader("x-api-key", apiKey); + request.setHeader("x-lancedb-database", database); + try { + if (body != null) { + request.setEntity( + new StringEntity(MAPPER.writeValueAsString(body), ContentType.APPLICATION_JSON)); + } + return http.execute( + request, + response -> { + String text = + response.getEntity() == null ? "" : EntityUtils.toString(response.getEntity()); + int status = response.getCode(); + if (status < 200 || status >= 300) { + throw new HttpException(status, "LanceDB request to " + path + " failed: " + text); + } + return text.isEmpty() ? null : MAPPER.readTree(text); + }); + } catch (IOException e) { + throw new UncheckedIOException("LanceDB request to " + path + " failed", e); + } + } + + @Override + public void close() throws IOException { + http.close(); + } + + /** + * A non-2xx response. + * + *

The status is exposed because callers act on it: {@link LanceDbTableLsm#checkpointLsm()} + * treats 429 and 503 as retryable and 421 as a lost node claim. + */ + public static class HttpException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private final int statusCode; + + public HttpException(int statusCode, String message) { + super(message); + this.statusCode = statusCode; + } + + /** The HTTP status the failed response carried. */ + public int statusCode() { + return statusCode; + } + } +} diff --git a/java/lancedb-core/src/main/java/com/lancedb/LanceDbTableLsm.java b/java/lancedb-core/src/main/java/com/lancedb/LanceDbTableLsm.java new file mode 100644 index 000000000..23b18199e --- /dev/null +++ b/java/lancedb-core/src/main/java/com/lancedb/LanceDbTableLsm.java @@ -0,0 +1,394 @@ +/* + * 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. + */ +package com.lancedb; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalLong; + +/** + * The MemWAL LSM write path for one LanceDB Cloud or Enterprise table. + * + *

Installing an {@link LsmWriteSpec} routes {@code mergeInsert} upserts through Lance's MemWAL — + * an LSM-style append — instead of the standard merge path. Rows land in an in-memory memtable, + * seal into L0 generations, and are merged into the base table by compaction. + * + *

These routes are not part of the Lance Namespace specification, so they are issued directly + * rather than through {@link org.lance.namespace.LanceNamespace}. + * + *

{@code
+ * LanceDbRestClient client = LanceDbNamespaceClientBuilder.newBuilder()
+ *     .apiKey("your_lancedb_cloud_api_key")
+ *     .database("your_database_name")
+ *     .buildRestClient();
+ *
+ * LanceDbTableLsm lsm = new LanceDbTableLsm(client, "my_table");
+ * lsm.setLsmWriteSpec(LsmWriteSpec.bucket("id", 16));
+ * // ... merge_insert traffic ...
+ * lsm.checkpointLsm();
+ * }
+ */ +public class LanceDbTableLsm { + + /** + * Interval between {@code get_lsm_stats} polls during a checkpoint. One interval is roughly one + * compaction pass, the granularity at which the answer can change. + */ + private static final long POLL_INTERVAL_MS = 5_000L; + + /** + * Cap on re-issues from {@code flushLsm} after a 421, so a crash-looping node cannot turn flush → + * compact → 421 → flush into a spin. + * + *

Deliberately not shared with {@link #MAX_RETRIES}: a claim that keeps evaporating is a + * broken node, while contention is routine and wants a real budget. + */ + private static final int MAX_REISSUES = 3; + + /** + * Retryable faults tolerated on a single request, reset on every success — scattered + * contention across a long checkpoint must not accumulate toward a cap. + */ + private static final int MAX_RETRIES = 8; + + private static final long RETRY_BACKOFF_BASE_MS = 100L; + private static final long RETRY_BACKOFF_MAX_MS = 5_000L; + + private final LanceDbRestClient client; + private final String tableIdentifier; + + /** + * Bind the LSM routes for one table. + * + * @param client Transport for the LanceDB endpoint. + * @param tableIdentifier The table's full identifier, {@code $}-delimited when it sits inside a + * namespace, such as {@code analytics$events}. + */ + public LanceDbTableLsm(LanceDbRestClient client, String tableIdentifier) { + if (client == null) { + throw new IllegalArgumentException("Client cannot be null"); + } + if (tableIdentifier == null || tableIdentifier.trim().isEmpty()) { + throw new IllegalArgumentException("Table identifier cannot be null or empty"); + } + this.client = client; + this.tableIdentifier = tableIdentifier; + } + + /** + * Install an {@link LsmWriteSpec} on this table, selecting the MemWAL LSM write path for future + * {@code mergeInsert} calls. + * + *

All variants require the table to have an unenforced primary key; bucket sharding + * additionally requires it to be the single column being bucketed. + */ + public void setLsmWriteSpec(LsmWriteSpec spec) { + if (spec == null) { + throw new IllegalArgumentException("Spec cannot be null"); + } + client.post(route("set_lsm_write_spec"), spec.toRequestBody()); + } + + /** + * Remove the {@link LsmWriteSpec} from this table, reverting to the standard {@code mergeInsert} + * write path. + * + *

Errors if no spec is currently set. + */ + public void unsetLsmWriteSpec() { + client.post(route("unset_lsm_write_spec"), null); + } + + /** + * Read the {@link LsmWriteSpec} currently installed on this table. + * + *

Empty when the LSM write path is not enabled. The returned spec mirrors what was installed, + * except that {@link LsmWriteSpec#maintainedIndexes()} always reports the concrete list resolved + * when the spec was set — a null selection never round-trips. + */ + public Optional getLsmWriteSpec() { + JsonNode response = client.post(route("get_lsm_write_spec"), null); + if (response == null || !response.hasNonNull("lsm_write_spec")) { + return Optional.empty(); + } + return Optional.of(LsmWriteSpec.fromJson(response.get("lsm_write_spec"))); + } + + /** + * Seal every bucket's active memtable into a new L0 generation. + * + *

Returns once the seal is committed. Sealing an empty memtable is a no-op, so this is safe to + * call repeatedly. + */ + public void flushLsm() { + client.post(route("flush_lsm"), null); + } + + /** + * Trigger a background L0 → base compaction pass per bucket. + * + *

Returns once the passes are dispatched, not once they finish — watch {@link + * #getLsmStats}, or use {@link #checkpointLsm} to wait for convergence. + */ + public void compactLsm() { + client.post(route("compact_lsm"), null); + } + + /** + * Read live per-bucket LSM state. + * + *

Answers "how far behind is my fresh tier", "which bucket is hot", and "why is my fresh-tier + * vector search brute-force". Mutates no table state. + * + *

Empty only when the LSM write path is not enabled — that is, when the server sends an absent + * or null {@code lsm_stats}. A stats object that is present is decoded strictly, and a malformed + * one throws rather than decoding to something empty, because {@link #checkpointLsm} reads + * convergence out of these numbers and cannot tell a defaulted array from a drained one. + * + * @param includeGenerationRows Also count rows per L0 generation. Off by default because each + * count opens an uncached Lance dataset. + * @throws IllegalStateException if the response is absent or does not decode. + */ + public Optional getLsmStats(boolean includeGenerationRows) { + Map body = new LinkedHashMap(); + body.put("include_generation_rows", includeGenerationRows); + JsonNode response = client.post(route("get_lsm_stats"), body); + if (response == null) { + throw new IllegalStateException("get_lsm_stats returned an empty response body"); + } + JsonNode stats = response.get("lsm_stats"); + if (stats == null || stats.isNull()) { + return Optional.empty(); + } + return Optional.of(LsmStats.fromJson(stats)); + } + + /** Equivalent to {@code getLsmStats(false)}. */ + public Optional getLsmStats() { + return getLsmStats(false); + } + + /** + * Converge this table's LSM write path into its base table. + * + *

Seals once, fixes a target watermark from the resulting L0, then triggers compaction and + * polls until that L0 is gone. The target set is fixed at the start, so generations created + * during the checkpoint are ignored — that is what lets it terminate under write load, + * and what makes it best-effort: it converges the fresh tier as of some instant. Idempotent, + * abandonable at any point, safe on a cadence. + * + *

The loop runs here, not on the server: {@link #compactLsm} dispatches a pass and returns, so + * nothing holds a socket and a client can vanish mid-operation with nothing to reconcile. + * Completion is read from generation numbers in the shard manifest — durable state, unlike a + * count in a compact response, which a concurrent write invalidates. + * + *

No liveness bound — the caller owns the deadline. The compactor pool is shared across + * tables, so a checkpoint queued behind unrelated work looks exactly like one that is merging. + */ + public void checkpointLsm() { + for (int reissue = 0; reissue <= MAX_REISSUES; reissue++) { + // The seal turns everything written before this call into a generation, so the + // watermark has to be read after it. Idempotent: sealing an empty memtable is a + // no-op, so a re-issue does not churn empty generations. + if (issueVoid(this::flushLsm)) { + backoff(reissue); + continue; + } + + Attempt> stats = issue(() -> getLsmStats(false)); + if (stats.lostClaim) { + backoff(reissue); + continue; + } + if (!stats.value.isPresent()) { + // Not WAL-backed; flushLsm would have errored first but for a race. + return; + } + + Map targets = newestGenerations(stats.value.get()); + if (targets.isEmpty()) { + return; + } + + if (drainToTargets(targets)) { + return; + } + backoff(reissue); + } + throw new IllegalStateException( + "checkpointLsm: the owning node kept losing its claim; re-issued from flush the maximum " + + "number of times"); + } + + /** + * Trigger and poll until no bucket holds a generation at or below its target. + * + * @return true when the drain finished, false when the table needs re-claiming from flush. + */ + private boolean drainToTargets(Map targets) { + while (true) { + Attempt> stats = issue(() -> getLsmStats(false)); + if (stats.lostClaim) { + return false; + } + if (!stats.value.isPresent()) { + return true; + } + + // `compacting` is the bucket's compaction latch, held from dispatch until the pass + // ends — including while it waits on a pod-wide permit. So it answers one question + // only: do not pile on. Buckets with nothing outstanding are skipped, not counted + // as idle. + long outstanding = 0; + boolean allCompacting = true; + for (BucketStats bucket : stats.value.get().buckets()) { + Long target = targets.get(bucket.shardId()); + if (target == null) { + continue; + } + long remaining = bucket.outstandingGenerations(target); + if (remaining > 0) { + outstanding += remaining; + allCompacting &= bucket.compacting(); + } + } + if (outstanding == 0) { + return true; + } + + if (!allCompacting) { + try { + compactLsm(); + } catch (LanceDbRestClient.HttpException e) { + if (isLostClaim(e)) { + return false; + } + if (!isRetryable(e)) { + throw e; + } + // A 429 here means the server could latch no bucket at all, which the poll + // above already handles. Not retried in place: the latch it would contend for + // is the one doing the work, so fall through and re-read — POLL_INTERVAL_MS is + // the backoff. + } + } + sleep(POLL_INTERVAL_MS); + } + } + + /** The newest generation held by each bucket, skipping buckets holding none. */ + private static Map newestGenerations(LsmStats stats) { + Map targets = new HashMap(); + for (BucketStats bucket : stats.buckets()) { + OptionalLong newest = bucket.newestGeneration(); + if (newest.isPresent()) { + targets.put(bucket.shardId(), newest.getAsLong()); + } + } + return targets; + } + + /** + * 429 (latch held, pool saturated, or the pod replaying its WAL) and 503 (a draining node, or a + * proxy between here and it). + */ + private static boolean isRetryable(LanceDbRestClient.HttpException e) { + return e.statusCode() == 429 || e.statusCode() == 503; + } + + /** + * 421: the owning node holds no claim. Only {@code flush} re-claims and replays, so this cannot + * be retried in place — the caller has to start over. + */ + private static boolean isLostClaim(LanceDbRestClient.HttpException e) { + return e.statusCode() == 421; + } + + /** + * Issue one LSM request, retrying in place while the fault is retryable. + * + *

The two recoverable faults have separate budgets: contention clears on its own and retries + * here against {@link #MAX_RETRIES}, while a 421 needs {@code flush} to re-claim, which only the + * caller can drive. + * + *

An exhausted budget propagates the last error as itself rather than a synthesized one — "429 + * after nine tries" beats "checkpoint failed". + */ + private static Attempt issue(Call call) { + int retries = 0; + while (true) { + try { + return new Attempt(call.run(), false); + } catch (LanceDbRestClient.HttpException e) { + if (isLostClaim(e)) { + return new Attempt(null, true); + } + if (!isRetryable(e) || retries >= MAX_RETRIES) { + throw e; + } + backoff(retries); + retries++; + } + } + } + + /** {@link #issue} for a call with no return value. Returns true when the claim was lost. */ + private static boolean issueVoid(Runnable call) { + return issue( + () -> { + call.run(); + return Boolean.TRUE; + }) + .lostClaim; + } + + /** Sleep before re-issuing a retryable request. Doubles up to {@link #RETRY_BACKOFF_MAX_MS}. */ + private static void backoff(int attempt) { + long delay = RETRY_BACKOFF_BASE_MS << Math.min(attempt, 8); + sleep(Math.min(delay, RETRY_BACKOFF_MAX_MS)); + } + + private static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting on the LSM checkpoint", e); + } + } + + private String route(String operation) { + return "/v1/table/" + tableIdentifier + "/" + operation + "/"; + } + + /** What one LSM request produced: its value, or word that the owning node holds no claim. */ + private static final class Attempt { + private final T value; + private final boolean lostClaim; + + private Attempt(T value, boolean lostClaim) { + this.value = value; + this.lostClaim = lostClaim; + } + } + + @FunctionalInterface + private interface Call { + T run(); + } +} diff --git a/java/lancedb-core/src/main/java/com/lancedb/LsmStats.java b/java/lancedb-core/src/main/java/com/lancedb/LsmStats.java new file mode 100644 index 000000000..3496ebc96 --- /dev/null +++ b/java/lancedb-core/src/main/java/com/lancedb/LsmStats.java @@ -0,0 +1,56 @@ +/* + * 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. + */ +package com.lancedb; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Live per-bucket LSM state, as returned by {@link LanceDbTableLsm#getLsmStats()}. + * + *

Nothing here is derived: sums and differences (total L0 bytes, WAL lag) are the caller's to + * compute. There is no "LSM is off" shape — that case is an empty {@link java.util.Optional}, + * because a stats object of zeros would read as measurements. + */ +public class LsmStats { + private static final String CONTEXT = "lsm stats"; + + private final List buckets; + + LsmStats(List buckets) { + this.buckets = Collections.unmodifiableList(buckets); + } + + /** One entry per bucket. */ + public List buckets() { + return buckets; + } + + static LsmStats fromJson(JsonNode node) { + JsonFields.requiredObject(node, CONTEXT); + List buckets = new ArrayList(); + for (JsonNode bucket : JsonFields.requiredArray(node, "buckets", CONTEXT)) { + buckets.add(BucketStats.fromJson(bucket)); + } + return new LsmStats(buckets); + } + + @Override + public String toString() { + return "LsmStats{buckets=" + buckets + "}"; + } +} diff --git a/java/lancedb-core/src/main/java/com/lancedb/LsmWriteSpec.java b/java/lancedb-core/src/main/java/com/lancedb/LsmWriteSpec.java new file mode 100644 index 000000000..da0966910 --- /dev/null +++ b/java/lancedb-core/src/main/java/com/lancedb/LsmWriteSpec.java @@ -0,0 +1,260 @@ +/* + * 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. + */ +package com.lancedb; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Specification selecting Lance's MemWAL LSM-style write path for {@code mergeInsert}. + * + *

Construct via {@link #bucket}, {@link #identity}, or {@link #unsharded}, then optionally chain + * {@link #withMaintainedIndexes} and {@link #withWriterConfigDefaults}. Install it with {@link + * LanceDbTableLsm#setLsmWriteSpec} and remove it with {@link LanceDbTableLsm#unsetLsmWriteSpec}. + * + *

This is deliberately not {@code org.lance.memwal.InitializeMemWalParams}. That type is Lance's + * own, and its maintained-index default is the opposite of this one: it defaults to maintaining + * nothing, while a fresh spec here maintains every index. It also cannot express + * the null that asks the server to resolve the set. + */ +public class LsmWriteSpec { + + /** How writes are routed to MemWAL shards. */ + public enum Sharding { + /** Hash-bucket writes by a scalar column. */ + BUCKET("bucket"), + /** Shard by the raw value of a scalar column. */ + IDENTITY("identity"), + /** Route every write to a single shard. */ + UNSHARDED("unsharded"); + + private final String wireName; + + Sharding(String wireName) { + this.wireName = wireName; + } + + String wireName() { + return wireName; + } + + static Sharding fromWireName(String name) { + for (Sharding s : values()) { + if (s.wireName.equals(name)) { + return s; + } + } + throw new IllegalArgumentException("Unknown sharding mode: " + name); + } + } + + private final Sharding sharding; + private final String column; + private final Integer numBuckets; + private final List maintainedIndexes; + private final Map writerConfigDefaults; + + private LsmWriteSpec( + Sharding sharding, + String column, + Integer numBuckets, + List maintainedIndexes, + Map writerConfigDefaults) { + this.sharding = sharding; + this.column = column; + this.numBuckets = numBuckets; + this.maintainedIndexes = maintainedIndexes; + this.writerConfigDefaults = writerConfigDefaults; + } + + /** + * Hash-bucket sharding by a scalar column, maintaining every index on the table. + * + *

Iceberg-compatible Murmur3-x86-32 (seed 0) is used, so each row's {@code bucket(column, + * numBuckets)} value is stable across processes. + * + * @param column A non-nested column with a supported scalar type. + * @param numBuckets The number of buckets, in {@code [1, 1024]}. + */ + public static LsmWriteSpec bucket(String column, int numBuckets) { + if (column == null || column.trim().isEmpty()) { + throw new IllegalArgumentException("Column cannot be null or empty"); + } + return new LsmWriteSpec( + Sharding.BUCKET, column, numBuckets, null, new HashMap()); + } + + /** + * Identity sharding — shard by the raw value of {@code column} — maintaining every index on the + * table. + * + *

{@code column} must be a deterministic function of the unenforced primary key: every row + * with a given primary key must always produce the same {@code column} value, or upserts of that + * key can land in different shards and a stale version can win. + */ + public static LsmWriteSpec identity(String column) { + if (column == null || column.trim().isEmpty()) { + throw new IllegalArgumentException("Column cannot be null or empty"); + } + return new LsmWriteSpec(Sharding.IDENTITY, column, null, null, new HashMap()); + } + + /** No sharding — every write goes to a single MemWAL shard — maintaining every index. */ + public static LsmWriteSpec unsharded() { + return new LsmWriteSpec(Sharding.UNSHARDED, null, null, null, new HashMap()); + } + + /** + * Set the indexes the MemWAL keeps up to date as rows are appended. + * + *

Pass {@code null} — the default for a fresh spec — to maintain every index the MemWAL can, + * resolved when the spec is installed. That is a snapshot: indexes created later are not + * maintained until the spec is unset and set again. Pass an empty list to maintain none. + * + *

Note that {@code null} and the empty list mean opposite things here. + */ + public LsmWriteSpec withMaintainedIndexes(List maintainedIndexes) { + return new LsmWriteSpec( + sharding, + column, + numBuckets, + maintainedIndexes == null ? null : new ArrayList(maintainedIndexes), + writerConfigDefaults); + } + + /** + * Set default {@code ShardWriter} configuration recorded in the MemWAL index. + * + *

A sparse override map — only the keys you set are recorded. Recognized keys include {@code + * durable_write}, {@code max_wal_buffer_size}, {@code max_memtable_size}, {@code + * max_memtable_rows}, {@code max_memtable_batches}, {@code manifest_scan_batch_size}, {@code + * max_unflushed_memtable_bytes}, and {@code enable_memtable}. Duration knobs carry an {@code _ms} + * suffix, such as {@code max_wal_flush_interval_ms}. + */ + public LsmWriteSpec withWriterConfigDefaults(Map writerConfigDefaults) { + if (writerConfigDefaults == null) { + throw new IllegalArgumentException("writerConfigDefaults cannot be null"); + } + return new LsmWriteSpec( + sharding, + column, + numBuckets, + maintainedIndexes, + new HashMap(writerConfigDefaults)); + } + + /** How writes are routed to shards. */ + public Sharding sharding() { + return sharding; + } + + /** The sharding column for {@link Sharding#BUCKET} and {@link Sharding#IDENTITY}, else null. */ + public String column() { + return column; + } + + /** The bucket count for {@link Sharding#BUCKET}, else null. */ + public Integer numBuckets() { + return numBuckets; + } + + /** + * The indexes the MemWAL maintains, or null to have the server resolve every maintainable index + * on install. An empty list means none. + */ + public List maintainedIndexes() { + return maintainedIndexes == null ? null : Collections.unmodifiableList(maintainedIndexes); + } + + /** Default {@code ShardWriter} configuration recorded in the MemWAL index. */ + public Map writerConfigDefaults() { + return Collections.unmodifiableMap(writerConfigDefaults); + } + + /** Render this spec as the {@code set_lsm_write_spec} request body. */ + Map toRequestBody() { + Map shardingBody = new LinkedHashMap(); + shardingBody.put("mode", sharding.wireName()); + if (column != null) { + shardingBody.put("column", column); + } + if (numBuckets != null) { + shardingBody.put("num_buckets", numBuckets); + } + + Map body = new LinkedHashMap(); + body.put("sharding", shardingBody); + // Null is meaningful: it asks the server to resolve every maintainable index. + body.put("maintained_indexes", maintainedIndexes); + body.put("writer_config_defaults", writerConfigDefaults); + return body; + } + + /** + * Rebuild a spec from a {@code get_lsm_write_spec} response body. + * + *

The server always reports a concrete maintained-index list, so a null selection never + * round-trips. + */ + static LsmWriteSpec fromJson(JsonNode node) { + JsonNode shardingNode = node.get("sharding"); + if (shardingNode == null || shardingNode.get("mode") == null) { + throw new IllegalStateException("get_lsm_write_spec response has no sharding mode"); + } + Sharding sharding = Sharding.fromWireName(shardingNode.get("mode").asText()); + + String column = shardingNode.hasNonNull("column") ? shardingNode.get("column").asText() : null; + Integer numBuckets = + shardingNode.hasNonNull("num_buckets") ? shardingNode.get("num_buckets").asInt() : null; + + List maintainedIndexes = new ArrayList(); + JsonNode indexesNode = node.get("maintained_indexes"); + if (indexesNode != null && indexesNode.isArray()) { + for (JsonNode index : indexesNode) { + maintainedIndexes.add(index.asText()); + } + } + + Map defaults = new HashMap(); + JsonNode defaultsNode = node.get("writer_config_defaults"); + if (defaultsNode != null && defaultsNode.isObject()) { + defaultsNode + .fieldNames() + .forEachRemaining(name -> defaults.put(name, defaultsNode.get(name).asText())); + } + + return new LsmWriteSpec(sharding, column, numBuckets, maintainedIndexes, defaults); + } + + @Override + public String toString() { + return "LsmWriteSpec{sharding=" + + sharding + + ", column=" + + column + + ", numBuckets=" + + numBuckets + + ", maintainedIndexes=" + + maintainedIndexes + + ", writerConfigDefaults=" + + writerConfigDefaults + + "}"; + } +} diff --git a/java/lancedb-core/src/main/java/com/lancedb/MemtableStats.java b/java/lancedb-core/src/main/java/com/lancedb/MemtableStats.java new file mode 100644 index 000000000..777e915aa --- /dev/null +++ b/java/lancedb-core/src/main/java/com/lancedb/MemtableStats.java @@ -0,0 +1,99 @@ +/* + * 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. + */ +package com.lancedb; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** One in-memory memtable. */ +public class MemtableStats { + private static final String CONTEXT = "memtable stats"; + + private final long generation; + private final long rows; + private final long bytes; + private final long batches; + private final List indexes; + + MemtableStats(long generation, long rows, long bytes, long batches, List indexes) { + this.generation = generation; + this.rows = rows; + this.bytes = bytes; + this.batches = batches; + this.indexes = Collections.unmodifiableList(indexes); + } + + /** The generation this memtable will become once sealed. */ + public long generation() { + return generation; + } + + /** Rows currently buffered. */ + public long rows() { + return rows; + } + + /** Estimated in-memory size. */ + public long bytes() { + return bytes; + } + + /** Record batches currently buffered. */ + public long batches() { + return batches; + } + + /** + * Names of the indexes this memtable carries. An absent name is the whole answer to "why is my + * fresh-tier search on that column brute-force". + */ + public List indexes() { + return indexes; + } + + static MemtableStats fromJson(JsonNode node) { + JsonFields.requiredObject(node, CONTEXT); + List indexes = new ArrayList(); + for (JsonNode index : JsonFields.requiredArray(node, "indexes", CONTEXT)) { + if (!index.isTextual()) { + throw new IllegalStateException(CONTEXT + " has a non-string index name: " + index); + } + indexes.add(index.asText()); + } + return new MemtableStats( + JsonFields.requiredLong(node, "generation", CONTEXT), + JsonFields.requiredLong(node, "rows", CONTEXT), + JsonFields.requiredLong(node, "bytes", CONTEXT), + JsonFields.requiredLong(node, "batches", CONTEXT), + indexes); + } + + @Override + public String toString() { + return "MemtableStats{generation=" + + generation + + ", rows=" + + rows + + ", bytes=" + + bytes + + ", batches=" + + batches + + ", indexes=" + + indexes + + "}"; + } +} diff --git a/java/lancedb-core/src/test/java/com/lancedb/LanceDbTableLsmTest.java b/java/lancedb-core/src/test/java/com/lancedb/LanceDbTableLsmTest.java new file mode 100644 index 000000000..e84fa5421 --- /dev/null +++ b/java/lancedb-core/src/test/java/com/lancedb/LanceDbTableLsmTest.java @@ -0,0 +1,570 @@ +/* + * 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. + */ +package com.lancedb; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Deque; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Unit tests for the MemWAL LSM routes, run against a scripted local HTTP server. + * + *

The wire assertions mirror the Rust mocked-endpoint tests in {@code + * rust/lancedb/src/remote/table.rs}, which are the contract these routes have to match. + */ +public class LanceDbTableLsmTest { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private HttpServer server; + private LanceDbRestClient client; + private LanceDbTableLsm lsm; + + private final List requestPaths = Collections.synchronizedList(new ArrayList()); + private final List requestBodies = Collections.synchronizedList(new ArrayList()); + private final Map> replies = new ConcurrentHashMap>(); + + @BeforeEach + public void setUp() throws IOException { + start(); + } + + /** Tear down and restart the scripted server, for a test that scripts several exchanges. */ + private void setUpFresh() { + try { + client.close(); + server.stop(0); + requestPaths.clear(); + requestBodies.clear(); + replies.clear(); + start(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + private void start() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext( + "/", + exchange -> { + String path = exchange.getRequestURI().getPath(); + requestPaths.add(path); + requestBodies.add(readAll(exchange.getRequestBody())); + + Reply reply = nextReply(path); + byte[] out = reply.body.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(reply.status, out.length == 0 ? -1 : out.length); + if (out.length > 0) { + exchange.getResponseBody().write(out); + } + exchange.close(); + }); + server.start(); + + client = + LanceDbNamespaceClientBuilder.newBuilder() + .apiKey("test-key") + .database("test-db") + .endpoint("http://127.0.0.1:" + server.getAddress().getPort()) + .buildRestClient(); + lsm = new LanceDbTableLsm(client, "my_table"); + } + + @AfterEach + public void tearDown() throws IOException { + client.close(); + server.stop(0); + } + + // =========================================================================== + // set / unset / get spec + // =========================================================================== + + @Test + public void testSetLsmWriteSpecUnsharded() throws Exception { + enqueue("set_lsm_write_spec", 200, ""); + + lsm.setLsmWriteSpec(LsmWriteSpec.unsharded()); + + assertEquals("/v1/table/my_table/set_lsm_write_spec/", requestPaths.get(0)); + JsonNode body = MAPPER.readTree(requestBodies.get(0)); + assertEquals("unsharded", body.get("sharding").get("mode").asText()); + assertFalse(body.get("sharding").has("column")); + assertFalse(body.get("sharding").has("num_buckets")); + } + + @Test + public void testSetLsmWriteSpecBucket() throws Exception { + enqueue("set_lsm_write_spec", 200, ""); + + lsm.setLsmWriteSpec( + LsmWriteSpec.bucket("id", 16).withMaintainedIndexes(Arrays.asList("id_idx"))); + + JsonNode body = MAPPER.readTree(requestBodies.get(0)); + assertEquals("bucket", body.get("sharding").get("mode").asText()); + assertEquals("id", body.get("sharding").get("column").asText()); + assertEquals(16, body.get("sharding").get("num_buckets").asInt()); + assertEquals(1, body.get("maintained_indexes").size()); + assertEquals("id_idx", body.get("maintained_indexes").get(0).asText()); + } + + @Test + public void testSetLsmWriteSpecIdentity() throws Exception { + enqueue("set_lsm_write_spec", 200, ""); + + lsm.setLsmWriteSpec(LsmWriteSpec.identity("tenant")); + + JsonNode body = MAPPER.readTree(requestBodies.get(0)); + assertEquals("identity", body.get("sharding").get("mode").asText()); + assertEquals("tenant", body.get("sharding").get("column").asText()); + assertFalse(body.get("sharding").has("num_buckets")); + } + + /** + * The tri-state that motivated a LanceDB-owned spec type: a null selection asks the server to + * resolve every maintainable index, while an empty list asks for none. They must not collapse. + */ + @Test + public void testMaintainedIndexesNullAndEmptyAreDistinctOnTheWire() throws Exception { + enqueue("set_lsm_write_spec", 200, ""); + + lsm.setLsmWriteSpec(LsmWriteSpec.unsharded()); + JsonNode fresh = MAPPER.readTree(requestBodies.get(0)); + assertTrue(fresh.has("maintained_indexes"), "the key must be present"); + assertTrue(fresh.get("maintained_indexes").isNull(), "a fresh spec sends null, not []"); + + lsm.setLsmWriteSpec( + LsmWriteSpec.unsharded().withMaintainedIndexes(Collections.emptyList())); + JsonNode none = MAPPER.readTree(requestBodies.get(1)); + assertTrue(none.get("maintained_indexes").isArray()); + assertEquals(0, none.get("maintained_indexes").size()); + } + + @Test + public void testSetLsmWriteSpecWriterConfigDefaults() throws Exception { + enqueue("set_lsm_write_spec", 200, ""); + + Map defaults = new HashMap(); + defaults.put("max_memtable_rows", "50000"); + lsm.setLsmWriteSpec(LsmWriteSpec.unsharded().withWriterConfigDefaults(defaults)); + + JsonNode body = MAPPER.readTree(requestBodies.get(0)); + assertEquals("50000", body.get("writer_config_defaults").get("max_memtable_rows").asText()); + } + + @Test + public void testUnsetLsmWriteSpec() { + enqueue("unset_lsm_write_spec", 200, ""); + + lsm.unsetLsmWriteSpec(); + + assertEquals("/v1/table/my_table/unset_lsm_write_spec/", requestPaths.get(0)); + assertEquals("", requestBodies.get(0)); + } + + @Test + public void testGetLsmWriteSpec() { + enqueue( + "get_lsm_write_spec", + 200, + "{\"lsm_write_spec\":{\"sharding\":{\"mode\":\"bucket\",\"column\":\"id\"," + + "\"num_buckets\":16},\"maintained_indexes\":[\"id_idx\"]," + + "\"writer_config_defaults\":{\"durable_write\":\"true\"}}}"); + + Optional spec = lsm.getLsmWriteSpec(); + + assertTrue(spec.isPresent()); + assertEquals(LsmWriteSpec.Sharding.BUCKET, spec.get().sharding()); + assertEquals("id", spec.get().column()); + assertEquals(Integer.valueOf(16), spec.get().numBuckets()); + assertEquals(Arrays.asList("id_idx"), spec.get().maintainedIndexes()); + assertEquals("true", spec.get().writerConfigDefaults().get("durable_write")); + } + + @Test + public void testGetLsmWriteSpecAbsent() { + enqueue("get_lsm_write_spec", 200, "{\"lsm_write_spec\":null}"); + + assertFalse(lsm.getLsmWriteSpec().isPresent()); + } + + // =========================================================================== + // stats + // =========================================================================== + + @Test + public void testGetLsmStats() throws Exception { + enqueue("get_lsm_stats", 200, stats(bucket("shard-0", false, 7L, 8L))); + + Optional got = lsm.getLsmStats(true); + + assertEquals("/v1/table/my_table/get_lsm_stats/", requestPaths.get(0)); + assertTrue(MAPPER.readTree(requestBodies.get(0)).get("include_generation_rows").asBoolean()); + assertTrue(got.isPresent()); + BucketStats decoded = got.get().buckets().get(0); + assertEquals("shard-0", decoded.shardId()); + assertEquals("Active", decoded.status()); + assertEquals(1, decoded.writerEpoch()); + assertEquals(2, decoded.manifestVersion()); + assertEquals(9, decoded.currentGeneration()); + assertFalse(decoded.compacting()); + assertEquals(Arrays.asList(7L, 8L), generationNumbers(decoded)); + assertEquals(1024, decoded.generations().get(0).bytes()); + assertFalse(decoded.generations().get(0).rows().isPresent(), "rows absent unless requested"); + assertFalse(decoded.memtables().isPresent(), "absent memtables stay absent"); + } + + /** The optional fields decode when the server does send them. */ + @Test + public void testGetLsmStatsDecodesOptionalFields() { + enqueue( + "get_lsm_stats", + 200, + "{\"lsm_stats\":{\"buckets\":[{\"shard_id\":\"shard-0\",\"status\":\"Active\"," + + "\"writer_epoch\":1,\"manifest_version\":2,\"current_generation\":9," + + "\"replay_after_wal_entry_position\":3,\"wal_entry_position_last_seen\":11," + + "\"generations\":[{\"generation\":7,\"bytes\":1024,\"rows\":42}]," + + "\"compacting\":true,\"memtables\":[{\"generation\":8,\"rows\":5," + + "\"bytes\":64,\"batches\":2,\"indexes\":[\"id_idx\"]}]}]}}"); + + BucketStats decoded = lsm.getLsmStats(true).get().buckets().get(0); + + assertEquals(3, decoded.replayAfterWalEntryPosition()); + assertEquals(11, decoded.walEntryPositionLastSeen()); + assertTrue(decoded.compacting()); + assertEquals(42, decoded.generations().get(0).rows().getAsLong()); + assertTrue(decoded.memtables().isPresent()); + MemtableStats memtable = decoded.memtables().get().get(0); + assertEquals(8, memtable.generation()); + assertEquals(5, memtable.rows()); + assertEquals(64, memtable.bytes()); + assertEquals(2, memtable.batches()); + assertEquals(Arrays.asList("id_idx"), memtable.indexes()); + } + + @Test + public void testGetLsmStatsAbsentWhenLsmDisabled() { + enqueue("get_lsm_stats", 200, "{\"lsm_stats\":null}"); + + assertFalse(lsm.getLsmStats().isPresent()); + } + + @Test + public void testGetLsmStatsDefaultsToExcludingGenerationRows() throws Exception { + enqueue("get_lsm_stats", 200, stats()); + + lsm.getLsmStats(); + + assertFalse(MAPPER.readTree(requestBodies.get(0)).get("include_generation_rows").asBoolean()); + } + + // =========================================================================== + // flush / compact + // =========================================================================== + + @Test + public void testFlushAndCompactRoutes() { + enqueue("flush_lsm", 200, ""); + enqueue("compact_lsm", 200, ""); + + lsm.flushLsm(); + lsm.compactLsm(); + + assertEquals("/v1/table/my_table/flush_lsm/", requestPaths.get(0)); + assertEquals("/v1/table/my_table/compact_lsm/", requestPaths.get(1)); + } + + @Test + public void testHttpErrorCarriesStatus() { + enqueue("flush_lsm", 404, "no such table"); + + LanceDbRestClient.HttpException e = + assertThrows(LanceDbRestClient.HttpException.class, () -> lsm.flushLsm()); + assertEquals(404, e.statusCode()); + } + + // =========================================================================== + // checkpoint + // =========================================================================== + + @Test + public void testCheckpointReturnsWhenLsmDisabled() { + enqueue("flush_lsm", 200, ""); + enqueue("get_lsm_stats", 200, "{\"lsm_stats\":null}"); + + lsm.checkpointLsm(); + + assertEquals(0, countCalls("compact_lsm"), "nothing to compact when the LSM path is off"); + } + + @Test + public void testCheckpointReturnsWhenNoGenerationsOutstanding() { + enqueue("flush_lsm", 200, ""); + // A bucket with no L0 generations yields no target, so the drain never starts. + enqueue("get_lsm_stats", 200, stats(bucket("shard-0", false))); + + lsm.checkpointLsm(); + + assertEquals(0, countCalls("compact_lsm")); + } + + @Test + public void testCheckpointConvergesOnceTargetGenerationsAreGone() { + enqueue("flush_lsm", 200, ""); + // Watermark read: shard-0 holds generations 7 and 8, so target = 8. + enqueue("get_lsm_stats", 200, stats(bucket("shard-0", false, 7L, 8L))); + // First drain poll: both still outstanding, nothing compacting -> dispatch a pass. + enqueue("get_lsm_stats", 200, stats(bucket("shard-0", false, 7L, 8L))); + // Second drain poll: drained past the target -> done. + enqueue("get_lsm_stats", 200, stats(bucket("shard-0", false, 9L))); + enqueue("compact_lsm", 200, ""); + + lsm.checkpointLsm(); + + assertEquals(1, countCalls("compact_lsm"), "one pass dispatched"); + assertEquals(3, countCalls("get_lsm_stats"), "watermark read plus two drain polls"); + } + + @Test + public void testCheckpointDoesNotPileOnWhileEveryTargetBucketIsCompacting() { + enqueue("flush_lsm", 200, ""); + enqueue("get_lsm_stats", 200, stats(bucket("shard-0", true, 4L))); + // Still compacting on the first poll, so no pass is dispatched; then it drains. + enqueue("get_lsm_stats", 200, stats(bucket("shard-0", true, 4L))); + enqueue("get_lsm_stats", 200, stats(bucket("shard-0", false, 5L))); + + lsm.checkpointLsm(); + + assertEquals(0, countCalls("compact_lsm"), "a latched bucket is left alone"); + } + + @Test + public void testCheckpointRetriesFromFlushAfterLostClaim() { + // 421 on the watermark read: the node lost its claim, so the whole thing restarts + // from flush rather than retrying the read in place. + enqueue("flush_lsm", 200, ""); + enqueue("get_lsm_stats", 421, "no claim"); + enqueue("get_lsm_stats", 200, stats(bucket("shard-0", false))); + + lsm.checkpointLsm(); + + assertEquals(2, countCalls("flush_lsm"), "re-issued from flush"); + } + + @Test + public void testCheckpointRetriesRetryableStatusInPlace() { + enqueue("flush_lsm", 429, "latch held"); + enqueue("flush_lsm", 200, ""); + enqueue("get_lsm_stats", 200, stats(bucket("shard-0", false))); + + lsm.checkpointLsm(); + + assertEquals(2, countCalls("flush_lsm"), "429 retried in place, not re-issued"); + } + + @Test + public void testCheckpointPropagatesTerminalStatus() { + enqueue("flush_lsm", 400, "bad request"); + + LanceDbRestClient.HttpException e = + assertThrows(LanceDbRestClient.HttpException.class, () -> lsm.checkpointLsm()); + assertEquals(400, e.statusCode()); + assertEquals(1, countCalls("flush_lsm"), "a terminal status is not retried"); + } + + @Test + public void testCheckpointGivesUpAfterRepeatedLostClaims() { + enqueue("flush_lsm", 421, "no claim"); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> lsm.checkpointLsm()); + assertTrue(e.getMessage().contains("kept losing its claim"), e.getMessage()); + assertEquals(4, countCalls("flush_lsm"), "the initial attempt plus MAX_REISSUES"); + } + + // =========================================================================== + // strict decoding + // =========================================================================== + + /** + * A stats payload that does not decode must fail closed. Every one of these bodies used to be + * read as "no buckets", which is indistinguishable from a drained table, so {@code checkpointLsm} + * reported convergence for a checkpoint that never ran. + */ + @Test + public void testCheckpointRejectsMalformedStats() { + Map malformed = new LinkedHashMap(); + malformed.put("no response body at all", ""); + malformed.put("stats object with no buckets", "{\"lsm_stats\":{}}"); + malformed.put("bucket missing its required fields", "{\"lsm_stats\":{\"buckets\":[{}]}}"); + malformed.put( + "bucket missing generations", + "{\"lsm_stats\":{\"buckets\":[{\"shard_id\":\"shard-0\",\"status\":\"Active\"," + + "\"writer_epoch\":1,\"manifest_version\":2,\"current_generation\":9," + + "\"replay_after_wal_entry_position\":0,\"wal_entry_position_last_seen\":0," + + "\"compacting\":false}]}}"); + malformed.put( + "generation with a non-numeric generation number", + "{\"lsm_stats\":{\"buckets\":[{\"shard_id\":\"shard-0\",\"status\":\"Active\"," + + "\"writer_epoch\":1,\"manifest_version\":2,\"current_generation\":9," + + "\"replay_after_wal_entry_position\":0,\"wal_entry_position_last_seen\":0," + + "\"generations\":[{\"generation\":\"7\",\"bytes\":1024}]," + + "\"compacting\":false}]}}"); + + for (Map.Entry each : malformed.entrySet()) { + setUpFresh(); + enqueue("flush_lsm", 200, ""); + enqueue("get_lsm_stats", 200, each.getValue()); + + assertThrows( + IllegalStateException.class, + () -> lsm.checkpointLsm(), + each.getKey() + " must not report convergence"); + } + } + + /** The one shape that legitimately means "this table has no LSM write path". */ + @Test + public void testCheckpointTreatsNullStatsAsNotWalBacked() { + enqueue("flush_lsm", 200, ""); + enqueue("get_lsm_stats", 200, "{\"lsm_stats\":null}"); + + lsm.checkpointLsm(); + + assertEquals(1, countCalls("get_lsm_stats")); + } + + // =========================================================================== + // retry budget + // =========================================================================== + + /** + * The transport must not retry on the checkpoint loop's behalf. Apache HttpClient's default + * strategy retries exactly 429 and 503 — the two statuses {@code isRetryable} owns — which + * doubled every budget here and also retried {@code compact_lsm} in place, where the loop is + * built to fall through to a fresh stats poll instead. + */ + @Test + public void testCheckpointRetryBudgetIsNotDoubledByTheTransport() { + enqueue("flush_lsm", 429, "latch held"); + + LanceDbRestClient.HttpException e = + assertThrows(LanceDbRestClient.HttpException.class, () -> lsm.checkpointLsm()); + + assertEquals(429, e.statusCode(), "the exhausted budget propagates the last error as itself"); + assertEquals(9, countCalls("flush_lsm"), "the initial request plus MAX_RETRIES, and no more"); + } + + // =========================================================================== + // harness + // =========================================================================== + + private static List generationNumbers(BucketStats bucket) { + List numbers = new ArrayList(); + for (GenerationStats generation : bucket.generations()) { + numbers.add(generation.generation()); + } + return numbers; + } + + /** Build an {@code lsm_stats} response body from bucket fragments. */ + private static String stats(String... buckets) { + return "{\"lsm_stats\":{\"buckets\":[" + String.join(",", buckets) + "]}}"; + } + + private static String bucket(String shardId, boolean compacting, Long... generations) { + StringBuilder gens = new StringBuilder(); + for (Long generation : generations) { + if (gens.length() > 0) { + gens.append(","); + } + gens.append("{\"generation\":").append(generation).append(",\"bytes\":1024}"); + } + return "{\"shard_id\":\"" + + shardId + + "\",\"status\":\"Active\",\"writer_epoch\":1,\"manifest_version\":2," + + "\"current_generation\":9,\"replay_after_wal_entry_position\":0," + + "\"wal_entry_position_last_seen\":0,\"generations\":[" + + gens + + "],\"compacting\":" + + compacting + + "}"; + } + + /** Queue a reply for an operation. The last queued reply repeats once the queue drains. */ + private void enqueue(String operation, int status, String body) { + replies.computeIfAbsent(operation, key -> new ArrayDeque()).add(new Reply(status, body)); + } + + private Reply nextReply(String path) { + String operation = operationOf(path); + Deque queued = replies.get(operation); + if (queued == null || queued.isEmpty()) { + return new Reply(200, ""); + } + return queued.size() > 1 ? queued.poll() : queued.peek(); + } + + private long countCalls(String operation) { + return requestPaths.stream().filter(path -> operationOf(path).equals(operation)).count(); + } + + /** {@code /v1/table/my_table/flush_lsm/} -> {@code flush_lsm}. */ + private static String operationOf(String path) { + String[] segments = path.split("/"); + return segments.length == 0 ? "" : segments[segments.length - 1]; + } + + private static String readAll(InputStream in) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int read; + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + return new String(out.toByteArray(), StandardCharsets.UTF_8); + } + + private static final class Reply { + private final int status; + private final String body; + + private Reply(int status, String body) { + this.status = status; + this.body = body; + } + } +} diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 5396a251a..80c50f1ac 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -3341,6 +3341,59 @@ describe("LSM merge insert", () => { }); }); +describe("LSM convergence and stats", () => { + let tmpDir: tmp.DirResult; + + beforeEach(() => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + }); + afterEach(() => tmpDir.removeCallback()); + + async function lsmTable(conn: Connection): Promise { + const table = await conn.createEmptyTable( + "t", + new arrow.Schema([new arrow.Field("id", new arrow.Utf8(), false)]), + ); + await table.setUnenforcedPrimaryKey("id"); + await table.setLsmWriteSpec({ specType: "unsharded" }); + return table; + } + + // These four route through the server that owns the MemWAL, so a local table + // rejects them rather than answering. What is asserted here is that the + // bindings reach the core at all; the behavior against a real endpoint is + // covered by the mocked endpoint tests in rust/lancedb/src/remote/table.rs. + it("rejects flushLsm on a local table", async () => { + const conn = await connect(tmpDir.name); + const table = await lsmTable(conn); + + await expect(table.flushLsm()).rejects.toThrow(/not supported/i); + }); + + it("rejects compactLsm on a local table", async () => { + const conn = await connect(tmpDir.name); + const table = await lsmTable(conn); + + await expect(table.compactLsm()).rejects.toThrow(/not supported/i); + }); + + it("rejects getLsmStats on a local table", async () => { + const conn = await connect(tmpDir.name); + const table = await lsmTable(conn); + + await expect(table.getLsmStats()).rejects.toThrow(/not supported/i); + await expect(table.getLsmStats(true)).rejects.toThrow(/not supported/i); + }); + + it("rejects checkpointLsm on a local table", async () => { + const conn = await connect(tmpDir.name); + const table = await lsmTable(conn); + + // checkpointLsm seals first, so it surfaces flushLsm's rejection. + await expect(table.checkpointLsm()).rejects.toThrow(/not supported/i); + }); +}); + describe("computed columns", () => { let tmpDir: tmp.DirResult; beforeEach(() => { diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 9f2e97989..6a5bfe3b4 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -147,6 +147,10 @@ export { FtsToken, TokenizeTableOptions, LsmWriteSpec, + LsmStats, + BucketStats, + GenerationStats, + MemtableStats, ColumnAlteration, FieldMetadataUpdate, } from "./table"; diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index a7dc8def1..964c2cea3 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -31,6 +31,7 @@ import { IndexConfig, IndexStatistics, Job, + LsmStats, Branches as NativeBranches, OptimizeStats, RefreshColumnResult, @@ -50,6 +51,12 @@ import { import { sanitizeType } from "./sanitize"; import { IntoSql, toSQL } from "./util"; export { IndexConfig } from "./native"; +export { + BucketStats, + GenerationStats, + LsmStats, + MemtableStats, +} from "./native"; /** * Progress snapshot for a write operation, delivered to the `progress` @@ -706,6 +713,59 @@ export abstract class Table { * @returns {Promise} */ abstract closeLsmWriters(): Promise; + /** + * Seal every bucket's active memtable into a new L0 generation. + * + * Returns once the seal is committed. Sealing an empty memtable is a no-op, + * so this is safe to call repeatedly. + * @returns {Promise} + */ + abstract flushLsm(): Promise; + /** + * Trigger a background L0 → base compaction pass per bucket. + * + * Returns once the passes are *dispatched*, not once they finish — watch + * {@link Table#getLsmStats} for progress, or use + * {@link Table#checkpointLsm} to wait for convergence. + * @returns {Promise} + */ + abstract compactLsm(): Promise; + /** + * Converge this table's LSM write path into its base table. + * + * Seals once, then triggers compaction and polls until the L0 that existed + * at the start is gone. The target set is fixed at the start, so + * generations created *during* the checkpoint are ignored — that is what + * lets it terminate under write load, and what makes it best-effort: it + * converges the fresh tier as of some instant. Idempotent, abandonable at + * any point, and safe to run on a cadence. + * + * There is no liveness bound — the compactor pool is shared across tables, + * so a checkpoint queued behind unrelated work looks exactly like one that + * is merging. The caller owns the deadline. + * @returns {Promise} + * @example + * ```ts + * const before = await table.getLsmStats(); + * await table.checkpointLsm(); + * const after = await table.getLsmStats(); + * ``` + */ + abstract checkpointLsm(): Promise; + /** + * Read live per-bucket LSM state. + * + * Answers "how far behind is my fresh tier", "which bucket is hot", and + * "why is my fresh-tier vector search brute-force". Mutates no table state. + * + * Resolves to `undefined` only when the LSM write path is not enabled. + * @param {boolean} includeGenerationRows Also count rows per L0 generation. + * Off by default because each count opens an uncached Lance dataset. + * @returns {Promise} + */ + abstract getLsmStats( + includeGenerationRows?: boolean, + ): Promise; /** Retrieve the version of the table */ abstract version(): Promise; @@ -1266,6 +1326,24 @@ export class LocalTable extends Table { return await this.inner.closeLsmWriters(); } + async flushLsm(): Promise { + return await this.inner.flushLsm(); + } + + async compactLsm(): Promise { + return await this.inner.compactLsm(); + } + + async checkpointLsm(): Promise { + return await this.inner.checkpointLsm(); + } + + async getLsmStats( + includeGenerationRows: boolean = false, + ): Promise { + return (await this.inner.getLsmStats(includeGenerationRows)) ?? undefined; + } + async version(): Promise { return await this.inner.version(); } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 4c45be668..b15491202 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -497,6 +497,34 @@ impl Table { self.inner_ref()?.close_lsm_writers().await.default_error() } + #[napi(catch_unwind)] + pub async fn flush_lsm(&self) -> napi::Result<()> { + self.inner_ref()?.flush_lsm().await.default_error() + } + + #[napi(catch_unwind)] + pub async fn compact_lsm(&self) -> napi::Result<()> { + self.inner_ref()?.compact_lsm().await.default_error() + } + + #[napi(catch_unwind)] + pub async fn checkpoint_lsm(&self) -> napi::Result<()> { + self.inner_ref()?.checkpoint_lsm().await.default_error() + } + + #[napi(catch_unwind)] + pub async fn get_lsm_stats( + &self, + include_generation_rows: bool, + ) -> napi::Result> { + let stats = self + .inner_ref()? + .get_lsm_stats(include_generation_rows) + .await + .default_error()?; + Ok(stats.map(LsmStats::from)) + } + #[napi(catch_unwind)] pub async fn version(&self) -> napi::Result { self.inner_ref()? @@ -889,6 +917,129 @@ impl From for LsmWriteSpec { } } +/// One flushed L0 generation. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct GenerationStats { + /// The generation number. Increases as memtables are sealed into L0. + pub generation: i64, + /// On-disk size of the generation. + pub bytes: i64, + /// Present only when `includeGenerationRows` was requested. Off by default + /// because each count opens an uncached Lance dataset. + pub rows: Option, +} + +impl From for GenerationStats { + fn from(g: lancedb::table::GenerationStats) -> Self { + Self { + generation: g.generation as i64, + bytes: g.bytes as i64, + rows: g.rows.map(|r| r as i64), + } + } +} + +/// One in-memory memtable. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct MemtableStats { + /// The generation this memtable will become once sealed. + pub generation: i64, + /// Rows currently buffered. + pub rows: i64, + /// Estimated in-memory size. + pub bytes: i64, + /// Record batches currently buffered. + pub batches: i64, + /// Names of the indexes this memtable carries. An absent name is the whole + /// answer to "why is my fresh-tier search on that column brute-force". + pub indexes: Vec, +} + +impl From for MemtableStats { + fn from(m: lancedb::table::MemtableStats) -> Self { + Self { + generation: m.generation as i64, + rows: m.rows as i64, + bytes: m.bytes as i64, + batches: m.batches as i64, + indexes: m.indexes, + } + } +} + +/// Live state of one bucket. A table is N buckets on one node; flattening to a +/// single number hides the one hot bucket that is usually why someone opened +/// this endpoint. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct BucketStats { + /// The shard this bucket writes. + pub shard_id: String, + /// `"Active"` or `"Sealed"` (drop-table 2PC in flight). + pub status: String, + /// Epoch of the writer that currently owns the shard. + pub writer_epoch: i64, + /// Version of the shard manifest these numbers were read from. + pub manifest_version: i64, + /// The generation the active memtable will become. + pub current_generation: i64, + /// WAL position replay resumes from. + pub replay_after_wal_entry_position: i64, + /// Highest WAL position the writer has seen. The difference against + /// `replayAfterWalEntryPosition` is the WAL lag. + pub wal_entry_position_last_seen: i64, + /// Flushed L0 generations not yet merged into the base table. + pub generations: Vec, + /// Whether a pass owns this bucket's compaction latch right now. Says *a* + /// driver is running, not *whose*, and the latch is held from dispatch — + /// including while the pass queues for a pod-wide compactor permit. Read it + /// as "do not pile on", never as "mine is progressing". + pub compacting: bool, + /// Oldest first, active last. Absent for a `"Sealed"` bucket, whose + /// in-memory state is torn down. + pub memtables: Option>, +} + +impl From for BucketStats { + fn from(b: lancedb::table::BucketStats) -> Self { + Self { + shard_id: b.shard_id, + status: b.status, + writer_epoch: b.writer_epoch as i64, + manifest_version: b.manifest_version as i64, + current_generation: b.current_generation as i64, + replay_after_wal_entry_position: b.replay_after_wal_entry_position as i64, + wal_entry_position_last_seen: b.wal_entry_position_last_seen as i64, + generations: b.generations.into_iter().map(Into::into).collect(), + compacting: b.compacting, + memtables: b + .memtables + .map(|ms| ms.into_iter().map(Into::into).collect()), + } + } +} + +/// Live per-bucket LSM state, as returned by `Table#getLsmStats`. +/// +/// Nothing here is derived: sums and differences (total L0 bytes, WAL lag) are +/// the caller's to compute. +#[napi(object)] +#[derive(Clone, Debug)] +pub struct LsmStats { + /// One entry per bucket backing this table. + pub buckets: Vec, +} + +impl From for LsmStats { + fn from(stats: lancedb::table::LsmStats) -> Self { + Self { + buckets: stats.buckets.into_iter().map(Into::into).collect(), + } + } +} + /// Statistics about a compaction operation. #[napi(object)] #[derive(Clone, Debug)] diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 235049f97..e12ef4e86 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -12,6 +12,7 @@ __version__ = importlib.metadata.version("lancedb") from ._lancedb import connect as lancedb_connect from ._lancedb import FtsToken +from ._lancedb import LsmWriteSpec from ._lancedb import tokenize as _tokenize from .common import URI, sanitize_uri from urllib.parse import urlparse @@ -518,6 +519,7 @@ __all__ = [ "Job", "LanceDBConnection", "LanceNamespaceDBConnection", + "LsmWriteSpec", "RemoteDBConnection", "Session", "Table", diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index f97d0331c..393b2eed3 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -4801,7 +4801,7 @@ class AsyncTable: Examples -------- - >>> from lancedb._lancedb import LsmWriteSpec + >>> from lancedb import LsmWriteSpec >>> # table.set_unenforced_primary_key("id") >>> # table.set_lsm_write_spec(LsmWriteSpec.bucket("id", 16)) """ From 27cea03b7d4a71665567e24a09abef30fa8b62d8 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Wed, 19 Aug 2026 13:18:27 -0700 Subject: [PATCH 052/206] chore: update lance dependency to v11.0.0-beta.15 (#3968) Bumps the Rust workspace Lance dependencies and Java lance-core to v11.0.0-beta.15. Updates the computed-column refresh path for the new `write_columns` API. Release: https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.15 --- Cargo.lock | 84 +++++++++++++++---------------- Cargo.toml | 28 +++++------ java/pom.xml | 2 +- rust/lancedb/src/table/refresh.rs | 6 +-- 4 files changed, 60 insertions(+), 60 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3f4d6682c..013850034 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow", "arrow-array", @@ -5013,8 +5013,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow", "arrow-array", @@ -5031,8 +5031,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "proc-macro2", "quote", @@ -5041,8 +5041,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow-arith", "arrow-array", @@ -5075,8 +5075,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow-arith", "arrow-array", @@ -5107,8 +5107,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arc-swap", "arrow", @@ -5172,8 +5172,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow-array", "arrow-schema", @@ -5195,8 +5195,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow", "arrow-array", @@ -5232,8 +5232,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow-array", "arrow-schema", @@ -5247,8 +5247,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow", "async-trait", @@ -5260,8 +5260,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow", "arrow-ipc", @@ -5314,8 +5314,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow-array", "arrow-buffer", @@ -5329,8 +5329,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow", "arrow-array", @@ -5370,8 +5370,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "arrow-array", "arrow-schema", @@ -5384,8 +5384,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.14#059f71af86c8e77d98bea2469e259e9a8363a460" +version = "11.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index c90fb81d8..0a8c0d36e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.14", default-features = false, "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.14", default-features = false, "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.14", default-features = false, "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.14", "tag" = "v11.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.15", default-features = false, "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.15", default-features = false, "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.15", default-features = false, "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } ahash = "0.8" # Note that this one does not include pyarrow arrow = { version = "58.0.0", optional = false } diff --git a/java/pom.xml b/java/pom.xml index 63711d0c9..92e6344f3 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.14 + 11.0.0-beta.15 false 2.30.0 1.7 diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index edc78387e..b29c97e98 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -12,7 +12,7 @@ //! decides whether the fragment is staged at all -- a fragment where nothing //! would change stages nothing, which is what lets an expression yielding //! null settle instead of restaging forever. The second streams the -//! fragment's physical rows into `write_column` a batch at a time, so peak +//! fragment's physical rows into `write_columns` a batch at a time, so peak //! memory is bounded by a scan batch. The expression is evaluated by this //! module, never through a projection alias, and only over rows being //! filled: every other row -- deleted, or already holding a value -- has its @@ -67,7 +67,7 @@ pub(crate) async fn execute_refresh_column( .ok_or_else(|| Error::ColumnNotFound { name: column.to_string(), })?; - // The dataset's own field, so the identity write_column checks against the + // The dataset's own field, so the identity write_columns checks against the // manifest holds by construction. let column_schema = LanceSchema { fields: vec![field.clone()], @@ -83,7 +83,7 @@ pub(crate) async fn execute_refresh_column( } rows_filled += gained; let values = fill_stream(&dataset, &fragment, bound.clone(), column).await?; - replacements.push(fragment.write_column(values, &column_schema).await?); + replacements.push(fragment.write_columns(values, &column_schema).await?); } if replacements.is_empty() { From 4e042af12fd0eb5ced85850c1a30ed70c4a8c2cd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 20 Aug 2026 10:55:16 -0700 Subject: [PATCH 053/206] chore(deps): bump cmov from 0.5.3 to 0.5.4 (#3974) Bumps [cmov](https://github.com/RustCrypto/utils) from 0.5.3 to 0.5.4.
Commits

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=cmov&package-manager=cargo&previous-version=0.5.3&new-version=0.5.4)](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 this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself) - `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself) You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/lancedb/lancedb/network/alerts).
Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 013850034..ddb9cf880 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1740,9 +1740,9 @@ dependencies = [ [[package]] name = "cmov" -version = "0.5.3" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f88a43d011fc4a6876cb7344703e297c71dda42494fee094d5f7c76bf13f746" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" [[package]] name = "colorchoice" From 061a3da8b98012995335d70b16ac19f5665bbdab Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Thu, 20 Aug 2026 12:05:40 -0700 Subject: [PATCH 054/206] fix(python): preserve JSON encoding in merge insert (#3976) ## Summary - preserve incoming PyArrow `arrow.json` fields while schema sanitization aligns input to a stored `lance.json` schema - let Lance perform the required JSONB encoding instead of relabeling raw JSON bytes as encoded storage - cover both merge insert and the conditional add sanitization path with end-to-end regression tests ## Root cause Python schema sanitization aligns incoming data to the table schema before passing it to Lance. Merge insert always takes this path, while add takes it conditionally for preprocessing such as non-default bad-vector handling or embedding functions. For JSON columns, the cast changed logical `arrow.json` strings into the table's JSONB-backed `lance.json` storage type without encoding the bytes, so Lance treated raw JSON text as JSONB. ## Validation - `cd python && uv run --extra tests pytest python/tests/test_table.py -k 'merge_insert or add_sanitization_encodes_json' -q` - targeted schema-cast and JSON encoding tests - `ruff check .` - `ruff format --check python/python/lancedb/table.py python/python/tests/test_table.py` Fixes #3923 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/python/lancedb/table.py | 24 +++++++++++++++ python/python/tests/test_table.py | 50 +++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 393b2eed3..79e67fdba 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -433,6 +433,20 @@ def _cast_to_target_schema( return pa.RecordBatchReader.from_batches(reordered_schema, gen()) +def _field_extension_name(field: pa.Field) -> Optional[str]: + extension_name = getattr(field.type, "extension_name", None) + if extension_name is not None: + return extension_name + + metadata = field.metadata or {} + extension_name = metadata.get(b"ARROW:extension:name") or metadata.get( + "ARROW:extension:name" + ) + if isinstance(extension_name, bytes): + return extension_name.decode() + return extension_name + + def _align_field_types( fields: List[pa.Field], target_fields: List[pa.Field], @@ -445,6 +459,16 @@ def _align_field_types( target_field = next((f for f in target_fields if f.name == field.name), None) if target_field is None: raise ValueError(f"Field '{field.name}' not found in target schema") + # Preserve arrow.json input until it reaches Lance. LanceDB exposes stored + # JSON columns as lance.json (JSONB-backed LargeBinary), but casting the + # input to that storage type here merely relabels the raw JSON bytes as + # JSONB. Lance must see arrow.json so it can perform the JSONB encoding. + if ( + _field_extension_name(field) == "arrow.json" + and _field_extension_name(target_field) == "lance.json" + ): + new_fields.append(field) + continue if pa.types.is_struct(target_field.type): if pa.types.is_struct(field.type): new_type = pa.struct( diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index bb011f8c0..b28cd9d66 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -2772,6 +2772,56 @@ async def test_merge_insert_async(mem_db_async: AsyncConnection): assert (await table.to_arrow()).sort_by("a") == expected +@pytest.mark.skipif(not hasattr(pa, "json_"), reason="requires PyArrow JSON type") +@pytest.mark.asyncio +async def test_merge_insert_encodes_json(mem_db_async: AsyncConnection): + json_type = pa.json_() + schema = pa.schema([pa.field("id", pa.string()), pa.field("j", json_type)]) + + def json_table(rows): + json_values = pa.ExtensionArray.from_storage( + json_type, + pa.array([value for _, value in rows], type=json_type.storage_type), + ) + return pa.Table.from_arrays( + [pa.array([row_id for row_id, _ in rows]), json_values], schema=schema + ) + + table = await mem_db_async.create_table("json_merge", schema=schema) + await table.add(json_table([("a", '{"k": 1}'), ("b", '{"k": 9}')])) + + await ( + table.merge_insert("id") + .when_matched_update_all() + .execute(json_table([("a", '{"k": 2}')])) + ) + + rows = sorted(await table.query().to_list(), key=lambda row: row["id"]) + assert rows == [ + {"id": "a", "j": '{"k":2}'}, + {"id": "b", "j": '{"k":9}'}, + ] + filtered = await table.query().where("json_extract(j, '$.k') = '2'").to_list() + assert filtered == [{"id": "a", "j": '{"k":2}'}] + + +@pytest.mark.skipif(not hasattr(pa, "json_"), reason="requires PyArrow JSON type") +@pytest.mark.asyncio +async def test_add_sanitization_encodes_json(mem_db_async: AsyncConnection): + json_type = pa.json_() + schema = pa.schema([pa.field("id", pa.string()), pa.field("j", json_type)]) + json_values = pa.ExtensionArray.from_storage( + json_type, pa.array(['{"k": 3}'], type=json_type.storage_type) + ) + data = pa.Table.from_arrays([pa.array(["c"]), json_values], schema=schema) + + table = await mem_db_async.create_table("json_add", schema=schema) + await table.add(data, on_bad_vectors="fill") + + rows = await table.query().where("json_extract(j, '$.k') = '3'").to_list() + assert rows == [{"id": "c", "j": '{"k":3}'}] + + def test_create_with_embedding_function(mem_db: DBConnection): class MyTable(LanceModel): text: str From 5c1b44020a1c101ffa55702ded6debe862d66f9d Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 20 Aug 2026 13:44:51 -0700 Subject: [PATCH 055/206] chore: enforce shared workspace dependencies via cargo-deny (#3975) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `cargo deny` did not check crate-level dependency declarations against `[workspace.dependencies]`, so a crate used by both the core crate and the bindings could be declared independently in each one and drift. For example `tokio` was pinned at `1.23` in `rust/lancedb` and `1.40` in `python`, and `pin-project` at `1.0.7` in the workspace table but `1.1.5` in `python`. This PR turns on cargo-deny's `bans.workspace-dependencies` lint, which fails when a dependency is used by more than one member without going through `workspace = true`, and when a `[workspace.dependencies]` entry is used by nobody. Enabling it surfaced 12 violations. Fixing them means adding `bytes`, `lancedb`, `serde`, `serde_json`, `tempfile`, `tokio`, and `uuid` to `[workspace.dependencies]`, and pointing the `arrow`, `arrow-buffer`, `async-trait`, `chrono`, and `pin-project` declarations at the entries that already existed. `Cargo.lock` is unchanged, so resolution is the same as before. The shared `chrono` entry now carries `default-features = false, features = ["clock"]`, matching what `nodejs` and `python` already asked for — cargo ignores a member's `default-features = false` unless the workspace entry sets it too. On the targets we build, `clock` covers everything `rust/lancedb` was getting from chrono's defaults. Co-authored-by: Claude Opus 5 (1M context) --- Cargo.toml | 9 ++++++++- deny.toml | 5 +++++ nodejs/Cargo.toml | 8 ++++---- python/Cargo.toml | 18 +++++++++--------- rust/lancedb/Cargo.toml | 20 ++++++++++---------- 5 files changed, 36 insertions(+), 24 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 0a8c0d36e..925910586 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,6 +27,7 @@ lance-testing = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git lance-datafusion = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } lance-encoding = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } lance-arrow = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow arrow = { version = "58.0.0", optional = false } @@ -39,6 +40,7 @@ arrow-schema = "58.0.0" arrow-select = "58.0.0" arrow-cast = "58.0.0" async-trait = "0" +bytes = "1" datafusion = { version = "54.0.0", default-features = false } datafusion-catalog = "54.0.0" datafusion-common = { version = "54.0.0", default-features = false } @@ -65,7 +67,12 @@ url = "2" num-traits = "0.2" regex = "1.10" semver = "1.0.25" -chrono = "0.4" +serde = "1" +serde_json = "1" +tempfile = "3.5.0" +tokio = { version = "1.23", features = ["rt-multi-thread", "sync"] } +uuid = { version = "1.7.0", features = ["v4"] } +chrono = { version = "0.4", default-features = false, features = ["clock"] } [profile.ci] debug = "line-tables-only" diff --git a/deny.toml b/deny.toml index cea2522fd..3672321d0 100644 --- a/deny.toml +++ b/deny.toml @@ -177,6 +177,11 @@ multiple-versions = "warn" # Wildcard version requirements (`foo = "*"`) are a footgun — they let any # future release in without review. Ban them outright. wildcards = "deny" +# Lint every dependency declared by a workspace member against the shared +# `[workspace.dependencies]` table: any crate used by more than one member must +# go through `workspace = true`, and entries nothing uses are an error. This +# keeps versions from drifting between the core crate and the bindings. +workspace-dependencies = { duplicates = "deny", unused = "deny" } # Internal workspace crates reference each other via `path = "..."`, which # cargo-deny sees as a wildcard version. That's fine for private workspace # members (not published to crates.io), so allow it specifically for paths. diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 9b9b56f7e..3c0b24db3 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -16,12 +16,12 @@ crate-type = ["cdylib"] async-trait.workspace = true arrow-ipc.workspace = true arrow-array.workspace = true -arrow-buffer = "58.0.0" +arrow-buffer.workspace = true half.workspace = true arrow-schema.workspace = true env_logger.workspace = true futures.workspace = true -lancedb = { path = "../rust/lancedb", default-features = false } +lancedb.workspace = true lance-namespace.workspace = true napi = { version = "3.8.3", default-features = false, features = [ "napi9", @@ -29,8 +29,8 @@ napi = { version = "3.8.3", default-features = false, features = [ "chrono_date", "serde-json", ] } -chrono = { version = "0.4", default-features = false, features = ["clock"] } -serde_json = "1" +chrono.workspace = true +serde_json.workspace = true napi-derive = "3.5.2" # Prevent dynamic linking of lzma, which comes from datafusion lzma-sys = { version = "0.1", features = ["static"] } diff --git a/python/Cargo.toml b/python/Cargo.toml index e41563266..5af99eac3 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -15,10 +15,10 @@ name = "_lancedb" crate-type = ["cdylib"] [dependencies] -arrow = { version = "58.0.0", features = ["pyarrow"] } -async-trait = "0.1" -bytes = "1" -lancedb = { path = "../rust/lancedb", default-features = false } +arrow = { workspace = true, features = ["pyarrow"] } +async-trait.workspace = true +bytes.workspace = true +lancedb.workspace = true datafusion-common.workspace = true lance-core.workspace = true lance-namespace.workspace = true @@ -27,17 +27,17 @@ lance-io.workspace = true env_logger.workspace = true log.workspace = true pyo3 = { version = "0.28", features = ["extension-module", "abi3-py310", "chrono"] } -chrono = { version = "0.4", default-features = false, features = ["clock"] } +chrono.workspace = true pyo3-async-runtimes = { version = "0.28", features = [ "attributes", "tokio-runtime", ] } -pin-project = "1.1.5" +pin-project.workspace = true futures.workspace = true -serde = "1" -serde_json = "1" +serde.workspace = true +serde_json.workspace = true snafu.workspace = true -tokio = { version = "1.40", features = ["sync", "rt-multi-thread"] } +tokio.workspace = true libc = "0.2" [build-dependencies] diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 69d07b2d8..ac1c8754c 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -51,20 +51,20 @@ metrics = { workspace = true, optional = true } metrics-util = { workspace = true, optional = true } moka = { workspace = true } pin-project = { workspace = true } -tokio = { version = "1.23", features = ["rt-multi-thread", "sync"] } +tokio = { workspace = true } log.workspace = true -async-trait = "0" -bytes = "1" +async-trait = { workspace = true } +bytes = { workspace = true } futures.workspace = true num-traits.workspace = true url.workspace = true rand.workspace = true regex.workspace = true -serde = { version = "^1" } -serde_json = { version = "1" } +serde = { workspace = true } +serde_json = { workspace = true } async-openai = { version = "0.20.0", optional = true } serde_with = { version = "3.8.1" } -tempfile = "3.5.0" +tempfile = { workspace = true } aws-sdk-bedrockruntime = { version = "1.27.0", optional = true } # For remote feature reqwest = { version = "0.12.0", default-features = false, features = [ @@ -79,7 +79,7 @@ reqwest = { version = "0.12.0", default-features = false, features = [ ], optional = true } http = { version = "1", optional = true } # Matching what is in reqwest urlencoding = { version = "2", optional = true } -uuid = { version = "1.7.0", features = ["v4", "v5"] } +uuid = { workspace = true, features = ["v5"] } polars-arrow = { version = ">=0.37,<0.40.0", optional = true } polars = { version = ">=0.37,<0.40.0", optional = true } hf-hub = { version = "0.4.1", optional = true, default-features = false, features = [ @@ -96,11 +96,11 @@ semver = { workspace = true } [dev-dependencies] anyhow = "1" lance-testing = { workspace = true } -tempfile = "3.5.0" +tempfile = { workspace = true } random_word = { version = "0.4.3", features = ["en"] } roaring = "0.11.4" -tokio = { version = "1.23", features = ["io-util", "macros", "net", "rt-multi-thread", "sync", "test-util"] } -uuid = { version = "1.7.0", features = ["v4"] } +tokio = { workspace = true, features = ["io-util", "macros", "net", "test-util"] } +uuid = { workspace = true } walkdir = "2" aws-sdk-dynamodb = { version = "1.55.0" } aws-sdk-s3 = { version = "1.55.0" } From e517ba5205a42d8a311d5521c27cb2c0040fd445 Mon Sep 17 00:00:00 2001 From: Dan Tasse <105866+dantasse@users.noreply.github.com> Date: Thu, 20 Aug 2026 18:03:24 -0400 Subject: [PATCH 056/206] refactor: remove unnecessary skill references (#3977) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Background: if we keep adding stuff to the lancedb skill that repeats other knowledge, we're basically creating a whole new docs site, which means one more thing that can get out of date. Worse, if it gets out of date, it will tell agents to do the wrong thing. These files were added without a ton of analysis of whether they'd be improving agent performance at all. It looks like they don't really: Screenshot 2026-08-20 at 5 21 03 PM (top run is without these docs, bottom run is with them - arguably these docs might even make the agent a little slower! that's probably noise though; I'd just say at least they're unnecessary.) So this PR just removes them. We'll more judiciously add bits we need and/or point to preexisting docs, to avoid duplication. --------- Co-authored-by: Claude Fable 5 --- plugins/lancedb/skills/lancedb/SKILL.md | 31 +++- .../references/python/api_reference.md | 138 -------------- .../lancedb/references/python/patterns.md | 173 ------------------ .../lancedb/references/python/performance.md | 131 ------------- .../references/typescript/api_reference.md | 105 ----------- .../lancedb/references/typescript/patterns.md | 100 ---------- .../references/typescript/performance.md | 78 -------- 7 files changed, 23 insertions(+), 733 deletions(-) delete mode 100644 plugins/lancedb/skills/lancedb/references/python/api_reference.md delete mode 100644 plugins/lancedb/skills/lancedb/references/python/patterns.md delete mode 100644 plugins/lancedb/skills/lancedb/references/python/performance.md delete mode 100644 plugins/lancedb/skills/lancedb/references/typescript/api_reference.md delete mode 100644 plugins/lancedb/skills/lancedb/references/typescript/patterns.md delete mode 100644 plugins/lancedb/skills/lancedb/references/typescript/performance.md diff --git a/plugins/lancedb/skills/lancedb/SKILL.md b/plugins/lancedb/skills/lancedb/SKILL.md index 8b8f761c2..47537f31a 100644 --- a/plugins/lancedb/skills/lancedb/SKILL.md +++ b/plugins/lancedb/skills/lancedb/SKILL.md @@ -20,18 +20,16 @@ Do NOT assume local-only table helpers exist on remote tables. If the user asks 1. Identify the SDK: Python, TypeScript, or both. 2. Identify the table mode: local/embedded OSS, remote Enterprise/Cloud, or portable across both. If the user says "LanceDB Enterprise", choose the remote table path. If the task involves jobs in any way (listing, inspecting, creating, or canceling jobs), it is always the remote path and requires a remote server connection — see "Connecting to the LanceDB remote server" below before doing anything else. -3. Read the matching language branch before writing or changing code: - - Python patterns: `references/python/patterns.md` - - Python API quick reference: `references/python/api_reference.md` - - Python performance guidance: `references/python/performance.md` - - TypeScript patterns: `references/typescript/patterns.md` - - TypeScript API quick reference: `references/typescript/api_reference.md` - - TypeScript performance guidance: `references/typescript/performance.md` +3. Read the matching topic reference before writing or changing code: - Column metadata authoring (both SDKs): `references/column_metadata.md` - Branch operations (both SDKs): `references/branch_ops.md` - Remote server connection resolution (jobs, raw REST): `references/remote_connect.md` - Job operations REST API (list/describe/cancel/query_events): `references/remote_jobs.md` -4. Start with `patterns.md` for the selected SDK. Read `api_reference.md` when choosing method names or return collectors. Read `performance.md` when the task involves ingestion, indexing, filtering, query tuning, diagnostics, or large datasets. Read `column_metadata.md` when the task is documenting, tagging, classifying, or grouping table columns (field descriptions, `lancedb:tag:*` tags, logical column families). Read `branch_ops.md` when the task involves branch lifecycle (list/create/delete), writing to a non-main branch, or verifying a change stayed off main. Read `remote_connect.md` when the task involves jobs or direct REST access to an Enterprise deployment, and `remote_jobs.md` for the job REST methods themselves (list, describe, cancel, query_events). + + There is no bundled per-language guide. For exact method names, signatures, and options, look them up in the canonical sources instead of relying on memory: + - Python: `docs/src/python/python.md` (the hand-maintained API reference) and the source under `python/python/lancedb/` when working inside the LanceDB repo; otherwise . + - TypeScript: the generated typedoc under `docs/src/js/` and the source under `nodejs/lancedb/` when working inside the LanceDB repo; otherwise . +4. Apply the SDK invariants in "Per-SDK Invariants" below. Read `column_metadata.md` when the task is documenting, tagging, classifying, or grouping table columns (field descriptions, `lancedb:tag:*` tags, logical column families). Read `branch_ops.md` when the task involves branch lifecycle (list/create/delete), writing to a non-main branch, or verifying a change stayed off main. Read `remote_connect.md` when the task involves jobs or direct REST access to an Enterprise deployment, and `remote_jobs.md` for the job REST methods themselves (list, describe, cancel, query_events). 5. For Python schemas, favor Pydantic models and validate records before writing. Use PyArrow schemas when Arrow-native, streaming, or highly dynamic data makes them materially better suited. 6. Prefer `search()` or `query()` builders with explicit `select()` and `limit()` for reads. 7. Avoid table-level full materialization in remote or portable code. This is the main local-vs-remote read pitfall. @@ -54,6 +52,23 @@ The unsafe pattern is table-level or unbounded collection, plus local-only datas - Python: `table.to_pandas()`, `table.to_arrow()`, `table.to_polars()`; `table.to_lance()` is local/OSS-only dataset access, not materialization - TypeScript: `await table.toArrow()`, `await table.query().toArray()` without `limit()` +## Per-SDK Invariants + +Python: + +- Result collectors: default to `.to_list()` (plain dicts, no extra dependency) or `.to_arrow()` (PyArrow ships with LanceDB). Use `.to_pandas()` / `.to_polars()` only when the project already declares that dependency — do not assume pandas or polars is installed. +- Plain scans differ by client: the sync client has no `.query()` method — use `table.search()` with no argument; the async client uses `await async_table.query()`. + +TypeScript: + +- Collect bounded results with `.toArray()` (objects) or `.toArrow()` (Arrow) after `select()` and `limit()`. +- For large reads, stream batches instead of collecting: `for await (const batch of table.query().where(...).select(...).limit(...)) { ... }`. + +Both SDKs: + +- Ingest in bulk or in batches of thousands of rows; never write per-row in a loop — each write creates a version and fragment, slowing ingestion and later queries. +- Build a vector index once brute-force search is too slow (rule of thumb: beyond roughly 100K vectors locally), and scalar indexes for filtered columns and merge/upsert keys. Use index defaults unless the task states recall/latency requirements. + ## Enterprise: never drop-then-reuse the same table name LanceDB Enterprise/Cloud splits a **control plane** (DDL: create/drop/rename) from a **data plane** (query nodes that serve reads). Query nodes cache the resolved dataset for a table name for up to `table_cache_ttl` — **default 300 seconds (5 minutes)**. After you drop or overwrite a table, the control plane updates immediately but the data plane keeps serving the *old* dataset until that cache entry expires. During the window the two planes disagree. diff --git a/plugins/lancedb/skills/lancedb/references/python/api_reference.md b/plugins/lancedb/skills/lancedb/references/python/api_reference.md deleted file mode 100644 index bbb209630..000000000 --- a/plugins/lancedb/skills/lancedb/references/python/api_reference.md +++ /dev/null @@ -1,138 +0,0 @@ -# Python API Reference - -Quick method reference for Python LanceDB code. Cross-check source for non-trivial claims. - -## Connect - -If you're connecting to a remote database, use this: -```python -import lancedb - -db = lancedb.connect("db://my-db", api_key=api_key, host_override=host_override) # remote -``` -(values may be found in LANCEDB_API_KEY and LANCEDB_HOST_OVERRIDE, either in env vars or a .env file) - -If you're connecting to a local table using OSS LanceDB, use this: -```python -db = lancedb.connect("./camelot-db") # local/OSS -``` -If you're not sure which, or if you can't find the api_key or host_override params, ask the user. - -**Place the local database directory next to the script/entrypoint that opens it** (i.e. resolve the path relative to the script, `Path(__file__).parent / "camelot-db"`), not buried under a shared `data/` folder. The Lance dataset is the database, not a data file — keeping it beside its code makes ownership obvious and paths stable regardless of the working directory the script is launched from. - -**Do not name the directory `lancedb`** (e.g. `./lancedb`, `./data/lancedb`). It collides with the imported `lancedb` package name, which is confusing to read and easy to shadow in scripts. Give it a name derived from the repo or dataset with a clear prefix/suffix — for example `./-db`, `./_lancedb`, or `./vectordb`. - -Async: - -```python -db = await lancedb.connect_async("./camelot-db") -``` - -## Table Reads - -| Task | Preferred API | -| --- | --- | -| Vector search | `table.search(query_vector).limit(k)` | -| Full scan with filters/projection (sync) | `table.search().where(...).select(...).limit(...)` | -| Full scan with filters/projection (async) | `table.query().where(...).select(...).limit(...)` | -| Filter | `.where("col > 10")` | -| Projection | `.select(["id", "text"])` | -| Bound result count | `.limit(20)` | -| Collect bounded result as Python objects (default, no extra deps) | `.to_list()` on query/search result | -| Collect bounded result as Arrow (default, `pyarrow` always available) | `.to_arrow()` on query/search result | -| Collect bounded result as pandas (only if project uses pandas) | `.to_pandas()` on query/search result | -| Collect bounded result as Polars (only if project uses polars) | `.to_polars()` on query/search result | - -## Sync vs Async Scan API - -The plain-scan entry point differs between the sync and async clients. **Verified against `lancedb` 0.34.0** — re-check if the pinned version changes: - -- **Sync** (`lancedb.connect(...)`): the table has **no `.query()` method**. Use `.search()` with no argument for a plain scan; it returns a query builder that supports `.where()`, `.select()`, `.limit()`, and the `.to_list()` / `.to_arrow()` / `.to_pandas()` / `.to_polars()` collectors. - ```python - rows = table.search().where("status = 'ready'").select(["id", "text"]).limit(20).to_list() - ``` -- **Async** (`lancedb.connect_async(...)`): the table has **both** `.query()` and `.search()`. Use `.query()` for a plain scan. - ```python - rows = await async_table.query().where("status = 'ready'").select(["id", "text"]).limit(20).to_list() - ``` - -Do not call `table.query()` on a sync table — it raises `AttributeError`. - -## Local vs Remote Table Methods - -| API | Local table | Remote table | Agent guidance | -| --- | --- | --- | --- | -| `table.search(...)` | Yes | Yes | Preferred read path (sync + async) | -| `table.query()` | Async only | Async only | Sync scan path is `table.search()`; `.query()` is the async scan builder | -| `table.to_pandas()` | Yes | No / unsafe for portability | Avoid in portable code | -| `table.to_arrow()` | Yes | No / unsafe for portability | Avoid in portable code | -| `table.to_polars()` | Yes | No / unsafe for portability | Avoid in portable code | -| `table.to_lance()` | Yes | No | Local/OSS escape hatch only | - -## Indexes - -Use `create_index(...)` for vector indexes and modern index configs. Use scalar indexes for filtered or merge keys. - -Common calls: - -```python -table.create_index("vector") -table.create_scalar_index("status") -table.create_fts_index("text") -``` - -Check source docs before specifying advanced index config names or parameters. - -## Filtering And Recall Knobs - -```python -table.search(query_vector).where("status = 'ready'") # pre-filter by default -table.search(query_vector).where("status = 'ready'", prefilter=False) -table.search(query_vector).limit(10).refine_factor(20) -table.search(query_vector).limit(10).nprobes(50) -``` - -Use post-filtering only when fewer than `limit` results are acceptable. - -## Diagnostics - -```python -print(table.search(query_vector).where("year > 2000").limit(10).analyze_plan()) -print(table.index_stats("vector_idx")) -``` - -Use these before changing indexes or search tuning. - -## Column (Field) Metadata - -```python -schema = table.schema # sync property; async: await table.schema() -meta = schema.field("category").metadata # dict[bytes, bytes] — Arrow metadata is bytes-keyed -res = table.update_field_metadata( # varargs: one dict per field; works local + remote - {"path": "category", "metadata": {"lancedb:description": "...", "lancedb:tag:field_type": "label"}} -) -res.version # new table version -``` - -Merges by default; a `None` value deletes that key; `"replace": True` swaps the whole map. Nested fields use dot-paths (`"a.b.c"`). `replace_field_metadata` is deprecated. See `references/column_metadata.md` for key conventions (`lancedb:description`, `lancedb:tag:`, `lancedb:logical-column`) and the authoring workflow. - -## Branches - -```python -table.branches.list() # non-main branches; {} = only main -exp = table.branches.create("exp") # fork off main -> handle scoped to the branch -wip = table.branches.checkout("wip") # existing branch -> scoped handle (version= pins read-only) -wip = db.open_table("t", branch="wip") # or open scoped directly -table.branches.delete("stale") # removes only the branch pointer -table.current_branch() # None = main -``` - -There is no global switch — scoping is per table handle: any read/write on a branch handle lands on that branch; the original handle keeps targeting main. See `references/branch_ops.md` for the model and isolation checks. - -## Maintenance - -```python -table.optimize() -``` - -Call this after every successful local/OSS ingestion. It handles compaction, cleanup of old versions according to retention, and index optimization. Do not add this for LanceDB Enterprise/Cloud remote tables; Enterprise handles compaction and cleanup automatically from cluster configuration. diff --git a/plugins/lancedb/skills/lancedb/references/python/patterns.md b/plugins/lancedb/skills/lancedb/references/python/patterns.md deleted file mode 100644 index 4d6be43ef..000000000 --- a/plugins/lancedb/skills/lancedb/references/python/patterns.md +++ /dev/null @@ -1,173 +0,0 @@ -# Python Patterns - -Use these patterns when writing Python code with `lancedb`. - -## Before Writing Code - -Choose the output type from what the project actually depends on. **Do not assume `pandas` or `polars` is installed** — they are heavy dependencies that many LanceDB projects do not use. `pyarrow`, by contrast, ships as a LanceDB dependency and is always available, so it is a safe default to lean on. - -Default output (after applying `select()` and `limit()`): - -- **Python objects**: `.to_list()` — a list of dicts, no extra dependencies. Prefer this for scripts, examples, and agent-generated code unless there is a reason to do otherwise. -- **PyArrow**: `.to_arrow()` — a `pyarrow.Table`, when the surrounding code is Arrow-native or you need columnar/zero-copy handoff. - -Only reach for a DataFrame when the project *already* declares that dependency: - -- Pandas projects (pandas in `pyproject.toml`/requirements): `.to_pandas()`. -- Polars projects (polars declared): `.to_polars()`. - -If unsure, check the dependency manifest or the imports in surrounding files. When in doubt, use `.to_list()` or `.to_arrow()`. - -## Schema Design and Validation - -Favor `LanceModel` and Pydantic validation for Python schemas. They keep field -types readable, validate source records before a write, and map directly to a -LanceDB schema. Use `Vector(dimension)` for fixed-size vectors: - -```python -from lancedb.pydantic import LanceModel, Vector - -class Document(LanceModel): - id: int - text: str - vector: Vector(384, nullable=False) - -rows = [Document.model_validate(row) for row in source_rows] -table = db.create_table("documents", schema=Document) -table.add(rows) -``` - -Use PyArrow schemas instead when the pipeline is already Arrow-native, needs -record-batch streaming, or has runtime schema requirements that would make a -Pydantic model harder to understand. Declare Pydantic as a direct project -dependency when application code imports it, even if LanceDB also depends on it. - -## Recommended Patterns - -### Bounded search or query - -Use this for application reads, examples, notebooks, and agent-generated scripts: - -```python -results = ( - table.search(query_vector) - .where("status = 'ready'") - .select(["id", "text"]) - .limit(20) - .to_list() # or .to_arrow(); .to_pandas()/.to_polars() only if the project uses them -) -``` - -Why: `search()` works across local and remote tables and on both the sync and async clients. `select()` avoids fetching unused columns. `limit()` prevents accidental full-table reads. `.to_list()` and `.to_arrow()` avoid assuming pandas/polars is installed (see "Before Writing Code"). - -For a **plain scan** (no query vector), the entry point differs by client: - -```python -# Sync client: no .query() method — use .search() with no argument. -rows = table.search().where("status = 'ready'").select(["id", "text"]).limit(20).to_list() - -# Async client: use .query(). -rows = await async_table.query().where("status = 'ready'").select(["id", "text"]).limit(20).to_list() -``` - -`table.query()` on a sync table raises `AttributeError` (verified on `lancedb` 0.34.0). See the "Sync vs Async Scan API" section in `api_reference.md`. - -### Bounded query result conversion - -It is fine to collect bounded query/search results: - -```python -arrow_table = table.search().select(["id"]).limit(100).to_arrow() # sync plain scan -rows = table.search(query_vector).limit(10).to_list() -df = table.search(query_vector).limit(10).to_pandas() # only if pandas is a project dep -``` - -### Local-only Lance dataset API - -`table.to_lance()` does not itself materialize the full dataset. It returns the underlying `lance.LanceDataset`, making the table accessible through the PyLance dataset API. Use it when the task is explicitly local/OSS and needs Lance dataset methods not exposed by LanceDB: - -```python -# Local/OSS only: RemoteTable does not expose table.to_lance(). -ds = table.to_lance() -for batch in ds.to_batches(columns=["id", "text"], batch_size=10_000): - process(batch) -``` - -### Async Python - -Keep the same shape and bound the result before collecting: - -```python -results = await ( - async_table.query() - .where("status = 'ready'") - .select(["id", "text"]) - .limit(20) - .to_list() # or .to_arrow() -) -``` - -## Anti-Patterns - -**Avoid the following anti-patterns in your code.** - -### Table-level full materialization - -Avoid whole-table collectors in portable or large-table code: - -```python -df = table.to_pandas() -arrow_table = table.to_arrow() -polars_df = table.to_polars() -``` - -Why: local tables expose these whole-table collectors, but remote tables intentionally do not — a remote production table can be far larger than a local development table, so it is easy to accidentally pull the entire table into memory. - -`table.to_lance()` is different: it is not a full materialization call, but it is still local/OSS-only and should not appear in code meant to run against remote Enterprise tables. - -### Unbounded result collection - -Avoid query/search collection without a meaningful limit: - -```python -rows = table.search().to_list() # unbounded plain scan -rows = table.search(query_vector).to_list() # unbounded vector search -``` - -Prefer `select(...).limit(...)` before collecting; for large reads, stream in batches instead. - -### Per-row writes - -Avoid loops that write one row per call: - -```python -for row in rows: - table.add([row]) # one commit + fragment per row -``` - -Each `add()` creates a new version and fragment. Pass the whole batch in a single call, or chunk very large inputs: - -```python -table.add(rows) # single commit -# for very large inputs, add batches of several thousand rows -``` - -After the final successful write to an embedded OSS table, call -`table.optimize()`. Skip this for Enterprise/Cloud tables because their -maintenance is automatic. - -### Drop-then-reuse the same table name (Enterprise/Cloud) - -Avoid dropping or overwriting a remote table and then reusing that name right away: - -```python -db.drop_table("my_table") -table = db.create_table("my_table", data=rows) # reads 500 for ~5 min -table = db.create_table("my_table", data=rows, mode="overwrite") # same problem -``` - -Why: Enterprise/Cloud splits DDL (control plane) from query serving (data plane). The data plane caches the dataset behind a table name for up to `table_cache_ttl` (default 300s / 5 min), so after a drop/overwrite the DDL succeeds but queries against the reused name return `500 Internal Server Error` until the cache expires — and a fresh `describe` may still show the old schema. Instead, write to a **fresh name**, use `list_tables()` and fail if it already exists, then `rename_table(fresh, final)` onto the final name only after the old table's drop has propagated (~5 min). See the "Enterprise: never drop-then-reuse the same table name" section in `SKILL.md`. Local/OSS tables have no separate data plane — overwrite freely there. - -### Guessing performance fixes - -Avoid changing `nprobes`, `refine_factor`, or index types before checking the query plan and index stats. Diagnose first, then tune one knob at a time. diff --git a/plugins/lancedb/skills/lancedb/references/python/performance.md b/plugins/lancedb/skills/lancedb/references/python/performance.md deleted file mode 100644 index 5fd27440b..000000000 --- a/plugins/lancedb/skills/lancedb/references/python/performance.md +++ /dev/null @@ -1,131 +0,0 @@ -# Python Performance Guidance - -Use this when writing Python code that ingests data, queries large tables, builds indexes, or investigates latency. - -## Ingestion - -### Recommended: validate schemas and records with Pydantic - -Favor `LanceModel` for readable Python schema definitions and validate source -records before writing. Use PyArrow directly for Arrow-native or streaming -pipelines where it is the clearer representation. - -```python -from lancedb.pydantic import LanceModel, Vector - -class Document(LanceModel): - id: int - text: str - vector: Vector(384, nullable=False) - -rows = [Document.model_validate(row) for row in source_rows] -table = db.create_table("documents", schema=Document) -table.add(rows) -``` - -### Recommended: bulk ingestion for materialized data - -```python -table.add(arrow_table) -table.add(df) -table.add(pa.dataset("data/", format="parquet")) -``` - -For very large initial loads, create the table empty first, then call `add(...)`. Passing data directly to `create_table(name, data)` can skip the auto-parallel write path. - -### Recommended: iterator ingestion for generated or streamed data - -```python -def batches(): - for raw in source: - vectors = model.encode(raw["text"]) - yield pa.RecordBatch.from_pydict({**raw, "vector": vectors}) - -table.add(batches()) -``` - -Use chunks of several thousand rows or more when practical. Tiny batches and per-row writes create many small fragments. - -### Anti-pattern: per-row `add()` - -```python -for row in rows: - table.add([row]) -``` - -Each call creates a version and fragment. This slows ingestion and later queries. - -## Indexing - -- Build a vector index once brute-force vector search becomes too slow. As a rule of thumb, local brute force is fine below roughly 100K vectors; beyond that, build an index. -- Use `IVF_PQ` as the general-purpose default. Enterprise builds this automatically. -- Use scalar indexes for filtered columns and merge/upsert keys. -- Use `BTREE` for mostly distinct numeric/string/temporal columns, `BITMAP` for booleans and low-cardinality columns, and `LABEL_LIST` for list membership queries. -- Keep full-text defaults unless phrase queries require position data. - -## Querying - -Always be explicit: - -```python -table.search(query_vector).select(["id", "title"]).limit(20) -``` - -- `select()` reduces bytes read and transferred. -- `limit()` prevents accidental full-table materialization. -- Pre-filtering is the default and guarantees returned rows satisfy the predicate. -- Use post-filtering only when fewer than `limit` results are acceptable. - -## Recall Tuning - -Tune one knob at a time: - -- Quantized indexes: raise `refine_factor` to rescore more candidates on full vectors. -- HNSW-backed indexes: raise `ef`; start around `1.5 * k`, increase toward `10 * k` if recall is short. -- IVF candidate breadth: `nprobes` is auto-tuned; override only when a selective pre-filter leaves too few neighbors. - -## Maintenance - -After every successful embedded OSS/local ingestion, call `table.optimize()`. -Do not add this to LanceDB Enterprise/Cloud remote table code; remote compaction -and cleanup are handled automatically based on the Enterprise cluster -configuration. - -Why local maintenance is needed: - -- Frequent writes can create many small fragments. Queries then need to scan across more files, which can increase latency. -- Updates, deletes, and appends create new table versions. Old versions are retained for time travel and rollback, which can grow disk usage. -- Indexes may have newly added rows that are not yet fully optimized into the index structure. - -For local/OSS tables, run `optimize()` after the final successful ingestion -write. Also run it after later batches of update/delete operations or on a -regular maintenance schedule: - -```python -table.optimize() -``` - -If the user wants more aggressive local disk cleanup, pass a shorter cleanup retention window: - -```python -from datetime import timedelta - -table.optimize(cleanup_older_than=timedelta(days=1)) -``` - -Do not use very short cleanup windows when the application depends on time travel, rollback, or old versions. - -## Diagnostics - -Before changing code or indexes, inspect: - -```python -print(table.search(query_vector).where("year > 2000").limit(10).analyze_plan()) -print(table.index_stats("vector_idx")) -``` - -Look for high scan bytes, missing indexes, fragmented data, and unindexed rows. - -## Python Multiprocessing - -When using multiprocessing, use `spawn` rather than `fork`. LanceDB is multi-threaded internally, and `fork` plus a multi-threaded process is unsafe. diff --git a/plugins/lancedb/skills/lancedb/references/typescript/api_reference.md b/plugins/lancedb/skills/lancedb/references/typescript/api_reference.md deleted file mode 100644 index c98f39a0c..000000000 --- a/plugins/lancedb/skills/lancedb/references/typescript/api_reference.md +++ /dev/null @@ -1,105 +0,0 @@ -# TypeScript API Reference - -Quick method reference for TypeScript LanceDB code. Cross-check source for non-trivial claims. - -## Connect - -```typescript -import * as lancedb from "@lancedb/lancedb"; - -const db = await lancedb.connect("./camelot-db"); -``` - -**Place the local database directory next to the script/entrypoint that opens it** (resolve the path relative to the module, e.g. via `import.meta.dirname` / `__dirname`), not buried under a shared `data/` folder. The Lance dataset is the database, not a data file — keeping it beside its code makes ownership obvious and paths stable regardless of the working directory the script is launched from. - -**Do not name the directory `lancedb`** (e.g. `./lancedb`, `./data/lancedb`). It collides with the imported `lancedb` package/namespace, which is confusing to read. Give it a name derived from the repo or dataset with a clear prefix/suffix — for example `./-db`, `./_lancedb`, or `./vectordb`. - -Remote connections use `db://...` plus Enterprise/Cloud credentials and deployment settings. Check current source/docs for exact connection options. - -## Table Reads - -| Task | Preferred API | -| --- | --- | -| Vector search | `table.search(queryVector).limit(k)` | -| Full scan with filters/projection | `table.query().where(...).select(...).limit(...)` | -| Filter | `.where("col > 10")` | -| Projection | `.select(["id", "text"])` | -| Bound result count | `.limit(20)` | -| Collect bounded result as objects | `.toArray()` on query/search result | -| Collect bounded result as Arrow | `.toArrow()` on query/search result | -| Stream result batches | `for await (const batch of table.query()...)` | - -## Local vs Remote Safety - -| API | Agent guidance | -| --- | --- | -| `table.search(...)` | Preferred read path | -| `table.query()` | Preferred scan/filter path | -| `await table.toArrow()` | Avoid in portable or large-table code | -| `await table.query().toArray()` with no `limit()` | Avoid; unbounded collection | -| `await table.query().toArrow()` with no `limit()` | Avoid; unbounded collection | - -## Indexes - -```typescript -await table.createIndex("vector"); -await table.createIndex("status"); -``` - -Use vector indexes for large vector search workloads and scalar indexes for filtered columns or merge/upsert keys. Check source/docs before specifying advanced index options. - -## Filtering And Recall Knobs - -```typescript -await table.search(queryVector).where("status = 'ready'").limit(10).toArray(); -await table.search(queryVector).limit(10).refineFactor(20).toArray(); -await table.search(queryVector).limit(10).nprobes(50).toArray(); -await table.search(queryVector).limit(10).ef(100).toArray(); -await table.search(queryVector).where("status = 'ready'").postfilter().limit(10).toArray(); -``` - -Use `postfilter()` only when fewer than `limit` results are acceptable. - -## Diagnostics - -```typescript -console.log(await table.search(queryVector).where("year > 2000").limit(10).analyzePlan()); -console.log(await table.indexStats("vector_idx")); -``` - -Use these before changing indexes or search tuning. - -## Column (Field) Metadata - -```typescript -const schema = await table.schema(); -const meta = schema.fields.find((f) => f.name === "category")?.metadata; // Map -const res = await table.updateFieldMetadata([ - { path: "category", metadata: { "lancedb:description": "...", "lancedb:tag:field_type": "label" } }, -]); -res.version; // new table version -``` - -Merges by default; a `null` value deletes that key; `replace: true` swaps the whole map. Nested fields use dot-paths (`"a.b.c"`). See `references/column_metadata.md` for key conventions (`lancedb:description`, `lancedb:tag:`, `lancedb:logical-column`) and the authoring workflow. - -## Branches - -```typescript -const branches = await table.branches(); // async manager -await branches.list(); // non-main branches; {} = only main -const exp = await branches.create("exp"); // fork off main -> Table scoped to the branch -const wip = await branches.checkout("wip"); // existing branch -> scoped Table (version arg pins read-only) -const wip2 = await db.openTable("t", { branch: "wip" }); // or open scoped directly -await branches.delete("stale"); // removes only the branch pointer -table.currentBranch(); // null = main -``` - -There is no global switch — scoping is per table handle: any read/write on a branch handle lands on that branch; the original handle keeps targeting main. See `references/branch_ops.md` for the model and isolation checks. - -## Maintenance - -```typescript -await table.optimize(); -``` - -Call this after every successful local/OSS ingestion. It handles compaction, cleanup of old versions according to retention, and index optimization. Do not add this for LanceDB Enterprise/Cloud remote tables; Enterprise handles compaction and cleanup automatically from cluster configuration. diff --git a/plugins/lancedb/skills/lancedb/references/typescript/patterns.md b/plugins/lancedb/skills/lancedb/references/typescript/patterns.md deleted file mode 100644 index 1aa380968..000000000 --- a/plugins/lancedb/skills/lancedb/references/typescript/patterns.md +++ /dev/null @@ -1,100 +0,0 @@ -# TypeScript Patterns - -Use these patterns when writing TypeScript code with `@lancedb/lancedb`. - -## Recommended Patterns - -### Bounded query - -Use this for application reads, scripts, and examples: - -```typescript -const rows = await table - .query() - .where("status = 'ready'") - .select(["id", "text"]) - .limit(20) - .toArray(); -``` - -### Bounded vector search - -```typescript -const rows = await table - .search(queryVector) - .select(["id", "text"]) - .limit(20) - .toArray(); -``` - -### Batch streaming for larger reads - -When the task needs many rows, avoid collecting everything at once: - -```typescript -for await (const batch of table - .query() - .where("status = 'ready'") - .select(["id", "text"]) - .limit(10_000)) { - process(batch); -} -``` - -## Anti-Patterns - -**Avoid the following anti-patterns in your code.** - -### Table-level full materialization - -Avoid whole-table collectors in portable or large-table code: - -```typescript -const tableArrow = await table.toArrow(); -``` - -Why: local tables expose these whole-table collectors, but remote tables intentionally do not — a remote production table can be far larger than a local development table, so it is easy to accidentally pull the entire table into memory. - -### Unbounded result collection - -Avoid query/search collection without a meaningful limit: - -```typescript -const rows = await table.query().toArray(); // unbounded plain scan -const rows = await table.search(queryVector).toArray(); // unbounded vector search -``` - -Prefer `select(...).limit(...)` before collecting; for large reads, stream in batches instead. - -### Per-row writes - -Avoid loops that write one row per call: - -```typescript -for (const row of rows) { - await table.add([row]); // one commit + fragment per row -} -``` - -Each `add()` creates a new version and fragment. Pass the whole batch in a single call, or chunk very large inputs: - -```typescript -await table.add(rows); // single commit -// for very large inputs, add in chunks of several thousand rows -``` - -### Drop-then-reuse the same table name (Enterprise/Cloud) - -Avoid dropping or overwriting a remote table and then reusing that name right away: - -```typescript -await db.dropTable("my_table"); -const table = await db.createTable("my_table", rows); // reads 500 for ~5 min -const table = await db.createTable("my_table", rows, { mode: "overwrite" }); // same problem -``` - -Why: Enterprise/Cloud splits DDL (control plane) from query serving (data plane). The data plane caches the dataset behind a table name for up to `table_cache_ttl` (default 300s / 5 min), so after a drop/overwrite the DDL succeeds but queries against the reused name return `500 Internal Server Error` until the cache expires — and a fresh `describe` may still show the old schema. Instead, write to a **fresh name**, use `tableNames()` and fail if it already exists, then `renameTable(fresh, final)` onto the final name only after the old table's drop has propagated (~5 min). See the "Enterprise: never drop-then-reuse the same table name" section in `SKILL.md`. Local/OSS tables have no separate data plane — overwrite freely there. - -### Guessing performance fixes - -Avoid changing `nprobes`, `refineFactor`, `ef`, or index settings before checking `analyzePlan()` and `indexStats(...)`. Diagnose first, then tune one knob at a time. diff --git a/plugins/lancedb/skills/lancedb/references/typescript/performance.md b/plugins/lancedb/skills/lancedb/references/typescript/performance.md deleted file mode 100644 index 9bf07e9ae..000000000 --- a/plugins/lancedb/skills/lancedb/references/typescript/performance.md +++ /dev/null @@ -1,78 +0,0 @@ -# TypeScript Performance Guidance - -Use this when writing TypeScript code that ingests data, queries large tables, builds indexes, or investigates latency. - -## Ingestion - -- Prefer bulk or batched writes. -- Avoid per-row write loops; they create many small commits/fragments. -- For generated data, accumulate reasonable batches before adding. -- For file-backed data, prefer APIs that stream from Arrow/Parquet-style inputs when available. - -## Indexing - -- Build a vector index once brute-force vector search becomes too slow. As a rule of thumb, local brute force is fine below roughly 100K vectors; beyond that, build an index. -- Use the general-purpose vector index defaults unless the task has explicit recall/latency requirements. -- Build scalar indexes for filtered columns and merge/upsert keys. -- Use full-text index phrase options only when phrase queries require them. - -## Querying - -Always be explicit: - -```typescript -await table.search(queryVector).select(["id", "title"]).limit(20).toArray(); -``` - -- `select()` reduces bytes read and transferred. -- `limit()` prevents accidental full-table collection. -- Pre-filtering is the default behavior. Use `postfilter()` only when fewer than `limit` results are acceptable. - -## Recall Tuning - -Tune one knob at a time: - -- Quantized indexes: raise `refineFactor(...)` to rescore more candidates on full vectors. -- HNSW-backed indexes: raise `ef(...)`; start around `1.5 * k`, increase toward `10 * k` if recall is short. -- IVF candidate breadth: `nprobes(...)` is usually auto-tuned; override only when a selective pre-filter leaves too few neighbors. - -## Maintenance - -After every successful embedded OSS/local ingestion, call `table.optimize()`. -Do not add this to LanceDB Enterprise/Cloud remote table code; remote compaction -and cleanup are handled automatically based on the Enterprise cluster -configuration. - -Why local maintenance is needed: - -- Frequent writes can create many small fragments. Queries then need to scan across more files, which can increase latency. -- Updates, deletes, and appends create new table versions. Old versions are retained for time travel and rollback, which can grow disk usage. -- Indexes may have newly added rows that are not yet fully optimized into the index structure. - -For local/OSS tables, run `optimize()` after the final successful ingestion -write. Also run it after later batches of update/delete operations or on a -regular maintenance schedule: - -```typescript -await table.optimize(); -``` - -If the user wants more aggressive local disk cleanup, pass a shorter cleanup retention window: - -```typescript -const olderThan = new Date(Date.now() - 24 * 60 * 60 * 1000); -await table.optimize({ cleanupOlderThan: olderThan }); -``` - -Do not use very short cleanup windows when the application depends on time travel, rollback, or old versions. - -## Diagnostics - -Before changing code or indexes, inspect: - -```typescript -console.log(await table.search(queryVector).where("year > 2000").limit(10).analyzePlan()); -console.log(await table.indexStats("vector_idx")); -``` - -Look for high scan cost, missing indexes, fragmented data, and unindexed rows. From 426684cf1b07306724261b986c7011e8b64abf9e Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 21 Aug 2026 15:48:09 +0800 Subject: [PATCH 057/206] feat: add first-class function wire contracts (#3985) ## Problem Enterprise Function-backed computed columns need a stable SDK contract before Sophon catalog and execution endpoints can be added. The existing `Job` API can only represent unit terminal results, and there is no shared Rust/Python wire definition for immutable Function versions, applications, bindings, or refresh results. ## Behavior This introduces remote-only canonical Function values in Rust and Python, evolves `Job` to decode typed remote terminal results while keeping local spawned operations unit-typed, and fixes the cross-language contract with shared JSON golden fixtures. Unknown fields and discriminator values remain forward-decodable, while canonical output contains only fields known to the client. Function models contain secret names only. Sophon remains the sole owner of catalog persistence, environment bake, secret resolution, execution, and publication. This PR does not add authoring/catalog endpoints, local execution, refresh runners, or live Sophon E2E coverage. --- docs/src/python/python.md | 41 +- python/python/lancedb/__init__.py | 6 + python/python/lancedb/functions.py | 379 ++++++++++++++ .../tests/test_first_class_function_slice1.py | 225 ++++++++ rust/lancedb/src/function.rs | 489 ++++++++++++++++++ rust/lancedb/src/job.rs | 134 ++++- rust/lancedb/src/lib.rs | 2 + rust/lancedb/src/remote/db.rs | 55 +- rust/lancedb/src/remote/job.rs | 160 ++++-- rust/lancedb/src/remote/table.rs | 6 +- .../tests/first_class_function_slice1.rs | 181 +++++++ ...remote_function_application.canonical.json | 1 + .../v1/remote_function_application.json | 20 + .../v1/remote_function_application_float.json | 8 + .../v1/remote_function_binding.canonical.json | 1 + .../v1/remote_function_binding.json | 15 + .../v1/remote_function_job.json | 31 ++ .../v1/remote_function_version.canonical.json | 1 + .../v1/remote_refresh_job.json | 15 + .../v1/remote_refresh_result.canonical.json | 1 + ...t_without_published_version.canonical.json | 1 + ...resh_result_without_published_version.json | 6 + .../v1/remote_unit_job.json | 9 + 23 files changed, 1679 insertions(+), 108 deletions(-) create mode 100644 python/python/lancedb/functions.py create mode 100644 python/python/tests/test_first_class_function_slice1.py create mode 100644 rust/lancedb/src/function.rs create mode 100644 rust/lancedb/tests/first_class_function_slice1.rs create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.canonical.json create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.json create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application_float.json create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.canonical.json create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.json create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_job.json create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_job.json create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_result.canonical.json create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_result_without_published_version.canonical.json create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_result_without_published_version.json create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_unit_job.json diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 1d5975dee..a99c0236a 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -54,6 +54,42 @@ listing a storage directory. ::: lancedb.LsmWriteSpec +## Functions and Jobs + +::: lancedb.functions.FunctionArtifact + +::: lancedb.functions.FunctionParameter + +::: lancedb.functions.FunctionResultField + +::: lancedb.functions.FunctionOutput + +::: lancedb.functions.FunctionSignature + +::: lancedb.functions.PythonEnvironmentSpec + +::: lancedb.functions.FunctionVersion + +::: lancedb.functions.PythonRuntimeSpec + +::: lancedb.functions.FunctionVersionRef + +::: lancedb.functions.ApplicationInput + +::: lancedb.functions.FunctionApplication + +::: lancedb.functions.InputBinding + +::: lancedb.functions.OutputMapping + +::: lancedb.functions.FunctionBinding + +::: lancedb.functions.RefreshColumnResult + +::: lancedb.job.Job + +::: lancedb.job.AsyncJob + ## Expressions Type-safe expression builder for filters and projections. Use these instead @@ -153,8 +189,9 @@ The same option is available on `lancedb.tokenize(...)` and the deprecated ```python import lancedb -tokens = list(lancedb.tokenize("acme makes searchable data", - custom_stop_words=["acme"])) +tokens = list( + lancedb.tokenize("acme makes searchable data", custom_stop_words=["acme"]) +) ``` ::: lancedb.tokenize diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index e12ef4e86..a8a336a6d 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -22,6 +22,12 @@ from .remote.db import RemoteDBConnection from .expr import Expr, col, lit, func from .schema import blob, vector, BlobType from .job import AsyncJob, Job +from .functions import ( + FunctionApplication as FunctionApplication, + FunctionBinding as FunctionBinding, + FunctionVersion as FunctionVersion, + PythonRuntimeSpec as PythonRuntimeSpec, +) from .table import AsyncTable, Table from .types import BaseTokenizerType from ._lancedb import Session diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py new file mode 100644 index 000000000..4ffb65e2c --- /dev/null +++ b/python/python/lancedb/functions.py @@ -0,0 +1,379 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Canonical values exchanged with LanceDB Enterprise Function services. + +These immutable models contain client/wire state only. Catalog persistence, +environment bake, secret resolution, and execution are owned by Sophon. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from typing import Any, Optional + +import pydantic +from pydantic import BaseModel, Field, conint + +_PYDANTIC_V2 = int(pydantic.VERSION.split(".", 1)[0]) >= 2 +if _PYDANTIC_V2: + from pydantic import field_validator, model_validator +else: + from pydantic import root_validator, validator + +_Int32 = conint(strict=True, ge=-(2**31), le=2**31 - 1) +_UInt32 = conint(strict=True, ge=0, le=2**32 - 1) +_UInt64 = conint(strict=True, ge=0, le=2**64 - 1) + + +class _FrozenDict(dict): + def _immutable(self, *args, **kwargs): + raise TypeError("remote canonical values are immutable") + + __setitem__ = _immutable + __delitem__ = _immutable + clear = _immutable + pop = _immutable + popitem = _immutable + setdefault = _immutable + update = _immutable + + def __ior__(self, other): + self._immutable() + + +def _freeze_value(value): + if isinstance(value, Mapping): + return _FrozenDict({key: _freeze_value(child) for key, child in value.items()}) + if isinstance(value, (list, tuple)): + return tuple(_freeze_value(child) for child in value) + return value + + +def _validate_literal(value): + if isinstance(value, float): + raise ValueError( + "floating-point Function literals are not part of the Slice 1 " + "canonical wire contract" + ) + if isinstance(value, int) and not isinstance(value, bool): + if not -(2**63) <= value <= 2**64 - 1: + raise ValueError( + "Function integer literal is outside the canonical JSON range" + ) + elif isinstance(value, Mapping): + for child in value.values(): + _validate_literal(child) + elif isinstance(value, (list, tuple)): + for child in value: + _validate_literal(child) + return value + + +def _known_wire_value(value): + if isinstance(value, _RemoteValue): + return value._known_dict() + if isinstance(value, Mapping): + return {key: _known_wire_value(child) for key, child in value.items()} + if isinstance(value, (list, tuple)): + return [_known_wire_value(child) for child in value] + return value + + +class _RemoteValue(BaseModel): + if _PYDANTIC_V2: + model_config = {"extra": "ignore", "frozen": True} + else: + + class Config: + allow_mutation = False + extra = "ignore" + + if _PYDANTIC_V2: + + @model_validator(mode="after") + def _freeze_mappings(self): + for name, value in self.__dict__.items(): + object.__setattr__(self, name, _freeze_value(value)) + return self + + else: + + @root_validator + def _freeze_mappings(cls, values): + return {name: _freeze_value(value) for name, value in values.items()} + + @classmethod + def from_json(cls, payload: str): + if _PYDANTIC_V2: + return cls.model_validate_json(payload) + return cls.parse_raw(payload) + + def _known_dict(self) -> dict[str, Any]: + fields = self.__class__.model_fields if _PYDANTIC_V2 else self.__fields__ + known = {} + for name, field in fields.items(): + value = getattr(self, name) + if value is None: + continue + required = field.is_required() if _PYDANTIC_V2 else field.required + if not required: + default_factory = field.default_factory + if default_factory is not None and value == default_factory(): + continue + if default_factory is None and value == field.default: + continue + known[name] = _known_wire_value(value) + return known + + def _copy(self, *, update: Mapping[str, Any]): + update = {name: _freeze_value(value) for name, value in update.items()} + if _PYDANTIC_V2: + return self.model_copy(update=update) + return self.copy(update=update) + + def to_canonical_json(self) -> str: + return json.dumps( + self._known_dict(), + ensure_ascii=False, + allow_nan=False, + sort_keys=True, + separators=(",", ":"), + ) + + +class FunctionArtifact(_RemoteValue): + """Content-addressed Python artifact identity.""" + + kind: str + digest: str + entrypoint: str + + +class FunctionParameter(_RemoteValue): + name: str + arrow_type: str + nullable: bool + + +class FunctionResultField(_RemoteValue): + name: str + arrow_type: str + nullable: bool + + +class FunctionOutput(_RemoteValue): + """Scalar or ordered named-struct output; unknown kinds remain decodable.""" + + kind: str + arrow_type: Optional[str] = None + nullable: Optional[bool] = None + fields: tuple[FunctionResultField, ...] = () + + +class FunctionSignature(_RemoteValue): + inputs: tuple[FunctionParameter, ...] + output: FunctionOutput + + +class PythonEnvironmentSpec(_RemoteValue): + """One Sophon-managed Python environment source.""" + + kind: str + packages: tuple[str, ...] = () + path: Optional[str] = None + modules: tuple[str, ...] = () + image: Optional[str] = None + + +class PythonRuntimeSpec(_RemoteValue): + """Remote runtime definition with non-secret environment values. + + V1 supports ``kind="python"``. Newer runtime kinds remain readable, while + their unknown payload fields are intentionally not retained by the client. + """ + + kind: str + python_version: Optional[str] = None + environment: Optional[PythonEnvironmentSpec] = None + env: Optional[Mapping[str, str]] = None + + if _PYDANTIC_V2: + + @model_validator(mode="after") + def _validate_runtime_kind(self): + if self.kind == "python": + if self.python_version is None: + raise ValueError("python runtime requires python_version") + if self.environment is None: + raise ValueError("python runtime requires environment") + else: + object.__setattr__(self, "python_version", None) + object.__setattr__(self, "environment", None) + object.__setattr__(self, "env", None) + return self + + else: + + @root_validator + def _validate_runtime_kind(cls, values): + if values.get("kind") == "python": + if values.get("python_version") is None: + raise ValueError("python runtime requires python_version") + if values.get("environment") is None: + raise ValueError("python runtime requires environment") + else: + values["python_version"] = None + values["environment"] = None + values["env"] = None + return values + + +class FunctionVersion(_RemoteValue): + """An exact immutable Function version returned by Enterprise. + + Scheduling resources, priority, concurrency, and retry policy belong to + the submitting Job and are not part of this identity. + """ + + name: str + version: str + artifact: FunctionArtifact + signature: FunctionSignature + runtime: PythonRuntimeSpec + runtime_digest: str + environment_digest: str + required_secrets: tuple[str, ...] = () + created_at: str + + +class FunctionVersionRef(_RemoteValue): + name: str + version: str + + +class ApplicationInput(_RemoteValue): + """One parameter value. + + Slice 1 freezes integers, strings, booleans, nulls, arrays, and objects. + Floating-point literal encoding is deferred until Python authoring is + introduced with a language-neutral numeric representation. + """ + + parameter: str + kind: str + value: Any + + if _PYDANTIC_V2: + + @field_validator("value") + @classmethod + def _validate_value(cls, value): + return _validate_literal(value) + + else: + + @validator("value") + def _validate_value(cls, value): + return _validate_literal(value) + + +class FunctionApplication(_RemoteValue): + """Immutable pre-declaration application of an exact Function version.""" + + function: FunctionVersionRef + inputs: tuple[ApplicationInput, ...] + output: FunctionOutput + group_id: str + columns: Mapping[str, str] = Field(default_factory=dict) + + def rename(self, *, columns: Mapping[str, str]) -> FunctionApplication: + """Return a copy with result-field to table-column aliases.""" + if self.output.kind != "named_struct": + raise ValueError("rename(columns=...) requires a named-struct application") + result_fields = {field.name for field in self.output.fields} + unknown = set(columns) - result_fields + if unknown: + raise ValueError(f"unknown Function result fields: {sorted(unknown)!r}") + merged = dict(self.columns) + merged.update(columns) + destinations = tuple( + merged.get(field.name, field.name) for field in self.output.fields + ) + if len(set(destinations)) != len(destinations): + raise ValueError("FunctionApplication rename destinations must be unique") + return self._copy(update={"columns": merged}) + + +class InputBinding(_RemoteValue): + parameter: str + field_id: _Int32 + field_path: str + arrow_type: str + nullable: bool + + +class OutputMapping(_RemoteValue): + """One stable result-field mapping. + + Assignment state is outside the Slice 1 client contract. During the NULL + transition Lance exposes no public cell-flag identifier to persist here. + """ + + result_field: str + output_name: str + output_field_id: _Int32 + output_ordinal: _UInt32 + arrow_type: str + nullable: bool + + +class FunctionBinding(_RemoteValue): + """Immutable grouped binding persisted by the Enterprise table service.""" + + binding_id: str + revision: _UInt64 + function: FunctionVersionRef + group_id: str + inputs: tuple[InputBinding, ...] + outputs: tuple[OutputMapping, ...] + + +class RefreshColumnResult(_RemoteValue): + """Terminal result of a remote Function-column refresh Job.""" + + rows_assigned: _UInt64 + rows_failed: _UInt64 + rows_remaining: _UInt64 + source_version: _UInt64 + published_version: Optional[_UInt64] = None + + @property + def rows_filled(self) -> int: + """Deprecated compatibility alias for :attr:`rows_assigned`.""" + return self.rows_assigned + + @property + def version(self) -> Optional[int]: + """Deprecated compatibility alias for :attr:`published_version`.""" + return self.published_version + + +__all__ = [ + "ApplicationInput", + "FunctionApplication", + "FunctionArtifact", + "FunctionBinding", + "FunctionOutput", + "FunctionParameter", + "FunctionResultField", + "FunctionSignature", + "FunctionVersion", + "FunctionVersionRef", + "InputBinding", + "OutputMapping", + "PythonEnvironmentSpec", + "PythonRuntimeSpec", + "RefreshColumnResult", +] diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py new file mode 100644 index 000000000..9f934507f --- /dev/null +++ b/python/python/tests/test_first_class_function_slice1.py @@ -0,0 +1,225 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import json +from pathlib import Path + +import pytest + +import lancedb.functions as functions +from lancedb.functions import ( + FunctionApplication, + FunctionBinding, + FunctionVersion, + PythonRuntimeSpec, + RefreshColumnResult, +) + + +FIXTURES = ( + Path(__file__).parents[3] + / "rust" + / "lancedb" + / "tests" + / "fixtures" + / "first_class_functions" + / "v1" +) + + +def fixture(name: str) -> str: + return (FIXTURES / name).read_text() + + +def job_result(name: str) -> dict: + return json.loads(fixture(name))["result"] + + +def assert_no_secret_values(value): + if isinstance(value, dict): + for key, child in value.items(): + assert key not in { + "secret_value", + "secret_values", + "resolved_secret", + "resolved_secrets", + } + assert_no_secret_values(child) + elif isinstance(value, list): + for child in value: + assert_no_secret_values(child) + + +def test_public_function_values_are_in_api_reference(): + docs = Path(__file__).parents[3] / "docs" / "src" / "python" / "python.md" + rendered = docs.read_text() + for name in functions.__all__: + assert f"::: lancedb.functions.{name}" in rendered + + +@pytest.mark.parametrize( + ("fixture_name", "canonical_name", "model", "nested_result"), + [ + ( + "remote_function_job.json", + "remote_function_version.canonical.json", + FunctionVersion, + True, + ), + ( + "remote_function_application.json", + "remote_function_application.canonical.json", + FunctionApplication, + False, + ), + ( + "remote_function_binding.json", + "remote_function_binding.canonical.json", + FunctionBinding, + False, + ), + ( + "remote_refresh_job.json", + "remote_refresh_result.canonical.json", + RefreshColumnResult, + True, + ), + ( + "remote_refresh_result_without_published_version.json", + "remote_refresh_result_without_published_version.canonical.json", + RefreshColumnResult, + False, + ), + ], +) +def test_python_and_rust_share_remote_canonical_goldens( + fixture_name, canonical_name, model, nested_result +): + value = json.loads(fixture(fixture_name)) + if nested_result: + value = value["result"] + decoded = model.from_json(json.dumps(value)) + assert decoded.to_canonical_json() == fixture(canonical_name).strip() + + +def test_function_version_identity_is_immutable_and_exact(): + value = job_result("remote_function_job.json") + version = FunctionVersion.from_json(json.dumps(value)) + assert version.name == "embed" + assert version.version == "fv_01K3EXACT" + assert version.required_secrets == ("HF_TOKEN",) + + with pytest.raises((TypeError, ValueError)): + version.version = "fv_changed" + with pytest.raises(TypeError, match="immutable"): + version.runtime.env["TOKENIZERS_PARALLELISM"] = "true" + + changed = dict(value) + changed["version"] = "fv_changed" + assert FunctionVersion(**changed) != version + + +def test_unknown_fields_and_discriminators_are_forward_decodable(): + value = job_result("remote_function_job.json") + value["future_version_metadata"] = {"retention_class": "catalog"} + value["runtime"] = {"kind": "wasm", "module_digest": "sha256:wasm"} + value["signature"]["output"]["kind"] = "future_output_shape" + + version = FunctionVersion.from_json(json.dumps(value)) + assert version.runtime.kind == "wasm" + assert version.runtime.python_version is None + assert version.runtime.environment is None + assert json.loads(version.to_canonical_json())["runtime"] == {"kind": "wasm"} + assert version.signature.output.kind == "future_output_shape" + + +def test_function_application_uses_rename_columns_only(): + application = FunctionApplication.from_json( + fixture("remote_function_application.json") + ) + renamed = application.rename(columns={"normalized_text": "body_normalized"}) + + assert application.columns["normalized_text"] == "search_text" + assert renamed.columns["normalized_text"] == "body_normalized" + assert renamed.function == application.function + assert renamed.group_id == application.group_id + assert not hasattr(application, "rename_outputs") + with pytest.raises(TypeError, match="immutable"): + renamed.columns["normalized_text"] = "changed" + with pytest.raises(TypeError, match="immutable"): + application.inputs[0].value["path"] = "changed" + + with pytest.raises(ValueError, match="unknown Function result fields"): + application.rename(columns={"missing": "search_text"}) + with pytest.raises(ValueError, match="destinations must be unique"): + application.rename(columns={"normalized_text": "same", "token_count": "same"}) + + bare_value = json.loads(fixture("remote_function_application.json")) + bare_value.pop("columns") + bare = FunctionApplication(**bare_value) + with pytest.raises(ValueError, match="destinations must be unique"): + bare.rename(columns={"normalized_text": "token_count"}) + + +def test_binding_and_refresh_result_keep_stable_remote_fields(): + binding = FunctionBinding.from_json(fixture("remote_function_binding.json")) + assert binding.revision == 3 + assert binding.function.version == "fv_01K3TEXT" + assert [output.output_ordinal for output in binding.outputs] == [0, 1] + + result = RefreshColumnResult.from_json( + json.dumps(job_result("remote_refresh_job.json")) + ) + assert result.rows_filled == result.rows_assigned + assert result.version == result.published_version + + result = RefreshColumnResult.from_json( + fixture("remote_refresh_result_without_published_version.json") + ) + assert result.published_version is None + assert RefreshColumnResult.from_json(result.to_canonical_json()) == result + + +def test_function_literal_numeric_domain_matches_rust(): + with pytest.raises(ValueError, match="floating-point Function literals"): + FunctionApplication.from_json(fixture("remote_function_application_float.json")) + + value = json.loads(fixture("remote_function_application_float.json")) + value["inputs"][0]["value"] = 2**64 + with pytest.raises(ValueError, match="outside the canonical JSON range"): + FunctionApplication.from_json(json.dumps(value)) + + +def test_empty_default_maps_have_stable_canonical_bytes(): + runtime = PythonRuntimeSpec( + kind="python", python_version="3.12", environment={"kind": "pip"} + ) + assert runtime.to_canonical_json() == ( + '{"environment":{"kind":"pip"},"kind":"python","python_version":"3.12"}' + ) + + value = json.loads(fixture("remote_function_application.json")) + value.pop("columns") + application = FunctionApplication.from_json(json.dumps(value)) + assert "columns" not in json.loads(application.to_canonical_json()) + + +@pytest.mark.parametrize("field", ["rows_assigned", "source_version"]) +def test_refresh_result_rejects_non_u64_values(field): + value = job_result("remote_refresh_job.json") + value[field] = -1 + with pytest.raises(ValueError): + RefreshColumnResult.from_json(json.dumps(value)) + + value[field] = "1" + with pytest.raises(ValueError): + RefreshColumnResult.from_json(json.dumps(value)) + + +def test_canonical_client_values_contain_secret_names_only(): + version = FunctionVersion.from_json( + json.dumps(job_result("remote_function_job.json")) + ) + canonical = json.loads(version.to_canonical_json()) + assert canonical["required_secrets"] == ["HF_TOKEN"] + assert_no_secret_values(canonical) diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs new file mode 100644 index 000000000..087a00b90 --- /dev/null +++ b/rust/lancedb/src/function.rs @@ -0,0 +1,489 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Canonical values exchanged with the Enterprise Function service. +//! +//! This module contains client/wire values only. Catalog persistence, +//! environment bake, secret resolution, and execution are owned by Sophon. + +use std::collections::BTreeMap; + +use serde::de::{self, DeserializeOwned}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde_json::Value; + +use crate::{Error, Result}; + +fn invalid_json(error: impl std::fmt::Display) -> Error { + Error::InvalidInput { + message: format!("invalid remote Function JSON: {error}"), + } +} + +fn write_canonical_json(value: &Value, output: &mut String) -> serde_json::Result<()> { + match value { + Value::Object(map) => { + output.push('{'); + let mut entries = map.iter().collect::>(); + entries.sort_unstable_by_key(|(key, _)| *key); + for (index, (key, value)) in entries.into_iter().enumerate() { + if index != 0 { + output.push(','); + } + output.push_str(&serde_json::to_string(key)?); + output.push(':'); + write_canonical_json(value, output)?; + } + output.push('}'); + } + Value::Array(values) => { + output.push('['); + for (index, value) in values.iter().enumerate() { + if index != 0 { + output.push(','); + } + write_canonical_json(value, output)?; + } + output.push(']'); + } + other => output.push_str(&serde_json::to_string(other)?), + } + Ok(()) +} + +fn canonical_json(value: &T) -> Result { + let value = serde_json::to_value(value).map_err(invalid_json)?; + let mut output = String::new(); + write_canonical_json(&value, &mut output).map_err(invalid_json)?; + Ok(output) +} + +fn from_json(json: &str) -> Result { + serde_json::from_str(json).map_err(invalid_json) +} + +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" + .to_string(), + }), + Value::Array(values) => values.iter().try_for_each(validate_literal), + Value::Object(values) => values.values().try_for_each(validate_literal), + _ => Ok(()), + } +} + +macro_rules! impl_json { + ($type:ty) => { + impl $type { + /// Decode a remote value. Unknown fields and discriminator values + /// are accepted so newer servers remain readable. + pub fn from_json(json: &str) -> Result { + from_json(json) + } + + /// Encode the known client contract with bytewise-sorted JSON keys. + pub fn to_canonical_json(&self) -> Result { + canonical_json(self) + } + } + }; +} + +/// Packaged Python artifact identity. Source bytes are never part of this value. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionArtifact { + pub kind: String, + pub digest: String, + pub entrypoint: String, +} + +/// One ordered Arrow input parameter. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionParameter { + pub name: String, + pub arrow_type: String, + pub nullable: bool, +} + +/// One field of an ordered named-struct result. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionResultField { + pub name: String, + pub arrow_type: String, + pub nullable: bool, +} + +/// Scalar or named-struct Function output. +/// +/// `kind` remains a string so unknown future result shapes can be decoded. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionOutput { + pub kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub arrow_type: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub nullable: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub fields: Vec, +} + +/// Ordered language-neutral Function signature. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionSignature { + pub inputs: Vec, + pub output: FunctionOutput, +} + +/// One Python environment source. +/// +/// The selected source is interpreted by Sophon. `kind` is open for forward +/// compatible decoding. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PythonEnvironmentSpec { + pub kind: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub packages: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub path: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub modules: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub image: Option, +} + +/// Reproducible Python runtime definition understood by Sophon. +/// +/// `env` contains non-secret values. Secret values have no client model; +/// [`FunctionVersion::required_secrets`] contains names only. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum PythonRuntimeSpec { + /// The V1 Sophon-managed Python runtime. + Python { + python_version: String, + environment: PythonEnvironmentSpec, + env: BTreeMap, + }, + /// A runtime kind introduced by a newer server. + /// + /// Unknown payload fields are intentionally not retained because the + /// client does not proxy catalog values. + Unrecognized { kind: String }, +} + +impl PythonRuntimeSpec { + /// The wire discriminator reported by Sophon. + pub fn kind(&self) -> &str { + match self { + Self::Python { .. } => "python", + Self::Unrecognized { kind } => kind, + } + } + + /// The Python version for the V1 runtime, or `None` for an unknown kind. + pub fn python_version(&self) -> Option<&str> { + match self { + Self::Python { python_version, .. } => Some(python_version), + Self::Unrecognized { .. } => None, + } + } + + /// The Python environment for the V1 runtime, or `None` for an unknown kind. + pub fn environment(&self) -> Option<&PythonEnvironmentSpec> { + match self { + Self::Python { environment, .. } => Some(environment), + Self::Unrecognized { .. } => None, + } + } + + /// Non-secret environment variables, or `None` for an unknown kind. + pub fn env(&self) -> Option<&BTreeMap> { + match self { + Self::Python { env, .. } => Some(env), + Self::Unrecognized { .. } => None, + } + } +} + +#[derive(Deserialize)] +struct PythonRuntimeWire { + kind: String, + #[serde(default)] + python_version: Option, + #[serde(default)] + environment: Option, + #[serde(default)] + env: BTreeMap, +} + +impl<'de> Deserialize<'de> for PythonRuntimeSpec { + fn deserialize>(deserializer: D) -> std::result::Result { + let wire = PythonRuntimeWire::deserialize(deserializer)?; + if wire.kind == "python" { + Ok(Self::Python { + python_version: wire + .python_version + .ok_or_else(|| de::Error::missing_field("python_version"))?, + environment: wire + .environment + .ok_or_else(|| de::Error::missing_field("environment"))?, + env: wire.env, + }) + } else { + Ok(Self::Unrecognized { kind: wire.kind }) + } + } +} + +impl Serialize for PythonRuntimeSpec { + fn serialize(&self, serializer: S) -> std::result::Result { + #[derive(Serialize)] + struct PythonRuntimeRef<'a> { + kind: &'static str, + python_version: &'a str, + environment: &'a PythonEnvironmentSpec, + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + env: &'a BTreeMap, + } + + #[derive(Serialize)] + struct UnrecognizedRuntimeRef<'a> { + kind: &'a str, + } + + match self { + Self::Python { + python_version, + environment, + env, + } => PythonRuntimeRef { + kind: "python", + python_version, + environment, + env, + } + .serialize(serializer), + Self::Unrecognized { kind } => UnrecognizedRuntimeRef { kind }.serialize(serializer), + } + } +} + +/// Immutable Function version returned by the Enterprise catalog. +/// +/// Scheduling resources, priority, concurrency, and retry policy belong to +/// the submitting Job and are not part of this identity. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionVersion { + name: String, + version: String, + artifact: FunctionArtifact, + signature: FunctionSignature, + runtime: PythonRuntimeSpec, + runtime_digest: String, + environment_digest: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + required_secrets: Vec, + created_at: String, +} + +impl FunctionVersion { + pub fn name(&self) -> &str { + &self.name + } + + pub fn version(&self) -> &str { + &self.version + } + + pub fn artifact(&self) -> &FunctionArtifact { + &self.artifact + } + + pub fn signature(&self) -> &FunctionSignature { + &self.signature + } + + pub fn runtime(&self) -> &PythonRuntimeSpec { + &self.runtime + } + + pub fn runtime_digest(&self) -> &str { + &self.runtime_digest + } + + pub fn environment_digest(&self) -> &str { + &self.environment_digest + } + + /// Required secret names. Resolved values exist only inside Sophon. + pub fn required_secrets(&self) -> &[String] { + &self.required_secrets + } + + pub fn created_at(&self) -> &str { + &self.created_at + } +} + +impl_json!(FunctionVersion); + +/// Exact FunctionVersion reference embedded in applications and bindings. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionVersionRef { + pub name: String, + pub version: String, +} + +/// Parameter binding in a FunctionApplication. +/// +/// `kind` remains open until Python authoring is added in Slice 2. Slice 1 +/// freezes JSON integers, strings, booleans, nulls, arrays, and objects as +/// canonical literal values. Floating-point literals are rejected until a +/// language-neutral numeric representation is defined. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ApplicationInput { + pub parameter: String, + pub kind: String, + pub value: Value, +} + +/// Pre-declaration application of an exact FunctionVersion. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct FunctionApplication { + function: FunctionVersionRef, + inputs: Vec, + output: FunctionOutput, + group_id: String, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + columns: BTreeMap, +} + +impl FunctionApplication { + pub fn function(&self) -> &FunctionVersionRef { + &self.function + } + + pub fn inputs(&self) -> &[ApplicationInput] { + &self.inputs + } + + pub fn output(&self) -> &FunctionOutput { + &self.output + } + + pub fn group_id(&self) -> &str { + &self.group_id + } + + pub fn columns(&self) -> &BTreeMap { + &self.columns + } + + /// Decode a remote application after validating the Slice 1 literal domain. + pub fn from_json(json: &str) -> Result { + let application: Self = from_json(json)?; + application + .inputs + .iter() + .try_for_each(|input| validate_literal(&input.value))?; + Ok(application) + } + + /// Encode the application with bytewise-sorted JSON keys. + pub fn to_canonical_json(&self) -> Result { + self.inputs + .iter() + .try_for_each(|input| validate_literal(&input.value))?; + canonical_json(self) + } +} + +/// Stable table input bound to a registered parameter. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct InputBinding { + pub parameter: String, + pub field_id: i32, + pub field_path: String, + pub arrow_type: String, + pub nullable: bool, +} + +/// Ordered result-field to table-field mapping for a grouped binding. +/// +/// Assignment state is not part of the Slice 1 client contract. During the +/// NULL transition there is no public Lance cell-flag identifier to persist. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct OutputMapping { + pub result_field: String, + pub output_name: String, + pub output_field_id: i32, + pub output_ordinal: u32, + pub arrow_type: String, + pub nullable: bool, +} + +/// Immutable grouped binding persisted by the Enterprise table service. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionBinding { + binding_id: String, + revision: u64, + function: FunctionVersionRef, + group_id: String, + inputs: Vec, + outputs: Vec, +} + +impl FunctionBinding { + pub fn binding_id(&self) -> &str { + &self.binding_id + } + + pub fn revision(&self) -> u64 { + self.revision + } + + pub fn function(&self) -> &FunctionVersionRef { + &self.function + } + + pub fn group_id(&self) -> &str { + &self.group_id + } + + pub fn inputs(&self) -> &[InputBinding] { + &self.inputs + } + + pub fn outputs(&self) -> &[OutputMapping] { + &self.outputs + } +} + +impl_json!(FunctionBinding); + +/// Stable terminal result of a remote Function-column refresh Job. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RefreshColumnResult { + pub rows_assigned: u64, + pub rows_failed: u64, + pub rows_remaining: u64, + pub source_version: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub published_version: Option, +} + +impl RefreshColumnResult { + /// Deprecated compatibility alias for `rows_assigned`. + pub fn rows_filled(&self) -> u64 { + self.rows_assigned + } + + /// Deprecated compatibility alias for `published_version`. + pub fn version(&self) -> Option { + self.published_version + } +} + +impl_json!(RefreshColumnResult); diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index d77dd6974..0f880e398 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -6,6 +6,8 @@ use std::sync::Arc; use async_trait::async_trait; +use serde::de::DeserializeOwned; +use serde_json::Value; use tokio::sync::watch; use tokio::task::{AbortHandle, JoinHandle}; @@ -19,43 +21,127 @@ pub(crate) trait JobHandle: Send + Sync { None } async fn status(&self) -> Result; - async fn wait(&self) -> Result<()>; + async fn wait(&self) -> Result; async fn cancel(&self) -> Result<()>; } +/// A backend-neutral successful terminal result. +/// +/// Local operations do not carry a value. Remote operations may carry JSON +/// that the public [`Job`] decodes according to its result type. +pub(crate) struct TerminalResult { + #[allow(dead_code)] // Typed remote submit endpoints consume this after Slice 1. + value: Option, + #[allow(dead_code)] // Preserved so typed decode errors retain request correlation. + request_id: Option, +} + +impl TerminalResult { + pub(crate) fn local() -> Self { + Self { + value: None, + request_id: None, + } + } + + pub(crate) fn remote(value: Option, request_id: String) -> Self { + Self { + value, + request_id: Some(request_id), + } + } + + #[allow(dead_code)] // Exercised by the remote typed-result fixtures in Slice 1. + fn decode(self) -> Result { + let request_id = self.request_id.unwrap_or_default(); + let value = self.value.ok_or_else(|| Error::Http { + source: "successful typed job response did not contain a result".into(), + request_id: request_id.clone(), + status_code: None, + })?; + serde_json::from_value(value).map_err(|error| Error::Http { + source: format!("failed to parse typed job result: {error}").into(), + request_id, + status_code: None, + }) + } +} + +type ResultDecoder = fn(TerminalResult) -> Result; + +enum JobInner { + Handle { + handle: Box, + decode: ResultDecoder, + }, + Completed(T), +} + /// A handle to an operation that may still be running. /// /// The operation may already be complete when the handle is created. -pub struct Job { - handle: Option>, +pub struct Job +where + T: Clone + Send + Sync + 'static, +{ + inner: JobInner, } -impl std::fmt::Debug for Job { +impl std::fmt::Debug for Job +where + T: Clone + Send + Sync + 'static, +{ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Job") .field("id", &self.id()) - .field("done", &self.handle.is_none()) + .field("done", &matches!(self.inner, JobInner::Completed(_))) .finish() } } -impl Job { +impl Job<()> { /// A job whose operation finished before the handle was created. pub(crate) fn new_done() -> Self { - Self { handle: None } + Self { + inner: JobInner::Completed(()), + } } pub(crate) fn new(handle: Box) -> Self { Self { - handle: Some(handle), + inner: JobInner::Handle { + handle, + decode: |_| Ok(()), + }, } } - /// A job running as a task in this process. + /// A unit-result job running as a task in this process. pub(crate) fn spawned(task: JoinHandle>) -> Self { Self::new(Box::new(SpawnedJob::new(task))) } +} +impl Job +where + T: Clone + DeserializeOwned + Send + Sync + 'static, +{ + /// Construct a typed remote Job before result-specific submit APIs are added. + #[allow(dead_code)] + pub(crate) fn new_typed(handle: Box) -> Self { + Self { + inner: JobInner::Handle { + handle, + decode: TerminalResult::decode::, + }, + } + } +} + +impl Job +where + T: Clone + Send + Sync + 'static, +{ /// Identifies the operation on the server that is running it. /// /// Returned for correlating with server logs or the jobs API. Operations @@ -63,7 +149,10 @@ impl Job { /// value is opaque: parsing it or storing it to resume the job later is /// not supported. pub fn id(&self) -> Option<&str> { - self.handle.as_ref().and_then(|handle| handle.id()) + match &self.inner { + JobInner::Handle { handle, .. } => handle.id(), + JobInner::Completed(_) => None, + } } /// The operation's current lifecycle state: "running", "finished", @@ -73,9 +162,9 @@ impl Job { /// terminal failure state, or retry. States a newer server reports that /// this client version does not know pass through as-is. pub async fn status(&self) -> Result { - match &self.handle { - None => Ok("finished".to_string()), - Some(handle) => handle.status().await, + match &self.inner { + JobInner::Handle { handle, .. } => handle.status().await, + JobInner::Completed(_) => Ok("finished".to_string()), } } @@ -83,10 +172,10 @@ impl Job { /// /// Returns [`crate::Error::JobFailed`] if the operation failed and /// [`crate::Error::JobCancelled`] if it was cancelled. - pub async fn wait(&self) -> Result<()> { - match &self.handle { - None => Ok(()), - Some(handle) => handle.wait().await, + pub async fn wait(&self) -> Result { + match &self.inner { + JobInner::Handle { handle, decode } => decode(handle.wait().await?), + JobInner::Completed(result) => Ok(result.clone()), } } @@ -94,9 +183,9 @@ impl Job { /// /// Cancelling an operation that already finished is a no-op. pub async fn cancel(&self) -> Result<()> { - match &self.handle { - None => Ok(()), - Some(handle) => handle.cancel().await, + match &self.inner { + JobInner::Handle { handle, .. } => handle.cancel().await, + JobInner::Completed(_) => Ok(()), } } } @@ -162,7 +251,7 @@ impl JobHandle for SpawnedJob { Ok(label.to_string()) } - async fn wait(&self) -> Result<()> { + async fn wait(&self) -> Result { let mut outcome = self.outcome.clone(); let settled = outcome .wait_for(|outcome| outcome.is_some()) @@ -172,7 +261,8 @@ impl JobHandle for SpawnedJob { })? .clone() .expect("wait_for returns once an outcome is set"); - settled.into_result() + settled.into_result()?; + Ok(TerminalResult::local()) } async fn cancel(&self) -> Result<()> { diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index 70d023ccc..291dcaf65 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -181,6 +181,7 @@ pub mod dataloader; pub mod embeddings; pub mod error; pub mod expr; +pub mod function; pub mod index; pub mod io; pub mod ipc; @@ -205,6 +206,7 @@ use serde::{Deserialize, Serialize}; pub use blob::{BlobRangeRequest, blob, is_blob}; pub use connection::{ConnectNamespaceBuilder, Connection}; pub use error::{Error, JobFailure, Result}; +pub use function::FunctionVersion; pub use job::Job; use lance_index::vector::ApproxMode as LanceApproxMode; use lance_linalg::distance::DistanceType as LanceDistanceType; diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 45a0bd925..03a13cb4e 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -25,7 +25,7 @@ use crate::database::{ }; use crate::error::Result; use crate::job::Job; -use crate::remote::job::RemoteJob; +use crate::remote::job::{DescribeJobResponse, RemoteJob, job_state_to_client}; use crate::remote::util::stream_as_body; use crate::table::BaseTable; @@ -472,48 +472,6 @@ struct RemoteListJobsResponse { page_token: Option, } -/// The server's account of why a job failed. Absent from older servers, -/// which report only the terminal state. -#[derive(serde::Deserialize)] -struct RemoteReportedFailure { - #[serde(default)] - phase: Option, - #[serde(default)] - message: Option, - #[serde(default)] - retryable: Option, -} - -#[derive(serde::Deserialize)] -struct RemoteDescribeJobResponse { - job_id: String, - #[serde(default)] - job_type: String, - job_state: String, - #[serde(default)] - creation_ms: i64, - #[serde(default)] - spec: serde_json::Value, - #[serde(default)] - failure: Option, -} - -/// Server job states -> the client vocabulary ("running" / "finished" / -/// "failed" / "cancelled"). Covers both the describe enum (IN_PROGRESS / -/// DONE / FAILED / CANCELLED) and the registry's lowercase list-row states -/// (in_progress / succeeded / failed / canceled / timed_out). States this -/// client version does not know (e.g. created, queued) pass through as-is. -fn job_state_to_client(state: &str) -> String { - match state { - "IN_PROGRESS" | "in_progress" => "running", - "DONE" | "done" | "succeeded" => "finished", - "FAILED" | "failed" | "TIMED_OUT" | "timed_out" => "failed", - "CANCELLED" | "cancelled" | "canceled" => "cancelled", - other => other, - } - .to_string() -} - /// Bound on `list_jobs` page walking; a warning is logged when the listing /// is truncated at this many pages. const MAX_LIST_JOBS_PAGES: usize = 100; @@ -586,19 +544,14 @@ impl Database for RemoteDatabase { }) => return Ok(None), Err(err) => return Err(err), }; - let body: RemoteDescribeJobResponse = rsp.json().await.err_to_http(request_id)?; + let body: DescribeJobResponse = rsp.json().await.err_to_http(request_id)?; Ok(Some(JobDescription { job_id: body.job_id, job_type: body.job_type, state: job_state_to_client(&body.job_state), creation_ms: body.creation_ms, spec: body.spec, - failure: body.failure.map(|reported| crate::error::JobFailure { - phase: reported.phase, - message: reported.message, - retryable: reported.retryable, - source: None, - }), + failure: body.failure.map(|reported| reported.into_job_failure()), })) } @@ -2507,7 +2460,7 @@ mod tests { http::Response::builder() .status(200) .body(format!( - r#"{{"job_id": "job-1", "job_type": "create_index", "job_state": "{}", "creation_ms": 1}}"#, + r#"{{"job_id": "job-1", "job_type": "create_function", "job_state": "{}", "creation_ms": 1, "result": {{"name": "embed", "version": "fv_1"}}}}"#, state )) .unwrap() diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 2fc99da59..0d41dbb35 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -8,10 +8,10 @@ use std::time::Duration; use async_trait::async_trait; use tokio::time::sleep; -use serde::{Deserialize, Deserializer}; +use serde::Deserialize; use crate::error::{Error, JobFailure, Result}; -use crate::job::JobHandle; +use crate::job::{JobHandle, TerminalResult}; use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; /// Delay before the second job-state poll; doubles up to [`MAX_POLL_INTERVAL`]. @@ -29,12 +29,6 @@ enum JobState { Other(String), } -impl<'de> Deserialize<'de> for JobState { - fn deserialize>(deserializer: D) -> std::result::Result { - Ok(Self::from(String::deserialize(deserializer)?.as_str())) - } -} - impl JobState { /// The client vocabulary label for this state. fn client_label(&self) -> String { @@ -51,22 +45,26 @@ impl JobState { impl From<&str> for JobState { fn from(state: &str) -> Self { match state { - "IN_PROGRESS" => Self::InProgress, - "CANCELLED" => Self::Cancelled, + "IN_PROGRESS" | "in_progress" => Self::InProgress, + "CANCELLED" | "cancelled" | "canceled" => Self::Cancelled, // The server reports a timed-out job as FAILED on describe; // accept the raw registry state too in case a future server // stops folding it. - "FAILED" | "TIMED_OUT" => Self::Failed, - "DONE" => Self::Done, + "FAILED" | "failed" | "TIMED_OUT" | "timed_out" => Self::Failed, + "DONE" | "done" | "succeeded" => Self::Done, other => Self::Other(other.to_string()), } } } +pub(super) fn job_state_to_client(state: &str) -> String { + JobState::from(state).client_label() +} + /// The server's account of why a job failed. Absent from older servers, which /// report only the terminal state. #[derive(Deserialize)] -struct ReportedFailure { +pub(super) struct ReportedFailure { #[serde(default)] phase: Option, #[serde(default)] @@ -75,11 +73,43 @@ struct ReportedFailure { retryable: Option, } +/// Forward-compatible `/v1/jobs/describe` wire envelope. #[derive(Deserialize)] -struct DescribeJobResponse { - job_state: JobState, +pub(super) struct DescribeJobResponse { #[serde(default)] - failure: Option, + pub(super) job_id: String, + #[serde(default)] + pub(super) job_type: String, + pub(super) job_state: String, + #[serde(default)] + pub(super) creation_ms: i64, + #[serde(default)] + pub(super) spec: serde_json::Value, + #[serde(default)] + result: Option, + #[serde(default)] + pub(super) failure: Option, +} + +impl ReportedFailure { + pub(super) fn into_job_failure(self) -> JobFailure { + JobFailure { + phase: self.phase, + message: self.message, + retryable: self.retryable, + source: None, + } + } +} + +impl DescribeJobResponse { + fn state(&self) -> JobState { + JobState::from(self.job_state.as_str()) + } + + fn into_terminal_result(self, request_id: String) -> TerminalResult { + TerminalResult::remote(self.result, request_id) + } } pub struct RemoteJob { @@ -93,7 +123,7 @@ impl RemoteJob { } /// One `/v1/jobs/describe` round trip. - async fn describe(&self) -> Result { + async fn describe(&self) -> Result<(String, DescribeJobResponse)> { let request = self .client .post("/v1/jobs/describe") @@ -104,10 +134,10 @@ impl RemoteJob { let description: DescribeJobResponse = serde_json::from_str(&body).map_err(|e| Error::Http { source: format!("failed to parse job description: {}", e).into(), - request_id, + request_id: request_id.clone(), status_code: None, })?; - Ok(description) + Ok((request_id, description)) } } @@ -118,26 +148,21 @@ impl JobHandle for RemoteJob { } async fn status(&self) -> Result { - Ok(self.describe().await?.job_state.client_label()) + Ok(self.describe().await?.1.state().client_label()) } - async fn wait(&self) -> Result<()> { + async fn wait(&self) -> Result { let mut interval = INITIAL_POLL_INTERVAL; loop { - let description = self.describe().await?; - match description.job_state { - JobState::Done => return Ok(()), + let (request_id, description) = self.describe().await?; + match description.state() { + JobState::Done => return Ok(description.into_terminal_result(request_id)), JobState::Failed => { return Err(Error::JobFailed { job_id: Some(self.job_id.clone()), failure: description .failure - .map(|reported| JobFailure { - phase: reported.phase, - message: reported.message, - retryable: reported.retryable, - source: None, - }) + .map(ReportedFailure::into_job_failure) .unwrap_or_default(), }); } @@ -168,3 +193,78 @@ impl JobHandle for RemoteJob { .map(|_| ()) } } + +#[cfg(test)] +mod tests { + use async_trait::async_trait; + + use crate::Result; + use crate::function::{FunctionVersion, RefreshColumnResult}; + use crate::job::{Job, JobHandle, TerminalResult}; + + use super::DescribeJobResponse; + + const FUNCTION_JOB: &str = + include_str!("../../tests/fixtures/first_class_functions/v1/remote_function_job.json"); + const REFRESH_JOB: &str = + include_str!("../../tests/fixtures/first_class_functions/v1/remote_refresh_job.json"); + const UNIT_JOB: &str = + include_str!("../../tests/fixtures/first_class_functions/v1/remote_unit_job.json"); + const MISSING_RESULT_JOB: &str = r#"{"job_state":"DONE"}"#; + + struct FixtureRemoteJob(&'static str); + + #[async_trait] + impl JobHandle for FixtureRemoteJob { + async fn status(&self) -> Result { + Ok("finished".to_string()) + } + + async fn wait(&self) -> Result { + let description: DescribeJobResponse = + serde_json::from_str(self.0).expect("remote job fixture"); + Ok(description.into_terminal_result("fixture-request".to_string())) + } + + async fn cancel(&self) -> Result<()> { + Ok(()) + } + } + + #[tokio::test] + async fn typed_remote_job_fixtures_decode_terminal_results() { + let function = Job::::new_typed(Box::new(FixtureRemoteJob(FUNCTION_JOB))); + let result = function.wait().await.expect("typed FunctionVersion result"); + assert_eq!(result.version(), "fv_01K3EXACT"); + + let refresh = + Job::::new_typed(Box::new(FixtureRemoteJob(REFRESH_JOB))); + let result = refresh.wait().await.expect("typed RefreshColumnResult"); + assert_eq!(result.rows_assigned, 999_998_800); + assert_eq!(result.rows_filled(), result.rows_assigned); + + let unit = Job::new(Box::new(FixtureRemoteJob(UNIT_JOB))); + unit.wait() + .await + .expect("unit result ignores additive remote payloads"); + } + + #[tokio::test] + async fn typed_remote_job_requires_a_terminal_result() { + let typed = + Job::::new_typed(Box::new(FixtureRemoteJob(MISSING_RESULT_JOB))); + let error = typed.wait().await.unwrap_err(); + assert!( + error + .to_string() + .contains("successful typed job response did not contain a result") + ); + } + + #[test] + fn remote_wire_unknown_fields_are_forward_decodable() { + let response: DescribeJobResponse = + serde_json::from_str(FUNCTION_JOB).expect("function job fixture"); + assert_eq!(response.job_state, "DONE"); + } +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index a0a4cebc2..328f2a708 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -162,13 +162,13 @@ impl crate::job::JobHandle for FreshnessJob { crate::job::JobHandle::status(&self.inner).await } - async fn wait(&self) -> Result<()> { - crate::job::JobHandle::wait(&self.inner).await?; + async fn wait(&self) -> Result { + let result = crate::job::JobHandle::wait(&self.inner).await?; let version = self.version.read().await; if version.is_none() { self.freshness.lock().unwrap().checkout_baseline = Some(SystemTime::now()); } - Ok(()) + Ok(result) } async fn cancel(&self) -> Result<()> { diff --git a/rust/lancedb/tests/first_class_function_slice1.rs b/rust/lancedb/tests/first_class_function_slice1.rs new file mode 100644 index 000000000..dab05fe48 --- /dev/null +++ b/rust/lancedb/tests/first_class_function_slice1.rs @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::fs; +use std::path::PathBuf; + +use lancedb::function::{ + FunctionApplication, FunctionBinding, FunctionVersion, RefreshColumnResult, +}; +use serde_json::Value; + +fn fixture(name: &str) -> String { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/first_class_functions/v1") + .join(name); + fs::read_to_string(path).expect("fixture must be readable") +} + +fn job_result(name: &str) -> Value { + serde_json::from_str::(&fixture(name)).expect("remote Job fixture")["result"].clone() +} + +fn assert_no_secret_values(value: &Value) { + match value { + Value::Object(values) => { + for (key, value) in values { + assert!( + !matches!( + key.as_str(), + "secret_value" | "secret_values" | "resolved_secret" | "resolved_secrets" + ), + "client canonical value must not model resolved secret material" + ); + assert_no_secret_values(value); + } + } + Value::Array(values) => values.iter().for_each(assert_no_secret_values), + _ => {} + } +} + +#[test] +fn function_version_job_result_matches_shared_canonical_golden() { + let result = job_result("remote_function_job.json"); + let version = FunctionVersion::from_json(&result.to_string()).expect("FunctionVersion result"); + + assert_eq!(version.name(), "embed"); + assert_eq!(version.version(), "fv_01K3EXACT"); + assert_eq!(version.runtime_digest(), "sha256:runtime"); + assert_eq!(version.required_secrets(), &["HF_TOKEN"]); + assert_eq!( + version.to_canonical_json().expect("canonical JSON"), + fixture("remote_function_version.canonical.json").trim() + ); +} + +#[test] +fn version_identity_is_immutable_and_exact() { + let original = job_result("remote_function_job.json"); + let version = + FunctionVersion::from_json(&original.to_string()).expect("FunctionVersion result"); + let reopened = version.clone(); + assert_eq!(reopened, version); + assert_eq!(reopened.name(), version.name()); + assert_eq!(reopened.version(), version.version()); + + let mut changed = original; + changed["version"] = Value::String("fv_01K3DIFFERENT".to_string()); + let changed = FunctionVersion::from_json(&changed.to_string()).expect("changed version"); + assert_ne!(changed, version); +} + +#[test] +fn application_and_binding_match_shared_remote_goldens() { + let application = FunctionApplication::from_json(&fixture("remote_function_application.json")) + .expect("application fixture"); + assert_eq!(application.function().version, "fv_01K3TEXT"); + assert_eq!(application.output().kind, "named_struct"); + assert_eq!(application.inputs().len(), 2); + assert_eq!( + application.to_canonical_json().expect("canonical JSON"), + fixture("remote_function_application.canonical.json").trim() + ); + + let binding = FunctionBinding::from_json(&fixture("remote_function_binding.json")) + .expect("binding fixture"); + assert_eq!(binding.revision(), 3); + assert_eq!(binding.function().version, "fv_01K3TEXT"); + assert_eq!(binding.outputs()[0].output_ordinal, 0); + assert_eq!(binding.outputs()[1].output_ordinal, 1); + assert_eq!( + binding.to_canonical_json().expect("canonical JSON"), + fixture("remote_function_binding.canonical.json").trim() + ); +} + +#[test] +fn refresh_job_result_matches_shared_canonical_golden() { + let result = job_result("remote_refresh_job.json"); + let result = RefreshColumnResult::from_json(&result.to_string()).expect("refresh result"); + assert_eq!(result.rows_assigned, 999_998_800); + assert_eq!(result.rows_filled(), result.rows_assigned); + assert_eq!(result.version(), result.published_version); + assert_eq!( + result.to_canonical_json().expect("canonical JSON"), + fixture("remote_refresh_result.canonical.json").trim() + ); + + let result = RefreshColumnResult::from_json(&fixture( + "remote_refresh_result_without_published_version.json", + )) + .expect("optional version"); + assert_eq!(result.published_version, None); + assert_eq!( + result + .to_canonical_json() + .expect("canonical result without version"), + fixture("remote_refresh_result_without_published_version.canonical.json").trim() + ); + assert_eq!( + RefreshColumnResult::from_json( + &result + .to_canonical_json() + .expect("canonical result without version") + ) + .expect("round-trip result without version"), + result + ); +} + +#[test] +fn unknown_fields_and_discriminators_are_forward_decodable() { + let mut result = job_result("remote_function_job.json"); + result["future_version_metadata"] = serde_json::json!({"retention_class": "catalog"}); + result["runtime"] = serde_json::json!({ + "kind": "wasm", + "module_digest": "sha256:wasm" + }); + result["signature"]["output"]["kind"] = Value::String("future_output_shape".to_string()); + + let version = FunctionVersion::from_json(&result.to_string()).expect("future remote value"); + assert_eq!(version.runtime().kind(), "wasm"); + assert_eq!(version.runtime().python_version(), None); + 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")["runtime"], + serde_json::json!({"kind": "wasm"}) + ); +} + +#[test] +fn floating_point_application_literals_are_rejected_consistently() { + let error = FunctionApplication::from_json(&fixture("remote_function_application_float.json")) + .unwrap_err(); + assert!( + error + .to_string() + .contains("floating-point Function literals") + ); +} + +#[test] +fn canonical_client_values_contain_secret_names_only() { + let result = job_result("remote_function_job.json"); + let version = FunctionVersion::from_json(&result.to_string()).expect("FunctionVersion result"); + let canonical: Value = serde_json::from_str( + &version + .to_canonical_json() + .expect("canonical FunctionVersion"), + ) + .expect("canonical JSON"); + + assert_eq!( + canonical["required_secrets"], + serde_json::json!(["HF_TOKEN"]) + ); + assert_no_secret_values(&canonical); +} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.canonical.json new file mode 100644 index 000000000..05da9fe39 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.canonical.json @@ -0,0 +1 @@ +{"columns":{"normalized_text":"search_text","token_count":"search_token_count"},"function":{"name":"text_features","version":"fv_01K3TEXT"},"group_id":"fg_01K3TEXT","inputs":[{"kind":"column","parameter":"title","value":{"path":"title"}},{"kind":"column","parameter":"body","value":{"path":"body"}}],"output":{"fields":[{"arrow_type":"utf8","name":"normalized_text","nullable":false},{"arrow_type":"int64","name":"token_count","nullable":false}],"kind":"named_struct"}} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.json new file mode 100644 index 000000000..44aeff460 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.json @@ -0,0 +1,20 @@ +{ + "function": {"name": "text_features", "version": "fv_01K3TEXT"}, + "inputs": [ + {"parameter": "title", "kind": "column", "value": {"path": "title"}}, + {"parameter": "body", "kind": "column", "value": {"path": "body"}} + ], + "output": { + "kind": "named_struct", + "fields": [ + {"name": "normalized_text", "arrow_type": "utf8", "nullable": false}, + {"name": "token_count", "arrow_type": "int64", "nullable": false} + ] + }, + "group_id": "fg_01K3TEXT", + "columns": { + "normalized_text": "search_text", + "token_count": "search_token_count" + }, + "future_application": {"declaration_mode": "managed"} +} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application_float.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application_float.json new file mode 100644 index 000000000..47724eee0 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application_float.json @@ -0,0 +1,8 @@ +{ + "function": {"name": "score", "version": "fv_01K3FLOAT"}, + "inputs": [ + {"parameter": "threshold", "kind": "literal", "value": 1e-7} + ], + "output": {"kind": "scalar", "arrow_type": "bool", "nullable": false}, + "group_id": "fg_01K3FLOAT" +} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.canonical.json new file mode 100644 index 000000000..c548c4a58 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.canonical.json @@ -0,0 +1 @@ +{"binding_id":"fb_01K3TEXT","function":{"name":"text_features","version":"fv_01K3TEXT"},"group_id":"fg_01K3TEXT","inputs":[{"arrow_type":"utf8","field_id":11,"field_path":"title","nullable":true,"parameter":"title"},{"arrow_type":"utf8","field_id":12,"field_path":"body","nullable":true,"parameter":"body"}],"outputs":[{"arrow_type":"utf8","nullable":false,"output_field_id":21,"output_name":"search_text","output_ordinal":0,"result_field":"normalized_text"},{"arrow_type":"int64","nullable":false,"output_field_id":22,"output_name":"search_token_count","output_ordinal":1,"result_field":"token_count"}],"revision":3} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.json new file mode 100644 index 000000000..5d8193eea --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.json @@ -0,0 +1,15 @@ +{ + "binding_id": "fb_01K3TEXT", + "revision": 3, + "function": {"name": "text_features", "version": "fv_01K3TEXT"}, + "group_id": "fg_01K3TEXT", + "inputs": [ + {"parameter": "title", "field_id": 11, "field_path": "title", "arrow_type": "utf8", "nullable": true}, + {"parameter": "body", "field_id": 12, "field_path": "body", "arrow_type": "utf8", "nullable": true} + ], + "outputs": [ + {"result_field": "normalized_text", "output_name": "search_text", "output_field_id": 21, "output_ordinal": 0, "arrow_type": "utf8", "nullable": false}, + {"result_field": "token_count", "output_name": "search_token_count", "output_field_id": 22, "output_ordinal": 1, "arrow_type": "int64", "nullable": false} + ], + "future_binding": {"metadata_revision": 1} +} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_job.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_job.json new file mode 100644 index 000000000..6ba4eb226 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_job.json @@ -0,0 +1,31 @@ +{ + "job_id": "job_function_01K3", + "job_type": "create_function", + "job_state": "DONE", + "creation_ms": 1787270400000, + "spec": {"name": "embed"}, + "result": { + "name": "embed", + "version": "fv_01K3EXACT", + "artifact": { + "kind": "python_callable", + "digest": "sha256:code", + "entrypoint": "embed" + }, + "signature": { + "inputs": [{"name": "text", "arrow_type": "utf8", "nullable": true}], + "output": {"kind": "scalar", "arrow_type": "list", "nullable": false} + }, + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": {"kind": "pip", "packages": ["sentence-transformers>=3"]}, + "env": {"TOKENIZERS_PARALLELISM": "false"} + }, + "runtime_digest": "sha256:runtime", + "environment_digest": "sha256:environment", + "required_secrets": ["HF_TOKEN"], + "created_at": "2026-08-21T00:00:00Z" + }, + "future_job": {"trace_id": "trace-1"} +} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json new file mode 100644 index 000000000..7ab632a98 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json @@ -0,0 +1 @@ +{"artifact":{"digest":"sha256:code","entrypoint":"embed","kind":"python_callable"},"created_at":"2026-08-21T00:00:00Z","environment_digest":"sha256:environment","name":"embed","required_secrets":["HF_TOKEN"],"runtime":{"env":{"TOKENIZERS_PARALLELISM":"false"},"environment":{"kind":"pip","packages":["sentence-transformers>=3"]},"kind":"python","python_version":"3.12"},"runtime_digest":"sha256:runtime","signature":{"inputs":[{"arrow_type":"utf8","name":"text","nullable":true}],"output":{"arrow_type":"list","kind":"scalar","nullable":false}},"version":"fv_01K3EXACT"} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_job.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_job.json new file mode 100644 index 000000000..bb2490bc8 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_job.json @@ -0,0 +1,15 @@ +{ + "job_id": "job_refresh_01K3", + "job_type": "refresh_function_columns", + "job_state": "DONE", + "creation_ms": 1787270400001, + "spec": {"table": "documents", "binding_revision": 3}, + "result": { + "rows_assigned": 999998800, + "rows_failed": 0, + "rows_remaining": 0, + "source_version": 812, + "published_version": 919, + "future_result": {"committed_fragment_groups": 100} + } +} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_result.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_result.canonical.json new file mode 100644 index 000000000..cda9287a3 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_result.canonical.json @@ -0,0 +1 @@ +{"published_version":919,"rows_assigned":999998800,"rows_failed":0,"rows_remaining":0,"source_version":812} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_result_without_published_version.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_result_without_published_version.canonical.json new file mode 100644 index 000000000..69c9c96c1 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_result_without_published_version.canonical.json @@ -0,0 +1 @@ +{"rows_assigned":120,"rows_failed":0,"rows_remaining":0,"source_version":812} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_result_without_published_version.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_result_without_published_version.json new file mode 100644 index 000000000..27231411e --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_result_without_published_version.json @@ -0,0 +1,6 @@ +{ + "rows_assigned": 120, + "rows_failed": 0, + "rows_remaining": 0, + "source_version": 812 +} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_unit_job.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_unit_job.json new file mode 100644 index 000000000..7f2b4c6de --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_unit_job.json @@ -0,0 +1,9 @@ +{ + "job_id": "job_index_01K3", + "job_type": "create_index", + "job_state": "DONE", + "creation_ms": 1787270400002, + "spec": {"column": "vector"}, + "result": {"future_information": "ignored by Job<()>"}, + "future_job": {"trace_id": "trace-2"} +} From c1331e5083fd662231a9fc8b23c763c5fbd53b04 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 21 Aug 2026 16:19:55 +0800 Subject: [PATCH 058/206] chore: remove repo-scoped lancedb skill reference (#3993) Remove the `.agents/skills/lancedb` symlink and its README documentation so the plugin-provided skill is no longer discovered as a repo-scoped skill. --- .agents/skills/README.md | 4 ---- .agents/skills/lancedb | 1 - 2 files changed, 5 deletions(-) delete mode 120000 .agents/skills/lancedb diff --git a/.agents/skills/README.md b/.agents/skills/README.md index d4e3dc45d..296ae3f86 100644 --- a/.agents/skills/README.md +++ b/.agents/skills/README.md @@ -5,7 +5,3 @@ This directory contains repo-scoped code agent skills for the LanceDB project. Each skill is a folder that contains a required `SKILL.md` and optional bundled resources. Codex discovers skills from `.agents/skills` in the current working directory and parent directories. - -The `lancedb` skill lives in the `plugins/lancedb` plugin (see `plugins/lancedb/skills/lancedb`) -so it can be installed via the plugin marketplaces (`.claude-plugin/marketplace.json` and -`.agents/plugins/marketplace.json`); the `lancedb` entry here is a symlink into that plugin. diff --git a/.agents/skills/lancedb b/.agents/skills/lancedb deleted file mode 120000 index 1a303efd6..000000000 --- a/.agents/skills/lancedb +++ /dev/null @@ -1 +0,0 @@ -../../plugins/lancedb/skills/lancedb \ No newline at end of file From 7adcffc2b4ca34ab20bb778f46ba58bd92ef9696 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 21 Aug 2026 16:37:48 +0800 Subject: [PATCH 059/206] fix(python): set LsmWriteSpec module metadata (#3995) PyO3 exposed `LsmWriteSpec` with its default `builtins` module, causing mkdocstrings to resolve the public `lancedb.LsmWriteSpec` re-export as `builtins.LsmWriteSpec` and fail the documentation build. Declare the native extension module and pin the public re-export with a regression test. This also applies the repository's current Ruff formatter to seven previously unformatted Python scripts. --- ci/check_breaking_changes.py | 3 ++- ci/check_lance_release.py | 17 ++++++++++++++--- ci/mock_openai.py | 15 +++++++++------ ci/semver_sort.py | 1 + ci/set_lance_version.py | 6 +++--- ci/validate_stable_lance.py | 2 +- .../lancedb/scripts/check_materialization.py | 4 +++- python/python/tests/test_lsm_write_spec.py | 5 +++++ python/src/table.rs | 2 +- 9 files changed, 39 insertions(+), 16 deletions(-) diff --git a/ci/check_breaking_changes.py b/ci/check_breaking_changes.py index bc7a562b8..e31eedf0c 100644 --- a/ci/check_breaking_changes.py +++ b/ci/check_breaking_changes.py @@ -2,6 +2,7 @@ Check whether there are any breaking changes in the PRs between the base and head commits. If there are, assert that we have incremented the minor version. """ + import argparse import os from packaging.version import parse @@ -27,7 +28,7 @@ if __name__ == "__main__": else: print("No breaking changes found.") exit(0) - + last_stable_version = parse(args.last_stable_version) current_version = parse(args.current_version) if current_version.minor <= last_stable_version.minor: diff --git a/ci/check_lance_release.py b/ci/check_lance_release.py index 47f1cdbde..9fff955ac 100755 --- a/ci/check_lance_release.py +++ b/ci/check_lance_release.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 """Determine whether a newer Lance tag exists and expose results for CI.""" + from __future__ import annotations import argparse @@ -36,8 +37,16 @@ class SemVer: prerelease: Tuple[Union[int, str], ...] def __lt__(self, other: "SemVer") -> bool: # pragma: no cover - simple comparison - if (self.major, self.minor, self.patch) != (other.major, other.minor, other.patch): - return (self.major, self.minor, self.patch) < (other.major, other.minor, other.patch) + if (self.major, self.minor, self.patch) != ( + other.major, + other.minor, + other.patch, + ): + return (self.major, self.minor, self.patch) < ( + other.major, + other.minor, + other.patch, + ) if self.prerelease == other.prerelease: return False if not self.prerelease: @@ -142,7 +151,9 @@ def read_current_version(repo_root: Path) -> str: deps = data["workspace"]["dependencies"] entry = deps["lance"] except KeyError as exc: # pragma: no cover - configuration guard - raise RuntimeError("Failed to locate workspace.dependencies.lance in Cargo.toml") from exc + raise RuntimeError( + "Failed to locate workspace.dependencies.lance in Cargo.toml" + ) from exc if isinstance(entry, str): raw_version = entry diff --git a/ci/mock_openai.py b/ci/mock_openai.py index da3cb6c46..4fcb62ad9 100644 --- a/ci/mock_openai.py +++ b/ci/mock_openai.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors """A zero-dependency mock OpenAI embeddings API endpoint for testing purposes.""" + import argparse import json import http.server @@ -22,11 +23,13 @@ class MockOpenAIRequestHandler(http.server.BaseHTTPRequestHandler): data = [] for i in range(num_inputs): - data.append({ - "object": "embedding", - "embedding": [0.1] * 1536, - "index": i, - }) + data.append( + { + "object": "embedding", + "embedding": [0.1] * 1536, + "index": i, + } + ) response = { "object": "list", @@ -35,7 +38,7 @@ class MockOpenAIRequestHandler(http.server.BaseHTTPRequestHandler): "usage": { "prompt_tokens": 0, "total_tokens": 0, - } + }, } self.send_response(200) diff --git a/ci/semver_sort.py b/ci/semver_sort.py index b90ba3319..5f99c6c4f 100644 --- a/ci/semver_sort.py +++ b/ci/semver_sort.py @@ -7,6 +7,7 @@ from packaging.version import parse, InvalidVersion if __name__ == "__main__": import argparse + parser = argparse.ArgumentParser() parser.add_argument("prefix", default="v") args = parser.parse_args() diff --git a/ci/set_lance_version.py b/ci/set_lance_version.py index e8c573ad4..f66761644 100644 --- a/ci/set_lance_version.py +++ b/ci/set_lance_version.py @@ -22,7 +22,7 @@ def run_command(command: str) -> str: def get_latest_stable_version() -> str: version_line = run_command("cargo info lance | grep '^version:'") # Example output: "version: 0.35.0 (latest 0.37.0)" - match = re.search(r'\(latest ([0-9.]+)\)', version_line) + match = re.search(r"\(latest ([0-9.]+)\)", version_line) if match: return match.group(1) # Fallback: use the first version after 'version:' @@ -69,7 +69,7 @@ def extract_default_features(line: str) -> bool: """ import re - match = re.search(r'default-features\s*=\s*false', line) + match = re.search(r"default-features\s*=\s*false", line) return match is not None @@ -104,7 +104,7 @@ def dict_to_toml_line(package_name: str, config: dict) -> str: # This shouldn't happen with our current usage parts.append(f'"{key}" = {json.dumps(value)}') - return f'{package_name} = {{ {", ".join(parts)} }}\n' + return f"{package_name} = {{ {', '.join(parts)} }}\n" def update_cargo_toml(line_updater): diff --git a/ci/validate_stable_lance.py b/ci/validate_stable_lance.py index 4edd4c522..240e64174 100644 --- a/ci/validate_stable_lance.py +++ b/ci/validate_stable_lance.py @@ -12,7 +12,7 @@ with open("Cargo.toml", "rb") as f: elif isinstance(dep, dict): # Version doesn't have the beta tag in it, so we instead look # at the git tag. - version = dep.get('tag', dep.get('version')) + version = dep.get("tag", dep.get("version")) else: raise ValueError("Unexpected type for dependency: " + str(dep)) diff --git a/plugins/lancedb/skills/lancedb/scripts/check_materialization.py b/plugins/lancedb/skills/lancedb/scripts/check_materialization.py index cbd8abc04..6b0f117a1 100644 --- a/plugins/lancedb/skills/lancedb/scripts/check_materialization.py +++ b/plugins/lancedb/skills/lancedb/scripts/check_materialization.py @@ -64,7 +64,9 @@ def scan_python(path: Path, text: str) -> list[Finding]: def statement_around(text: str, start: int, end: int) -> str: before = max(text.rfind(";", 0, start), text.rfind("\n\n", 0, start)) - after_candidates = [pos for pos in (text.find(";", end), text.find("\n\n", end)) if pos != -1] + after_candidates = [ + pos for pos in (text.find(";", end), text.find("\n\n", end)) if pos != -1 + ] after = min(after_candidates) if after_candidates else len(text) return text[before + 1 : after].strip() diff --git a/python/python/tests/test_lsm_write_spec.py b/python/python/tests/test_lsm_write_spec.py index 218793b89..d43cb7532 100644 --- a/python/python/tests/test_lsm_write_spec.py +++ b/python/python/tests/test_lsm_write_spec.py @@ -21,6 +21,11 @@ SCHEMA = pa.schema( ) +def test_lsm_write_spec_module_metadata(): + assert lancedb.LsmWriteSpec is LsmWriteSpec + assert LsmWriteSpec.__module__ == "lancedb._lancedb" + + def _batch(ids, vs): return pa.RecordBatch.from_arrays( [pa.array(ids, type=pa.utf8()), pa.array(vs, type=pa.int32())], diff --git a/python/src/table.rs b/python/src/table.rs index 35ee92dc4..0e3eb4cf8 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -262,7 +262,7 @@ fn fmt_maintained(maintained: &Option>) -> String { /// classmethods, then optionally chain `with_maintained_indexes(...)` and /// `with_writer_config_defaults(...)`. A fresh spec maintains every index the /// MemWAL supports, resolved on install. -#[pyclass(from_py_object)] +#[pyclass(module = "lancedb._lancedb", from_py_object)] #[derive(Clone, Debug)] pub struct LsmWriteSpec { inner: lancedb::table::LsmWriteSpec, From 09843410ecd370356c2ad1a4ea334ee986e4bc4b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 21 Aug 2026 16:42:59 +0800 Subject: [PATCH 060/206] build: avoid fat LTO in local Cargo profiles (#3996) Local benchmarks currently inherit the release profile's fat LTO and single codegen unit, making local iteration pay release-artifact build costs. Provide repository-defined profiles for no-LTO local work and cheaper benchmark builds, and document when each profile is appropriate. Release artifacts continue to use fat LTO. --- .cargo/config.toml | 12 ++++++++++++ AGENTS.md | 3 +++ rust/lancedb/examples/bench_open_missing_table.rs | 4 ++-- rust/lancedb/examples/bench_streaming_dataloader.rs | 4 ++-- 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/.cargo/config.toml b/.cargo/config.toml index 0a4e3990e..95f9e7df4 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -9,6 +9,18 @@ debug = true codegen-units = 16 lto = "thin" +[profile.release-no-lto] +inherits = "release" +debug = true +lto = false +# Prioritize compile time when LTO is not relevant to the measurement. +codegen-units = 16 + +[profile.bench] +inherits = "release" +lto = "thin" +codegen-units = 16 + [target.'cfg(all())'] rustflags = [ "-Wclippy::all", diff --git a/AGENTS.md b/AGENTS.md index 21631a2cd..1e072446a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,6 +18,9 @@ Common commands: * Run specific test: `cargo test --quiet --features remote -p --test ` * Lint: `cargo clippy --quiet --features remote --tests --examples` * Format Rust: `cargo fmt --all` +* Use repository-defined Cargo profiles instead of ad hoc LTO overrides. +* Use `release-with-debug` for benchmarks and profiling so optimized builds keep debug symbols without a rebuild. +* Use `release-no-lto` only for local debugging, IO-bound benchmarks, or compile-time-sensitive performance investigation where LTO would not affect the measured bottleneck. * Format Python: `ruff format .` * Lint Python: `ruff check .` * Bootstrap Python dev env: `cd python && uv run --extra tests --extra dev maturin develop --extras tests,dev` diff --git a/rust/lancedb/examples/bench_open_missing_table.rs b/rust/lancedb/examples/bench_open_missing_table.rs index 8e6b16e11..fbfddf86c 100644 --- a/rust/lancedb/examples/bench_open_missing_table.rs +++ b/rust/lancedb/examples/bench_open_missing_table.rs @@ -1,14 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -// Release benchmark for opening a missing table as sibling-table cardinality grows. +// Benchmark for opening a missing table as sibling-table cardinality grows. // // The fixture uses real `.lance` directories and marker files. Fixture creation is // outside the timed section. Defaults intentionally cover 1k, 10k, and 100k siblings // with 10 warmups and 100 distinct missing-table opens per scale: // // ```text -// cargo run --release -p lancedb --example bench_open_missing_table +// cargo run --profile release-no-lto -p lancedb --example bench_open_missing_table // ``` // // `BENCH_SIBLINGS`, `BENCH_WARMUPS`, and `BENCH_TRIALS` override those defaults. diff --git a/rust/lancedb/examples/bench_streaming_dataloader.rs b/rust/lancedb/examples/bench_streaming_dataloader.rs index 087268ff8..a46d924d1 100644 --- a/rust/lancedb/examples/bench_streaming_dataloader.rs +++ b/rust/lancedb/examples/bench_streaming_dataloader.rs @@ -5,10 +5,10 @@ //! streaming dataloader. //! //! Normal sweep: -//! cargo run --release --example bench_streaming_dataloader +//! cargo run --profile release-with-debug --example bench_streaming_dataloader //! //! Flamegraph (self-contained, no perf/dtrace needed): -//! BENCH_PROFILE=1 BENCH_CHUNK=64 cargo run --release \ +//! BENCH_PROFILE=1 BENCH_CHUNK=64 cargo run --profile release-with-debug \ //! --example bench_streaming_dataloader //! # writes flamegraph.svg in the current directory //! From 4ba24212545b8cf31bbe8f5fe865a8f8ae5e1052 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 21 Aug 2026 16:50:00 +0800 Subject: [PATCH 061/206] refactor(python): require pydantic v2 (#3990) LanceDB's Python SDK now requires Pydantic `>=2.7.4,<3` and uses the v2 APIs throughout. This removes dual-version behavior from schema conversion, query serialization, embedding models, and Function wire models while preserving their existing public and canonical-wire behavior. The minimum-dependencies CI job pins Pydantic 2.7.4 so the declared compatibility floor remains covered. --- .github/workflows/python.yml | 6 +- docs/requirements.txt | 4 +- python/pyproject.toml | 2 +- python/python/lancedb/embeddings/base.py | 1 - python/python/lancedb/embeddings/bedrock.py | 11 +- .../python/lancedb/embeddings/gemini_text.py | 11 +- python/python/lancedb/embeddings/imagebind.py | 11 +- .../python/lancedb/embeddings/transformers.py | 11 +- python/python/lancedb/functions.py | 113 ++++++------------ python/python/lancedb/pydantic.py | 106 ++-------------- python/python/lancedb/query.py | 16 +-- python/python/tests/test_pydantic.py | 22 +--- python/uv.lock | 2 +- 13 files changed, 69 insertions(+), 247 deletions(-) diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 52582395f..db8919ddc 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -229,7 +229,8 @@ jobs: # Make sure wheels are not included in the Rust cache - name: Delete wheels run: rm -rf target/wheels - pydantic1x: + min-deps: + name: "Minimum dependencies" timeout-minutes: 60 runs-on: "ubuntu-24.04" defaults: @@ -259,8 +260,7 @@ jobs: save-if: ${{ github.ref == 'refs/heads/main' }} - name: Install lancedb run: | - pip install "pydantic<2" - pip install pyarrow==16 + pip install "pydantic==2.7.4" "pyarrow==16" pip install --extra-index-url https://pypi.fury.io/lance-format/ --extra-index-url https://pypi.fury.io/lancedb/ -e .[tests] - name: Run tests run: pytest -m "not slow and not s3_test" -x -v --durations=30 python/tests diff --git a/docs/requirements.txt b/docs/requirements.txt index e5f3867cb..89de1cb71 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -5,5 +5,5 @@ mkdocs-autorefs>=0.5,<=1.0 mkdocstrings[python]>=0.24,<1.0 griffe>=0.40,<1.0 mkdocs-render-swagger-plugin>=0.1.0 -pydantic>=2.0,<3.0 -mkdocs-redirects>=1.2.0 \ No newline at end of file +pydantic>=2.7.4,<3 +mkdocs-redirects>=1.2.0 diff --git a/python/pyproject.toml b/python/pyproject.toml index ce71484de..ae42172c0 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -8,7 +8,7 @@ dependencies = [ "overrides>=0.7; python_version<'3.12'", "packaging>=23.0", "pyarrow>=16", - "pydantic>=1.10", + "pydantic>=2.7.4,<3", "tqdm>=4.27.0", "lance-namespace>=0.3.2" ] diff --git a/python/python/lancedb/embeddings/base.py b/python/python/lancedb/embeddings/base.py index f711e5b7d..149b9c089 100644 --- a/python/python/lancedb/embeddings/base.py +++ b/python/python/lancedb/embeddings/base.py @@ -26,7 +26,6 @@ class EmbeddingFunction(BaseModel, ABC): 3. ndims() which returns the number of dimensions of the vector column """ - __slots__ = ("__weakref__",) # pydantic 1.x compatibility max_retries: int = ( 7 # Setting 0 disables retires. Maybe this should not be enabled by default, ) diff --git a/python/python/lancedb/embeddings/bedrock.py b/python/python/lancedb/embeddings/bedrock.py index dc2badceb..dc93a2da9 100644 --- a/python/python/lancedb/embeddings/bedrock.py +++ b/python/python/lancedb/embeddings/bedrock.py @@ -7,8 +7,7 @@ from functools import cached_property from typing import List, Union import numpy as np - -from lancedb.pydantic import PYDANTIC_VERSION +from pydantic import ConfigDict from ..util import attempt_import_or_raise from .base import TextEmbeddingFunction @@ -67,13 +66,7 @@ class BedRockText(TextEmbeddingFunction): source_input_type: str = "search_document" query_input_type: str = "search_query" - if PYDANTIC_VERSION.major < 2: # Pydantic 1.x compat - - class Config: - keep_untouched = (cached_property,) - else: - model_config = dict() - model_config["ignored_types"] = (cached_property,) + model_config = ConfigDict(ignored_types=(cached_property,)) def ndims(self): # return len(self._generate_embedding("test")) diff --git a/python/python/lancedb/embeddings/gemini_text.py b/python/python/lancedb/embeddings/gemini_text.py index 32f2d4d04..d3bf79af4 100644 --- a/python/python/lancedb/embeddings/gemini_text.py +++ b/python/python/lancedb/embeddings/gemini_text.py @@ -7,8 +7,7 @@ from functools import cached_property from typing import List, Optional, Union import numpy as np - -from lancedb.pydantic import PYDANTIC_VERSION +from pydantic import ConfigDict from ..util import attempt_import_or_raise from .base import TextEmbeddingFunction @@ -87,13 +86,7 @@ class GeminiText(TextEmbeddingFunction): query_task_type: str = "retrieval_query" source_task_type: str = "retrieval_document" - if PYDANTIC_VERSION.major < 2: # Pydantic 1.x compat - - class Config: - keep_untouched = (cached_property,) - else: - model_config = dict() - model_config["ignored_types"] = (cached_property,) + model_config = ConfigDict(ignored_types=(cached_property,)) def ndims(self): if self.dim: diff --git a/python/python/lancedb/embeddings/imagebind.py b/python/python/lancedb/embeddings/imagebind.py index 84bb0a123..c8051f14d 100644 --- a/python/python/lancedb/embeddings/imagebind.py +++ b/python/python/lancedb/embeddings/imagebind.py @@ -7,14 +7,13 @@ from typing import List, Union import numpy as np import pyarrow as pa +from pydantic import ConfigDict from ..util import attempt_import_or_raise from .base import EmbeddingFunction from .registry import register from .utils import AUDIO, IMAGES, TEXT -from lancedb.pydantic import PYDANTIC_VERSION - @register("imagebind") class ImageBindEmbeddings(EmbeddingFunction): @@ -31,13 +30,7 @@ class ImageBindEmbeddings(EmbeddingFunction): device: str = "cpu" normalize: bool = False - if PYDANTIC_VERSION.major < 2: # Pydantic 1.x compat - - class Config: - keep_untouched = (cached_property,) - else: - model_config = dict() - model_config["ignored_types"] = (cached_property,) + model_config = ConfigDict(ignored_types=(cached_property,)) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) diff --git a/python/python/lancedb/embeddings/transformers.py b/python/python/lancedb/embeddings/transformers.py index c8a65b9ca..3f42edfdd 100644 --- a/python/python/lancedb/embeddings/transformers.py +++ b/python/python/lancedb/embeddings/transformers.py @@ -7,8 +7,7 @@ from typing import List, Any import numpy as np -from pydantic import PrivateAttr -from lancedb.pydantic import PYDANTIC_VERSION +from pydantic import ConfigDict, PrivateAttr from ..util import attempt_import_or_raise from .base import EmbeddingFunction @@ -59,13 +58,7 @@ class TransformersEmbeddingFunction(EmbeddingFunction): ) self._model.to(self.device) - if PYDANTIC_VERSION.major < 2: # Pydantic 1.x compat - - class Config: - keep_untouched = (cached_property,) - else: - model_config = dict() - model_config["ignored_types"] = (cached_property,) + model_config = ConfigDict(ignored_types=(cached_property,)) def ndims(self): self._ndims = self._model.config.hidden_size diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 4ffb65e2c..9c4b063cd 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -13,14 +13,14 @@ import json from collections.abc import Mapping from typing import Any, Optional -import pydantic -from pydantic import BaseModel, Field, conint - -_PYDANTIC_V2 = int(pydantic.VERSION.split(".", 1)[0]) >= 2 -if _PYDANTIC_V2: - from pydantic import field_validator, model_validator -else: - from pydantic import root_validator, validator +from pydantic import ( + BaseModel, + ConfigDict, + Field, + conint, + field_validator, + model_validator, +) _Int32 = conint(strict=True, ge=-(2**31), le=2**31 - 1) _UInt32 = conint(strict=True, ge=0, le=2**32 - 1) @@ -82,43 +82,25 @@ def _known_wire_value(value): class _RemoteValue(BaseModel): - if _PYDANTIC_V2: - model_config = {"extra": "ignore", "frozen": True} - else: + model_config = ConfigDict(extra="ignore", frozen=True) - class Config: - allow_mutation = False - extra = "ignore" - - if _PYDANTIC_V2: - - @model_validator(mode="after") - def _freeze_mappings(self): - for name, value in self.__dict__.items(): - object.__setattr__(self, name, _freeze_value(value)) - return self - - else: - - @root_validator - def _freeze_mappings(cls, values): - return {name: _freeze_value(value) for name, value in values.items()} + @model_validator(mode="after") + def _freeze_mappings(self): + for name, value in self.__dict__.items(): + object.__setattr__(self, name, _freeze_value(value)) + return self @classmethod def from_json(cls, payload: str): - if _PYDANTIC_V2: - return cls.model_validate_json(payload) - return cls.parse_raw(payload) + return cls.model_validate_json(payload) def _known_dict(self) -> dict[str, Any]: - fields = self.__class__.model_fields if _PYDANTIC_V2 else self.__fields__ known = {} - for name, field in fields.items(): + for name, field in self.__class__.model_fields.items(): value = getattr(self, name) if value is None: continue - required = field.is_required() if _PYDANTIC_V2 else field.required - if not required: + if not field.is_required(): default_factory = field.default_factory if default_factory is not None and value == default_factory(): continue @@ -129,9 +111,7 @@ class _RemoteValue(BaseModel): def _copy(self, *, update: Mapping[str, Any]): update = {name: _freeze_value(value) for name, value in update.items()} - if _PYDANTIC_V2: - return self.model_copy(update=update) - return self.copy(update=update) + return self.model_copy(update=update) def to_canonical_json(self) -> str: return json.dumps( @@ -199,35 +179,18 @@ class PythonRuntimeSpec(_RemoteValue): environment: Optional[PythonEnvironmentSpec] = None env: Optional[Mapping[str, str]] = None - if _PYDANTIC_V2: - - @model_validator(mode="after") - def _validate_runtime_kind(self): - if self.kind == "python": - if self.python_version is None: - raise ValueError("python runtime requires python_version") - if self.environment is None: - raise ValueError("python runtime requires environment") - else: - object.__setattr__(self, "python_version", None) - object.__setattr__(self, "environment", None) - object.__setattr__(self, "env", None) - return self - - else: - - @root_validator - def _validate_runtime_kind(cls, values): - if values.get("kind") == "python": - if values.get("python_version") is None: - raise ValueError("python runtime requires python_version") - if values.get("environment") is None: - raise ValueError("python runtime requires environment") - else: - values["python_version"] = None - values["environment"] = None - values["env"] = None - return values + @model_validator(mode="after") + def _validate_runtime_kind(self): + if self.kind == "python": + if self.python_version is None: + raise ValueError("python runtime requires python_version") + if self.environment is None: + raise ValueError("python runtime requires environment") + else: + object.__setattr__(self, "python_version", None) + object.__setattr__(self, "environment", None) + object.__setattr__(self, "env", None) + return self class FunctionVersion(_RemoteValue): @@ -265,18 +228,10 @@ class ApplicationInput(_RemoteValue): kind: str value: Any - if _PYDANTIC_V2: - - @field_validator("value") - @classmethod - def _validate_value(cls, value): - return _validate_literal(value) - - else: - - @validator("value") - def _validate_value(cls, value): - return _validate_literal(value) + @field_validator("value") + @classmethod + def _validate_value(cls, value): + return _validate_literal(value) class FunctionApplication(_RemoteValue): diff --git a/python/python/lancedb/pydantic.py b/python/python/lancedb/pydantic.py index 1ab6e6fcc..528d865d7 100644 --- a/python/python/lancedb/pydantic.py +++ b/python/python/lancedb/pydantic.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors -"""Pydantic (v1 / v2) adapter for LanceDB""" +"""Pydantic adapter for LanceDB.""" from __future__ import annotations @@ -14,9 +14,6 @@ from enum import Enum from typing import ( TYPE_CHECKING, Any, - Callable, - Dict, - Generator, List, Type, Union, @@ -24,17 +21,9 @@ from typing import ( GenericAlias, ) -import numpy as np import pyarrow as pa import pydantic -from packaging.version import Version - -PYDANTIC_VERSION = Version(pydantic.__version__) -try: - from pydantic_core import CoreSchema, core_schema -except ImportError: - if PYDANTIC_VERSION.major >= 2: - raise +from pydantic_core import CoreSchema, core_schema if TYPE_CHECKING: from pydantic.fields import FieldInfo @@ -131,25 +120,6 @@ def Vector( ), ) - @classmethod - def __get_validators__(cls) -> Generator[Callable, None, None]: - yield cls.validate - - # For pydantic v1 - @classmethod - def validate(cls, v): - if not isinstance(v, (list, range, np.ndarray)) or len(v) != dim: - raise TypeError("A list of numbers or numpy.ndarray is needed") - return cls(v) - - if PYDANTIC_VERSION.major < 2: - - @classmethod - def __modify_schema__(cls, field_schema: Dict[str, Any]): - field_schema["items"] = {"type": "number"} - field_schema["maxItems"] = dim - field_schema["minItems"] = dim - return FixedSizeList @@ -157,9 +127,8 @@ def _raise_bare_vector_error(*_args): raise TypeError("Vector must be parameterized with a dimension, e.g. Vector(128).") -# Pydantic v1 and v2 otherwise treat the bare Vector factory as a field validator -# and inspect its signature, which produces misleading errors about internal types. -setattr(Vector, "__get_validators__", _raise_bare_vector_error) +# Pydantic otherwise inspects the bare factory as a field type and produces +# misleading errors about its internal annotations. setattr(Vector, "__get_pydantic_core_schema__", _raise_bare_vector_error) @@ -233,31 +202,6 @@ def MultiVector( ), ) - @classmethod - def __get_validators__(cls) -> Generator[Callable, None, None]: - yield cls.validate - - # For pydantic v1 - @classmethod - def validate(cls, v): - if not isinstance(v, (list, range)): - raise TypeError("A list of vectors is needed") - for vec in v: - if not isinstance(vec, (list, range, np.ndarray)) or len(vec) != dim: - raise TypeError(f"Each vector must be a list of {dim} numbers") - return cls(v) - - if PYDANTIC_VERSION.major < 2: - - @classmethod - def __modify_schema__(cls, field_schema: Dict[str, Any]): - field_schema["items"] = { - "type": "array", - "items": {"type": "number"}, - "minItems": dim, - "maxItems": dim, - } - return MultiVectorList @@ -303,20 +247,10 @@ def _py_type_to_arrow_type(py_type: Type[Any], field: FieldInfo) -> pa.DataType: ) -if PYDANTIC_VERSION.major < 2: - - def _pydantic_model_to_fields(model: pydantic.BaseModel) -> List[pa.Field]: - return [ - _pydantic_to_field(name, field) for name, field in model.__fields__.items() - ] - -else: - - def _pydantic_model_to_fields(model: pydantic.BaseModel) -> List[pa.Field]: - return [ - _pydantic_to_field(name, field) - for name, field in model.model_fields.items() - ] +def _pydantic_model_to_fields(model: pydantic.BaseModel) -> List[pa.Field]: + return [ + _pydantic_to_field(name, field) for name, field in model.model_fields.items() + ] def _pydantic_type_to_arrow_type(tp: Any, field: FieldInfo) -> pa.DataType: @@ -509,8 +443,6 @@ class LanceModel(pydantic.BaseModel): @classmethod def safe_get_fields(cls): - if PYDANTIC_VERSION.major < 2: - return cls.__fields__ return cls.model_fields @classmethod @@ -548,23 +480,9 @@ def get_extras(field_info: FieldInfo, key: str) -> Any: """ Get the extra metadata from a Pydantic FieldInfo. """ - if PYDANTIC_VERSION.major >= 2: - return (field_info.json_schema_extra or {}).get(key) - return (field_info.field_info.extra or {}).get("json_schema_extra", {}).get(key) + return (field_info.json_schema_extra or {}).get(key) -if PYDANTIC_VERSION.major < 2: - - def model_to_dict(model: pydantic.BaseModel) -> Dict[str, Any]: - """ - Convert a Pydantic model to a dictionary. - """ - return model.dict() - -else: - - def model_to_dict(model: pydantic.BaseModel) -> Dict[str, Any]: - """ - Convert a Pydantic model to a dictionary. - """ - return model.model_dump() +def model_to_dict(model: pydantic.BaseModel) -> dict[str, Any]: + """Convert a Pydantic model to a dictionary.""" + return model.model_dump() diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index e2bb491ea..bd5e2cea2 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -32,8 +32,6 @@ from typing_extensions import Annotated from lancedb._lancedb import fts_query_to_json from lancedb.background_loop import LOOP -from lancedb.pydantic import PYDANTIC_VERSION - from . import __version__ from .arrow import AsyncRecordBatchReader from .dependencies import pandas as pd @@ -827,12 +825,7 @@ class Query(pydantic.BaseModel): # This tells pydantic to allow custom types (needed for the `vector` query since # pa.Array wouln't be allowed otherwise) - if PYDANTIC_VERSION.major < 2: # Pydantic 1.x compat - - class Config: - arbitrary_types_allowed = True - else: - model_config = {"arbitrary_types_allowed": True} + model_config = pydantic.ConfigDict(arbitrary_types_allowed=True) class LanceQueryBuilder(ABC): @@ -3251,12 +3244,7 @@ class AsyncStandardQuery(AsyncQueryBase): if ordering is None: self._inner.order_by(None) else: - self._inner.order_by( - [ - o.model_dump() if hasattr(o, "model_dump") else o.dict() - for o in ordering - ] - ) + self._inner.order_by([o.model_dump() for o in ordering]) return self def fast_search(self) -> Self: diff --git a/python/python/tests/test_pydantic.py b/python/python/tests/test_pydantic.py index db93d7c64..ca03940f2 100644 --- a/python/python/tests/test_pydantic.py +++ b/python/python/tests/test_pydantic.py @@ -10,11 +10,10 @@ import pyarrow as pa import pydantic import pytest from lancedb.pydantic import ( - PYDANTIC_VERSION, LanceModel, + MultiVector, Vector, pydantic_to_schema, - MultiVector, ) from pydantic import BaseModel from pydantic import Field @@ -432,16 +431,10 @@ def test_fixed_size_list_field(): li: List[int] data = TestModel(vec=list(range(16)), li=[1, 2, 3]) - if PYDANTIC_VERSION.major >= 2: - assert json.loads(data.model_dump_json()) == { - "vec": list(range(16)), - "li": [1, 2, 3], - } - else: - assert data.dict() == { - "vec": list(range(16)), - "li": [1, 2, 3], - } + assert json.loads(data.model_dump_json()) == { + "vec": list(range(16)), + "li": [1, 2, 3], + } schema = pydantic_to_schema(TestModel) assert schema == pa.schema( @@ -451,10 +444,7 @@ def test_fixed_size_list_field(): ] ) - if PYDANTIC_VERSION.major >= 2: - json_schema = TestModel.model_json_schema() - else: - json_schema = TestModel.schema() + json_schema = TestModel.model_json_schema() assert json_schema == { "properties": { diff --git a/python/uv.lock b/python/uv.lock index 2cdcb182e..c957a4c06 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -2003,7 +2003,7 @@ requires-dist = [ { name = "pyarrow", specifier = ">=16" }, { name = "pyarrow", marker = "extra == 'tests'", specifier = "<25" }, { name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" }, - { name = "pydantic", specifier = ">=1.10" }, + { name = "pydantic", specifier = ">=2.7.4,<3" }, { name = "pylance", marker = "extra == 'pylance'", specifier = ">=5.0.0b5" }, { name = "pylance", marker = "extra == 'tests'", specifier = "==9.0.0rc1" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" }, From 685cb01d6d4aa354ba818b013f9ab002bbc6e8c1 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 21 Aug 2026 17:01:04 +0800 Subject: [PATCH 062/206] feat: add grouped function column bindings (#3994) Function applications from the canonical remote contract cannot currently declare scalar or grouped computed-column outputs atomically. This adds the remote-only declaration contract for scalar, struct-as-one-column, and expanded named-struct outputs. It validates result mappings, fixes exact input/output Arrow schemas in the request, persists grouped sibling metadata, and keeps local Function execution unsupported. Unknown newer application or binding metadata remains readable, while schema-changing mutations fail closed instead of rewriting it. Stable Lance field IDs are deliberately not a declaration prerequisite in this slice. Inputs bind by parameter name and field path; Sophon remains responsible for exact-version validation, atomic all-NULL sibling creation, binding identity and revision allocation, and persisted output identities. --- python/python/lancedb/_lancedb.pyi | 3 + python/python/lancedb/functions.py | 56 +- python/python/lancedb/remote/table.py | 5 +- python/python/lancedb/table.py | 63 +- .../tests/test_first_class_function_slice1.py | 86 ++ python/src/table.rs | 18 + rust/lancedb/src/function.rs | 69 +- rust/lancedb/src/remote/table.rs | 244 +++- rust/lancedb/src/table.rs | 11 + rust/lancedb/src/table/add_columns.rs | 82 +- rust/lancedb/src/table/computed_columns.rs | 1084 ++++++++++++++++- rust/lancedb/src/table/merge.rs | 4 + rust/lancedb/src/table/refresh.rs | 3 + rust/lancedb/src/table/schema_evolution.rs | 17 + rust/lancedb/src/table/update.rs | 4 + .../tests/first_class_function_slice1.rs | 2 + .../v1/remote_function_binding.canonical.json | 2 +- .../v1/remote_function_binding.json | 12 + .../remote_grouped_declaration_request.json | 45 + .../v1/remote_scalar_declaration_request.json | 41 + 20 files changed, 1799 insertions(+), 52 deletions(-) create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_grouped_declaration_request.json create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_scalar_declaration_request.json diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 22878fd85..ea5d3e972 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -341,6 +341,9 @@ class Table: async def add_computed_columns( self, columns: list[tuple[str, str]] ) -> AddColumnsResult: ... + async def add_function_columns( + self, application_json: str, output_name: Optional[str] + ) -> AddColumnsResult: ... async def refresh_column(self, column: str) -> RefreshColumnResult: ... async def refresh_column_async(self, column: str) -> Job: ... async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ... diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 9c4b063cd..df781f665 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -123,6 +123,23 @@ class _RemoteValue(BaseModel): ) +class _OpenRemoteValue(_RemoteValue): + """Forward-readable value whose extras stay out of canonical encoding.""" + + if _PYDANTIC_V2: + model_config = {"extra": "allow", "frozen": True} + else: + + class Config: + allow_mutation = False + extra = "allow" + + def _unknown_field_names(self) -> set[str]: + if _PYDANTIC_V2: + return set((self.__pydantic_extra__ or {}).keys()) + return set(self.__dict__) - set(self.__fields__) + + class FunctionArtifact(_RemoteValue): """Content-addressed Python artifact identity.""" @@ -137,13 +154,13 @@ class FunctionParameter(_RemoteValue): nullable: bool -class FunctionResultField(_RemoteValue): +class FunctionResultField(_OpenRemoteValue): name: str arrow_type: str nullable: bool -class FunctionOutput(_RemoteValue): +class FunctionOutput(_OpenRemoteValue): """Scalar or ordered named-struct output; unknown kinds remain decodable.""" kind: str @@ -211,12 +228,12 @@ class FunctionVersion(_RemoteValue): created_at: str -class FunctionVersionRef(_RemoteValue): +class FunctionVersionRef(_OpenRemoteValue): name: str version: str -class ApplicationInput(_RemoteValue): +class ApplicationInput(_OpenRemoteValue): """One parameter value. Slice 1 freezes integers, strings, booleans, nulls, arrays, and objects. @@ -234,7 +251,7 @@ class ApplicationInput(_RemoteValue): return _validate_literal(value) -class FunctionApplication(_RemoteValue): +class FunctionApplication(_OpenRemoteValue): """Immutable pre-declaration application of an exact Function version.""" function: FunctionVersionRef @@ -243,6 +260,33 @@ class FunctionApplication(_RemoteValue): group_id: str columns: Mapping[str, str] = Field(default_factory=dict) + def _known_dict(self) -> dict[str, Any]: + value = super()._known_dict() + for name in self._unknown_field_names(): + value.pop(name, None) + return value + + def _ensure_declarable(self) -> None: + unknown = {f"application.{name}" for name in self._unknown_field_names()} + unknown.update( + f"function.{name}" for name in self.function._unknown_field_names() + ) + for index, input_value in enumerate(self.inputs): + unknown.update( + f"inputs[{index}].{name}" for name in input_value._unknown_field_names() + ) + unknown.update(f"output.{name}" for name in self.output._unknown_field_names()) + for index, field in enumerate(self.output.fields): + unknown.update( + f"output.fields[{index}].{name}" + for name in field._unknown_field_names() + ) + if unknown: + raise ValueError( + "Function application contains fields from a newer contract: " + f"{sorted(unknown)!r}" + ) + def rename(self, *, columns: Mapping[str, str]) -> FunctionApplication: """Return a copy with result-field to table-column aliases.""" if self.output.kind != "named_struct": @@ -293,6 +337,8 @@ class FunctionBinding(_RemoteValue): group_id: str inputs: tuple[InputBinding, ...] outputs: tuple[OutputMapping, ...] + input_schema: Optional[Mapping[str, Any]] = None + output_schema: Optional[Mapping[str, Any]] = None class RefreshColumnResult(_RemoteValue): diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 25363cf8f..b97f8f194 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -49,6 +49,7 @@ from lancedb.index import ( LabelList, ) from lancedb.job import Job +from lancedb.functions import FunctionApplication from lancedb.remote.db import LOOP from lancedb.table import IndexConfigType, KNOWN_METRICS import pyarrow as pa @@ -960,7 +961,9 @@ class RemoteTable(Table): def add_columns( self, - transforms: Dict[str, str] | None = None, + transforms: Dict[str, str | FunctionApplication] + | FunctionApplication + | None = None, *, computed: Dict[str, str] | None = None, ) -> AddColumnsResult: diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 79e67fdba..913ab5289 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -72,6 +72,7 @@ from .index import ( FTS, ) from .expr import Expr +from .functions import FunctionApplication from .merge import LanceMergeInsertBuilder from .pydantic import LanceModel, model_to_dict from .query import ( @@ -1942,7 +1943,8 @@ class Table(ABC): @abstractmethod def add_columns( self, - transforms: Dict[str, str] + transforms: Dict[str, str | FunctionApplication] + | FunctionApplication | pa.Field | List[pa.Field] | pa.Schema @@ -1955,13 +1957,21 @@ class Table(ABC): Parameters ---------- - transforms: Dict[str, str], pa.Field, List[pa.Field], pa.Schema + transforms: Dict[str, str | FunctionApplication], FunctionApplication, + pa.Field, List[pa.Field], pa.Schema A map of column name to a SQL expression to use to calculate the value of the new column. These expressions will be evaluated for each row in the table, and can reference existing columns. Alternatively, a pyarrow Field or Schema can be provided to add new columns with the specified data types. The new columns will be initialized with null values. + + A mapping with one ``FunctionApplication`` value keeps its scalar + or named-struct result in the named table column. A bare + named-struct application expands its ordered result fields as one + atomic sibling group; aliases come from ``rename(columns=...)``. + Function columns are supported only on LanceDB Cloud and + Enterprise. computed: Dict[str, str], optional A map of column name to a SQL expression defining the column. The column's type and inputs are derived from the expression, so no @@ -4056,9 +4066,10 @@ class LanceTable(Table): def add_columns( self, - transforms: Dict[str, str] - | pa.field - | List[pa.field] + transforms: Dict[str, str | FunctionApplication] + | FunctionApplication + | pa.Field + | List[pa.Field] | pa.Schema | None = None, *, @@ -5992,9 +6003,10 @@ class AsyncTable: async def add_columns( self, - transforms: dict[str, str] - | pa.field - | List[pa.field] + transforms: dict[str, str | FunctionApplication] + | FunctionApplication + | pa.Field + | List[pa.Field] | pa.Schema | None = None, *, @@ -6005,12 +6017,19 @@ class AsyncTable: Parameters ---------- - transforms: Dict[str, str] + transforms: Dict[str, str | FunctionApplication] or FunctionApplication A map of column name to a SQL expression to use to calculate the value of the new column. These expressions will be evaluated for each row in the table, and can reference existing columns. Alternatively, you can pass a pyarrow field or schema to add new columns with NULLs. + + A mapping with one ``FunctionApplication`` value keeps its scalar + or named-struct result in the named table column. A bare + named-struct application expands its ordered result fields as one + atomic sibling group; aliases come from ``rename(columns=...)``. + Function columns are supported only on LanceDB Cloud and + Enterprise. computed: Dict[str, str], optional A map of column name to a SQL expression defining the column. The column's type and inputs are derived from the expression. @@ -6034,6 +6053,32 @@ class AsyncTable: version: the new version number of the table after adding columns. """ + function_application = None + function_output_name = None + if isinstance(transforms, FunctionApplication): + function_application = transforms + elif isinstance(transforms, dict) and any( + isinstance(value, FunctionApplication) for value in transforms.values() + ): + if len(transforms) != 1 or not all( + isinstance(value, FunctionApplication) for value in transforms.values() + ): + raise ValueError( + "one add_columns call declares exactly one Function sibling group" + ) + function_output_name, function_application = next(iter(transforms.items())) + + if function_application is not None: + if computed: + raise ValueError( + "add_columns cannot mix a Function application with SQL " + "computed columns" + ) + function_application._ensure_declarable() + return await self._inner.add_function_columns( + function_application.to_canonical_json(), function_output_name + ) + if isinstance(transforms, pa.Field): transforms = [transforms] if isinstance(transforms, list) and all( diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index 9f934507f..fead28bc8 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -14,6 +14,7 @@ from lancedb.functions import ( PythonRuntimeSpec, RefreshColumnResult, ) +from lancedb.table import AsyncTable FIXTURES = ( @@ -166,6 +167,8 @@ def test_binding_and_refresh_result_keep_stable_remote_fields(): assert binding.revision == 3 assert binding.function.version == "fv_01K3TEXT" assert [output.output_ordinal for output in binding.outputs] == [0, 1] + assert binding.input_schema is not None + assert binding.output_schema is not None result = RefreshColumnResult.from_json( json.dumps(job_result("remote_refresh_job.json")) @@ -223,3 +226,86 @@ def test_canonical_client_values_contain_secret_names_only(): canonical = json.loads(version.to_canonical_json()) assert canonical["required_secrets"] == ["HF_TOKEN"] assert_no_secret_values(canonical) + + +class _FunctionDeclarationInner: + def __init__(self): + self.calls = [] + + async def add_function_columns(self, application_json, output_name): + self.calls.append((json.loads(application_json), output_name)) + return "declared" + + +def known_application() -> FunctionApplication: + value = json.loads(fixture("remote_function_application.json")) + value.pop("future_application") + return FunctionApplication(**value) + + +@pytest.mark.asyncio +async def test_add_columns_routes_struct_as_one_and_grouped_expansion_atomically(): + inner = _FunctionDeclarationInner() + table = AsyncTable(inner) + application = known_application() + + result = await table.add_columns( + {"features": application._copy(update={"columns": {}})} + ) + assert result == "declared" + assert inner.calls[-1][1] == "features" + + bare = application._copy(update={"columns": {}}).rename( + columns={"normalized_text": "search_text"} + ) + result = await table.add_columns(bare) + assert result == "declared" + assert inner.calls[-1][1] is None + assert inner.calls[-1][0]["columns"] == {"normalized_text": "search_text"} + + +@pytest.mark.asyncio +async def test_add_columns_rejects_mixed_groups_and_unknown_newer_application(): + inner = _FunctionDeclarationInner() + table = AsyncTable(inner) + application = known_application() + + with pytest.raises(ValueError, match="exactly one Function sibling group"): + await table.add_columns({"a": application, "b": application}) + + future = json.loads(fixture("remote_function_application.json")) + application = FunctionApplication(**future) + with pytest.raises(ValueError, match="newer contract"): + await table.add_columns(application) + + future.pop("future_application") + future["output"]["assignment"] = "cell_flag" + application = FunctionApplication(**future) + assert "assignment" not in json.loads(application.to_canonical_json())["output"] + with pytest.raises(ValueError, match="output.assignment"): + await table.add_columns(application) + assert inner.calls == [] + + +def test_rename_requires_named_struct_and_keeps_partial_mapping_immutable(): + scalar = FunctionApplication.from_json( + json.dumps( + { + "function": {"name": "embed", "version": "fv_exact"}, + "inputs": [], + "output": { + "kind": "scalar", + "arrow_type": "list", + "nullable": False, + }, + "group_id": "fg_scalar", + } + ) + ) + with pytest.raises(ValueError, match="named-struct"): + scalar.rename(columns={"value": "embedding"}) + + application = known_application()._copy(update={"columns": {}}) + renamed = application.rename(columns={"normalized_text": "search_text"}) + assert dict(application.columns) == {} + assert dict(renamed.columns) == {"normalized_text": "search_text"} diff --git a/python/src/table.rs b/python/src/table.rs index 0e3eb4cf8..cb4752cce 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1551,6 +1551,24 @@ impl Table { }) } + pub fn add_function_columns( + self_: PyRef<'_, Self>, + application_json: String, + output_name: Option, + ) -> PyResult> { + let application = + lancedb::function::FunctionApplication::from_json(&application_json).infer_error()?; + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let builder = match output_name { + Some(name) => inner.add_columns().function_as(name, application), + None => inner.add_columns().function(application), + }; + let result = builder.execute().await.infer_error()?; + Ok(AddColumnsResult::from(result)) + }) + } + pub fn refresh_column(self_: PyRef<'_, Self>, column: String) -> PyResult> { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 087a00b90..fe91f1680 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -74,6 +74,46 @@ fn validate_literal(value: &Value) -> Result<()> { } } +fn has_unknown_keys(value: &Value, allowed: &[&str]) -> bool { + value + .as_object() + .is_some_and(|object| object.keys().any(|key| !allowed.contains(&key.as_str()))) +} + +fn application_has_unknown_nested_fields(value: &Value) -> bool { + let Some(application) = value.as_object() else { + return false; + }; + if application + .get("function") + .is_some_and(|value| has_unknown_keys(value, &["name", "version"])) + { + return true; + } + if application + .get("inputs") + .and_then(Value::as_array) + .is_some_and(|inputs| { + inputs + .iter() + .any(|input| has_unknown_keys(input, &["parameter", "kind", "value"])) + }) + { + return true; + } + application.get("output").is_some_and(|output| { + has_unknown_keys(output, &["kind", "arrow_type", "nullable", "fields"]) + || output + .get("fields") + .and_then(Value::as_array) + .is_some_and(|fields| { + fields + .iter() + .any(|field| has_unknown_keys(field, &["name", "arrow_type", "nullable"])) + }) + }) +} + macro_rules! impl_json { ($type:ty) => { impl $type { @@ -358,6 +398,10 @@ pub struct FunctionApplication { group_id: String, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] columns: BTreeMap, + #[serde(default, flatten, skip_serializing)] + unknown_fields: BTreeMap, + #[serde(default, skip)] + unknown_nested_fields: bool, } impl FunctionApplication { @@ -380,10 +424,18 @@ impl FunctionApplication { pub fn columns(&self) -> &BTreeMap { &self.columns } + /// Whether a newer writer attached application fields this client cannot + /// validate. Such applications remain readable but must not be declared. + pub fn has_unknown_fields(&self) -> bool { + !self.unknown_fields.is_empty() || self.unknown_nested_fields + } /// Decode a remote application after validating the Slice 1 literal domain. pub fn from_json(json: &str) -> Result { - let application: Self = from_json(json)?; + let value: Value = from_json(json)?; + let has_unknown_nested_fields = application_has_unknown_nested_fields(&value); + let mut application: Self = serde_json::from_value(value).map_err(invalid_json)?; + application.unknown_nested_fields = has_unknown_nested_fields; application .inputs .iter() @@ -433,6 +485,13 @@ pub struct FunctionBinding { group_id: String, inputs: Vec, outputs: Vec, + /// Exact Arrow schema presented to the Function, encoded with the Lance + /// Namespace Arrow JSON representation. + #[serde(default, skip_serializing_if = "Option::is_none")] + input_schema: Option, + /// Exact physical Arrow schema of the grouped table outputs. + #[serde(default, skip_serializing_if = "Option::is_none")] + output_schema: Option, } impl FunctionBinding { @@ -459,6 +518,14 @@ impl FunctionBinding { pub fn outputs(&self) -> &[OutputMapping] { &self.outputs } + + pub fn input_schema(&self) -> Option<&Value> { + self.input_schema.as_ref() + } + + pub fn output_schema(&self) -> Option<&Value> { + self.output_schema.as_ref() + } } impl_json!(FunctionBinding); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 328f2a708..1e5691554 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2147,6 +2147,7 @@ impl BaseTable for RemoteTable { self.check_mutable().await?; let table_schema = self.schema().await?; + crate::table::computed_columns::ensure_supported_function_metadata(table_schema.as_ref())?; let table_def = TableDefinition::try_from_rich_schema(table_schema.clone())?; let num_partitions = if self.server_version.support_multipart_write() { @@ -2698,6 +2699,10 @@ impl BaseTable for RemoteTable { _read_columns: Option>, ) -> Result { self.check_mutable().await?; + crate::table::computed_columns::ensure_no_function_bindings_for_mutation( + self.schema().await?.as_ref(), + "schema evolution", + )?; match transforms { NewColumnTransform::SqlExpressions(expressions) => { let body = expressions @@ -2746,6 +2751,10 @@ impl BaseTable for RemoteTable { async fn add_computed_columns(&self, columns: &[(String, String)]) -> Result { self.check_mutable().await?; + crate::table::computed_columns::ensure_no_function_bindings_for_mutation( + self.schema().await?.as_ref(), + "schema evolution", + )?; // The server plans the declaration: expression validation, type // inference and the persisted binding all happen there. let entries = columns @@ -2785,6 +2794,63 @@ impl BaseTable for RemoteTable { Ok(result) } + async fn add_function_columns( + &self, + application: &crate::function::FunctionApplication, + output_name: Option<&str>, + ) -> Result { + self.check_mutable().await?; + let schema = self.schema().await?; + let plan = crate::table::computed_columns::plan_function_application( + schema.as_ref(), + application, + output_name, + )?; + let new_columns = plan + .outputs + .iter() + .map(|output| { + serde_json::json!({ + "name": output.output_name, + "all_null": true, + }) + }) + .collect::>(); + let mut body = serde_json::json!({ + "new_columns": new_columns, + "function": { + "application": plan.application, + "binding_metadata_version": plan.binding_metadata_version, + "input_bindings": plan.input_bindings, + "input_schema": plan.input_schema, + "output_schema": plan.output_schema, + "outputs": plan.outputs, + }, + }); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!("/v1/table/{}/add_columns/", 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())?; + + if body.trim().is_empty() { + return Ok(AddColumnsResult { version: 0 }); + } + + let result: AddColumnsResult = serde_json::from_str(&body).map_err(|e| Error::Http { + source: format!("Failed to parse add Function columns response: {e}").into(), + request_id, + status_code: None, + })?; + + self.invalidate_schema_cache(); + self.track_write_version(result.version); + Ok(result) + } + async fn refresh_column(&self, _column: &str) -> Result { // The server runs a refresh as a job and does not report a fill // count, so the blocking form has no honest result to return. @@ -3810,11 +3876,14 @@ mod tests { assert_eq!(rename, "y"); if old_server { - http::Response::builder().status(200).body("{}").unwrap() + http::Response::builder() + .status(200) + .body("{}".to_string()) + .unwrap() } else { http::Response::builder() .status(200) - .body(r#"{"version": 43}"#) + .body(r#"{"version": 43}"#.to_string()) .unwrap() } } else { @@ -3945,11 +4014,14 @@ mod tests { assert_eq!(predicate, "id in (1, 2, 3)"); if old_server { - http::Response::builder().status(200).body("{}").unwrap() + http::Response::builder() + .status(200) + .body("{}".to_string()) + .unwrap() } else { http::Response::builder() .status(200) - .body(r#"{"version": 43}"#) + .body(r#"{"version": 43}"#.to_string()) .unwrap() } } else { @@ -6516,7 +6588,9 @@ mod tests { #[tokio::test] async fn test_add_columns(#[case] old_server: bool) { let table = Table::new_with_handler("my_table", move |request| { - if request.url().path() == "/v1/table/my_table/add_columns/" { + if request.url().path() == "/v1/table/my_table/describe/" { + simple_describe_response() + } else if request.url().path() == "/v1/table/my_table/add_columns/" { assert_eq!(request.method(), "POST"); assert_eq!( request.headers().get("Content-Type").unwrap(), @@ -6540,11 +6614,14 @@ mod tests { assert_eq!(expression, "cast(NULL as int32)"); if old_server { - http::Response::builder().status(200).body("{}").unwrap() + http::Response::builder() + .status(200) + .body("{}".to_string()) + .unwrap() } else { http::Response::builder() .status(200) - .body(r#"{"version": 43}"#) + .body(r#"{"version": 43}"#.to_string()) .unwrap() } } else { @@ -6569,19 +6646,22 @@ mod tests { /// plan; the client never types the expression itself. #[tokio::test] async fn test_add_computed_columns_sends_the_expression() { - let table = Table::new_with_handler("my_table", |request| { - assert_eq!(request.method(), "POST"); - assert_eq!(request.url().path(), "/v1/table/my_table/add_columns/"); - let body = request.body().unwrap().as_bytes().unwrap(); - let value: serde_json::Value = serde_json::from_slice(body).unwrap(); - assert_eq!( - value["new_columns"], - serde_json::json!([{"name": "doubled", "computed": "x * 2"}]) - ); - http::Response::builder() - .status(200) - .body(r#"{"version": 7}"#) - .unwrap() + let table = Table::new_with_handler("my_table", |request| match request.url().path() { + "/v1/table/my_table/describe/" => simple_describe_response(), + "/v1/table/my_table/add_columns/" => { + assert_eq!(request.method(), "POST"); + let body = request.body().unwrap().as_bytes().unwrap(); + let value: serde_json::Value = serde_json::from_slice(body).unwrap(); + assert_eq!( + value["new_columns"], + serde_json::json!([{"name": "doubled", "computed": "x * 2"}]) + ); + http::Response::builder() + .status(200) + .body(r#"{"version": 7}"#.to_string()) + .unwrap() + } + path => panic!("Unexpected path: {path}"), }); let result = table @@ -6593,6 +6673,129 @@ mod tests { assert_eq!(result.version, 7); } + #[tokio::test] + async fn test_add_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(); + let expected: serde_json::Value = serde_json::from_str(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_scalar_declaration_request.json" + )) + .unwrap(); + assert_eq!(actual, expected); + 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":"embed","version":"fv_01K3EXACT"}, + "inputs":[{"parameter":"text","kind":"column","value":{"path":"description"}}], + "output":{"kind":"scalar","arrow_type":"list","nullable":false}, + "group_id":"fg_scalar" + }"#, + ) + .unwrap(); + + let result = table + .add_columns() + .function_as("embedding", application) + .execute() + .await + .unwrap(); + assert_eq!(result.version, 8); + } + + #[tokio::test] + async fn test_add_named_struct_function_expands_one_atomic_sibling_group() { + 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":"title","nullable":true,"type":{"type":"string"}}, + {"name":"body","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(); + let expected: serde_json::Value = serde_json::from_str(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_grouped_declaration_request.json" + )) + .unwrap(); + assert_eq!(actual, expected); + http::Response::builder() + .status(200) + .body(r#"{"version":9}"#) + .unwrap() + } + path => panic!("Unexpected path: {path}"), + }); + let application = crate::function::FunctionApplication::from_json( + r#"{ + "function":{"name":"text_features","version":"fv_01K3TEXT"}, + "inputs":[ + {"parameter":"title","kind":"column","value":{"path":"title"}}, + {"parameter":"body","kind":"column","value":{"path":"body"}} + ], + "output":{"kind":"named_struct","fields":[ + {"name":"normalized_text","arrow_type":"utf8","nullable":false}, + {"name":"token_count","arrow_type":"int64","nullable":false} + ]}, + "group_id":"fg_01K3TEXT", + "columns":{"normalized_text":"search_text"} + }"#, + ) + .unwrap(); + + let result = table + .add_columns() + .function(application) + .execute() + .await + .unwrap(); + assert_eq!(result.version, 9); + } + + #[tokio::test] + async fn test_add_columns_fails_closed_on_newer_function_binding_metadata() { + 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":"x","nullable":true,"type":{"type":"int32"}}],"metadata":{"lancedb::function_bindings":"{\"version\":2,\"bindings\":[]}"}}}"#, + ) + .unwrap(), + path => panic!("mutation request must not be sent: {path}"), + } + }); + + let err = table + .add_columns() + .computed("doubled", "x * 2") + .execute() + .await + .unwrap_err(); + assert!(matches!(err, Error::NotSupported { .. })); + } + /// A remote refresh is a server job: the async form returns its handle, /// and the blocking form refuses rather than invent a fill count. #[tokio::test] @@ -10911,6 +11114,7 @@ mod tests { .status(200) .body("{}".to_string()) .unwrap(), + "/v1/table/my_table/describe/" => simple_describe_response(), "/v1/table/my_table/add_columns/" | "/v1/table/my_table/alter_columns/" | "/v1/table/my_table/drop_columns/" => { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 2e16b0940..9228b4baf 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -760,6 +760,16 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "computed columns are not supported on this table type".into(), }) } + /// Declare one immutable registered-Function output group. + async fn add_function_columns( + &self, + _application: &crate::function::FunctionApplication, + _output_name: Option<&str>, + ) -> Result { + Err(Error::NotSupported { + message: "Function columns are supported only on LanceDB Cloud and Enterprise".into(), + }) + } /// Fill a computed column's unfilled rows. /// /// The default returns `NotSupported`; Lance-backed tables override it. @@ -3158,6 +3168,7 @@ impl BaseTable for NativeTable { let ds = self.dataset.get().await?; let table_schema = Schema::from(&ds.schema().clone()); + computed_columns::ensure_supported_function_metadata(&table_schema)?; computed_columns::ensure_not_written( &table_schema, add.data.schema().fields().iter().map(|f| f.name().as_str()), diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index 67764c346..3b91c30e4 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -9,6 +9,7 @@ use lance::dataset::NewColumnTransform; use super::BaseTable; use super::schema_evolution::AddColumnsResult; +use crate::function::FunctionApplication; use crate::{Error, Result}; /// Adds columns to a table. See [`Table::add_columns`](super::Table::add_columns). @@ -16,6 +17,7 @@ pub struct AddColumnsBuilder { parent: Arc, transform: Option, computed: Vec<(String, String)>, + function: Option<(FunctionApplication, Option)>, read_columns: Option>, } @@ -25,6 +27,7 @@ impl std::fmt::Debug for AddColumnsBuilder { .field("parent", &self.parent) .field("has_transform", &self.transform.is_some()) .field("computed", &self.computed) + .field("has_function", &self.function.is_some()) .field("read_columns", &self.read_columns) .finish() } @@ -36,6 +39,7 @@ impl AddColumnsBuilder { parent, transform: None, computed: Vec::new(), + function: None, read_columns: None, } } @@ -83,6 +87,48 @@ impl AddColumnsBuilder { self } + /// Declare every field of a named-struct Function result as one atomic + /// sibling group. Result-field aliases come from + /// [`FunctionApplication::columns`](crate::function::FunctionApplication::columns). + /// + /// ``` + /// # use lancedb::Table; + /// # use lancedb::function::FunctionApplication; + /// # async fn declare(table: &Table, application: FunctionApplication) -> lancedb::Result<()> { + /// table.add_columns().function(application).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn function(mut self, application: FunctionApplication) -> Self { + self.function = Some((application, None)); + self + } + + /// Declare a scalar or entire named-struct Function result as one table + /// column. The physical column starts all-null and is materialized by the + /// remote Function refresh path. + /// + /// ``` + /// # use lancedb::Table; + /// # use lancedb::function::FunctionApplication; + /// # async fn declare(table: &Table, application: FunctionApplication) -> lancedb::Result<()> { + /// table + /// .add_columns() + /// .function_as("embedding", application) + /// .execute() + /// .await?; + /// # Ok(()) + /// # } + /// ``` + pub fn function_as( + mut self, + name: impl Into, + application: FunctionApplication, + ) -> Self { + self.function = Some((application, Some(name.into()))); + self + } + /// Limit which existing columns a [`NewColumnTransform::BatchUDF`] mapper /// receives. Every other transform, and a computed column, determines what /// it reads, so setting this alongside one is an error rather than a silent @@ -98,21 +144,23 @@ impl AddColumnsBuilder { parent, transform, computed, + function, read_columns, } = self; - match (transform, computed.is_empty()) { - (None, true) => Err(Error::InvalidInput { + let declaration_count = usize::from(!computed.is_empty()) + usize::from(function.is_some()); + if transform.is_some() && declaration_count != 0 || declaration_count > 1 { + return Err(Error::InvalidInput { + message: "add_columns cannot mix transforms, SQL computed columns, and a Function application; they cannot be added atomically in one call" + .into(), + }); + } + + match (transform, computed.is_empty(), function) { + (None, true, None) => Err(Error::InvalidInput { message: "add_columns requires a transform or a computed column".into(), }), - // The two commit through different transforms, so one call covering - // both would be two commits and could half-apply. - (Some(_), false) => Err(Error::InvalidInput { - message: "add_columns cannot mix a transform with computed columns; \ - they cannot be added atomically in one call" - .into(), - }), - (Some(transform), true) => { + (Some(transform), true, None) => { if read_columns.is_some() && !matches!(transform, NewColumnTransform::BatchUDF(_)) { return Err(Error::InvalidInput { message: "read_columns applies only to a BatchUDF transform; \ @@ -122,7 +170,7 @@ impl AddColumnsBuilder { } parent.add_columns(transform, read_columns).await } - (None, false) => { + (None, false, None) => { if read_columns.is_some() { return Err(Error::InvalidInput { message: "read_columns applies only to a BatchUDF transform; \ @@ -132,6 +180,18 @@ impl AddColumnsBuilder { } parent.add_computed_columns(&computed).await } + (None, true, Some((application, output_name))) => { + if read_columns.is_some() { + return Err(Error::InvalidInput { + message: "read_columns does not apply to a Function application; its inputs are already bound" + .into(), + }); + } + parent + .add_function_columns(&application, output_name.as_deref()) + .await + } + _ => unreachable!("mixed add_columns modes were rejected above"), } } } diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 9a6a2585d..841b13856 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -12,13 +12,14 @@ //! where the column's type and inputs come from. A SQL expression is //! self-describing -- both are derived from the expression, so a caller writes //! neither -- while a kind resolved through a registry cannot be typed without -//! consulting it. Only SQL exists today; the tag is what lets another kind be -//! added without a second reading of the same key. +//! consulting it. Registered Functions use an exact remote version plus a +//! schema-level grouped binding; unknown newer kinds remain readable and fail +//! closed before mutation. //! //! [`computed_columns`] and [`computed_column_from_field`] read declarations //! back off a schema. -use std::collections::HashMap; +use std::collections::{BTreeSet, HashMap}; use std::sync::Arc; use arrow_schema::{DataType, Field as ArrowField, Schema as ArrowSchema, SchemaRef}; @@ -26,7 +27,11 @@ use datafusion_common::tree_node::TreeNode; use datafusion_physical_plan::PhysicalExpr; use lance::dataset::NewColumnTransform; use lance_datafusion::planner::Planner; +use lance_namespace::models::{JsonArrowDataType, JsonArrowField, JsonArrowSchema}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use crate::function::{FunctionApplication, FunctionBinding}; use crate::{Error, Result}; /// Field metadata key marking a column as computed. The value is `"true"`. @@ -41,9 +46,28 @@ pub const EXPRESSION_META_KEY: &str = "computed_column.expression"; /// Field metadata key holding the column's inputs, as a JSON array of names. pub const INPUTS_META_KEY: &str = "computed_column.inputs"; +/// Field metadata key holding the grouped Function binding identity. +pub const FUNCTION_BINDING_ID_META_KEY: &str = "computed_column.function.binding_id"; + +/// Field metadata key holding this sibling's ordered Function output ordinal. +pub const FUNCTION_OUTPUT_ORDINAL_META_KEY: &str = "computed_column.function.output_ordinal"; + +/// Schema metadata key holding all immutable grouped Function bindings. +pub const FUNCTION_BINDINGS_META_KEY: &str = "lancedb::function_bindings"; + +/// Version of the schema-level grouped Function binding envelope. +pub const FUNCTION_BINDINGS_VERSION: u32 = 1; + /// Value of [`KIND_META_KEY`] for a column defined by a SQL expression. pub const SQL_KIND: &str = "sql"; +/// Value of [`KIND_META_KEY`] for a registered Function binding. +pub const FUNCTION_KIND: &str = "function"; + +/// Synthetic result identity used when the entire Function result maps to one +/// table column (scalar or struct-as-one-column). +pub const WHOLE_RESULT_FIELD: &str = "$value"; + /// The rule that defines a computed column's values. /// /// Non-exhaustive: a kind added later is an additive change, and a caller that @@ -57,6 +81,14 @@ pub enum ComputedColumnKind { /// The expression. expression: String, }, + /// One physical output in an immutable grouped registered-Function + /// binding. The full binding lives in schema metadata. + Function { + /// Shared immutable binding identity. + binding_id: String, + /// Position of this field in the binding's ordered sibling outputs. + output_ordinal: u32, + }, /// A kind this version does not understand, written by a newer one. /// /// Reported rather than hidden so a caller can tell a column it cannot @@ -97,6 +129,251 @@ fn computed_column_metadata(expression: &str, inputs: &[String]) -> HashMap HashMap { + HashMap::from([ + (COMPUTED_COLUMN_META_KEY.to_string(), "true".to_string()), + (KIND_META_KEY.to_string(), FUNCTION_KIND.to_string()), + ( + FUNCTION_BINDING_ID_META_KEY.to_string(), + binding_id.to_string(), + ), + ( + FUNCTION_OUTPUT_ORDINAL_META_KEY.to_string(), + output_ordinal.to_string(), + ), + ( + INPUTS_META_KEY.to_string(), + serde_json::to_string(inputs).unwrap_or_else(|_| "[]".to_string()), + ), + ]) +} + +#[derive(Debug, Serialize, Deserialize)] +struct FunctionBindingEnvelope { + version: u32, + bindings: Vec, +} + +/// Encode immutable grouped bindings for schema-level persistence. +pub fn function_bindings_metadata(bindings: &[FunctionBinding]) -> Result { + let bindings = bindings + .iter() + .map(serde_json::to_value) + .collect::, _>>() + .map_err(|e| Error::InvalidInput { + message: format!("invalid Function binding metadata: {e}"), + })?; + serde_json::to_string(&FunctionBindingEnvelope { + version: FUNCTION_BINDINGS_VERSION, + bindings, + }) + .map_err(|e| Error::InvalidInput { + message: format!("invalid Function binding metadata: {e}"), + }) +} + +/// Decode known grouped Function bindings without rewriting their raw schema +/// metadata. Unknown envelope versions fail closed. +pub fn function_bindings(schema: &ArrowSchema) -> Result> { + let Some(envelope) = function_binding_envelope(schema)? else { + return Ok(Vec::new()); + }; + envelope + .bindings + .into_iter() + .map(|binding| { + serde_json::from_value(binding).map_err(|e| Error::InvalidInput { + message: format!("invalid Function binding metadata: {e}"), + }) + }) + .collect() +} + +fn function_binding_envelope(schema: &ArrowSchema) -> Result> { + let Some(raw) = schema.metadata().get(FUNCTION_BINDINGS_META_KEY) else { + return Ok(None); + }; + let envelope: FunctionBindingEnvelope = + serde_json::from_str(raw).map_err(|e| Error::InvalidInput { + message: format!("invalid Function binding metadata: {e}"), + })?; + if envelope.version != FUNCTION_BINDINGS_VERSION { + return Err(Error::NotSupported { + message: format!( + "Function binding metadata version {} is not supported by this client", + envelope.version + ), + }); + } + Ok(Some(envelope)) +} + +/// Validate metadata before a schema mutation. Read-only access remains +/// possible for older datasets, while incomplete or newer contracts cannot be +/// silently rewritten by this client. +pub(crate) fn ensure_supported_function_metadata(schema: &ArrowSchema) -> Result<()> { + let raw_bindings = function_binding_envelope(schema)? + .map(|envelope| envelope.bindings) + .unwrap_or_default(); + for value in &raw_bindings { + ensure_known_binding_shape(value)?; + } + let bindings = raw_bindings + .into_iter() + .map(|binding| { + serde_json::from_value(binding).map_err(|e| Error::InvalidInput { + message: format!("invalid Function binding metadata: {e}"), + }) + }) + .collect::>>()?; + let mut binding_ids = BTreeSet::new(); + for binding in &bindings { + if !binding_ids.insert(binding.binding_id().to_string()) { + return Err(Error::InvalidInput { + message: format!("duplicate Function binding '{}'", binding.binding_id()), + }); + } + if binding.revision() == 0 || binding.outputs().is_empty() { + return Err(Error::InvalidInput { + message: format!( + "Function binding '{}' has no immutable revision or outputs", + binding.binding_id() + ), + }); + } + if binding.function().name.is_empty() + || binding.function().version.is_empty() + || binding.group_id().is_empty() + { + return Err(Error::InvalidInput { + message: format!( + "Function binding '{}' has no exact version or group identity", + binding.binding_id() + ), + }); + } + if binding.input_schema().is_none() || binding.output_schema().is_none() { + return Err(Error::NotSupported { + message: format!( + "Function binding '{}' does not contain exact Arrow schemas", + binding.binding_id() + ), + }); + } + for (ordinal, output) in binding.outputs().iter().enumerate() { + if output.output_ordinal != ordinal as u32 { + return Err(Error::InvalidInput { + message: format!( + "Function binding '{}' has non-canonical output ordinals", + binding.binding_id() + ), + }); + } + } + ensure_binding_matches_schema(schema, binding)?; + } + + let bindings_by_id = bindings + .iter() + .map(|binding| (binding.binding_id(), binding)) + .collect::>(); + for field in schema.fields() { + if field + .metadata() + .get(COMPUTED_COLUMN_META_KEY) + .map(String::as_str) + != Some("true") + { + continue; + } + match computed_column_from_field(field) { + Some(ComputedColumn { + kind: + ComputedColumnKind::Function { + binding_id, + output_ordinal, + }, + .. + }) => { + let binding = + bindings_by_id + .get(binding_id.as_str()) + .ok_or_else(|| Error::InvalidInput { + message: format!( + "Function output '{}' references missing binding '{}'", + field.name(), + binding_id + ), + })?; + let output = binding + .outputs() + .get(output_ordinal as usize) + .ok_or_else(|| Error::InvalidInput { + message: format!( + "Function output '{}' has invalid ordinal {}", + field.name(), + output_ordinal + ), + })?; + if output.output_name != field.name().as_str() { + return Err(Error::InvalidInput { + message: format!( + "Function output '{}' does not match binding destination '{}'", + field.name(), + output.output_name + ), + }); + } + } + Some(ComputedColumn { + kind: ComputedColumnKind::Sql { .. }, + .. + }) => {} + Some(ComputedColumn { + kind: ComputedColumnKind::Unrecognized { kind }, + .. + }) => { + return Err(Error::NotSupported { + message: format!( + "computed column '{}' uses unsupported kind '{}'", + field.name(), + kind + ), + }); + } + None => { + return Err(Error::InvalidInput { + message: format!( + "computed column '{}' has incomplete declaration metadata", + field.name() + ), + }); + } + } + } + Ok(()) +} + +pub(crate) fn ensure_no_function_bindings_for_mutation( + schema: &ArrowSchema, + operation: &str, +) -> Result<()> { + ensure_supported_function_metadata(schema)?; + if !function_bindings(schema)?.is_empty() { + return Err(Error::NotSupported { + message: format!( + "{operation} is not supported on a table with registered Function bindings" + ), + }); + } + Ok(()) +} + /// Read a field's computed-column declaration, if it carries one. /// /// A field flagged computed but carrying no kind, or a SQL one missing its @@ -114,6 +391,22 @@ pub fn computed_column_from_field(field: &ArrowField) -> Option SQL_KIND => ComputedColumnKind::Sql { expression: metadata.get(EXPRESSION_META_KEY)?.clone(), }, + FUNCTION_KIND => match ( + metadata.get(FUNCTION_BINDING_ID_META_KEY), + metadata + .get(FUNCTION_OUTPUT_ORDINAL_META_KEY) + .and_then(|value| value.parse::().ok()), + ) { + (Some(binding_id), Some(output_ordinal)) if !binding_id.is_empty() => { + ComputedColumnKind::Function { + binding_id: binding_id.clone(), + output_ordinal, + } + } + _ => ComputedColumnKind::Unrecognized { + kind: FUNCTION_KIND.to_string(), + }, + }, other => ComputedColumnKind::Unrecognized { kind: other.to_string(), }, @@ -142,6 +435,552 @@ pub fn computed_columns(schema: &ArrowSchema) -> Vec { .collect() } +#[derive(Debug, Clone, Serialize)] +pub(crate) struct FunctionOutputTarget { + pub result_field: String, + pub output_name: String, + pub output_ordinal: u32, +} + +#[derive(Debug, Clone, Serialize)] +pub(crate) struct FunctionInputTarget { + pub parameter: String, + pub field_path: String, + pub arrow_type: String, + pub nullable: bool, +} + +#[derive(Debug, Clone, Serialize)] +pub(crate) struct FunctionDeclarationPlan { + pub application: FunctionApplication, + pub binding_metadata_version: u32, + pub input_bindings: Vec, + pub input_schema: JsonArrowSchema, + pub output_schema: JsonArrowSchema, + pub outputs: Vec, +} + +fn invalid_function(message: impl Into) -> Error { + Error::InvalidInput { + message: message.into(), + } +} + +fn reject_unknown_object_fields(value: &Value, allowed: &[&str], context: &str) -> Result<()> { + let object = value.as_object().ok_or_else(|| { + invalid_function(format!( + "invalid Function binding metadata: {context} must be an object" + )) + })?; + let unknown = object + .keys() + .filter(|key| !allowed.contains(&key.as_str())) + .cloned() + .collect::>(); + if unknown.is_empty() { + Ok(()) + } else { + Err(Error::NotSupported { + message: format!( + "Function binding metadata contains newer {context} fields: {unknown:?}" + ), + }) + } +} + +fn ensure_known_binding_shape(value: &Value) -> Result<()> { + reject_unknown_object_fields( + value, + &[ + "binding_id", + "revision", + "function", + "group_id", + "inputs", + "outputs", + "input_schema", + "output_schema", + ], + "binding", + )?; + let object = value.as_object().unwrap(); + reject_unknown_object_fields( + object + .get("function") + .ok_or_else(|| invalid_function("Function binding is missing its exact version"))?, + &["name", "version"], + "version reference", + )?; + for input in object + .get("inputs") + .and_then(Value::as_array) + .ok_or_else(|| invalid_function("Function binding inputs must be an array"))? + { + reject_unknown_object_fields( + input, + &[ + "parameter", + "field_id", + "field_path", + "arrow_type", + "nullable", + ], + "input binding", + )?; + } + for output in object + .get("outputs") + .and_then(Value::as_array) + .ok_or_else(|| invalid_function("Function binding outputs must be an array"))? + { + reject_unknown_object_fields( + output, + &[ + "result_field", + "output_name", + "output_field_id", + "output_ordinal", + "arrow_type", + "nullable", + ], + "output mapping", + )?; + } + Ok(()) +} + +fn resolve_field_path<'a>(schema: &'a ArrowSchema, path: &str) -> Result<&'a ArrowField> { + let parts = lance_core::datatypes::parse_field_path(path).map_err(|e| { + invalid_function(format!("invalid Function input field path '{path}': {e}")) + })?; + let Some((root, children)) = parts.split_first() else { + return Err(invalid_function( + "Function input field path cannot be empty", + )); + }; + let mut field = schema + .field_with_name(root) + .map_err(|_| invalid_function(format!("unknown Function input column '{path}'")))?; + for child in children { + let DataType::Struct(fields) = field.data_type() else { + return Err(invalid_function(format!( + "Function input field path '{path}' traverses a non-struct field" + ))); + }; + field = fields + .iter() + .find(|field| field.name() == child) + .map(AsRef::as_ref) + .ok_or_else(|| invalid_function(format!("unknown Function input column '{path}'")))?; + } + Ok(field) +} + +fn canonical_input_arrow_type(field: &JsonArrowField) -> Result { + if field.r#type.fields.is_none() && field.r#type.length.is_none() { + Ok(field.r#type.r#type.clone()) + } else { + serde_json::to_string(field.r#type.as_ref()).map_err(|e| { + invalid_function(format!("could not encode exact Function input type: {e}")) + }) + } +} + +fn parse_output_arrow_type(raw: &str) -> Result { + fn parse(raw: &str) -> Result { + let raw = raw.trim(); + if raw.starts_with('{') { + return serde_json::from_str(raw).map_err(|e| { + invalid_function(format!("invalid Function Arrow type '{raw}': {e}")) + }); + } + if let Some(inner) = raw + .strip_prefix("list<") + .and_then(|value| value.strip_suffix('>')) + { + let mut data_type = JsonArrowDataType::new("list".to_string()); + data_type.fields = Some(vec![JsonArrowField::new( + "item".to_string(), + false, + parse(inner)?, + )]); + return Ok(data_type); + } + if let Some(inner) = raw + .strip_prefix("large_list<") + .and_then(|value| value.strip_suffix('>')) + { + let mut data_type = JsonArrowDataType::new("large_list".to_string()); + data_type.fields = Some(vec![JsonArrowField::new( + "item".to_string(), + false, + parse(inner)?, + )]); + return Ok(data_type); + } + let normalized = match raw { + "boolean" => "bool", + "string" => "utf8", + "large_string" => "large_utf8", + "halffloat" => "float16", + "float" => "float32", + "double" => "float64", + other => other, + }; + Ok(JsonArrowDataType::new(normalized.to_string())) + } + + let data_type = parse(raw)?; + lance_namespace::schema::convert_json_arrow_type(&data_type) + .map_err(|e| invalid_function(format!("unsupported Function Arrow type '{raw}': {e}")))?; + Ok(data_type) +} + +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() { + let field = resolve_field_path(schema, &input.field_path)?; + if field + .metadata() + .get(COMPUTED_COLUMN_META_KEY) + .map(String::as_str) + == Some("true") + { + return Err(invalid_function(format!( + "Function input '{}' is computed", + input.field_path + ))); + } + if field.is_nullable() != input.nullable { + return Err(invalid_function(format!( + "Function input '{}' no longer matches binding '{}'", + input.field_path, + binding.binding_id() + ))); + } + let parameter_field = ArrowField::new( + input.parameter.clone(), + field.data_type().clone(), + field.is_nullable(), + ) + .with_metadata(field.metadata().clone()); + let json = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ + parameter_field.clone(), + ])) + .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; + let json_field = json.fields.into_iter().next().unwrap(); + if canonical_input_arrow_type(&json_field)? != input.arrow_type { + return Err(invalid_function(format!( + "Function input '{}' type no longer matches binding '{}'", + input.field_path, + binding.binding_id() + ))); + } + input_fields.push(parameter_field); + } + 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}")))?; + let input_schema = serde_json::to_value(input_schema).map_err(|e| { + invalid_function(format!("could not encode exact Function input schema: {e}")) + })?; + if binding.input_schema() != Some(&input_schema) { + return Err(invalid_function(format!( + "Function binding '{}' input schema does not match its inputs", + binding.binding_id() + ))); + } + + let mut output_fields = Vec::with_capacity(binding.outputs().len()); + for output in binding.outputs() { + let field = schema.field_with_name(&output.output_name).map_err(|_| { + invalid_function(format!( + "Function binding '{}' output '{}' is missing", + binding.binding_id(), + output.output_name + )) + })?; + if field.name() != &output.output_name || !field.is_nullable() || output.nullable { + return Err(invalid_function(format!( + "Function output '{}' no longer matches binding '{}'", + output.output_name, + binding.binding_id() + ))); + } + let expected_type = parse_output_arrow_type(&output.arrow_type)?; + let expected_type = lance_namespace::schema::convert_json_arrow_type(&expected_type) + .map_err(|e| invalid_function(format!("invalid Function output type: {e}")))?; + if field.data_type() != &expected_type { + return Err(invalid_function(format!( + "Function output '{}' type no longer matches binding '{}'", + output.output_name, + binding.binding_id() + ))); + } + output_fields.push(ArrowField::new( + field.name().clone(), + field.data_type().clone(), + true, + )); + } + let output_schema = + lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(output_fields)) + .map_err(|e| invalid_function(format!("invalid Function output schema: {e}")))?; + let output_schema = serde_json::to_value(output_schema).map_err(|e| { + invalid_function(format!( + "could not encode exact Function output schema: {e}" + )) + })?; + if binding.output_schema() != Some(&output_schema) { + return Err(invalid_function(format!( + "Function binding '{}' output schema does not match physical siblings", + binding.binding_id() + ))); + } + Ok(()) +} + +/// Resolve a Function application against a table schema before any request is +/// serialized. Input paths and the complete sibling output schema are fixed in +/// one plan. +pub(crate) fn plan_function_application( + schema: &ArrowSchema, + application: &FunctionApplication, + output_name: Option<&str>, +) -> Result { + ensure_no_function_bindings_for_mutation(schema, "Function binding declaration")?; + if application.has_unknown_fields() { + return Err(Error::NotSupported { + message: "Function application contains fields from a newer contract".into(), + }); + } + if application.function().name.is_empty() + || application.function().version.is_empty() + || application.group_id().is_empty() + { + return Err(invalid_function( + "Function application requires an exact version and group identity", + )); + } + + let mut parameters = BTreeSet::new(); + let mut input_bindings = Vec::with_capacity(application.inputs().len()); + let mut input_fields = Vec::with_capacity(application.inputs().len()); + for input in application.inputs() { + if !parameters.insert(input.parameter.as_str()) { + return Err(invalid_function(format!( + "duplicate Function parameter '{}'", + input.parameter + ))); + } + if input.kind != "column" { + return Err(Error::NotSupported { + message: format!( + "Function input kind '{}' is not supported for column declaration", + input.kind + ), + }); + } + let source = input.value.as_object().ok_or_else(|| { + invalid_function(format!( + "Function parameter '{}' has an invalid column source", + input.parameter + )) + })?; + if source.len() != 1 { + return Err(Error::NotSupported { + message: format!( + "Function parameter '{}' uses a newer column source contract", + input.parameter + ), + }); + } + let path = source.get("path").and_then(Value::as_str).ok_or_else(|| { + invalid_function(format!( + "Function parameter '{}' requires a column path", + input.parameter + )) + })?; + let field = resolve_field_path(schema, path)?; + if field + .metadata() + .get(COMPUTED_COLUMN_META_KEY) + .map(String::as_str) + == Some("true") + { + return Err(invalid_function(format!( + "Function input '{path}' is computed; computed-on-computed bindings are not supported" + ))); + } + let parameter_field = ArrowField::new( + input.parameter.clone(), + field.data_type().clone(), + field.is_nullable(), + ) + .with_metadata(field.metadata().clone()); + let input_schema = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ + parameter_field.clone(), + ])) + .map_err(|e| invalid_function(format!("invalid Function input schema: {e}")))?; + let json_field = input_schema.fields.into_iter().next().unwrap(); + input_bindings.push(FunctionInputTarget { + parameter: input.parameter.clone(), + field_path: path.to_string(), + arrow_type: canonical_input_arrow_type(&json_field)?, + nullable: field.is_nullable(), + }); + input_fields.push(parameter_field); + } + 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}")))?; + + let output = application.output(); + let mut outputs = Vec::new(); + let mut output_fields = Vec::new(); + match output.kind.as_str() { + "scalar" => { + if !application.columns().is_empty() { + return Err(invalid_function( + "scalar Function applications cannot rename result fields", + )); + } + let name = output_name.ok_or_else(|| { + invalid_function( + "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 data_type = + parse_output_arrow_type(output.arrow_type.as_deref().ok_or_else(|| { + invalid_function("scalar Function output is missing its Arrow type") + })?)?; + outputs.push(FunctionOutputTarget { + result_field: WHOLE_RESULT_FIELD.to_string(), + output_name: name.to_string(), + output_ordinal: 0, + }); + output_fields.push(JsonArrowField::new(name.to_string(), true, data_type)); + } + "named_struct" => { + if output.fields.is_empty() { + return Err(invalid_function( + "named-struct Function output requires at least one field", + )); + } + let result_names = output + .fields + .iter() + .map(|field| field.name.as_str()) + .collect::>(); + if result_names.len() != output.fields.len() { + return Err(invalid_function( + "named-struct Function result field names must be unique", + )); + } + if output.fields.iter().any(|field| field.nullable) { + return Err(invalid_function( + "Function logical outputs must be non-nullable during NULL assignment", + )); + } + let unknown = application + .columns() + .keys() + .filter(|name| !result_names.contains(name.as_str())) + .cloned() + .collect::>(); + if !unknown.is_empty() { + return Err(invalid_function(format!( + "unknown Function result fields: {unknown:?}" + ))); + } + + if let Some(name) = output_name { + if !application.columns().is_empty() { + return Err(invalid_function( + "a named-struct mapped to one column cannot also rename expanded fields", + )); + } + let fields = output + .fields + .iter() + .map(|field| { + Ok(JsonArrowField::new( + field.name.clone(), + false, + parse_output_arrow_type(&field.arrow_type)?, + )) + }) + .collect::>>()?; + let mut data_type = JsonArrowDataType::new("struct".to_string()); + data_type.fields = Some(fields); + outputs.push(FunctionOutputTarget { + result_field: WHOLE_RESULT_FIELD.to_string(), + output_name: name.to_string(), + output_ordinal: 0, + }); + output_fields.push(JsonArrowField::new(name.to_string(), true, data_type)); + } else { + let mut destinations = BTreeSet::new(); + for (ordinal, field) in output.fields.iter().enumerate() { + let name = application + .columns() + .get(&field.name) + .unwrap_or(&field.name); + if !destinations.insert(name.as_str()) { + return Err(invalid_function( + "Function output destinations must be unique", + )); + } + outputs.push(FunctionOutputTarget { + result_field: field.name.clone(), + output_name: name.clone(), + output_ordinal: ordinal as u32, + }); + output_fields.push(JsonArrowField::new( + name.clone(), + true, + parse_output_arrow_type(&field.arrow_type)?, + )); + } + } + } + kind => { + return Err(Error::NotSupported { + message: format!( + "Function output kind '{kind}' is not supported for column declaration" + ), + }); + } + } + + for output in &outputs { + if output.output_name.is_empty() { + return Err(invalid_function( + "Function output column name cannot be empty", + )); + } + if schema.field_with_name(&output.output_name).is_ok() { + return Err(Error::ColumnAlreadyExists { + name: output.output_name.clone(), + }); + } + } + + Ok(FunctionDeclarationPlan { + application: application.clone(), + binding_metadata_version: FUNCTION_BINDINGS_VERSION, + input_bindings, + input_schema, + output_schema: JsonArrowSchema::new(output_fields), + outputs, + }) +} + /// Reject a schema change to a column some declaration reads. /// /// A binding is SQL text naming its inputs, so renaming, retyping or dropping @@ -783,7 +1622,7 @@ mod tests { let err = add_computed(&table, &[("embedding".into(), "x * 2".into())]) .await .unwrap_err(); - assert!(matches!(err, Error::ColumnAlreadyExists { name } if name == "embedding")); + assert!(matches!(err, Error::NotSupported { .. })); } /// A kind is what makes a declaration readable at all, so the flag alone @@ -1345,4 +2184,241 @@ mod tests { table.drop_columns(&["doubled"]).await.unwrap(); assert!(declared(&table).await.is_empty()); } + + fn function_input_schema() -> ArrowSchema { + ArrowSchema::new(vec![ + ArrowField::new("title", DataType::Utf8, true), + ArrowField::new("body", DataType::Utf8, true), + ]) + } + + fn named_struct_application(columns: &str) -> FunctionApplication { + FunctionApplication::from_json(&format!( + r#"{{ + "function":{{"name":"text_features","version":"fv_exact"}}, + "inputs":[ + {{"parameter":"title","kind":"column","value":{{"path":"title"}}}}, + {{"parameter":"body","kind":"column","value":{{"path":"body"}}}} + ], + "output":{{"kind":"named_struct","fields":[ + {{"name":"normalized_text","arrow_type":"utf8","nullable":false}}, + {{"name":"token_count","arrow_type":"int64","nullable":false}} + ]}}, + "group_id":"fg_exact", + "columns":{columns} + }}"# + )) + .unwrap() + } + + #[test] + fn test_function_binding_metadata_survives_schema_round_trip() { + let binding = FunctionBinding::from_json(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + let raw = function_bindings_metadata(std::slice::from_ref(&binding)).unwrap(); + let mut fields = vec![ + ArrowField::new("title", DataType::Utf8, true), + ArrowField::new("body", DataType::Utf8, true), + ]; + fields.extend( + binding + .outputs() + .iter() + .map(|output| { + let data_type = match output.arrow_type.as_str() { + "utf8" => DataType::Utf8, + "int64" => DataType::Int64, + other => panic!("unexpected fixture output type {other}"), + }; + let metadata = function_computed_column_metadata( + binding.binding_id(), + output.output_ordinal, + &["title".into(), "body".into()], + ); + ArrowField::new(&output.output_name, data_type, true).with_metadata(metadata) + }) + .collect::>(), + ); + let schema = ArrowSchema::new_with_metadata( + fields, + HashMap::from([(FUNCTION_BINDINGS_META_KEY.to_string(), raw)]), + ); + + let reopened = + ArrowSchema::new_with_metadata(schema.fields().to_vec(), schema.metadata().clone()); + let bindings = function_bindings(&reopened).unwrap(); + assert_eq!(bindings, vec![binding.clone()]); + assert!(bindings[0].input_schema().is_some()); + assert!(bindings[0].output_schema().is_some()); + assert!(matches!( + computed_column_from_field(reopened.field(3)).unwrap().kind, + ComputedColumnKind::Function { + ref binding_id, + output_ordinal: 1, + } if binding_id == "fb_01K3TEXT" + )); + let err = plan_function_application(&reopened, &named_struct_application("{}"), None) + .unwrap_err(); + assert!(matches!(err, Error::NotSupported { .. })); + } + + #[test] + fn test_newer_binding_fields_remain_readable_but_fail_closed_on_mutation() { + let raw_binding: Value = serde_json::from_str(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + let binding: FunctionBinding = serde_json::from_value(raw_binding.clone()).unwrap(); + assert_eq!(binding.binding_id(), "fb_01K3TEXT"); + + let schema = ArrowSchema::new_with_metadata( + Vec::::new(), + HashMap::from([( + FUNCTION_BINDINGS_META_KEY.to_string(), + serde_json::json!({ + "version": FUNCTION_BINDINGS_VERSION, + "bindings": [raw_binding], + }) + .to_string(), + )]), + ); + let err = ensure_supported_function_metadata(&schema).unwrap_err(); + assert!(matches!(err, Error::NotSupported { .. })); + } + + #[test] + fn test_named_struct_can_be_kept_as_one_nullable_physical_column() { + let application = named_struct_application("{}"); + let plan = + plan_function_application(&function_input_schema(), &application, Some("features")) + .unwrap(); + + assert_eq!(plan.outputs.len(), 1); + assert_eq!(plan.outputs[0].result_field, WHOLE_RESULT_FIELD); + 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, "struct"); + assert_eq!( + plan.output_schema.fields[0] + .r#type + .fields + .as_ref() + .unwrap() + .len(), + 2 + ); + } + + #[test] + fn test_function_mapping_and_sibling_collisions_fail_before_request() { + let unknown = named_struct_application(r#"{"missing":"renamed"}"#); + let err = plan_function_application(&function_input_schema(), &unknown, None).unwrap_err(); + assert!(matches!(&err, Error::InvalidInput { message } if message.contains("unknown"))); + + let duplicate = + named_struct_application(r#"{"normalized_text":"same","token_count":"same"}"#); + let err = + plan_function_application(&function_input_schema(), &duplicate, None).unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("destinations")) + ); + + let mut fields = function_input_schema().fields().to_vec(); + fields.push(Arc::new(ArrowField::new( + "token_count", + DataType::Int64, + true, + ))); + let collision_schema = ArrowSchema::new(fields); + let err = + plan_function_application(&collision_schema, &named_struct_application("{}"), None) + .unwrap_err(); + assert!(matches!(err, Error::ColumnAlreadyExists { name } if name == "token_count")); + } + + #[test] + fn test_unknown_and_mixed_version_function_contracts_fail_closed() { + let application = FunctionApplication::from_json( + r#"{ + "function":{"name":"f","version":"fv"}, + "inputs":[{"parameter":"title","kind":"future_source","value":{"path":"title"}}], + "output":{"kind":"scalar","arrow_type":"int64","nullable":false}, + "group_id":"fg" + }"#, + ) + .unwrap(); + let err = plan_function_application(&function_input_schema(), &application, Some("out")) + .unwrap_err(); + assert!(matches!(err, Error::NotSupported { .. })); + + let future_application = FunctionApplication::from_json( + r#"{ + "function":{"name":"f","version":"fv"}, + "inputs":[], + "output":{"kind":"scalar","arrow_type":"int64","nullable":false}, + "group_id":"fg", + "future_declaration":{"mode":"managed"} + }"#, + ) + .unwrap(); + let err = + plan_function_application(&function_input_schema(), &future_application, Some("out")) + .unwrap_err(); + assert!(matches!(err, Error::NotSupported { .. })); + + let nested_future_application = FunctionApplication::from_json( + r#"{ + "function":{"name":"f","version":"fv"}, + "inputs":[], + "output":{"kind":"scalar","arrow_type":"int64","nullable":false,"assignment":"cell_flag"}, + "group_id":"fg" + }"#, + ) + .unwrap(); + let err = plan_function_application( + &function_input_schema(), + &nested_future_application, + Some("out"), + ) + .unwrap_err(); + assert!(matches!(err, Error::NotSupported { .. })); + + let mixed_schema = ArrowSchema::new_with_metadata( + function_input_schema().fields().to_vec(), + HashMap::from([( + FUNCTION_BINDINGS_META_KEY.to_string(), + r#"{"version":2,"bindings":[]}"#.to_string(), + )]), + ); + let err = plan_function_application(&mixed_schema, &named_struct_application("{}"), None) + .unwrap_err(); + assert!(matches!(err, Error::NotSupported { .. })); + } + + #[test] + fn test_function_inputs_use_paths_and_cannot_be_computed() { + let mut schema = function_input_schema(); + let plan = + plan_function_application(&schema, &named_struct_application("{}"), None).unwrap(); + assert_eq!(plan.input_bindings[0].field_path, "title"); + assert_eq!(plan.input_bindings[1].field_path, "body"); + + let title = schema + .field(0) + .as_ref() + .clone() + .with_metadata(HashMap::from([ + (COMPUTED_COLUMN_META_KEY.to_string(), "true".to_string()), + (KIND_META_KEY.to_string(), SQL_KIND.to_string()), + (EXPRESSION_META_KEY.to_string(), "title".to_string()), + ])); + schema = ArrowSchema::new(vec![title, schema.field(1).as_ref().clone()]); + let err = + plan_function_application(&schema, &named_struct_application("{}"), None).unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("computed-on-computed")) + ); + } } diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 3a5b6882d..ea68e99df 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -233,6 +233,10 @@ pub(crate) async fn execute_merge_insert( params: MergeInsertBuilder, new_data: Box, ) -> Result { + super::computed_columns::ensure_no_function_bindings_for_mutation( + table.schema().await?.as_ref(), + "merge_insert", + )?; match lsm::lsm_dispatch_decision(table, ¶ms).await? { lsm::LsmDispatch::Lsm(plan) => { let future = diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index b29c97e98..e94f20f2b 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -169,6 +169,9 @@ fn declared_expression(dataset: &Dataset, column: &str) -> Result { })?; match declaration.kind { ComputedColumnKind::Sql { expression } => Ok(expression), + ComputedColumnKind::Function { .. } => Err(Error::NotSupported { + message: "registered Function columns are refreshed only by a remote server Job".into(), + }), ComputedColumnKind::Unrecognized { kind } => Err(Error::NotSupported { message: format!( "computed column '{column}' is defined by '{kind}', which this version of \ diff --git a/rust/lancedb/src/table/schema_evolution.rs b/rust/lancedb/src/table/schema_evolution.rs index 7503fd790..4e41f0e85 100644 --- a/rust/lancedb/src/table/schema_evolution.rs +++ b/rust/lancedb/src/table/schema_evolution.rs @@ -101,6 +101,10 @@ pub(crate) async fn execute_add_columns( transforms: NewColumnTransform, read_columns: Option>, ) -> Result { + computed_columns::ensure_no_function_bindings_for_mutation( + table.schema().await?.as_ref(), + "schema evolution", + )?; // Declarations are admitted only through [`execute_declare`]. match &transforms { NewColumnTransform::AllNulls(schema) => { @@ -124,6 +128,10 @@ pub(crate) async fn execute_declare( // checked against latest committed state, not this handle's snapshot. // The catch-up flag outlives unset and marks retained SSTable rows. table.checkout_latest().await?; + computed_columns::ensure_no_function_bindings_for_mutation( + table.schema().await?.as_ref(), + "schema evolution", + )?; let catchup = table.dataset.get().await?.manifest().reader_feature_flags & lance_table::feature_flags::FLAG_MEM_WAL_INDEX_CATCHUP != 0; @@ -163,6 +171,10 @@ pub(crate) async fn execute_alter_columns( // Nullability is not part of what an expression resolves against, so only // a rename or a retype can invalidate a binding. let schema = std::sync::Arc::new(ArrowSchema::from(dataset.schema())); + computed_columns::ensure_no_function_bindings_for_mutation( + schema.as_ref(), + "schema evolution", + )?; let rebinding = alterations .iter() .filter(|alteration| alteration.rename.is_some() || alteration.data_type.is_some()) @@ -190,6 +202,10 @@ pub(crate) async fn execute_drop_columns( ) -> Result { table.dataset.ensure_mutable()?; let mut dataset = (*table.dataset.get().await?).clone(); + computed_columns::ensure_no_function_bindings_for_mutation( + &ArrowSchema::from(dataset.schema()), + "schema evolution", + )?; computed_columns::ensure_not_an_input( &std::sync::Arc::new(ArrowSchema::from(dataset.schema())), columns, @@ -215,6 +231,7 @@ pub(crate) async fn execute_update_field_metadata( // binding out from under a refresh. A replace on a declared column would // silently erase it. let schema = ArrowSchema::from(dataset.schema()); + computed_columns::ensure_no_function_bindings_for_mutation(&schema, "schema evolution")?; let declared: Vec = computed_columns::computed_columns(&schema) .into_iter() .map(|declaration| declaration.name) diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index fd9fa6828..98050dfe8 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -82,6 +82,10 @@ pub(crate) async fn execute_update( // 1. Snapshot the current dataset let dataset = table.dataset.get().await?; + super::computed_columns::ensure_no_function_bindings_for_mutation( + &arrow_schema::Schema::from(dataset.schema()), + "update", + )?; super::computed_columns::ensure_not_written( &arrow_schema::Schema::from(dataset.schema()), update.columns.iter().map(|(name, _)| name.as_str()), diff --git a/rust/lancedb/tests/first_class_function_slice1.rs b/rust/lancedb/tests/first_class_function_slice1.rs index dab05fe48..dc565d309 100644 --- a/rust/lancedb/tests/first_class_function_slice1.rs +++ b/rust/lancedb/tests/first_class_function_slice1.rs @@ -88,6 +88,8 @@ fn application_and_binding_match_shared_remote_goldens() { assert_eq!(binding.function().version, "fv_01K3TEXT"); assert_eq!(binding.outputs()[0].output_ordinal, 0); assert_eq!(binding.outputs()[1].output_ordinal, 1); + assert!(binding.input_schema().is_some()); + assert!(binding.output_schema().is_some()); assert_eq!( binding.to_canonical_json().expect("canonical JSON"), fixture("remote_function_binding.canonical.json").trim() diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.canonical.json index c548c4a58..7bf93b8a8 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.canonical.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.canonical.json @@ -1 +1 @@ -{"binding_id":"fb_01K3TEXT","function":{"name":"text_features","version":"fv_01K3TEXT"},"group_id":"fg_01K3TEXT","inputs":[{"arrow_type":"utf8","field_id":11,"field_path":"title","nullable":true,"parameter":"title"},{"arrow_type":"utf8","field_id":12,"field_path":"body","nullable":true,"parameter":"body"}],"outputs":[{"arrow_type":"utf8","nullable":false,"output_field_id":21,"output_name":"search_text","output_ordinal":0,"result_field":"normalized_text"},{"arrow_type":"int64","nullable":false,"output_field_id":22,"output_name":"search_token_count","output_ordinal":1,"result_field":"token_count"}],"revision":3} +{"binding_id":"fb_01K3TEXT","function":{"name":"text_features","version":"fv_01K3TEXT"},"group_id":"fg_01K3TEXT","input_schema":{"fields":[{"name":"title","nullable":true,"type":{"type":"utf8"}},{"name":"body","nullable":true,"type":{"type":"utf8"}}]},"inputs":[{"arrow_type":"utf8","field_id":11,"field_path":"title","nullable":true,"parameter":"title"},{"arrow_type":"utf8","field_id":12,"field_path":"body","nullable":true,"parameter":"body"}],"output_schema":{"fields":[{"name":"search_text","nullable":true,"type":{"type":"utf8"}},{"name":"search_token_count","nullable":true,"type":{"type":"int64"}}]},"outputs":[{"arrow_type":"utf8","nullable":false,"output_field_id":21,"output_name":"search_text","output_ordinal":0,"result_field":"normalized_text"},{"arrow_type":"int64","nullable":false,"output_field_id":22,"output_name":"search_token_count","output_ordinal":1,"result_field":"token_count"}],"revision":3} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.json index 5d8193eea..1a2053e42 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.json @@ -11,5 +11,17 @@ {"result_field": "normalized_text", "output_name": "search_text", "output_field_id": 21, "output_ordinal": 0, "arrow_type": "utf8", "nullable": false}, {"result_field": "token_count", "output_name": "search_token_count", "output_field_id": 22, "output_ordinal": 1, "arrow_type": "int64", "nullable": false} ], + "input_schema": { + "fields": [ + {"name": "title", "nullable": true, "type": {"type": "utf8"}}, + {"name": "body", "nullable": true, "type": {"type": "utf8"}} + ] + }, + "output_schema": { + "fields": [ + {"name": "search_text", "nullable": true, "type": {"type": "utf8"}}, + {"name": "search_token_count", "nullable": true, "type": {"type": "int64"}} + ] + }, "future_binding": {"metadata_revision": 1} } diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_grouped_declaration_request.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_grouped_declaration_request.json new file mode 100644 index 000000000..d0b42cc99 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_grouped_declaration_request.json @@ -0,0 +1,45 @@ +{ + "new_columns": [ + {"name": "search_text", "all_null": true}, + {"name": "token_count", "all_null": true} + ], + "function": { + "application": { + "function": {"name": "text_features", "version": "fv_01K3TEXT"}, + "inputs": [ + {"parameter": "title", "kind": "column", "value": {"path": "title"}}, + {"parameter": "body", "kind": "column", "value": {"path": "body"}} + ], + "output": { + "kind": "named_struct", + "fields": [ + {"name": "normalized_text", "arrow_type": "utf8", "nullable": false}, + {"name": "token_count", "arrow_type": "int64", "nullable": false} + ] + }, + "group_id": "fg_01K3TEXT", + "columns": {"normalized_text": "search_text"} + }, + "binding_metadata_version": 1, + "input_bindings": [ + {"parameter": "title", "field_path": "title", "arrow_type": "utf8", "nullable": true}, + {"parameter": "body", "field_path": "body", "arrow_type": "utf8", "nullable": true} + ], + "input_schema": { + "fields": [ + {"name": "title", "nullable": true, "type": {"type": "utf8"}}, + {"name": "body", "nullable": true, "type": {"type": "utf8"}} + ] + }, + "output_schema": { + "fields": [ + {"name": "search_text", "nullable": true, "type": {"type": "utf8"}}, + {"name": "token_count", "nullable": true, "type": {"type": "int64"}} + ] + }, + "outputs": [ + {"result_field": "normalized_text", "output_name": "search_text", "output_ordinal": 0}, + {"result_field": "token_count", "output_name": "token_count", "output_ordinal": 1} + ] + } +} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_scalar_declaration_request.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_scalar_declaration_request.json new file mode 100644 index 000000000..0aaa0cf72 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_scalar_declaration_request.json @@ -0,0 +1,41 @@ +{ + "new_columns": [ + {"name": "embedding", "all_null": true} + ], + "function": { + "application": { + "function": {"name": "embed", "version": "fv_01K3EXACT"}, + "inputs": [ + {"parameter": "text", "kind": "column", "value": {"path": "description"}} + ], + "output": {"kind": "scalar", "arrow_type": "list", "nullable": false}, + "group_id": "fg_scalar" + }, + "binding_metadata_version": 1, + "input_bindings": [ + {"parameter": "text", "field_path": "description", "arrow_type": "utf8", "nullable": true} + ], + "input_schema": { + "fields": [ + {"name": "text", "nullable": true, "type": {"type": "utf8"}} + ] + }, + "output_schema": { + "fields": [ + { + "name": "embedding", + "nullable": true, + "type": { + "type": "list", + "fields": [ + {"name": "item", "nullable": false, "type": {"type": "float32"}} + ] + } + } + ] + }, + "outputs": [ + {"result_field": "$value", "output_name": "embedding", "output_ordinal": 0} + ] + } +} From a588208de68e1d887a17d02b3b326812b42f56fc Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 21 Aug 2026 17:19:13 +0800 Subject: [PATCH 063/206] feat: add scalar function authoring and catalog client (#3991) ## Problem The canonical Function wire values and typed remote Job contract do not yet provide a Python authoring surface or catalog client, so users cannot package a scalar callable, register it, or reopen the exact immutable Function version. ## Behavior This adds scalar-only `@udf` authoring with deterministic annotation or explicit Arrow schema validation, content-addressed Python artifacts, and an internal scalar-to-Arrow-batch adapter descriptor. Registration payloads model non-secret environment values and secret names only. Remote connections can submit `create_function_async` and receive a typed `Job`, then reopen that exact version by name and version ID. Synchronous connections can call `create_function` to submit and wait for the immutable version in one operation. Local Function catalog operations return a stable `NotSupported` error. Shared Rust/Python golden payloads and mocked catalog responses freeze the request, typed terminal result, and exact lookup contract. ## Validation - Rust formatting, remote check, clippy, and focused LDB-1/LDB-2 tests - Python formatting, lint, and focused LDB-1/LDB-2 tests - Python API documentation build --- docs/src/python/python.md | 12 + python/python/lancedb/__init__.py | 4 + python/python/lancedb/_lancedb.pyi | 9 + python/python/lancedb/db.py | 56 +- python/python/lancedb/functions.py | 553 +++++++++++++++++- python/python/lancedb/job.py | 53 +- python/python/lancedb/remote/db.py | 9 + .../tests/test_first_class_function_slice2.py | 254 ++++++++ python/src/connection.rs | 32 + python/src/job.rs | 53 ++ python/src/lib.rs | 1 + rust/lancedb/src/connection.rs | 27 + rust/lancedb/src/database.rs | 21 + rust/lancedb/src/function.rs | 50 ++ rust/lancedb/src/job.rs | 3 +- rust/lancedb/src/remote/db.rs | 88 +++ .../tests/first_class_function_slice2.rs | 81 +++ ...nction_registration_request.canonical.json | 1 + .../remote_function_registration_request.json | 46 ++ 19 files changed, 1326 insertions(+), 27 deletions(-) create mode 100644 python/python/tests/test_first_class_function_slice2.py create mode 100644 rust/lancedb/tests/first_class_function_slice2.rs create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_registration_request.canonical.json create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_registration_request.json diff --git a/docs/src/python/python.md b/docs/src/python/python.md index a99c0236a..70b2a7207 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -68,6 +68,18 @@ listing a storage directory. ::: lancedb.functions.PythonEnvironmentSpec +::: lancedb.functions.udf + +::: lancedb.functions.UdfDefinition + +::: lancedb.functions.FunctionRegistrationRequest + +::: lancedb.functions.FunctionArtifactRequest + +::: lancedb.functions.FunctionArtifactContent + +::: lancedb.functions.PythonAdapterSpec + ::: lancedb.functions.FunctionVersion ::: lancedb.functions.PythonRuntimeSpec diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index a8a336a6d..0ceda4558 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -23,10 +23,14 @@ from .expr import Expr, col, lit, func from .schema import blob, vector, BlobType from .job import AsyncJob, Job from .functions import ( + FunctionArtifactRequest as FunctionArtifactRequest, FunctionApplication as FunctionApplication, FunctionBinding as FunctionBinding, + FunctionRegistrationRequest as FunctionRegistrationRequest, FunctionVersion as FunctionVersion, PythonRuntimeSpec as PythonRuntimeSpec, + UdfDefinition as UdfDefinition, + udf as udf, ) from .table import AsyncTable, Table from .types import BaseTokenizerType diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index ea5d3e972..59537f45a 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -147,6 +147,8 @@ class Connection(object): limit: Optional[int], ) -> list[str]: ... # Deprecated: Use list_tables instead def job(self, job_id: str) -> Job: ... + async def create_function_async(self, request_json: str) -> FunctionJob: ... + async def get_function(self, name: str, version: str) -> str: ... async def list_jobs(self) -> List[JobInfo]: ... async def get_job(self, job_id: str) -> Optional[JobDescription]: ... async def cancel_job(self, job_id: str) -> bool: ... @@ -226,6 +228,13 @@ class Job: async def wait(self) -> None: ... async def cancel(self) -> None: ... +class FunctionJob: + @property + def id(self) -> Optional[str]: ... + async def status(self) -> str: ... + async def wait(self) -> str: ... + async def cancel(self) -> None: ... + class JobInfo: @property def job_id(self) -> str: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 14b6c0b0d..af18b6944 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -45,7 +45,8 @@ from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError from . import __version__ from ._lancedb import connect as lancedb_connect # type: ignore -from .job import AsyncJob, Job +from .functions import FunctionVersion, UdfDefinition +from .job import AsyncJob, Job, _function_job from .table import ( AsyncTable, LanceTable, @@ -616,6 +617,31 @@ class DBConnection(EnforceOverrides): """ raise NotImplementedError("serialize is not supported for this connection type") + def create_function(self, definition: UdfDefinition) -> FunctionVersion: + """Register a scalar Python UDF and wait for its immutable version. + + This is the blocking counterpart of :meth:`create_function_async`. + Local connections raise ``NotImplementedError``. + """ + return self.create_function_async(definition).wait() + + def create_function_async(self, definition: UdfDefinition) -> Job[FunctionVersion]: + """Register a scalar Python UDF through the remote Function catalog. + + Submission returns a typed job. The immutable Function version becomes + available only when :meth:`Job.wait` succeeds. Local connections raise + ``NotImplementedError``. + """ + raise NotImplementedError( + "Function catalog operations are not supported for this connection type" + ) + + def get_function(self, name: str, *, version: str) -> FunctionVersion: + """Open one exact immutable Function version from the remote catalog.""" + raise NotImplementedError( + "Function catalog operations are not supported for this connection type" + ) + def job(self, job_id: str) -> Job: """A [Job][lancedb.job.Job] handle for a server-side job by id. @@ -1256,6 +1282,15 @@ class LanceDBConnection(DBConnection): """ return Job(self._conn.job(job_id)) + @override + def create_function_async(self, definition: UdfDefinition) -> Job[FunctionVersion]: + job = LOOP.run(self._conn.create_function_async(definition)) + return Job(job) + + @override + def get_function(self, name: str, *, version: str) -> FunctionVersion: + return LOOP.run(self._conn.get_function(name, version=version)) + @override def list_jobs(self) -> List[JobInfo]: """List server-side jobs across the database's tables.""" @@ -2023,6 +2058,25 @@ class AsyncConnection(object): """ return AsyncJob(self._inner.job(job_id)) + async def create_function_async( + self, definition: UdfDefinition + ) -> AsyncJob[FunctionVersion]: + """Register a scalar Python UDF through the remote Function catalog. + + The returned typed job resolves to the immutable Function version. + Local connections raise ``NotImplementedError``. + """ + if not isinstance(definition, UdfDefinition): + raise TypeError("create_function_async requires a @udf definition") + inner = await self._inner.create_function_async( + definition.registration_request.to_canonical_json() + ) + return _function_job(inner) + + async def get_function(self, name: str, *, version: str) -> FunctionVersion: + """Open one exact immutable Function version from the remote catalog.""" + return FunctionVersion.from_json(await self._inner.get_function(name, version)) + async def list_jobs(self) -> List[JobInfo]: """List server-side jobs across the database's tables.""" return await self._inner.list_jobs() diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index df781f665..1613e03b4 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -9,10 +9,32 @@ environment bake, secret resolution, and execution are owned by Sophon. from __future__ import annotations +import ast +import base64 +import functools +import hashlib +import inspect import json +import math +import re +import sys +import textwrap +import types from collections.abc import Mapping -from typing import Any, Optional +from datetime import date, datetime +from typing import ( + Annotated, + Any, + Callable, + Optional, + Union, + get_args, + get_origin, + get_type_hints, + overload, +) +import pyarrow as pa from pydantic import ( BaseModel, ConfigDict, @@ -126,18 +148,10 @@ class _RemoteValue(BaseModel): class _OpenRemoteValue(_RemoteValue): """Forward-readable value whose extras stay out of canonical encoding.""" - if _PYDANTIC_V2: - model_config = {"extra": "allow", "frozen": True} - else: - - class Config: - allow_mutation = False - extra = "allow" + model_config = ConfigDict(extra="allow", frozen=True) def _unknown_field_names(self) -> set[str]: - if _PYDANTIC_V2: - return set((self.__pydantic_extra__ or {}).keys()) - return set(self.__dict__) - set(self.__fields__) + return set((self.__pydantic_extra__ or {}).keys()) class FunctionArtifact(_RemoteValue): @@ -148,6 +162,30 @@ class FunctionArtifact(_RemoteValue): entrypoint: str +class FunctionArtifactContent(_RemoteValue): + """Encoded artifact bytes uploaded during remote registration.""" + + encoding: str + data: str + + +class PythonAdapterSpec(_RemoteValue): + """Internal scalar-callable to Arrow-batch adapter selection.""" + + kind: str + version: _UInt32 + + +class FunctionArtifactRequest(_RemoteValue): + """Source artifact uploaded while registering a Function.""" + + kind: str + digest: str + entrypoint: str + content: FunctionArtifactContent + adapter: PythonAdapterSpec + + class FunctionParameter(_RemoteValue): name: str arrow_type: str @@ -228,6 +266,20 @@ class FunctionVersion(_RemoteValue): created_at: str +class FunctionRegistrationRequest(_RemoteValue): + """Stable remote registration envelope produced by :func:`udf`. + + Only secret names are represented. Secret values are resolved inside the + remote service and have no client request field. + """ + + name: str + artifact: FunctionArtifactRequest + signature: FunctionSignature + runtime: PythonRuntimeSpec + required_secrets: tuple[str, ...] = () + + class FunctionVersionRef(_OpenRemoteValue): name: str version: str @@ -361,13 +413,489 @@ class RefreshColumnResult(_RemoteValue): return self.published_version +_FUNCTION_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]*$") +_SECRET_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") + + +def _canonical_arrow_type(data_type: pa.DataType) -> str: + primitive_types = ( + (pa.bool_(), "bool"), + (pa.int8(), "int8"), + (pa.int16(), "int16"), + (pa.int32(), "int32"), + (pa.int64(), "int64"), + (pa.uint8(), "uint8"), + (pa.uint16(), "uint16"), + (pa.uint32(), "uint32"), + (pa.uint64(), "uint64"), + (pa.float16(), "float16"), + (pa.float32(), "float32"), + (pa.float64(), "float64"), + (pa.string(), "utf8"), + (pa.large_utf8(), "large_utf8"), + (pa.binary(), "binary"), + (pa.large_binary(), "large_binary"), + (pa.date32(), "date32"), + (pa.date64(), "date64"), + ) + for candidate, name in primitive_types: + if data_type == candidate: + return name + if pa.types.is_fixed_size_binary(data_type): + return f"fixed_size_binary[{data_type.byte_width}]" + if pa.types.is_list(data_type): + return f"list<{_canonical_arrow_type(data_type.value_type)}>" + if pa.types.is_large_list(data_type): + return f"large_list<{_canonical_arrow_type(data_type.value_type)}>" + if pa.types.is_fixed_size_list(data_type): + return ( + f"fixed_size_list<{_canonical_arrow_type(data_type.value_type)}>" + f"[{data_type.list_size}]" + ) + if pa.types.is_struct(data_type): + fields = ",".join( + f"{field.name}:{_canonical_arrow_type(field.type)}" for field in data_type + ) + return f"struct<{fields}>" + if pa.types.is_timestamp(data_type): + timezone = f",tz={data_type.tz}" if data_type.tz is not None else "" + return f"timestamp[{data_type.unit}{timezone}]" + if pa.types.is_time32(data_type) or pa.types.is_time64(data_type): + return f"time[{data_type.unit}]" + if pa.types.is_duration(data_type): + return f"duration[{data_type.unit}]" + if pa.types.is_decimal(data_type): + bit_width = data_type.bit_width + return f"decimal{bit_width}({data_type.precision},{data_type.scale})" + raise TypeError(f"unsupported Arrow type for Function signature: {data_type}") + + +def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: + nullable = False + origin = get_origin(annotation) + if origin in (Union, types.UnionType): + arguments = get_args(annotation) + non_none = tuple( + argument for argument in arguments if argument is not type(None) + ) + if len(non_none) != 1 or len(non_none) == len(arguments): + raise TypeError(f"unsupported union annotation: {annotation!r}") + annotation = non_none[0] + nullable = True + + origin = get_origin(annotation) + if origin is Annotated: + base, *metadata = get_args(annotation) + arrow_types = [value for value in metadata if isinstance(value, pa.DataType)] + if len(arrow_types) != 1: + raise TypeError( + "Annotated Function types require exactly one PyArrow DataType" + ) + _, base_nullable = _annotation_type(base) + return arrow_types[0], nullable or base_nullable + + if isinstance(annotation, pa.DataType): + return annotation, nullable + if annotation is bool: + return pa.bool_(), nullable + if annotation is int: + return pa.int64(), nullable + if annotation is float: + return pa.float64(), nullable + if annotation is str: + return pa.string(), nullable + if annotation is bytes: + return pa.binary(), nullable + if annotation is date: + return pa.date32(), nullable + if annotation is datetime: + return pa.timestamp("us"), nullable + if get_origin(annotation) is list: + arguments = get_args(annotation) + if len(arguments) != 1: + raise TypeError(f"unsupported list annotation: {annotation!r}") + value_type, value_nullable = _annotation_type(arguments[0]) + if value_nullable: + raise TypeError("nullable Function list elements are not supported") + return pa.list_(value_type), nullable + raise TypeError(f"unsupported Function annotation: {annotation!r}") + + +def _callable_parameters(function: Callable[..., Any]) -> tuple[inspect.Parameter, ...]: + parameters = tuple(inspect.signature(function).parameters.values()) + for parameter in parameters: + if parameter.kind in ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.VAR_POSITIONAL, + inspect.Parameter.VAR_KEYWORD, + ): + 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") + return parameters + + +def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutput: + if isinstance(output, pa.Schema): + fields = tuple(output) + elif isinstance(output, pa.Field) and pa.types.is_struct(output.type): + if output.nullable: + raise ValueError("Function output must be non-nullable") + fields = tuple(output.type) + elif isinstance(output, pa.DataType) and pa.types.is_struct(output): + fields = tuple(output) + else: + field = ( + output + if isinstance(output, pa.Field) + else pa.field("result", output, nullable=False) + ) + if not isinstance(field, pa.Field): + raise TypeError( + "output_schema must be a PyArrow DataType, Field, or Schema" + ) + if field.nullable: + raise ValueError("Function output must be non-nullable") + return FunctionOutput( + kind="scalar", + arrow_type=_canonical_arrow_type(field.type), + nullable=False, + ) + + if not fields: + raise ValueError("named-struct Function output must contain at least one field") + if any(field.nullable for field in fields): + raise ValueError("Function output fields must be non-nullable") + names = [field.name for field in fields] + if len(set(names)) != len(names): + raise ValueError("Function output field names must be unique") + return FunctionOutput( + kind="named_struct", + fields=tuple( + FunctionResultField( + name=field.name, + arrow_type=_canonical_arrow_type(field.type), + nullable=False, + ) + for field in fields + ), + ) + + +def _infer_signature( + function: Callable[..., Any], + input_schema: Optional[pa.Schema], + output_schema: Optional[pa.DataType | pa.Field | pa.Schema], +) -> FunctionSignature: + parameters = _callable_parameters(function) + if (input_schema is None) != (output_schema is None): + raise ValueError("input_schema and output_schema must be provided together") + + if input_schema is not None: + if not isinstance(input_schema, pa.Schema): + raise TypeError("input_schema must be a PyArrow Schema") + expected = tuple(parameter.name for parameter in parameters) + actual = tuple(input_schema.names) + if actual != expected: + raise ValueError( + "input_schema fields must exactly match callable parameters in order: " + f"expected {expected!r}, got {actual!r}" + ) + inputs = tuple( + FunctionParameter( + name=field.name, + arrow_type=_canonical_arrow_type(field.type), + nullable=field.nullable, + ) + for field in input_schema + ) + return FunctionSignature(inputs=inputs, output=_function_output(output_schema)) + + try: + annotations = get_type_hints(function, include_extras=True) + except Exception as error: + raise TypeError(f"failed to resolve Function annotations: {error}") from error + missing = [ + parameter.name for parameter in parameters if parameter.name not in annotations + ] + if missing or "return" not in annotations: + names = missing + ([] if "return" in annotations else ["return"]) + raise TypeError(f"missing Function annotations: {names!r}") + inputs = [] + for parameter in parameters: + data_type, nullable = _annotation_type(annotations[parameter.name]) + inputs.append( + FunctionParameter( + name=parameter.name, + arrow_type=_canonical_arrow_type(data_type), + nullable=nullable, + ) + ) + output_type, output_nullable = _annotation_type(annotations["return"]) + if output_nullable: + raise ValueError("Function output must be non-nullable") + return FunctionSignature( + inputs=tuple(inputs), + output=_function_output(pa.field("result", output_type, nullable=False)), + ) + + +def _is_udf_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" + ) + + +def _literal_source(value: Any) -> 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) + if len(value) == 1: + children += "," + return f"({children})" + raise TypeError( + "Function source references an unsupported global value of type " + f"{type(value).__name__}" + ) + + +def _package_source(function: Callable[..., Any]) -> bytes: + if not inspect.isfunction(function) or inspect.iscoroutinefunction(function): + raise TypeError("@udf requires a synchronous Python function") + try: + source = textwrap.dedent(inspect.getsource(function)) + except (OSError, TypeError) as error: + raise ValueError("@udf requires inspectable Python source") from error + module = ast.parse(source) + definitions = [ + node + for node in module.body + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and node.name == function.__name__ + ] + if len(definitions) != 1 or not isinstance(definitions[0], ast.FunctionDef): + raise ValueError("@udf source must contain exactly one synchronous function") + definition = definitions[0] + if any(not _is_udf_decorator(decorator) for decorator in definition.decorator_list): + raise ValueError("@udf cannot package additional Python decorators") + definition.decorator_list = [] + + closure = inspect.getclosurevars(function) + if closure.nonlocals: + raise ValueError("@udf cannot package functions that capture closure values") + if closure.unbound: + raise ValueError( + f"@udf source contains unresolved global names: {sorted(closure.unbound)!r}" + ) + globals_source = [] + for name, value in sorted(closure.globals.items()): + if isinstance(value, types.ModuleType): + globals_source.append(f"import {value.__name__} as {name}") + else: + globals_source.append(f"{name} = {_literal_source(value)}") + + function_source = ast.unparse(definition) + parts = ["from __future__ import annotations"] + if globals_source: + parts.extend(["", *globals_source]) + parts.extend(["", function_source, ""]) + return "\n".join(parts).encode("utf-8") + + +class UdfDefinition: + """A scalar Python callable prepared for remote Function registration. + + Instances are created with :func:`udf`. Calling an instance executes the + original scalar Python function, which keeps local unit testing ordinary. + Remote execution adapts that scalar callable to the internal Arrow batch + ABI described by the registration artifact. + """ + + def __init__( + self, + function: Callable[..., Any], + *, + name: Optional[str], + input_schema: Optional[pa.Schema], + output_schema: Optional[pa.DataType | pa.Field | pa.Schema], + pip: tuple[str, ...], + env: Mapping[str, str], + secrets: tuple[str, ...], + python_version: Optional[str], + ): + function_name = name or function.__name__ + if not _FUNCTION_NAME.fullmatch(function_name): + raise ValueError(f"invalid Function name: {function_name!r}") + packages = tuple(sorted(set(pip))) + if any(not package or package != package.strip() for package in packages): + raise ValueError("pip requirements must be non-empty and trimmed") + environment = dict(env) + if any( + not isinstance(key, str) or not isinstance(value, str) + for key, value in environment.items() + ): + raise TypeError("Function env keys and values must be strings") + required_secrets = tuple(sorted(set(secrets))) + invalid_secrets = [ + secret for secret in required_secrets if not _SECRET_NAME.fullmatch(secret) + ] + if invalid_secrets: + raise ValueError(f"invalid Function secret names: {invalid_secrets!r}") + overlap = set(environment) & set(required_secrets) + if overlap: + raise ValueError( + f"Function env and secret names must be disjoint: {sorted(overlap)!r}" + ) + + signature = _infer_signature(function, input_schema, output_schema) + source = _package_source(function) + digest = f"sha256:{hashlib.sha256(source).hexdigest()}" + runtime = PythonRuntimeSpec( + kind="python", + python_version=python_version + or f"{sys.version_info.major}.{sys.version_info.minor}", + environment=PythonEnvironmentSpec(kind="pip", packages=packages), + env=environment, + ) + self._function = function + self._request = FunctionRegistrationRequest( + name=function_name, + artifact=FunctionArtifactRequest( + kind="python_callable", + digest=digest, + entrypoint=function.__name__, + content=FunctionArtifactContent( + encoding="base64", + data=base64.b64encode(source).decode("ascii"), + ), + adapter=PythonAdapterSpec( + kind="scalar_to_arrow_batch", + version=1, + ), + ), + signature=signature, + runtime=runtime, + required_secrets=required_secrets, + ) + functools.update_wrapper(self, function) + + @property + def registration_request(self) -> FunctionRegistrationRequest: + """The immutable request sent by ``create_function_async``.""" + return self._request + + def __call__(self, *args, **kwargs): + return self._function(*args, **kwargs) + + +@overload +def udf(function: Callable[..., Any]) -> UdfDefinition: ... + + +@overload +def udf( + function: None = None, + *, + name: Optional[str] = None, + input_schema: Optional[pa.Schema] = None, + output_schema: Optional[pa.DataType | pa.Field | pa.Schema] = None, + pip: tuple[str, ...] | list[str] = (), + env: Optional[Mapping[str, str]] = None, + secrets: tuple[str, ...] | list[str] = (), + python_version: Optional[str] = None, +) -> Callable[[Callable[..., Any]], UdfDefinition]: ... + + +def udf( + function: Optional[Callable[..., Any]] = None, + *, + name: Optional[str] = None, + input_schema: Optional[pa.Schema] = None, + output_schema: Optional[pa.DataType | pa.Field | pa.Schema] = None, + pip: tuple[str, ...] | list[str] = (), + env: Optional[Mapping[str, str]] = None, + secrets: tuple[str, ...] | list[str] = (), + python_version: Optional[str] = None, +): + """Prepare a scalar Python callable for remote Function registration. + + Input and output signatures are inferred from supported annotations. For + Arrow types annotations cannot express precisely, pass ``input_schema`` + and ``output_schema`` together. Nullable outputs are rejected because V1 + uses physical NULL to represent unassigned computed-column rows. + + Parameters + ---------- + function : Callable, optional + The synchronous scalar callable to package. + name : str, optional + The remote Function name. Defaults to the callable name. + input_schema : pyarrow.Schema, optional + Explicit input fields in the exact order of the callable parameters. + Must be provided together with ``output_schema``. + output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional + Explicit scalar or named-struct output. Must be non-nullable and be + provided together with ``input_schema``. + pip : sequence of str, optional + Pip requirements for the remote environment. + env : mapping of str to str, optional + Non-secret environment variables. Use ``secrets`` for credentials. + secrets : sequence of str, optional + Names of secrets resolved by the remote service. Secret values are not + accepted by this API or included in the registration request. + python_version : str, optional + Remote Python major/minor version. Defaults to the client version. + + Returns + ------- + UdfDefinition + A callable definition accepted by + :meth:`lancedb.db.DBConnection.create_function`, + :meth:`lancedb.db.AsyncConnection.create_function_async` and + :meth:`lancedb.db.DBConnection.create_function_async`. + + Examples + -------- + >>> from lancedb import udf + >>> @udf(pip=["numpy==2.2.0"], secrets=["MODEL_TOKEN"]) + ... def score(value: float) -> float: + ... return value * 2 + >>> score(1.5) + 3.0 + """ + + def decorate(target: Callable[..., Any]) -> UdfDefinition: + return UdfDefinition( + target, + name=name, + input_schema=input_schema, + output_schema=output_schema, + pip=tuple(pip), + env={} if env is None else env, + secrets=tuple(secrets), + python_version=python_version, + ) + + if function is None: + return decorate + return decorate(function) + + __all__ = [ "ApplicationInput", "FunctionApplication", "FunctionArtifact", + "FunctionArtifactContent", + "FunctionArtifactRequest", "FunctionBinding", "FunctionOutput", "FunctionParameter", + "FunctionRegistrationRequest", "FunctionResultField", "FunctionSignature", "FunctionVersion", @@ -375,6 +903,9 @@ __all__ = [ "InputBinding", "OutputMapping", "PythonEnvironmentSpec", + "PythonAdapterSpec", "PythonRuntimeSpec", "RefreshColumnResult", + "UdfDefinition", + "udf", ] diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index d33b62cbf..7bd600a74 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -5,20 +5,23 @@ import asyncio from datetime import timedelta -from typing import Optional +from typing import Any, Generic, Optional, TypeVar, cast from lancedb.background_loop import LOOP from . import _lancedb +from .functions import FunctionVersion + +T = TypeVar("T") -class AsyncJob: +class AsyncJob(Generic[T]): """A handle to an operation that may still be running. The operation may already be complete when the handle is created. """ - def __init__(self, inner: Optional["_lancedb.Job"]): + def __init__(self, inner: Optional[Any]): self._inner = inner @property @@ -44,18 +47,20 @@ class AsyncJob: return "finished" return await self._inner.status() - async def wait(self, timeout: Optional[timedelta] = None): + async def wait(self, timeout: Optional[timedelta] = None) -> T: """Wait until the operation reaches a terminal state. Raises `JobFailedError` if the operation failed, `JobCancelledError` if it was cancelled, and `TimeoutError` if `timeout` elapses first. """ if self._inner is None: - return + return cast(T, None) if timeout is None: - await self._inner.wait() - else: - await asyncio.wait_for(self._inner.wait(), timeout.total_seconds()) + return cast(T, await self._inner.wait()) + return cast( + T, + await asyncio.wait_for(self._inner.wait(), timeout.total_seconds()), + ) async def cancel(self): """Request cancellation. Cancelling a finished operation is a no-op.""" @@ -64,10 +69,10 @@ class AsyncJob: await self._inner.cancel() -class Job: +class Job(Generic[T]): """Synchronous counterpart of `AsyncJob`.""" - def __init__(self, inner: Optional[AsyncJob]): + def __init__(self, inner: Optional[AsyncJob[T]]): self._inner = inner @property @@ -88,18 +93,40 @@ class Job: return "finished" return LOOP.run(self._inner.status()) - def wait(self, timeout: Optional[timedelta] = None): + def wait(self, timeout: Optional[timedelta] = None) -> T: """Block until the operation reaches a terminal state. Raises `JobFailedError` if the operation failed, `JobCancelledError` if it was cancelled, and `TimeoutError` if `timeout` elapses first. """ if self._inner is None: - return - LOOP.run(self._inner.wait(timeout)) + return cast(T, None) + return LOOP.run(self._inner.wait(timeout)) def cancel(self): """Request cancellation. Cancelling a finished operation is a no-op.""" if self._inner is None: return LOOP.run(self._inner.cancel()) + + +class _FunctionJobAdapter: + def __init__(self, inner: "_lancedb.FunctionJob"): + self._inner = inner + + @property + def id(self) -> Optional[str]: + return self._inner.id + + async def status(self) -> str: + return await self._inner.status() + + async def wait(self) -> FunctionVersion: + return FunctionVersion.from_json(await self._inner.wait()) + + async def cancel(self): + await self._inner.cancel() + + +def _function_job(inner: "_lancedb.FunctionJob") -> AsyncJob[FunctionVersion]: + return AsyncJob(_FunctionJobAdapter(inner)) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 16ad65dcb..822756a34 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -23,6 +23,7 @@ import pyarrow as pa from ..common import DATA from ..db import DBConnection, LOOP +from ..functions import FunctionVersion, UdfDefinition from ..job import AsyncJob, Job if TYPE_CHECKING: @@ -713,6 +714,14 @@ class RemoteDBConnection(DBConnection): """ return Job(self._conn.job(job_id)) + @override + def create_function_async(self, definition: UdfDefinition) -> Job[FunctionVersion]: + return Job(LOOP.run(self._conn.create_function_async(definition))) + + @override + def get_function(self, name: str, *, version: str) -> FunctionVersion: + return LOOP.run(self._conn.get_function(name, version=version)) + @override def list_jobs(self) -> List["JobInfo"]: """List server-side jobs across the database's tables.""" diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py new file mode 100644 index 000000000..612a711af --- /dev/null +++ b/python/python/tests/test_first_class_function_slice2.py @@ -0,0 +1,254 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from __future__ import annotations + +import contextlib +import http.server +import json +from pathlib import Path +import threading +from typing import Optional + +import pyarrow as pa +import pytest + +import lancedb +from lancedb.functions import UdfDefinition, udf + + +FIXTURES = ( + Path(__file__).parents[3] + / "rust" + / "lancedb" + / "tests" + / "fixtures" + / "first_class_functions" + / "v1" +) + + +@udf( + pip=["numpy>=2"], + env={"MODE": "test"}, + secrets=["API_TOKEN"], + python_version="3.12", +) +def normalize_score(value: float) -> float: + return value / 100.0 + + +def _assert_no_secret_values(value): + if isinstance(value, dict): + for key, child in value.items(): + assert key not in { + "secret_value", + "secret_values", + "resolved_secret", + "resolved_secrets", + } + _assert_no_secret_values(child) + elif isinstance(value, list): + for child in value: + _assert_no_secret_values(child) + + +def test_scalar_udf_matches_shared_registration_golden_and_remains_callable(): + assert isinstance(normalize_score, UdfDefinition) + assert normalize_score(25.0) == 0.25 + assert ( + normalize_score.registration_request.to_canonical_json() + == (FIXTURES / "remote_function_registration_request.canonical.json") + .read_text() + .strip() + ) + request = json.loads(normalize_score.registration_request.to_canonical_json()) + assert request["artifact"]["adapter"] == { + "kind": "scalar_to_arrow_batch", + "version": 1, + } + assert request["required_secrets"] == ["API_TOKEN"] + _assert_no_secret_values(request) + + +def test_explicit_arrow_schema_is_deterministic(): + input_schema = pa.schema([pa.field("value", pa.float32(), nullable=True)]) + output_schema = pa.field("embedding", pa.list_(pa.float32(), 3), nullable=False) + + @udf(input_schema=input_schema, output_schema=output_schema) + def explicit(value): + return [value, value, value] + + signature = explicit.registration_request.signature + assert signature.inputs[0].arrow_type == "float32" + assert signature.inputs[0].nullable is True + assert signature.output.arrow_type == "fixed_size_list[3]" + assert signature.output.nullable is False + + +def test_annotation_and_explicit_schema_validation_fail_closed(): + with pytest.raises(TypeError, match="missing Function annotations"): + + @udf + def missing(value): + return value + + with pytest.raises(TypeError, match="unsupported Function annotation"): + + @udf + def unsupported(value: set[str]) -> str: + return "" + + with pytest.raises(ValueError, match="output must be non-nullable"): + + @udf + def nullable_output(value: int) -> Optional[int]: + return value + + with pytest.raises(ValueError, match="provided together"): + + @udf(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( + input_schema=pa.schema([pa.field("other", pa.int64())]), + output_schema=pa.int64(), + ) + def wrong_name(value): + return value + + with pytest.raises(ValueError, match="output must be non-nullable"): + + @udf( + input_schema=pa.schema([pa.field("value", pa.int64())]), + output_schema=pa.field("result", pa.int64(), nullable=True), + ) + def nullable_explicit(value): + return value + + +def test_environment_rejects_secret_value_overlap(): + with pytest.raises(ValueError, match="must be disjoint"): + + @udf(env={"TOKEN": "plaintext"}, secrets=["TOKEN"]) + def overlapping(value: int) -> int: + return value + + +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" + with pytest.raises(NotImplementedError, match=message): + db.create_function(normalize_score) + with pytest.raises(NotImplementedError, match=message): + db.create_function_async(normalize_score) + with pytest.raises(NotImplementedError, match=message): + db.get_function("normalize_score", version="fv_exact") + + +@contextlib.contextmanager +def _mock_remote_function_catalog(): + state = {"requests": [], "version": None} + + class Handler(http.server.BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length", "0")) + body = json.loads(self.rfile.read(length) or b"{}") + state["requests"].append((self.path, body)) + status = 200 + if self.path == "/v1/function/create": + state["version"] = { + "name": body["name"], + "version": "fv_exact", + "artifact": { + key: body["artifact"][key] + for key in ("kind", "digest", "entrypoint") + }, + "signature": body["signature"], + "runtime": body["runtime"], + "runtime_digest": "sha256:runtime", + "environment_digest": "sha256:environment", + "required_secrets": body.get("required_secrets", []), + "created_at": "2026-08-21T00:00:00Z", + } + response = {"job_id": "job-register"} + status = 202 + elif self.path == "/v1/jobs/describe": + assert body == {"job_id": "job-register"} + response = { + "job_id": "job-register", + "job_type": "create_function", + "job_state": "DONE", + "result": state["version"], + } + elif self.path == "/v1/function/describe": + assert body == { + "name": "normalize_score", + "version": "fv_exact", + } + response = state["version"] + else: + status = 404 + response = {"error": "not found"} + encoded = json.dumps(response).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + with http.server.HTTPServer(("localhost", 0), Handler) as server: + thread = threading.Thread(target=server.serve_forever) + thread.start() + try: + yield f"http://localhost:{server.server_address[1]}", state + finally: + server.shutdown() + thread.join() + + +def test_remote_registration_job_and_exact_version_reopen_round_trip(): + with _mock_remote_function_catalog() as (host, state): + db = lancedb.connect( + "db://dev", + api_key="fake", + host_override=host, + client_config={"retry_config": {"retries": 0}}, + ) + registration = db.create_function_async(normalize_score) + assert registration.id == "job-register" + created = registration.wait() + reopened = db.get_function("normalize_score", version=created.version) + + assert created == reopened + assert reopened.name == "normalize_score" + assert reopened.version == "fv_exact" + create_request = state["requests"][0][1] + assert create_request == json.loads( + normalize_score.registration_request.to_canonical_json() + ) + _assert_no_secret_values(create_request) + + +def test_blocking_remote_registration_returns_function_version(): + with _mock_remote_function_catalog() as (host, state): + db = lancedb.connect( + "db://dev", + api_key="fake", + host_override=host, + client_config={"retry_config": {"retries": 0}}, + ) + created = db.create_function(normalize_score) + + assert created.name == "normalize_score" + assert created.version == "fv_exact" + assert [path for path, _ in state["requests"]] == [ + "/v1/function/create", + "/v1/jobs/describe", + ] diff --git a/python/src/connection.rs b/python/src/connection.rs index dbda29ba6..87870b800 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -563,6 +563,38 @@ impl Connection { Ok(crate::job::Job::new(inner.job(job_id).infer_error()?)) } + pub fn create_function_async( + self_: PyRef<'_, Self>, + request_json: String, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + let request = lancedb::function::FunctionRegistrationRequest::from_json(&request_json) + .infer_error()?; + future_into_py(self_.py(), async move { + inner + .create_function_async(request) + .await + .infer_error() + .map(crate::job::FunctionJob::new) + }) + } + + pub fn get_function( + self_: PyRef<'_, Self>, + name: String, + version: String, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + inner + .get_function(name, version) + .await + .infer_error()? + .to_canonical_json() + .infer_error() + }) + } + pub fn list_jobs(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { diff --git a/python/src/job.rs b/python/src/job.rs index 56ee211f4..2755a28c5 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -13,6 +13,23 @@ pub struct Job { inner: Arc, } +/// Python bridge for a typed remote Function registration job. +/// +/// The public Python layer decodes the canonical JSON returned by `wait` +/// into its immutable `FunctionVersion` model. +#[pyclass] +pub struct FunctionJob { + inner: Arc>, +} + +impl FunctionJob { + pub(crate) fn new(inner: lancedb::Job) -> Self { + Self { + inner: Arc::new(inner), + } + } +} + impl Job { pub(crate) fn new(inner: lancedb::Job) -> Self { Self { @@ -21,6 +38,42 @@ impl Job { } } +#[pymethods] +impl FunctionJob { + #[getter] + pub fn id(&self) -> Option { + self.inner.id().map(str::to_string) + } + + pub fn status(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py( + self_.py(), + async move { inner.status().await.infer_error() }, + ) + } + + pub fn wait(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + inner + .wait() + .await + .infer_error()? + .to_canonical_json() + .infer_error() + }) + } + + pub fn cancel(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + inner.cancel().await.infer_error()?; + Ok(()) + }) + } +} + #[pymethods] impl Job { #[getter] diff --git a/python/src/lib.rs b/python/src/lib.rs index a19bf172d..756b3557f 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -47,6 +47,7 @@ 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::()?; diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 12ca306b8..8935855a8 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -496,6 +496,33 @@ impl Connection { ) } + /// Register a Python callable as a new immutable Function version. + /// + /// Registration is remote-only and always asynchronous. Waiting on the + /// returned typed job yields the durable [`crate::function::FunctionVersion`]. + /// Local databases return [`Error::NotSupported`]. + pub async fn create_function_async( + &self, + request: crate::function::FunctionRegistrationRequest, + ) -> Result> { + self.internal.create_function_async(request).await + } + + /// 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. + /// Local databases return [`Error::NotSupported`]. + pub async fn get_function( + &self, + name: impl AsRef, + version: impl AsRef, + ) -> Result { + self.internal + .get_function(name.as_ref(), version.as_ref()) + .await + } + /// Rename a table in the database. /// /// This is only supported in LanceDB Cloud. diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index f52c02439..6c4537972 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -241,6 +241,12 @@ fn job_op_not_supported(what: &str) -> Result { }) } +fn function_catalog_not_supported() -> Result { + Err(crate::error::Error::NotSupported { + message: "Function catalog operations are not supported by this database".to_string(), + }) +} + /// The `Database` trait defines the interface for database implementations. /// /// A database is responsible for managing tables and their metadata. @@ -286,6 +292,21 @@ pub trait Database: /// /// See [`CloneTableRequest`] for detailed documentation and examples. async fn clone_table(&self, request: CloneTableRequest) -> Result>; + /// Register an immutable Function version through the remote catalog. + async fn create_function_async( + &self, + _request: crate::function::FunctionRegistrationRequest, + ) -> Result> { + function_catalog_not_supported() + } + /// Look up one exact immutable Function version. + async fn get_function( + &self, + _name: &str, + _version: &str, + ) -> Result { + function_catalog_not_supported() + } /// A [`crate::job::Job`] handle for a server-side job by id, suitable for /// waiting on or cancelling the job. The handle is constructed without a /// server round trip; an unknown id surfaces when the handle is used. diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index fe91f1680..835fca9a2 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -369,6 +369,56 @@ impl FunctionVersion { impl_json!(FunctionVersion); +/// Encoded artifact bytes uploaded with a Function registration request. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionArtifactContent { + /// Encoding of `data`. V1 Python authoring uses `base64`. + pub encoding: String, + pub data: String, +} + +/// Internal execution adapter selected for a Python callable artifact. +/// +/// The adapter converts the public scalar callable to the Arrow batch ABI +/// used by the remote executor. It is part of the request envelope, not a +/// public batch-UDF authoring mode. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PythonAdapterSpec { + pub kind: String, + pub version: u32, +} + +/// Python artifact uploaded while registering a Function. +/// +/// Unlike [`FunctionArtifact`], which is the durable artifact identity +/// returned by the catalog, this request value contains the encoded source +/// bytes that Sophon must durably bake before publishing a FunctionVersion. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionArtifactRequest { + pub kind: String, + pub digest: String, + pub entrypoint: String, + pub content: FunctionArtifactContent, + pub adapter: PythonAdapterSpec, +} + +/// Stable request envelope for remote immutable Function registration. +/// +/// Secret values deliberately have no field in this model. The only secret +/// material the client may send is the ordered set of names Sophon resolves +/// inside the remote runtime. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct FunctionRegistrationRequest { + pub name: String, + pub artifact: FunctionArtifactRequest, + pub signature: FunctionSignature, + pub runtime: PythonRuntimeSpec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub required_secrets: Vec, +} + +impl_json!(FunctionRegistrationRequest); + /// Exact FunctionVersion reference embedded in applications and bindings. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionVersionRef { diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 0f880e398..1a76c7683 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -126,8 +126,7 @@ impl Job where T: Clone + DeserializeOwned + Send + Sync + 'static, { - /// Construct a typed remote Job before result-specific submit APIs are added. - #[allow(dead_code)] + /// Construct a typed remote Job for a result-specific submit API. pub(crate) fn new_typed(handle: Box) -> Self { Self { inner: JobInner::Handle { diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 03a13cb4e..08f71368c 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -24,6 +24,7 @@ use crate::database::{ JobDescription, JobInfo, OpenTableRequest, ReadConsistency, TableNamesRequest, }; use crate::error::Result; +use crate::function::{FunctionRegistrationRequest, FunctionVersion}; use crate::job::Job; use crate::remote::job::{DescribeJobResponse, RemoteJob, job_state_to_client}; use crate::remote::util::stream_as_body; @@ -489,6 +490,39 @@ impl Database for RemoteDatabase { }) } + async fn create_function_async( + &self, + request: FunctionRegistrationRequest, + ) -> Result> { + let req = self.client.post("/v1/function/create").json(&request); + let (request_id, response) = self.client.send(req).await?; + let response = self.client.check_response(&request_id, response).await?; + let status = response.status(); + let body = response.text().await.err_to_http(request_id.clone())?; + let job_id = extract_job_id(&body).ok_or_else(|| Error::Http { + source: "Function registration response did not contain a valid job_id".into(), + request_id, + status_code: Some(status), + })?; + Ok(Job::new_typed(Box::new(RemoteJob::new( + self.client.clone(), + job_id, + )))) + } + + async fn get_function(&self, name: &str, version: &str) -> Result { + let req = self + .client + .post("/v1/function/describe") + .json(&serde_json::json!({ + "name": name, + "version": version, + })); + let (request_id, response) = self.client.send(req).await?; + let response = self.client.check_response(&request_id, response).await?; + response.json().await.err_to_http(request_id) + } + fn job(&self, job_id: &str) -> Result { Ok(crate::job::Job::new(Box::new(super::job::RemoteJob::new( self.client.clone(), @@ -2446,6 +2480,60 @@ mod tests { assert_eq!(batches[0].num_rows(), 2); } + #[tokio::test] + async fn test_create_function_async_sends_canonical_request_and_decodes_typed_job() { + const REQUEST: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json" + ); + const FUNCTION_JOB: &str = + include_str!("../../tests/fixtures/first_class_functions/v1/remote_function_job.json"); + let expected: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); + let conn = Connection::new_with_handler(move |request| match request.url().path() { + "/v1/function/create" => { + assert_eq!(request.method(), &reqwest::Method::POST); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body, expected); + http::Response::builder() + .status(202) + .body(r#"{"job_id":"job-function-1"}"#) + .unwrap() + } + "/v1/jobs/describe" => http::Response::builder() + .status(200) + .body(FUNCTION_JOB) + .unwrap(), + path => panic!("unexpected path: {path}"), + }); + let request = crate::function::FunctionRegistrationRequest::from_json(REQUEST).unwrap(); + let job = conn.create_function_async(request).await.unwrap(); + assert_eq!(job.id(), Some("job-function-1")); + let version = job.wait().await.unwrap(); + assert_eq!(version.name(), "embed"); + assert_eq!(version.version(), "fv_01K3EXACT"); + } + + #[tokio::test] + async fn test_get_function_requires_and_sends_exact_version() { + const VERSION: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::POST); + assert_eq!(request.url().path(), "/v1/function/describe"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!( + body, + serde_json::json!({"name": "embed", "version": "fv_01K3EXACT"}) + ); + http::Response::builder().status(200).body(VERSION).unwrap() + }); + let version = conn.get_function("embed", "fv_01K3EXACT").await.unwrap(); + assert_eq!(version.name(), "embed"); + assert_eq!(version.version(), "fv_01K3EXACT"); + } + #[tokio::test] async fn test_conn_job_waits_to_done() { let polls = Arc::new(AtomicUsize::new(0)); diff --git a/rust/lancedb/tests/first_class_function_slice2.rs b/rust/lancedb/tests/first_class_function_slice2.rs new file mode 100644 index 000000000..3bae57122 --- /dev/null +++ b/rust/lancedb/tests/first_class_function_slice2.rs @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::fs; +use std::path::PathBuf; + +use lancedb::Error; +use lancedb::function::FunctionRegistrationRequest; +use serde_json::Value; + +fn fixture(name: &str) -> String { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/first_class_functions/v1") + .join(name); + fs::read_to_string(path).expect("fixture must be readable") +} + +fn assert_no_secret_values(value: &Value) { + match value { + Value::Object(values) => { + for (key, value) in values { + assert!( + !matches!( + key.as_str(), + "secret_value" | "secret_values" | "resolved_secret" | "resolved_secrets" + ), + "registration requests must not model resolved secret material" + ); + assert_no_secret_values(value); + } + } + Value::Array(values) => values.iter().for_each(assert_no_secret_values), + _ => {} + } +} + +#[test] +fn registration_request_matches_shared_canonical_golden() { + let request = FunctionRegistrationRequest::from_json(&fixture( + "remote_function_registration_request.json", + )) + .expect("registration request"); + assert_eq!(request.name, "normalize_score"); + assert_eq!(request.artifact.adapter.kind, "scalar_to_arrow_batch"); + assert_eq!(request.required_secrets, ["API_TOKEN"]); + assert_eq!( + request.to_canonical_json().expect("canonical request"), + fixture("remote_function_registration_request.canonical.json").trim() + ); + + let value: Value = + serde_json::from_str(&request.to_canonical_json().expect("canonical request")) + .expect("request JSON"); + assert_no_secret_values(&value); +} + +#[tokio::test] +async fn local_function_catalog_operations_return_stable_not_supported() { + let directory = tempfile::tempdir().unwrap(); + let connection = lancedb::connect(directory.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let request = FunctionRegistrationRequest::from_json(&fixture( + "remote_function_registration_request.json", + )) + .unwrap(); + + let create_error = connection.create_function_async(request).await.unwrap_err(); + let lookup_error = connection + .get_function("normalize_score", "fv_exact") + .await + .unwrap_err(); + for error in [create_error, lookup_error] { + assert!(matches!( + error, + Error::NotSupported { message } + if message == "Function catalog operations are not supported by this database" + )); + } +} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_registration_request.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_registration_request.canonical.json new file mode 100644 index 000000000..24fa2cf30 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_registration_request.canonical.json @@ -0,0 +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"},"name":"normalize_score","required_secrets":["API_TOKEN"],"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_registration_request.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_registration_request.json new file mode 100644 index 000000000..bbfec3169 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_registration_request.json @@ -0,0 +1,46 @@ +{ + "name": "normalize_score", + "artifact": { + "kind": "python_callable", + "digest": "sha256:760784bdcef57b802f389b97804cc0b618aae39e86044733451bcd0b13089a7f", + "entrypoint": "normalize_score", + "content": { + "encoding": "base64", + "data": "ZnJvbSBfX2Z1dHVyZV9fIGltcG9ydCBhbm5vdGF0aW9ucwoKZGVmIG5vcm1hbGl6ZV9zY29yZSh2YWx1ZTogZmxvYXQpIC0+IGZsb2F0OgogICAgcmV0dXJuIHZhbHVlIC8gMTAwLjAK" + }, + "adapter": { + "kind": "scalar_to_arrow_batch", + "version": 1 + } + }, + "signature": { + "inputs": [ + { + "name": "value", + "arrow_type": "float64", + "nullable": false + } + ], + "output": { + "kind": "scalar", + "arrow_type": "float64", + "nullable": false + } + }, + "runtime": { + "kind": "python", + "python_version": "3.12", + "environment": { + "kind": "pip", + "packages": [ + "numpy>=2" + ] + }, + "env": { + "MODE": "test" + } + }, + "required_secrets": [ + "API_TOKEN" + ] +} From f76ee304b8baa1ad117caefc7e30730ffc5f015f Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 21 Aug 2026 18:18:55 +0800 Subject: [PATCH 064/206] ci: isolate remote Rust tests (#3998) The Linux Rust job can exhaust its disk after restoring a large fallback target cache and compiling multiple feature graphs into one target directory. Run remote tests in an independent job with registry-only caching, and run the simple example with all features so it reuses the preceding build artifacts. This preserves remote coverage and fork behavior while preventing all-features and remote-only artifacts from accumulating together. Failure evidence: https://github.com/lancedb/lancedb/actions/runs/32467317540/job/96726650990 --- .github/workflows/rust.yml | 38 +++++++++++++++++++++++++++++++++----- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 471da43e0..cd872621b 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -121,7 +121,6 @@ jobs: # Need up-to-date compilers for kernels CC: clang-18 CXX: clang++-18 - GH_TOKEN: ${{ secrets.SOPHON_READ_TOKEN }} steps: - uses: actions/checkout@v6 with: @@ -165,11 +164,40 @@ jobs: - name: Run feature tests run: CARGO_ARGS="--profile ci" make -C ./lancedb feature-tests - name: Run examples - run: cargo run --profile ci --example simple --locked + run: cargo run --profile ci --all-features --example simple --locked + + remote: + timeout-minutes: 30 + # Running this requires access to secrets, so skip if this is a PR from a + # fork. Keep it separate from the all-features build so Cargo does not + # retain both dependency graphs in one target directory. + if: github.event_name != 'pull_request' || !github.event.pull_request.head.repo.fork + runs-on: ubuntu-2404-4x-x64 + defaults: + run: + shell: bash + working-directory: rust + env: + CC: clang-18 + CXX: clang++-18 + GH_TOKEN: ${{ secrets.SOPHON_READ_TOKEN }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + lfs: true + - uses: Swatinem/rust-cache@v2 + with: + # Remote tests use a different feature graph from the main Linux + # job. Cache downloads, but build into a fresh target directory. + cache-targets: false + save-if: ${{ github.ref == 'refs/heads/main' }} + - name: Install dependencies + run: | + sudo apt update + sudo apt install -y protobuf-compiler libssl-dev + - uses: rui314/setup-mold@v1 - name: Run remote tests - # Running this requires access to secrets, so skip if this is - # a PR from a fork. - if: github.event_name != 'pull_request' || !github.event.pull_request.head.repo.fork run: CARGO_ARGS="--profile ci" make -C ./lancedb remote-tests macos: From cf27f6902ead4da5a923c545be7d51f2e74c6a7e Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Fri, 21 Aug 2026 03:24:22 -0700 Subject: [PATCH 065/206] chore: update lance dependency to v11.0.0-beta.16 (#3992) Updates Lance dependencies and Java lance-core to v11.0.0-beta.16. Also narrows the dependency updater's package matching so the local LanceDB crate remains a path dependency. Lance tag: https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.16 --------- Co-authored-by: Yang Cen --- .github/workflows/ci-scripts.yml | 30 +++++ Cargo.lock | 84 ++++++------- Cargo.toml | 28 ++--- ci/set_lance_version.py | 2 +- ci/tests/test_set_lance_version.py | 185 +++++++++++++++++++++++++++++ java/pom.xml | 2 +- 6 files changed, 273 insertions(+), 58 deletions(-) create mode 100644 .github/workflows/ci-scripts.yml create mode 100644 ci/tests/test_set_lance_version.py diff --git a/.github/workflows/ci-scripts.yml b/.github/workflows/ci-scripts.yml new file mode 100644 index 000000000..9b9124ab2 --- /dev/null +++ b/.github/workflows/ci-scripts.yml @@ -0,0 +1,30 @@ +name: CI scripts + +on: + push: + branches: + - main + paths: + - ci/set_lance_version.py + - ci/tests/** + - .github/workflows/ci-scripts.yml + pull_request: + paths: + - ci/set_lance_version.py + - ci/tests/** + - .github/workflows/ci-scripts.yml + +permissions: + contents: read + +jobs: + test: + name: Test CI scripts + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-python@v6 + with: + python-version: "3.13" + - name: Run tests + run: python -m unittest discover -s ci/tests -v diff --git a/Cargo.lock b/Cargo.lock index ddb9cf880..34a164181 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow", "arrow-array", @@ -5013,8 +5013,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow", "arrow-array", @@ -5031,8 +5031,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "proc-macro2", "quote", @@ -5041,8 +5041,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow-arith", "arrow-array", @@ -5075,8 +5075,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow-arith", "arrow-array", @@ -5107,8 +5107,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arc-swap", "arrow", @@ -5172,8 +5172,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow-array", "arrow-schema", @@ -5195,8 +5195,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow", "arrow-array", @@ -5232,8 +5232,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow-array", "arrow-schema", @@ -5247,8 +5247,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow", "async-trait", @@ -5260,8 +5260,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow", "arrow-ipc", @@ -5314,8 +5314,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow-array", "arrow-buffer", @@ -5329,8 +5329,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow", "arrow-array", @@ -5370,8 +5370,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "arrow-array", "arrow-schema", @@ -5384,8 +5384,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.15#8064b3a27dc4e05a6ab6ceb439fa1be9950e00eb" +version = "11.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 925910586..ac5db7f38 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.15", default-features = false, "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.15", default-features = false, "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.15", default-features = false, "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.15", "tag" = "v11.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.16", default-features = false, "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.16", default-features = false, "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.16", default-features = false, "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/ci/set_lance_version.py b/ci/set_lance_version.py index f66761644..c7bf41f55 100644 --- a/ci/set_lance_version.py +++ b/ci/set_lance_version.py @@ -119,7 +119,7 @@ def update_cargo_toml(line_updater): lance_line = "" is_parsing_lance_line = False for line in lines: - if line.startswith("lance"): + if re.match(r"^lance(?:\s|[-_])", line): # Check if this is a single-line or multi-line entry # Single-line entries either: # 1. End with } (complete inline table) diff --git a/ci/tests/test_set_lance_version.py b/ci/tests/test_set_lance_version.py new file mode 100644 index 000000000..1493fc59d --- /dev/null +++ b/ci/tests/test_set_lance_version.py @@ -0,0 +1,185 @@ +import os +import stat +import subprocess +import sys +import tempfile +import textwrap +import unittest +from pathlib import Path + + +REPO_ROOT = Path(__file__).resolve().parents[2] +SCRIPT = REPO_ROOT / "ci" / "set_lance_version.py" +LANCE_GIT_URL = "https://github.com/lance-format/lance.git" + +CARGO_TOML = """\ +[workspace.dependencies] +lance = { "version" = "=1.0.0", default-features = false, "features" = ["dynamodb"] } +lance-core = "1.0.0" +lance_datafusion = { + "version" = "=1.0.0", + "features" = ["substrait"] +} +lancedb = { path = "rust/lancedb", default-features = false } +lancedb-common = { path = "rust/lancedb-common" } +lancewood = "1.0.0" +my-lance = "1.0.0" +""" + +UNTOUCHED_DEPENDENCIES = """\ +lancedb = { path = "rust/lancedb", default-features = false } +lancedb-common = { path = "rust/lancedb-common" } +lancewood = "1.0.0" +my-lance = "1.0.0" +""" + + +class SetLanceVersionTest(unittest.TestCase): + def test_supported_update_modes_only_rewrite_lance_dependencies(self): + cases = { + "stable": ( + """\ +lance = { "version" = "=9.9.9", default-features = false, "features" = ["dynamodb"] } +lance-core = "=9.9.9" +lance_datafusion = { "version" = "=9.9.9", "features" = ["substrait"] } +""", + ["cargo info lance", "cargo metadata"], + ), + "preview": ( + f"""\ +lance = {{ "version" = "=10.0.0-beta.3", default-features = false, "features" = ["dynamodb"], "tag" = "v10.0.0-beta.3", "git" = "{LANCE_GIT_URL}" }} +lance-core = {{ "version" = "=10.0.0-beta.3", "tag" = "v10.0.0-beta.3", "git" = "{LANCE_GIT_URL}" }} +lance_datafusion = {{ "version" = "=10.0.0-beta.3", "features" = ["substrait"], "tag" = "v10.0.0-beta.3", "git" = "{LANCE_GIT_URL}" }} +""", + ["git ls-remote --tags", "cargo metadata"], + ), + "local": ( + """\ +lance = { "path" = "../lance/rust/lance", default-features = false, "features" = ["dynamodb"] } +lance-core = { "path" = "../lance/rust/lance-core" } +lance_datafusion = { "path" = "../lance/rust/lance_datafusion", "features" = ["substrait"] } +""", + ["cargo metadata"], + ), + "v8.1.2": ( + """\ +lance = { "version" = "=8.1.2", default-features = false, "features" = ["dynamodb"] } +lance-core = "=8.1.2" +lance_datafusion = { "version" = "=8.1.2", "features" = ["substrait"] } +""", + ["cargo metadata"], + ), + "v8.2.0-beta.4": ( + f"""\ +lance = {{ "version" = "=8.2.0-beta.4", default-features = false, "features" = ["dynamodb"], "tag" = "v8.2.0-beta.4", "git" = "{LANCE_GIT_URL}" }} +lance-core = {{ "version" = "=8.2.0-beta.4", "tag" = "v8.2.0-beta.4", "git" = "{LANCE_GIT_URL}" }} +lance_datafusion = {{ "version" = "=8.2.0-beta.4", "features" = ["substrait"], "tag" = "v8.2.0-beta.4", "git" = "{LANCE_GIT_URL}" }} +""", + ["cargo metadata"], + ), + } + + for version, (updated_dependencies, expected_commands) in cases.items(): + with self.subTest(version=version), tempfile.TemporaryDirectory() as tmp: + workdir = Path(tmp) + (workdir / "Cargo.toml").write_text(CARGO_TOML) + command_log = workdir / "commands.log" + fake_bin = workdir / "bin" + fake_bin.mkdir() + self._write_fake_executables(fake_bin) + self._write_fake_python_dependencies(workdir) + + env = os.environ.copy() + env["PATH"] = os.pathsep.join([str(fake_bin), env["PATH"]]) + env["FAKE_COMMAND_LOG"] = str(command_log) + env["PYTHONPATH"] = os.pathsep.join( + filter(None, [str(workdir), env.get("PYTHONPATH")]) + ) + result = subprocess.run( + [sys.executable, str(SCRIPT), version], + cwd=workdir, + env=env, + capture_output=True, + text=True, + timeout=10, + ) + + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + (workdir / "Cargo.toml").read_text(), + "[workspace.dependencies]\n" + + updated_dependencies + + UNTOUCHED_DEPENDENCIES, + ) + commands = command_log.read_text().splitlines() + for command in expected_commands: + self.assertTrue( + any(line.startswith(command) for line in commands), + f"{command!r} not found in {commands!r}", + ) + + def _write_fake_executables(self, fake_bin: Path) -> None: + cargo = fake_bin / "cargo" + cargo.write_text( + textwrap.dedent( + """\ + #!/bin/sh + printf 'cargo %s\\n' "$*" >> "$FAKE_COMMAND_LOG" + case "$1" in + info) + printf '%s\\n' 'version: 8.8.8 (latest 9.9.9)' + ;; + metadata) + ;; + *) + exit 2 + ;; + esac + """ + ) + ) + cargo.chmod(cargo.stat().st_mode | stat.S_IXUSR) + + git = fake_bin / "git" + git.write_text( + textwrap.dedent( + """\ + #!/bin/sh + printf 'git %s\\n' "$*" >> "$FAKE_COMMAND_LOG" + if [ "$1" != "ls-remote" ]; then + exit 2 + fi + printf '%s\\n' \\ + '111111 refs/tags/v9.9.9' \\ + '222222 refs/tags/v10.0.0-beta.1' \\ + '333333 refs/tags/v10.0.0-beta.3' + """ + ) + ) + git.chmod(git.stat().st_mode | stat.S_IXUSR) + + def _write_fake_python_dependencies(self, workdir: Path) -> None: + packaging = workdir / "packaging" + packaging.mkdir() + (packaging / "__init__.py").write_text("") + (packaging / "version.py").write_text( + textwrap.dedent( + """\ + class Version: + def __init__(self, value): + release, _, prerelease = value.partition("-beta.") + self._key = ( + tuple(int(part) for part in release.split(".")), + not prerelease, + int(prerelease or 0), + ) + + def __lt__(self, other): + return self._key < other._key + """ + ) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/java/pom.xml b/java/pom.xml index 92e6344f3..e5b2ac45e 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.15 + 11.0.0-beta.16 false 2.30.0 1.7 From 593ef1c47188a88bb49738ad25df9b897ef4b9d6 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Fri, 21 Aug 2026 10:25:20 +0000 Subject: [PATCH 066/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.2=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package-lock.json | 4 ++-- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index b0be7dc82..b1d2bf1dc 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.2" +current_version = "0.38.0-beta.3" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 34a164181..e0e10bf62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5398,7 +5398,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.2" +version = "0.38.0-beta.3" dependencies = [ "ahash", "anyhow", @@ -5486,7 +5486,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.2" +version = "0.38.0-beta.3" dependencies = [ "arrow-array", "arrow-buffer", @@ -5511,7 +5511,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.2" +version = "0.38.0-beta.3" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 452bd54f4..a8869d319 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.38.0-beta.2 + 0.38.0-beta.3 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 60c1549e3..9de14d1f9 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.2 + 0.38.0-beta.3 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index e5b2ac45e..d4d5c2687 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.2 + 0.38.0-beta.3 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 3c0b24db3..cba7012d1 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.2" +version = "0.38.0-beta.3" 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 c2be3aeac..3c76481fc 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.38.0-beta.2", + "version": "0.38.0-beta.3", "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 901405fe4..7a1a3af03 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.38.0-beta.2", + "version": "0.38.0-beta.3", "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 415e60c78..7175233af 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.38.0-beta.2", + "version": "0.38.0-beta.3", "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 22416dbcb..add5a1da2 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.38.0-beta.2", + "version": "0.38.0-beta.3", "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 77d6a5dd5..72a82bf6d 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.38.0-beta.2", + "version": "0.38.0-beta.3", "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 0dea90f81..c69beeb8a 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.38.0-beta.2", + "version": "0.38.0-beta.3", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 0be0b457b..d21fc1eb3 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.38.0-beta.2", + "version": "0.38.0-beta.3", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index 999b3f16f..1c368dab5 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.2", + "version": "0.38.0-beta.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.2", + "version": "0.38.0-beta.3", "cpu": [ "x64", "arm64" diff --git a/nodejs/package.json b/nodejs/package.json index 8291d3dc8..7f72eb8b0 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.2", + "version": "0.38.0-beta.3", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 5af99eac3..6181f704f 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.2" +version = "0.38.0-beta.3" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index ac1c8754c..f785e6743 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.2" +version = "0.38.0-beta.3" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From fbfb53e30fad500e7c4a486816e2beb7b633f0dd Mon Sep 17 00:00:00 2001 From: XY Zhan Date: Fri, 21 Aug 2026 07:35:42 -0400 Subject: [PATCH 067/206] refactor(lsm): remove the index-catchup activation surface (#3980) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follows lance-format/lance#8680, which removes `FLAG_MEM_WAL_INDEX_CATCHUP`. With one set of semantics there is no mode to switch into. ## Removed `require_mem_wal_index_catchup` — the activation entry point — from the trait, from `Table`, and from the LSM merge module. ## The read path `exclusion_watermarks` loses its `catchup_required` argument and keeps the conservative branch: an index with no entry is not known to hold these rows, so every generation stays readable from its SSTable. Nothing is excluded until an index records that it covers those generations, so a table that has never recorded catch-up reads every row from its SSTables rather than assuming the base covers them. ## One guard needed a replacement, not deletion `refresh_column` and computed-column declaration refuse a table whose rows sit in un-compacted tiers, since refresh enumerates base fragments and would silently omit them. They keyed on the feature bit because `unset_lsm_write_spec` **drops the MemWAL index** — after an unset the write spec no longer describes such a table, and the bit was the only marker that outlived it. Two tests covered this, so deleting the term would have dropped a tested property. Both guards now check for MemWAL shard directories on storage, which outlive the index. That is strictly wider than the bit ever was: the bit only marked tables where activation had run. ## Two tests conflated two different things An index that is *caught up* and one that is *untracked* both fell back to the compaction watermark, because absence carried no information without the bit. Absence now means "not caught up", so untracked retains everything. `an_untracked_index_does_not_widen_a_lagging_sibling` becomes `an_untracked_index_retains_everything`, with the genuinely-caught-up case asserted separately. ## Testing 933 `lancedb` lib tests. `cargo fmt` clean. (The pre-existing `Error::Http` build failure in `job.rs` without the `remote` feature is unrelated and untouched.) --- rust/lancedb/src/table.rs | 27 ------- rust/lancedb/src/table/computed_columns.rs | 1 - rust/lancedb/src/table/merge/lsm.rs | 30 -------- rust/lancedb/src/table/query/lsm.rs | 88 ++++++---------------- rust/lancedb/src/table/refresh.rs | 19 +++-- rust/lancedb/src/table/schema_evolution.rs | 18 +++-- 6 files changed, 51 insertions(+), 132 deletions(-) diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 9228b4baf..e1dd942db 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -643,15 +643,6 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "set_lsm_write_spec is not supported on this table type".into(), }) } - /// Switch this table to required index catch-up, one way. - /// - /// The default implementation returns `NotSupported`. Implementations - /// that support the MemWAL LSM write path must override this. - async fn require_mem_wal_index_catchup(&self) -> Result<()> { - Err(Error::NotSupported { - message: "require_mem_wal_index_catchup is not supported on this table type".into(), - }) - } /// Remove the [`LsmWriteSpec`] from this table. /// /// This is a no-op if no spec is currently set. @@ -1793,20 +1784,6 @@ impl Table { self.inner.set_lsm_write_spec(spec).await } - /// Switch this table to required index catch-up, one way. - /// - /// Separate from [`Self::set_lsm_write_spec`] on purpose: a table carrying - /// the bit retains its SSTables until an index records that it holds the - /// compacted rows, so turn it on only once something can repair coverage. - /// A writer that already holds the dataset can call the equivalent on - /// `DatasetMemWalExt` instead; this is the table-level entry point. - /// - /// Errors if no spec is set, or if the table already records SSTable - /// compaction progress from before this protocol. - pub async fn require_mem_wal_index_catchup(&self) -> Result<()> { - self.inner.require_mem_wal_index_catchup().await - } - /// Remove the [`LsmWriteSpec`] from this table, reverting to the standard /// `merge_insert` write path. /// @@ -3354,10 +3331,6 @@ impl BaseTable for NativeTable { merge::lsm::set_lsm_write_spec(self, spec).await } - async fn require_mem_wal_index_catchup(&self) -> Result<()> { - merge::lsm::require_mem_wal_index_catchup(self).await - } - async fn unset_lsm_write_spec(&self) -> Result<()> { merge::lsm::unset_lsm_write_spec(self).await } diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 841b13856..24cc48658 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -2151,7 +2151,6 @@ mod tests { .set_lsm_write_spec(LsmWriteSpec::unsharded()) .await .unwrap(); - table.require_mem_wal_index_catchup().await.unwrap(); let mut merge = table.merge_insert(&["id"]); merge diff --git a/rust/lancedb/src/table/merge/lsm.rs b/rust/lancedb/src/table/merge/lsm.rs index 5751cd916..44a2874de 100644 --- a/rust/lancedb/src/table/merge/lsm.rs +++ b/rust/lancedb/src/table/merge/lsm.rs @@ -192,36 +192,6 @@ fn index_name_list(indices: &[IndexConfig]) -> String { format!("[{}]", names.join(", ")) } -// ============================================================================= -// require_mem_wal_index_catchup -// ============================================================================= - -/// Switch this table to required index catch-up, one way. -/// -/// Deliberately **not** part of installing the write spec. Until something can -/// actually repair coverage, a table carrying the bit reports every index as -/// not known to hold the compacted rows, so its SSTables are retained -/// indefinitely -- and the WAL pod trims on the legacy rule meanwhile, leaving -/// readers pointed at files that are gone. Turn this on only once remote -/// maintenance owns the merge and the repair for the table. -/// -/// Lance refuses the activation if the table already records SSTable -/// compaction progress: those numbers predate this protocol and cannot be -/// validated, so such a table must be drained rather than activated. -#[allow(clippy::redundant_pub_crate)] -pub(crate) async fn require_mem_wal_index_catchup(table: &NativeTable) -> Result<()> { - table.dataset.ensure_mutable()?; - let mut dataset = (*table.dataset.get().await?).clone(); - if dataset.mem_wal_index_details().await?.is_none() { - return Err(Error::InvalidInput { - message: "require_mem_wal_index_catchup: no LSM write spec is set on this table".into(), - }); - } - dataset.require_mem_wal_index_catchup().await?; - table.dataset.update(dataset); - Ok(()) -} - // ============================================================================= // unset_lsm_write_spec // ============================================================================= diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index 6155ec095..255d649b1 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -36,7 +36,6 @@ use lance::dataset::mem_wal::{ DatasetMemWalExt, LsmScanner, ShardManifestStore, ShardSnapshot, ShardWriterConfig, }; use lance_index::mem_wal::{MemWalIndexDetails, ShardManifest}; -use lance_table::feature_flags::FLAG_MEM_WAL_INDEX_CATCHUP; use uuid::Uuid; use super::NativeTable; @@ -249,7 +248,6 @@ fn pk_columns(dataset: &Dataset) -> Result> { fn exclusion_watermarks( details: &MemWalIndexDetails, index_names: &[String], - catchup_required: bool, ) -> HashMap { let mut exclude: HashMap = HashMap::new(); for entry in &details.compacted_sstables { @@ -262,13 +260,10 @@ fn exclusion_watermarks( .and_then(|icp| icp.caught_up_generation_for_shard(&entry.shard_id)) { Some(caught_up) => watermark = watermark.min(caught_up), - // No entry. On a table that requires catch-up this means the - // index is *not* known to hold these rows, and the base arm is - // index-only -- so every generation stays readable from its - // SSTable. Without the bit the field is not maintained at all, - // and absence carries no information. - None if catchup_required => watermark = 0, - None => {} + // No entry means the index is *not* known to hold these rows, + // and the base arm is index-only -- so every generation stays + // readable from its SSTable. + None => watermark = 0, } } exclude.entry(entry.shard_id).or_insert(watermark); @@ -283,26 +278,13 @@ fn exclusion_watermarks( /// with a live cached `ShardWriter` (this session's in-flight writes) the /// writer's authoritative in-memory manifest and memtables override the /// on-disk view so a read sees data not yet flushed. -/// Whether this table reads a missing `index_catchup` entry as "not caught up". -/// -/// Both words must be set. A reader honouring the bit while a writer does not -/// would retain SSTables the writer had already trimmed, and the reverse would -/// serve rows from files the writer still expects to be excluded -- so a -/// half-set manifest is treated as legacy, which is the conservative side. -fn requires_index_catchup(dataset: &Dataset) -> bool { - let manifest = dataset.manifest(); - manifest.reader_feature_flags & FLAG_MEM_WAL_INDEX_CATCHUP != 0 - && manifest.writer_feature_flags & FLAG_MEM_WAL_INDEX_CATCHUP != 0 -} - async fn build_read_context( table: &NativeTable, dataset: &Dataset, details: &MemWalIndexDetails, index_names: &[String], ) -> Result<(Vec, HashMap)> { - let catchup_required = requires_index_catchup(dataset); - let exclude = exclusion_watermarks(details, index_names, catchup_required); + let exclude = exclusion_watermarks(details, index_names); let shard_ids = dataset.list_mem_wal_latest_shard_ids().await?; // Use the dataset's own object store (not `ObjectStore::from_uri`, which @@ -789,50 +771,29 @@ mod tests { }; // Plain scan: drop every compacted generation (through 5). - assert_eq!( - exclusion_watermarks(&details, &[], false).get(&shard), - Some(&5) - ); + assert_eq!(exclusion_watermarks(&details, &[]).get(&shard), Some(&5)); // FTS arm with a lagging index: exclusion is capped at the index catch-up // (2), so SSTable generations 3..=5 are retained until the index covers // them — otherwise those documents would silently vanish from FTS results. assert_eq!( - exclusion_watermarks(&details, &["fts_idx".to_string()], false).get(&shard), + exclusion_watermarks(&details, &["fts_idx".to_string()]).get(&shard), Some(&2) ); - // A caught-up index — or one untracked in index_catchup — falls back to the - // compaction watermark. + // An index absent from index_catchup is *not* known to hold these rows, + // so nothing may be excluded and every generation stays readable from + // its SSTable. An indexed query against an index that has not caught up + // must not silently lose rows. assert_eq!( - exclusion_watermarks(&details, &["caught_up_idx".to_string()], false).get(&shard), - Some(&5) - ); - - // The same missing entry, once the table requires catch-up: absence now - // means "not known to hold these rows", so nothing may be excluded and - // every generation stays readable from its SSTable. This is the whole - // point of the protocol -- an indexed query against a table whose index - // has not caught up must not silently lose rows. - assert_eq!( - exclusion_watermarks(&details, &["untracked_idx".to_string()], true).get(&shard), + exclusion_watermarks(&details, &["untracked_idx".to_string()]).get(&shard), Some(&0) ); - // A tracked index is unaffected by the mode: the recorded position is - // information either way, and it still caps the exclusion. - assert_eq!( - exclusion_watermarks(&details, &["fts_idx".to_string()], true).get(&shard), - Some(&2) - ); - // One missing entry is enough to hold everything back, even alongside an // index that has caught up. let mixed = vec!["fts_idx".to_string(), "untracked_idx".to_string()]; - assert_eq!( - exclusion_watermarks(&details, &mixed, true).get(&shard), - Some(&0) - ); + assert_eq!(exclusion_watermarks(&details, &mixed).get(&shard), Some(&0)); } /// A hybrid search reads a vector and a full-text index, and either may lag. @@ -859,31 +820,29 @@ mod tests { // Each index alone stops at its own catch-up. assert_eq!( - exclusion_watermarks(&details, &["vec_idx".to_string()], false).get(&shard), + exclusion_watermarks(&details, &["vec_idx".to_string()]).get(&shard), Some(&7) ); assert_eq!( - exclusion_watermarks(&details, &["fts_idx".to_string()], false).get(&shard), + exclusion_watermarks(&details, &["fts_idx".to_string()]).get(&shard), Some(&4) ); // Used together, the lower one governs regardless of order. let both = ["vec_idx".to_string(), "fts_idx".to_string()]; - assert_eq!( - exclusion_watermarks(&details, &both, false).get(&shard), - Some(&4) - ); + assert_eq!(exclusion_watermarks(&details, &both).get(&shard), Some(&4)); let reversed = ["fts_idx".to_string(), "vec_idx".to_string()]; assert_eq!( - exclusion_watermarks(&details, &reversed, false).get(&shard), + exclusion_watermarks(&details, &reversed).get(&shard), Some(&4) ); } - /// An index with no catch-up entry contributes no cap today, so a lagging - /// sibling must still govern rather than being widened by the untracked one. + /// An index with no catch-up entry is not known to hold these rows, so it + /// retains everything -- it is never widened by a tracked sibling that has + /// caught up further. #[test] - fn an_untracked_index_does_not_widen_a_lagging_sibling() { + fn an_untracked_index_retains_everything() { let shard = Uuid::from_u128(1); let details = MemWalIndexDetails { compacted_sstables: vec![CompactedSsTable::new(shard, 9)], @@ -896,8 +855,11 @@ mod tests { }; let both = ["fts_idx".to_string(), "untracked_idx".to_string()]; + assert_eq!(exclusion_watermarks(&details, &both).get(&shard), Some(&0)); + + // The tracked sibling still caps on its own. assert_eq!( - exclusion_watermarks(&details, &both, false).get(&shard), + exclusion_watermarks(&details, &["fts_idx".to_string()]).get(&shard), Some(&4) ); } diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index e94f20f2b..a3f3da92f 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -141,11 +141,19 @@ pub(crate) async fn execute_refresh_column_async(table: &NativeTable, column: &s /// un-compacted MemWAL tiers it cannot reach -- success would silently omit /// readable rows. async fn ensure_no_lsm_write_spec(table: &NativeTable) -> Result<()> { - // The catch-up flag outlives unset and marks retained SSTable rows. - let catchup = table.dataset.get().await?.manifest().reader_feature_flags - & lance_table::feature_flags::FLAG_MEM_WAL_INDEX_CATCHUP - != 0; - if catchup || table.get_lsm_write_spec().await?.is_some() { + use lance::dataset::mem_wal::DatasetMemWalExt; + + // Unset drops the MemWAL index, so the spec alone stops describing a table + // whose SSTables still hold rows. The shard directories outlive it and are + // the durable evidence. + let retained_sstables = !table + .dataset + .get() + .await? + .list_mem_wal_latest_shard_ids() + .await? + .is_empty(); + if retained_sstables || table.get_lsm_write_spec().await?.is_some() { return Err(Error::NotSupported { message: "refresh_column is not supported on a table with an LSM write \ spec: rows in un-compacted tiers are invisible to refresh" @@ -921,7 +929,6 @@ mod tests { .set_lsm_write_spec(LsmWriteSpec::unsharded()) .await .unwrap(); - table.require_mem_wal_index_catchup().await.unwrap(); let mut merge = table.merge_insert(&["x"]); merge .when_matched_update_all(None) diff --git a/rust/lancedb/src/table/schema_evolution.rs b/rust/lancedb/src/table/schema_evolution.rs index 4e41f0e85..d10a45eea 100644 --- a/rust/lancedb/src/table/schema_evolution.rs +++ b/rust/lancedb/src/table/schema_evolution.rs @@ -124,18 +124,26 @@ pub(crate) async fn execute_declare( table: &NativeTable, columns: &[(String, String)], ) -> Result { + use lance::dataset::mem_wal::DatasetMemWalExt; + // An LSM write spec keeps visible rows in tiers refresh cannot reach; // checked against latest committed state, not this handle's snapshot. - // The catch-up flag outlives unset and marks retained SSTable rows. table.checkout_latest().await?; computed_columns::ensure_no_function_bindings_for_mutation( table.schema().await?.as_ref(), "schema evolution", )?; - let catchup = table.dataset.get().await?.manifest().reader_feature_flags - & lance_table::feature_flags::FLAG_MEM_WAL_INDEX_CATCHUP - != 0; - if catchup || table.get_lsm_write_spec().await?.is_some() { + // Unset drops the MemWAL index, so the spec alone stops describing a table + // whose SSTables still hold rows. The shard directories outlive it and are + // the durable evidence. + let retained_sstables = !table + .dataset + .get() + .await? + .list_mem_wal_latest_shard_ids() + .await? + .is_empty(); + if retained_sstables || table.get_lsm_write_spec().await?.is_some() { return Err(Error::NotSupported { message: "computed columns are not supported on a table with an LSM write \ spec: rows in un-compacted tiers are invisible to refresh" From 6a0df4de474b88fa0e151953540f55cbbe4e0485 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 21 Aug 2026 19:42:37 +0800 Subject: [PATCH 068/206] fix(python): return None from unit jobs (#3999) ## Problem Generic job result propagation exposed the PyO3 representation of Rust's unit value as `()` in Python. Unit jobs therefore returned an empty tuple instead of `None`, breaking the documented `Job.wait()` contract and the Python doctest workflow. ## Behavior Unit job completion now converts explicitly to Python `None`. Typed job results continue to pass through unchanged, with synchronous and asynchronous regression coverage. --- python/python/tests/test_table.py | 4 ++-- python/src/job.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index b28cd9d66..0f98219bf 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -3947,7 +3947,7 @@ def test_refresh_column_async_returns_job(tmp_path): job = table.refresh_column_async("doubled") assert job.id is None # in-process jobs have no server id - job.wait() + assert job.wait() is None assert job.status() == "finished" assert sorted(table.to_arrow()["doubled"].to_pylist()) == [2, 4] @@ -3963,6 +3963,6 @@ async def test_refresh_column_async_job_async_table(tmp_path): await table.add_columns(computed={"tripled": "x * 3"}) job = await table.refresh_column_async("tripled") - await job.wait() + assert await job.wait() is None assert await job.status() == "finished" assert (await table.to_arrow())["tripled"].to_pylist() == [9] diff --git a/python/src/job.rs b/python/src/job.rs index 2755a28c5..a08b958a6 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -93,7 +93,7 @@ impl Job { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { inner.wait().await.infer_error()?; - Ok(()) + Ok(None::<()>) }) } From fd2a202a46ef962d8a7232237a583fb6fbf4e8fd Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Fri, 21 Aug 2026 05:30:24 -0700 Subject: [PATCH 069/206] chore: update lance dependency to v11.0.0-beta.18 (#4000) Updates the Rust workspace Lance dependencies and Java lance-core dependency to v11.0.0-beta.18. Lance tag: https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.18 --- Cargo.lock | 84 ++++++++++++++++++++++++++-------------------------- Cargo.toml | 28 +++++++++--------- java/pom.xml | 2 +- 3 files changed, 57 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e0e10bf62..73f5923fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow", "arrow-array", @@ -5013,8 +5013,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow", "arrow-array", @@ -5031,8 +5031,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "proc-macro2", "quote", @@ -5041,8 +5041,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow-arith", "arrow-array", @@ -5075,8 +5075,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow-arith", "arrow-array", @@ -5107,8 +5107,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arc-swap", "arrow", @@ -5172,8 +5172,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow-array", "arrow-schema", @@ -5195,8 +5195,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow", "arrow-array", @@ -5232,8 +5232,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow-array", "arrow-schema", @@ -5247,8 +5247,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow", "async-trait", @@ -5260,8 +5260,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow", "arrow-ipc", @@ -5314,8 +5314,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow-array", "arrow-buffer", @@ -5329,8 +5329,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow", "arrow-array", @@ -5370,8 +5370,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "arrow-array", "arrow-schema", @@ -5384,8 +5384,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.16#d514a61fa7e449dedcd03571eabd338b3c84b170" +version = "11.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index ac5db7f38..9aeccd76f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.16", default-features = false, "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.16", default-features = false, "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.16", default-features = false, "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.16", "tag" = "v11.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.18", default-features = false, "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.18", default-features = false, "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.18", default-features = false, "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index d4d5c2687..978f7c7c7 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.16 + 11.0.0-beta.18 false 2.30.0 1.7 From 944398d807f55821c29ca410c6990b979ff0411e Mon Sep 17 00:00:00 2001 From: Dan Tasse <105866+dantasse@users.noreply.github.com> Date: Fri, 21 Aug 2026 12:06:20 -0400 Subject: [PATCH 070/206] refactor: make branch ops instructions less redundant, point to docs (#3978) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As in https://github.com/lancedb/lancedb/pull/3977, we're trying to reduce anything in the lancedb skill that duplicates other docs. So this shrinks the branch-ops logic down to a few lines that mostly just point the agent to fetch the branching docs from lancedb.github.io. Run stats (2 runs each): Screenshot 2026-08-20 at 5 02 34 PM This is out of order, rearranged: |condition|time (sec)|cost| |---|---|---| |No branch_ops.md|250|1.33| |No branch_ops.md|227|1.26| |Old branch_ops.md|116|0.83| |Old branch_ops.md|127|0.87| |New branch_ops.md|135|0.86| |New branch_ops.md|147|0.93| Averaged between each of the two runs: Screenshot 2026-08-20 at 5 34 15 PM It seems helpful to have *some* doc about branching; otherwise the model gets a little confused about our branch model and what methods to call. But it looks like the new one (in this PR; all just references to current docs) is basically as good as the old one (lots of duplicative text). --------- Co-authored-by: Claude Fable 5 --- .../skills/lancedb/references/branch_ops.md | 184 +----------------- 1 file changed, 9 insertions(+), 175 deletions(-) diff --git a/plugins/lancedb/skills/lancedb/references/branch_ops.md b/plugins/lancedb/skills/lancedb/references/branch_ops.md index e94c7e6db..d79e5c8bc 100644 --- a/plugins/lancedb/skills/lancedb/references/branch_ops.md +++ b/plugins/lancedb/skills/lancedb/references/branch_ops.md @@ -1,182 +1,16 @@ # Branch Operations -Manage branches on a LanceDB table: list what exists, create new ones, delete stale ones, and direct read/write operations at a specific branch without touching main. Use for branch lifecycle tasks, experimental/isolated table versions, targeting an operation at a non-main branch, or confirming a mutation did not affect main. +Branches are isolated, writable lines of history forked from `main` by default (or from another branch/version via `create`'s `from_ref`/`from_version`). There is no global "switch branch" state: `branches.create(...)` / `branches.checkout(...)` return a **table handle scoped to that branch**, and every read/write on that handle lands on the branch while the original main handle is unaffected. Unpinned handles track the branch's latest version and are writable; `checkout(name, version=...)` pins the handle to that version and is read-only. -Works on local/OSS and remote Enterprise/Cloud tables, except merging a branch into main, which is Enterprise-only. +Don't work from memory — read the public docs for the current API: -## The branch model (important) +- **Branching guide (concepts + Python/TypeScript examples):** — covers creating, writing to, reopening, and deleting branches; applying branch-tested changes back to main; diff/merge (Enterprise only); and building indexes on a branch. +- **How branches relate to versions and tags:** +- **Python API reference** (`Table.branches`, `Table.current_branch`, `Branches`/`AsyncBranches` with `list`/`create`/`checkout`/`delete`/`diff`/`merge`): +- **TypeScript API reference** (`Branches` class, same methods; `table.branches()` is async, `table.currentBranch()` returns `null` for main): -Branches are isolated, writable lines of history forked from another branch (or a specific version). Writes on a branch never affect `main`. +Notes the docs may not state prominently: -There is **no global "switch branch" state** — you never repoint the whole table at a branch. Instead, **operations are scoped by which table handle you use**: +- Branch lifecycle works on local/OSS and remote Cloud/Enterprise tables; **merging into main is Enterprise-only** (others raise `NotSupported`). A rejected merge is not an exception — inspect the returned `status` and `diff.mergeBlockers`. +- To verify isolation after a branch write, read through both handles: the branch handle sees the change, the main handle must not. -- The handle you got from `open_table(name)` / `openTable(name)` targets `main`. -- `branches.create(...)` and `branches.checkout(...)` return a **new table handle scoped to that branch**. Every read/write on that handle (add, update, `update_field_metadata`, `create_index`, search, …) lands on the branch. -- The original main handle is unaffected — keep it around to verify isolation. - -`branches.list()` returns only non-main branches. Main always exists and is not listed. - -## Python - -`table.branches` is a property returning the branch manager; `table.current_branch()` tells you what a handle is scoped to (`None` = main). - -```python -table = db.open_table("products") # scoped to main - -# list — dict of name -> metadata (parent_branch, parent_version, ...); {} = only main -table.branches.list() - -# create: forks from main by default and returns a handle scoped to the new branch -exp = table.branches.create("experiment-reindex") -exp = table.branches.create("exp2", from_ref="main", from_version=None) # optional fork point - -# checkout an existing branch -> branch-scoped handle -wip = table.branches.checkout("wip-branch") -# with version= it pins to that version (read-only detached view); omit to track latest, writable - -# operate on the branch simply by using its handle -wip.update_field_metadata( - {"path": "category", "metadata": {"lancedb:description": "Product category label."}} -) -wip.create_scalar_index("category") - -# delete: removes only the branch pointer; main and row data remain intact -table.branches.delete("stale-2024") - -# alternatively, open a branch handle directly from the connection -wip = db.open_table("products", branch="wip-branch") - -exp.current_branch() # "experiment-reindex" -table.current_branch() # None (main) -``` - -Async: same shape — `table.branches` returns `AsyncBranches`; `await table.branches.create(...)` etc. - -## TypeScript - -`table.branches()` is an **async method** returning the `Branches` manager; `table.currentBranch()` returns the scoped branch or `null` for main. - -```typescript -const table = await db.openTable("products"); // scoped to main -const branches = await table.branches(); - -// list — Record; {} = only main -await branches.list(); - -// create: forks from main by default, returns a Table scoped to the new branch -const exp = await branches.create("experiment-reindex"); -const exp2 = await branches.create("exp2", "main" /* fromRef */, undefined /* fromVersion */); - -// checkout an existing branch -> branch-scoped Table -const wip = await branches.checkout("wip-branch"); -// with a version arg it pins (read-only detached view); omit to track latest, writable - -// operate on the branch simply by using its handle -await wip.updateFieldMetadata([ - { path: "category", metadata: { "lancedb:description": "Product category label." } }, -]); -await wip.createIndex("category"); - -// delete: removes only the branch pointer; main and row data remain intact -await branches.delete("stale-2024"); - -// alternatively, open a branch handle directly from the connection -const wip2 = await db.openTable("products", { branch: "wip-branch" }); - -exp.currentBranch(); // "experiment-reindex" -table.currentBranch(); // null (main) -``` - -## Verifying isolation - -After writing to a branch, confirm the change did NOT land on main by reading through both handles: - -```python -wip = table.branches.checkout("wip-branch") -wip.update_field_metadata({"path": "category", "metadata": {"lancedb:description": "..."}}) - -assert b"lancedb:description" in (wip.schema.field("category").metadata or {}) -assert b"lancedb:description" not in (table.schema.field("category").metadata or {}) # main untouched -``` - -Two handles on the same branch see each other's writes (e.g. `table.branches.create("exp")` and `db.open_table(name, branch="exp")`); main stays isolated. - -## Merging a branch into main (Enterprise only) - -Merge is available through the SDKs (`table.branches.merge(...)`) on **Enterprise tables only** — it is not supported on Cloud or local/OSS tables, which raise `NotSupported`. - -`merge` takes the branch to merge **from** and a `dry_run` flag. Both the SDK method and the underlying REST endpoint **actually merge by default** (`dry_run=False`); pass `dry_run=True` to only preview. A rejected merge is **not an exception** — it returns a result with `status="rejected"` rather than raising, so inspect the return value. Use `branches.diff(from_branch)` to inspect a branch's pending diff without attempting a merge. - -```python -exp = "experiment-reindex" - -# preview only — returns status="ready" if it would merge cleanly -preview = table.branches.merge(exp, dry_run=True) - -# actually merge (default) -result = table.branches.merge(exp) -if result["status"] == "merged": - print("landed at", result["mainVersionAfter"]) -elif result["status"] == "rejected": - print(result["diff"]["mergeBlockers"]) # why it was refused - -# inspect a branch's pending diff without merging -diff = table.branches.diff(exp) -``` - -Async: `await table.branches.merge(exp)`, `await table.branches.diff(exp)`. - -```typescript -const branches = await table.branches(); -const exp = "experiment-reindex"; - -// preview only (second arg is dryRun) -const preview = await branches.merge(exp, true); - -// actually merge (default) -const result = await branches.merge(exp); -if (result.status === "merged") { - console.log("landed at", result.mainVersionAfter); -} else if (result.status === "rejected") { - console.log(result.diff.mergeBlockers); -} - -const diff = await branches.diff(exp); -``` - -The result is the wire JSON, containing `status` (`ready` on a passing dry run, `merged` on success, `rejected` when refused — also `notImplemented`/`unknown`), the branch `diff` (including `mergeBlockers` explaining any rejection), a `preview` of the columns that would be promoted, and — after a real merge — `mainVersionAfter`. - -### Merge preconditions - -Merge only **promotes newly added columns** onto main; it does not replay arbitrary commits. Practically, a branch is mergeable only if it has **exactly one commit since it was created, and that commit added a column**. The merge is rejected (`status: "rejected"`, with `mergeBlockers` set) if: - -- the branch was forked from another branch rather than directly from main -- main has advanced since the branch was forked -- the branch's rows changed since the fork (row counts must match main exactly) -- the branch removed columns or changed a column's type/nullability -- the branch added no columns (index-only changes are not merged) - -### Adding a column in a single commit - -Because the branch must contain just one column-adding commit, add the column with its values in one operation rather than add-then-backfill: - -1. **SQL transformation** — `add_columns` with a SQL expression computed from existing columns, so the column lands populated in one commit. -2. **Precompute the values** — compute the column's values externally, then add the fully-populated column in a single operation (e.g. via `merge_insert`/`add_columns` with the data ready). -3. **Lance-format-level data evolution (pylance)** — use Lance's data evolution with backfill, documented at . - -## Quick reference - -| Goal | Python | TypeScript | -|------|--------|------------| -| List branches (non-main) | `table.branches.list()` | `await (await table.branches()).list()` | -| Create branch (off main) | `table.branches.create(name)` → branch handle | `await branches.create(name)` → branch `Table` | -| Create from a fork point | `table.branches.create(name, from_ref=..., from_version=...)` | `await branches.create(name, fromRef, fromVersion)` | -| Get a branch handle | `table.branches.checkout(name)` or `db.open_table(t, branch=name)` | `await branches.checkout(name)` or `await db.openTable(t, { branch: name })` | -| Pin to a branch version (read-only) | `table.branches.checkout(name, version=v)` | `await branches.checkout(name, v)` | -| Delete branch | `table.branches.delete(name)` | `await branches.delete(name)` | -| Which branch is this handle on? | `table.current_branch()` (`None` = main) | `table.currentBranch()` (`null` = main) | -| Target main | use the original (non-branch) handle | use the original (non-branch) handle | -| Merge branch into main (Enterprise only) | `table.branches.merge(from_branch, dry_run=False)` | `await branches.merge(fromBranch, dryRun)` | -| Preview a branch's pending diff (Enterprise only) | `table.branches.diff(from_branch)` | `await branches.diff(fromBranch)` | - -Branch names must be non-empty; empty names raise a validation error. From fe992bf4eee913d0ab12fce6bebf654cb245ffc1 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 22 Aug 2026 00:17:04 +0800 Subject: [PATCH 071/206] fix(python): use canonical remote function endpoints (#4008) Remote Function catalog requests used singular endpoints that are not exposed by Phalanx. Route registration to `POST /v1/functions/create` and exact-version lookup to `POST /v1/functions/get`, while preserving the existing typed Job submission and wait behavior. --- python/python/tests/test_first_class_function_slice2.py | 6 +++--- rust/lancedb/src/remote/db.rs | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 612a711af..99c68876c 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -162,7 +162,7 @@ def _mock_remote_function_catalog(): body = json.loads(self.rfile.read(length) or b"{}") state["requests"].append((self.path, body)) status = 200 - if self.path == "/v1/function/create": + if self.path == "/v1/functions/create": state["version"] = { "name": body["name"], "version": "fv_exact", @@ -187,7 +187,7 @@ def _mock_remote_function_catalog(): "job_state": "DONE", "result": state["version"], } - elif self.path == "/v1/function/describe": + elif self.path == "/v1/functions/get": assert body == { "name": "normalize_score", "version": "fv_exact", @@ -249,6 +249,6 @@ def test_blocking_remote_registration_returns_function_version(): assert created.name == "normalize_score" assert created.version == "fv_exact" assert [path for path, _ in state["requests"]] == [ - "/v1/function/create", + "/v1/functions/create", "/v1/jobs/describe", ] diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 08f71368c..169d0fda5 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -494,7 +494,7 @@ impl Database for RemoteDatabase { &self, request: FunctionRegistrationRequest, ) -> Result> { - let req = self.client.post("/v1/function/create").json(&request); + let req = self.client.post("/v1/functions/create").json(&request); let (request_id, response) = self.client.send(req).await?; let response = self.client.check_response(&request_id, response).await?; let status = response.status(); @@ -513,7 +513,7 @@ impl Database for RemoteDatabase { async fn get_function(&self, name: &str, version: &str) -> Result { let req = self .client - .post("/v1/function/describe") + .post("/v1/functions/get") .json(&serde_json::json!({ "name": name, "version": version, @@ -2489,7 +2489,7 @@ mod tests { include_str!("../../tests/fixtures/first_class_functions/v1/remote_function_job.json"); let expected: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); let conn = Connection::new_with_handler(move |request| match request.url().path() { - "/v1/function/create" => { + "/v1/functions/create" => { assert_eq!(request.method(), &reqwest::Method::POST); let body: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); @@ -2520,7 +2520,7 @@ mod tests { ); let conn = Connection::new_with_handler(|request| { assert_eq!(request.method(), &reqwest::Method::POST); - assert_eq!(request.url().path(), "/v1/function/describe"); + assert_eq!(request.url().path(), "/v1/functions/get"); let body: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); assert_eq!( From 5c3bc7f643ed97da7344b8a228a89bed4d6f0905 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 22 Aug 2026 00:22:28 +0800 Subject: [PATCH 072/206] fix: accept non-null Function inputs for nullable parameters (#4006) Remote Function bindings can expose a nullable parameter schema even when the source table column is non-nullable. Binding validation rebuilt the exact input schema from table nullability and rejected this safe widening. Accept non-null table columns for nullable Function parameters while continuing to reject nullable table columns for non-null parameters. All other input schema fields remain exact, including named multi-input ordering, names, types, and metadata. --- rust/lancedb/src/table/computed_columns.rs | 50 ++++++++++++++++++++-- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 24cc48658..b1c0b8370 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -651,17 +651,20 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding input.field_path ))); } - if field.is_nullable() != input.nullable { + // A non-null source is within a nullable parameter's domain. The + // reverse can pass nulls to a Function that does not accept them. + if field.is_nullable() && !input.nullable { return Err(invalid_function(format!( - "Function input '{}' no longer matches binding '{}'", + "Function input column '{}' is nullable, but parameter '{}' in binding '{}' is non-nullable", input.field_path, + input.parameter, binding.binding_id() ))); } let parameter_field = ArrowField::new( input.parameter.clone(), field.data_type().clone(), - field.is_nullable(), + input.nullable, ) .with_metadata(field.metadata().clone()); let json = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ @@ -2210,6 +2213,47 @@ mod tests { .unwrap() } + fn function_binding_schema(title_nullable: bool, body_nullable: bool) -> ArrowSchema { + ArrowSchema::new(vec![ + ArrowField::new("title", DataType::Utf8, title_nullable), + ArrowField::new("body", DataType::Utf8, body_nullable), + ArrowField::new("search_text", DataType::Utf8, true), + ArrowField::new("search_token_count", DataType::Int64, true), + ]) + } + + #[test] + fn test_non_nullable_function_inputs_can_bind_to_nullable_parameters() { + let binding = FunctionBinding::from_json(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + + ensure_binding_matches_schema(&function_binding_schema(false, false), &binding).unwrap(); + } + + #[test] + fn test_nullable_function_input_cannot_bind_to_non_nullable_parameter() { + let mut raw_binding: Value = serde_json::from_str(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + raw_binding["inputs"][0]["nullable"] = Value::Bool(false); + raw_binding["input_schema"]["fields"][0]["nullable"] = Value::Bool(false); + let binding: FunctionBinding = serde_json::from_value(raw_binding).unwrap(); + + let err = ensure_binding_matches_schema(&function_binding_schema(true, false), &binding) + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } + if message.contains("input column 'title' is nullable") + && message.contains("parameter 'title'") + && message.contains("binding 'fb_01K3TEXT'") + && message.contains("non-nullable")), + "{err:?}" + ); + } + #[test] fn test_function_binding_metadata_survives_schema_round_trip() { let binding = FunctionBinding::from_json(include_str!( From 7fd881bbe387f8b802d212ab16b141473c217cc0 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Fri, 21 Aug 2026 09:23:40 -0700 Subject: [PATCH 073/206] fix(nodejs)!: key parsed embedding configs by vector column (#4003) Two bugs in Node's reading of the embedding_functions schema metadata. First, parseFunctions keyed its result map by function name, so a table whose metadata configures the same function for two vector columns came back with only the last one. It now keys by the vector column, the convention Python's parser already uses. Second, Node could not read metadata written by the Python bindings at all, which spell the keys snake_case: configs parsed with both columns undefined, breaking embedding application on add() and leaving only query-side embedding working. The parse now accepts both spellings. Both fixes land in one shared parser used by every reader -- parseFunctions and the makeArrowTable schema validator, which had its own private camelCase-only parse -- so the wire contract cannot fork between entry points. A config naming no source or vector column is an error at the boundary rather than a default downstream, as are two configs claiming one column. The "vector" fallback remains only on the optional field of user-supplied configs. Breaking: parseFunctions is exported and its map keys change from function name to vector column. Co-authored-by: Claude Opus 5 (1M context) --- docs/src/js/namespaces/embedding/README.md | 3 + .../functions/parseEmbeddingMetadata.md | 22 ++++ .../type-aliases/EmbeddingMetadataEntry.md | 40 +++++++ .../ResolvedEmbeddingFunctionConfig.md | 22 ++++ nodejs/__test__/arrow.test.ts | 30 ++++++ nodejs/__test__/registry.test.ts | 71 ++++++++++++ nodejs/lancedb/arrow.ts | 13 ++- nodejs/lancedb/embedding/registry.ts | 101 ++++++++++++------ 8 files changed, 265 insertions(+), 37 deletions(-) create mode 100644 docs/src/js/namespaces/embedding/functions/parseEmbeddingMetadata.md create mode 100644 docs/src/js/namespaces/embedding/type-aliases/EmbeddingMetadataEntry.md create mode 100644 docs/src/js/namespaces/embedding/type-aliases/ResolvedEmbeddingFunctionConfig.md diff --git a/docs/src/js/namespaces/embedding/README.md b/docs/src/js/namespaces/embedding/README.md index 157018e16..a736674c0 100644 --- a/docs/src/js/namespaces/embedding/README.md +++ b/docs/src/js/namespaces/embedding/README.md @@ -25,9 +25,12 @@ ### Type Aliases - [CreateReturnType](type-aliases/CreateReturnType.md) +- [EmbeddingMetadataEntry](type-aliases/EmbeddingMetadataEntry.md) +- [ResolvedEmbeddingFunctionConfig](type-aliases/ResolvedEmbeddingFunctionConfig.md) ### Functions - [LanceSchema](functions/LanceSchema.md) - [getRegistry](functions/getRegistry.md) +- [parseEmbeddingMetadata](functions/parseEmbeddingMetadata.md) - [register](functions/register.md) diff --git a/docs/src/js/namespaces/embedding/functions/parseEmbeddingMetadata.md b/docs/src/js/namespaces/embedding/functions/parseEmbeddingMetadata.md new file mode 100644 index 000000000..d6c381bb3 --- /dev/null +++ b/docs/src/js/namespaces/embedding/functions/parseEmbeddingMetadata.md @@ -0,0 +1,22 @@ +[**@lancedb/lancedb**](../../../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../../../globals.md) / [embedding](../README.md) / parseEmbeddingMetadata + +# Function: parseEmbeddingMetadata() + +```ts +function parseEmbeddingMetadata(json): EmbeddingMetadataEntry[] +``` + +The single parser for `embedding_functions` schema metadata: every reader +goes through here, so the wire contract cannot fork between them. + +## Parameters + +* **json**: `string` + +## Returns + +[`EmbeddingMetadataEntry`](../type-aliases/EmbeddingMetadataEntry.md)[] diff --git a/docs/src/js/namespaces/embedding/type-aliases/EmbeddingMetadataEntry.md b/docs/src/js/namespaces/embedding/type-aliases/EmbeddingMetadataEntry.md new file mode 100644 index 000000000..a1bd247f6 --- /dev/null +++ b/docs/src/js/namespaces/embedding/type-aliases/EmbeddingMetadataEntry.md @@ -0,0 +1,40 @@ +[**@lancedb/lancedb**](../../../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../../../globals.md) / [embedding](../README.md) / EmbeddingMetadataEntry + +# Type Alias: EmbeddingMetadataEntry + +```ts +type EmbeddingMetadataEntry: object; +``` + +One entry of the `embedding_functions` schema metadata, with the column +keys normalized across the bindings' spellings. + +## Type declaration + +### model + +```ts +model: EmbeddingFunction["TOptions"]; +``` + +### name + +```ts +name: string; +``` + +### sourceColumn + +```ts +sourceColumn: string; +``` + +### vectorColumn + +```ts +vectorColumn: string; +``` diff --git a/docs/src/js/namespaces/embedding/type-aliases/ResolvedEmbeddingFunctionConfig.md b/docs/src/js/namespaces/embedding/type-aliases/ResolvedEmbeddingFunctionConfig.md new file mode 100644 index 000000000..864dfedfc --- /dev/null +++ b/docs/src/js/namespaces/embedding/type-aliases/ResolvedEmbeddingFunctionConfig.md @@ -0,0 +1,22 @@ +[**@lancedb/lancedb**](../../../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../../../globals.md) / [embedding](../README.md) / ResolvedEmbeddingFunctionConfig + +# Type Alias: ResolvedEmbeddingFunctionConfig + +```ts +type ResolvedEmbeddingFunctionConfig: EmbeddingFunctionConfig & object; +``` + +An [EmbeddingFunctionConfig] read back from table metadata, where the +vector column is always recorded. + +## Type declaration + +### vectorColumn + +```ts +vectorColumn: string; +``` diff --git a/nodejs/__test__/arrow.test.ts b/nodejs/__test__/arrow.test.ts index 29030d4f8..160f4d5ef 100644 --- a/nodejs/__test__/arrow.test.ts +++ b/nodejs/__test__/arrow.test.ts @@ -173,6 +173,36 @@ describe.each([arrow15, arrow16, arrow17, arrow18])( } describe("The function makeArrowTable", function () { + it("accepts snake_case embedding metadata like camelCase", function () { + const spellings = [ + // biome-ignore lint/style/useNamingConvention: the Python wire spelling + { source_column: "text", vector_column: "vector" }, + { sourceColumn: "text", vectorColumn: "vector" }, + ]; + for (const columns of spellings) { + const schema = new Schema( + [ + new Field("text", new Utf8(), false), + new Field( + "vector", + new FixedSizeList(3, new Field("item", new Float32(), true)), + false, + ), + ], + new Map([ + [ + "embedding_functions", + JSON.stringify([{ name: "mock", model: {}, ...columns }]), + ], + ]), + ); + // The vector field is non-nullable and absent from the data; only a + // recognized embedding config makes that acceptable. + const table = makeArrowTable([{ text: "hello" }], { schema }); + expect(table.numRows).toBe(1); + } + }); + it("will use data types from a provided schema instead of inference", async function () { const schema = new Schema([ new Field("a", new Int32(), false), diff --git a/nodejs/__test__/registry.test.ts b/nodejs/__test__/registry.test.ts index a5cf73e74..973ad8a25 100644 --- a/nodejs/__test__/registry.test.ts +++ b/nodejs/__test__/registry.test.ts @@ -106,6 +106,77 @@ describe.each([arrow15, arrow16, arrow17, arrow18])("Registry", (arrow) => { 'Embedding function with alias "mock-embedding" already exists', ); }); + test("parseFunctions keeps entries sharing a function name", async () => { + class MockEmbeddingFunction extends EmbeddingFunction { + ndims() { + return 3; + } + embeddingDataType() { + return new arrow.Float32() as apiArrow.Float; + } + async computeSourceEmbeddings(data: string[]) { + return data.map(() => [1, 2, 3]); + } + } + register("mock-embedding")(MockEmbeddingFunction); + const parsed = await getRegistry().parseFunctions( + new Map([ + [ + "embedding_functions", + JSON.stringify([ + { + name: "mock-embedding", + sourceColumn: "text", + vectorColumn: "vector_a", + model: {}, + }, + { + name: "mock-embedding", + sourceColumn: "text", + vectorColumn: "vector_b", + model: {}, + }, + ]), + ], + ]), + ); + expect([...parsed.values()].map((f) => f.vectorColumn)).toEqual([ + "vector_a", + "vector_b", + ]); + + // The Python bindings write snake_case keys. + const snake = await getRegistry().parseFunctions( + new Map([ + [ + "embedding_functions", + JSON.stringify([ + { + name: "mock-embedding", + // biome-ignore lint/style/useNamingConvention: the Python wire spelling + source_column: "text", + // biome-ignore lint/style/useNamingConvention: the Python wire spelling + vector_column: "vector_a", + model: {}, + }, + { + name: "mock-embedding", + // biome-ignore lint/style/useNamingConvention: the Python wire spelling + source_column: "text", + // biome-ignore lint/style/useNamingConvention: the Python wire spelling + vector_column: "vector_b", + model: {}, + }, + ]), + ], + ]), + ); + expect([...snake.keys()]).toEqual(["vector_a", "vector_b"]); + expect([...snake.values()].map((f) => f.sourceColumn)).toEqual([ + "text", + "text", + ]); + }); test("schema should contain correct metadata", async () => { class MockEmbeddingFunction extends EmbeddingFunction { constructor(args: FunctionOptions = {}) { diff --git a/nodejs/lancedb/arrow.ts b/nodejs/lancedb/arrow.ts index 587d30b19..8b388d593 100644 --- a/nodejs/lancedb/arrow.ts +++ b/nodejs/lancedb/arrow.ts @@ -48,7 +48,11 @@ import { } from "apache-arrow"; import { Buffers } from "apache-arrow/data"; import { type EmbeddingFunction } from "./embedding/embedding_function"; -import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry"; +import { + EmbeddingFunctionConfig, + getRegistry, + parseEmbeddingMetadata, +} from "./embedding/registry"; import { sanitizeField, sanitizeSchema, @@ -933,7 +937,7 @@ async function applyEmbeddingsFromMetadata( for (const functionEntry of functions.values()) { const sourceColumn = columns[functionEntry.sourceColumn]; - const destColumn = functionEntry.vectorColumn ?? "vector"; + const destColumn = functionEntry.vectorColumn; if (sourceColumn === undefined) { throw new Error( `Cannot apply embedding function because the source column '${functionEntry.sourceColumn}' was not present in the data`, @@ -1385,11 +1389,10 @@ function validateSchemaEmbeddings( // Check schema metadata for embedding functions if (schema.metadata.has("embedding_functions")) { - const embeddings = JSON.parse( + const entries = parseEmbeddingMetadata( schema.metadata.get("embedding_functions")!, ); - // biome-ignore lint/suspicious/noExplicitAny: we don't know the type of `f` - if (embeddings.find((f: any) => f["vectorColumn"] === field.name)) { + if (entries.some((f) => f.vectorColumn === field.name)) { hasEmbeddingFunction = true; } } diff --git a/nodejs/lancedb/embedding/registry.ts b/nodejs/lancedb/embedding/registry.ts index 2eae90ed3..5f32f683c 100644 --- a/nodejs/lancedb/embedding/registry.ts +++ b/nodejs/lancedb/embedding/registry.ts @@ -104,41 +104,29 @@ export class EmbeddingFunctionRegistry { async parseFunctions( this: EmbeddingFunctionRegistry, metadata: Map, - ): Promise> { + ): Promise> { if (!metadata.has("embedding_functions")) { return new Map(); - } else { - type FunctionConfig = { - name: string; - sourceColumn: string; - vectorColumn: string; - model: EmbeddingFunction["TOptions"]; - }; - - const functions = ( - JSON.parse(metadata.get("embedding_functions")!) - ); - - const items: [string, EmbeddingFunctionConfig][] = await Promise.all( - functions.map(async (f) => { - const fn = this.get(f.name); - if (!fn) { - throw new Error(`Function "${f.name}" not found in registry`); - } - const func = await this.get(f.name)!.create(f.model); - return [ - f.name, - { - sourceColumn: f.sourceColumn, - vectorColumn: f.vectorColumn, - function: func, - }, - ]; - }), - ); - - return new Map(items); } + const entries = parseEmbeddingMetadata( + metadata.get("embedding_functions")!, + ); + const items = await Promise.all( + entries.map(async (f): Promise => { + const fn = this.get(f.name); + if (!fn) { + throw new Error(`Function "${f.name}" not found in registry`); + } + const func = await fn.create(f.model); + return { + sourceColumn: f.sourceColumn, + vectorColumn: f.vectorColumn, + function: func, + }; + }), + ); + // Keyed by output column: one function may serve several columns. + return new Map(items.map((config) => [config.vectorColumn, config])); } // biome-ignore lint/suspicious/noExplicitAny: functionToMetadata(conf: EmbeddingFunctionConfig): Record { @@ -218,3 +206,52 @@ export interface EmbeddingFunctionConfig { vectorColumn?: string; function: EmbeddingFunction; } + +/** An [EmbeddingFunctionConfig] read back from table metadata, where the + * vector column is always recorded. */ +export type ResolvedEmbeddingFunctionConfig = EmbeddingFunctionConfig & { + vectorColumn: string; +}; + +/** One entry of the `embedding_functions` schema metadata, with the column + * keys normalized across the bindings' spellings. */ +export type EmbeddingMetadataEntry = { + name: string; + sourceColumn: string; + vectorColumn: string; + model: EmbeddingFunction["TOptions"]; +}; + +/** The single parser for `embedding_functions` schema metadata: every reader + * goes through here, so the wire contract cannot fork between them. */ +export function parseEmbeddingMetadata(json: string): EmbeddingMetadataEntry[] { + // The wire format, honestly: the Python bindings write snake_case keys. + type Raw = { + name: string; + sourceColumn?: string; + // biome-ignore lint/style/useNamingConvention: the Python wire spelling + source_column?: string; + vectorColumn?: string; + // biome-ignore lint/style/useNamingConvention: the Python wire spelling + vector_column?: string; + model: EmbeddingFunction["TOptions"]; + }; + const entries = JSON.parse(json); + const seen = new Set(); + return entries.map((f) => { + const sourceColumn = f.sourceColumn ?? f.source_column; + const vectorColumn = f.vectorColumn ?? f.vector_column; + if (sourceColumn === undefined || vectorColumn === undefined) { + throw new Error( + `Embedding function "${f.name}" metadata names no source or vector column`, + ); + } + if (seen.has(vectorColumn)) { + throw new Error( + `Multiple embedding configs claim vector column "${vectorColumn}"`, + ); + } + seen.add(vectorColumn); + return { name: f.name, sourceColumn, vectorColumn, model: f.model }; + }); +} From bacd0e4c3c9e29870dd823f295d92f5779f16439 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Fri, 21 Aug 2026 09:30:12 -0700 Subject: [PATCH 074/206] ci: group arrow and datafusion dependabot updates into one PR (#3738) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The arrow-rs and datafusion crates are released in lockstep, but Dependabot has been opening one PR per sub-crate for them — the 58.3.0 to 58.4.0 wave produced four separate PRs for `arrow`, `arrow-array`, `arrow-schema`, and `arrow-buffer`. The existing `rust-minor-patch` group did not catch them because it only filters on `update-types` and declares no patterns. This PR adds an explicit `arrow-datafusion` group matching `arrow*`, `parquet*`, `datafusion*`, and `object_store`, so those bumps arrive as a single PR. It is listed before `rust-minor-patch` because a dependency joins the first group it matches, and it deliberately omits `update-types` so major bumps are grouped too. Co-authored-by: Claude Opus 5 (1M context) --- .github/dependabot.yml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index d5d4cab08..eee966f76 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -17,6 +17,18 @@ updates: # newer minimum versions. 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: update-types: - minor From 217ea1a799e23d2badb02b8e638e2b778ef67769 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Fri, 21 Aug 2026 09:30:20 -0700 Subject: [PATCH 075/206] ci: use thin LTO and a larger runner for the Windows wheel build (#3716) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Windows wheel job is the slowest job in the PyPI release workflow. Fat LTO of the cdylib is single-threaded and the peak-memory step of the build, so it does not get faster with more cores — and it has already caused rustc-LLVM OOM on the Windows runners for the nodejs builds. Switch the job to thin LTO with 16 codegen units on a `windows-2025-8x-x64` runner, trading some runtime performance on our least performance-sensitive platform for build time. This matches what the nodejs Windows builds in `npm-publish.yml` already do. `pypi-publish.yml` is in this workflow's `pull_request` paths filter, so this PR triggers a dry-run build that shows the new timing. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5 (1M context) --- .github/workflows/pypi-publish.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/pypi-publish.yml b/.github/workflows/pypi-publish.yml index 4f5a927dc..b80c1b019 100644 --- a/.github/workflows/pypi-publish.yml +++ b/.github/workflows/pypi-publish.yml @@ -129,6 +129,12 @@ jobs: # link.exe is single-threaded and the long pole on Windows builds. Use # rustc's bundled lld-link instead. CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_LINKER: rust-lld + # Fat LTO of the cdylib is single-threaded and the peak-memory step of the + # build. ThinLTO parallelizes it across the runner's cores, at some cost + # to runtime performance on our least performance-sensitive platform. + # Matches what the nodejs Windows builds already do in npm-publish.yml. + CARGO_PROFILE_RELEASE_LTO: thin + CARGO_PROFILE_RELEASE_CODEGEN_UNITS: 16 steps: - uses: actions/checkout@v6 with: From fa3d9b2ce2937c50e1f10eda8716b10491d84143 Mon Sep 17 00:00:00 2001 From: Dan Tasse <105866+dantasse@users.noreply.github.com> Date: Fri, 21 Aug 2026 12:33:57 -0400 Subject: [PATCH 076/206] refactor: move plugin/skills to lancedb-agent-plugins repo (#4009) Moving the skills and plugins to https://github.com/lancedb/lancedb-agent-plugins --- plugins/lancedb/.claude-plugin/plugin.json | 21 -- plugins/lancedb/.codex-plugin/plugin.json | 33 ---- plugins/lancedb/assets/logo-dark.png | Bin 10619 -> 0 bytes plugins/lancedb/assets/logo.png | Bin 36230 -> 0 bytes plugins/lancedb/skills/lancedb/SKILL.md | 102 ---------- .../lancedb/skills/lancedb/agents/openai.yaml | 6 - .../lancedb/skills/lancedb/assets/icon.png | Bin 23274 -> 0 bytes .../skills/lancedb/references/branch_ops.md | 16 -- .../lancedb/references/column_metadata.md | 183 ------------------ .../lancedb/references/remote_connect.md | 45 ----- .../skills/lancedb/references/remote_jobs.md | 151 --------------- .../lancedb/scripts/check_materialization.py | 137 ------------- 12 files changed, 694 deletions(-) delete mode 100644 plugins/lancedb/.claude-plugin/plugin.json delete mode 100644 plugins/lancedb/.codex-plugin/plugin.json delete mode 100644 plugins/lancedb/assets/logo-dark.png delete mode 100644 plugins/lancedb/assets/logo.png delete mode 100644 plugins/lancedb/skills/lancedb/SKILL.md delete mode 100644 plugins/lancedb/skills/lancedb/agents/openai.yaml delete mode 100644 plugins/lancedb/skills/lancedb/assets/icon.png delete mode 100644 plugins/lancedb/skills/lancedb/references/branch_ops.md delete mode 100644 plugins/lancedb/skills/lancedb/references/column_metadata.md delete mode 100644 plugins/lancedb/skills/lancedb/references/remote_connect.md delete mode 100644 plugins/lancedb/skills/lancedb/references/remote_jobs.md delete mode 100644 plugins/lancedb/skills/lancedb/scripts/check_materialization.py diff --git a/plugins/lancedb/.claude-plugin/plugin.json b/plugins/lancedb/.claude-plugin/plugin.json deleted file mode 100644 index 9fe3d4b67..000000000 --- a/plugins/lancedb/.claude-plugin/plugin.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "lancedb", - "description": "Write, review, debug, and document LanceDB pipelines in Python and TypeScript that work across local LanceDB OSS tables and remote LanceDB Enterprise/Cloud tables, with idiomatic query/search patterns and performance defaults for ingestion, indexing, filtering, and diagnostics.", - "version": "0.1.0", - "author": { - "name": "LanceDB" - }, - "homepage": "https://www.lancedb.com", - "keywords": [ - "lancedb", - "vector-search", - "full-text-search", - "hybrid-search", - "python", - "typescript", - "pipelines", - "ingestion", - "indexing", - "performance" - ] -} diff --git a/plugins/lancedb/.codex-plugin/plugin.json b/plugins/lancedb/.codex-plugin/plugin.json deleted file mode 100644 index bb824ceb4..000000000 --- a/plugins/lancedb/.codex-plugin/plugin.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "lancedb", - "version": "0.1.0", - "description": "Codex plugin for building LanceDB pipelines in Python and TypeScript.", - "author": { - "name": "LanceDB" - }, - "keywords": [ - "lancedb", - "vector-search", - "full-text-search", - "hybrid-search", - "python", - "typescript", - "pipelines" - ], - "skills": "./skills/", - "interface": { - "displayName": "LanceDB", - "shortDescription": "Build LanceDB pipelines in Python and TypeScript.", - "longDescription": "Write, review, debug, and document LanceDB pipelines in Python and TypeScript that work across local LanceDB OSS tables and remote LanceDB Enterprise/Cloud tables, with idiomatic query/search patterns and performance defaults for ingestion, indexing, filtering, and diagnostics.", - "developerName": "LanceDB", - "websiteURL": "https://www.lancedb.com", - "category": "Developer Tools", - "capabilities": [ - "Developer Tools" - ], - "defaultPrompt": "Create a LanceDB table, embed sample text, and run a vector search.", - "composerIcon": "./assets/logo.png", - "logo": "./assets/logo.png", - "logoDark": "./assets/logo-dark.png" - } -} diff --git a/plugins/lancedb/assets/logo-dark.png b/plugins/lancedb/assets/logo-dark.png deleted file mode 100644 index 8fd8f220ed6ed02531d28815e826b6aa56fc7346..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10619 zcmb7}cQ{*L{P=^SHEYFIjoQ2Rro?J(Ay#Ye5j9FtRjn1HYLwcWn4yT;B}QwPP`j!| z3AJngZa>fO`~Cl$Jb9kvoO{ka_vV~?UhmgC)=*!Il8l861Oid&XlodQKm?e7pPM8= ziOiS%1`vq|1F;aooVJd{$7f-wTrtd?fUi zl6~HtdV&ZR#<9oQUe*w@MLqM_IJ1B#K19CNcUev7Y41wdY5*sxJm%cxrl>~mRrWj7 zEYVR)Oq+Xo;3KX-5V1Z$kY3#rQLxM4CCEW zf5g1%)SBs$GP$}u;JwFGJ%0*T;I?}Hh$V}u=`C7@C&`=lcURr5kg|Jl(*?8?Ejg=W z+dXi3ntz90*M!LKeFh===NJw%F?al3aFg;$JiONgX4R}*%?Z}Vbzi!aM-I=5SiQ(+ z$xC~|9`ytJHl%b+U8suXhA9JzYGe13bwcLfY)WUuVap+?4v@U`GSeW zJd-AIPe)mOn{%?z(HUifkZ%#aE8*xm$?uO5LLwnM^R!q(hJl%G_Cw_dHmm&Q2l)YV z3KOyL3sLZK&PRfNUk#ycmy>tztcy|<;yS>qY1NSpnx53AEPK12_#d8Y@EHyz`@Pl^ z32Iqy2l1bym9N5OR7fag4I>`0vn2#I4%hnmKkc<|B z>vq?_NR6gV3^k4a3l|$3pd+Wp{np%_dq8Gv=b>ussoV9Afalv6NXWu2bsJZ4=Ml%eLA9Am zOrJzmmPpX9_rV!PCK4DN)gvmQw8iJeyR~L_!E^m93pddDHjn6#a)OD;rlzFNAdt*a ztE#BHTP?%w_rTwRHWDq1*Yf^xT_u_9p@O!;H@TsKR%ffFhupiK_ zXK6AFB?-dds))51VwU?Zaqo2775SMbdJlS6evqYw_CgGVZkHd^mk8%e=nCh(YiWM| z2o?*?g&TIus|#gdkKAgQ*~mA7^>LiwgXcm0@gLwruV1BHpmMs=yiSjwE%?}ri`pAa z$Fq24I*|19NsS66!dEk~G)N|DIPz=77v}8hlhi9_`17Ukkg%IvGfb#6D~3Dho9a*} zt+>%;S)cpEu4w`|MOf(2;(jlo&ZKOlL%2ci_-`6ml^g2sOgIxO`SD8Nii%&^pjaOE zP^@AFjyenaF-orhtazQ(Q7u+}-3hVaIK8T_2tO*n-p|GkZSBe@$CNk9g`qkuJOr>t zx*a^@3VXT0CYmiqo%Bi|GgoMw%fYMvics6zM$GuQ#klWd>~Wf|(d>hr<_Z;75KnI| zM#Ej#=w0rOx9k+Gw8V}{e|F_7azX$@hOxsFKHpK&?RL3wKyM#%o%GYH}hgmwM$8q3CWI*~$&cd-y_m=g5IQ72azJEWClanaa(qn6|hMlA)pviV+k) z>`1U^iXLX)3o#Os#q;V3z10YikgY6r{K%pXTe_ZzseYbB7<~_I2s^g@1uPu1=OiwC z(y@ZBe*-F`s=IASYz#)zhnYORK77t&L#q->jVzN~-xv4GNZwVmZld0cyNq>nreN%a z=n0LL%Q+*WEUYiKy?TX2M&lzataIU<@M;NJ2VPl2Iq4<7qZ$*(?Hi=dlLy$98dB8o z3b1f!$R%BCn6nGwL`V66eIyoJvuot|#QJWa;)j@-K5uzUuX}Dc^Z7gUb#axsptQYx zGB3DkGh#m692`n>r=J z^JyB&_!zHRlORtek4ATg>G_!^`ckkfUy#f(P_asVhUBvG>4>N$9t1Uxy>xS)ikGQ` z7O9AyISO#c{akT~U~a^9GwT)~w0(0Qy;GH1Nr!YtbLT&vc#u3O>RAkBv6CpH3-s=r z@TlsiL85}uR1z}98_Oi3iTSTQFR=$Q#P)V&N@Ih+Vu`Wvt^QXjc5hLU5|V32EPG#H zq3fchsBvuQx=|jmoP7kD)8;Zof}8;t54g9G$KPAq!m)k`X~*=~z)wmq*0uNeV8r<< zQ;HKDoDJ5cac~wkGrAf~Ms*YwibA=Rji#o1SE5~Vjgz{Tch}tqzjeWF?Ue!$rRSHb zi!piLLAryfG1!xKm;rB%^@6`be}C@DAa@+FC$30Gw9b3uwvWOr$jj_Co_QnD0|?=U zhR$Xmwvj)o?fY;?O!}fj#OnQL2xqp60GN)m3oTD*_*9U*MiN@~5fk!q(cZ4&>@`}| zKGP(1p=40;$lgQoyNhlwB$!U;^mT_3#+ILlrHnw{0K<)SUSB^|1tlz_!1XhVz zqbaNSZzDs|GqsJJt_3!V)onJM5tc59sYL6rzNSrbT@O{Eec3-$yO?*(b8}I1#5?12 z${4*nz>IyK?l!(~($Ic1JS$vtN2FmZt2ZeYny40yQsx0q&Fm4xG0-@bX5P7PyFZROqtf z*~GEYi#?Z#fGzgd6+Y5ZpC-q^=jIMR9tCB*o)Qanm*S`{;d>T} zJJ!(H{+i-;XB4x8TV-@3$1Mk5-b86}^en(M>v9vB6(k;FXH@)>w%i!a$+x_x*|Gmn z5&$Rc0~f~oe7w-$>-THWWAzBwQTwyNcF7Gd;jInKGr>g#SeSQ?)mq>Wi5-K4W^&dp zcJtdvkI|+f4sv8{Zrr#t>oyJoDLyE8f&3CIDLM%f1n;coYv%pCmpFJ%-8Gp_Oc(S*ZPcgxS`%Y_iMU>jKh*t5|p80dRqeHjHAb4?HVv;HZzZYlsC7odia&a z9>3rD%Zkh5aGXa=pSYvohv|i$S4!q5cb#InT^WOoPeT@4_TpKZlAs3sU)mRe4#UF@ zNd0Au`;D77@6KYqT4hhv2@BZ{;#ul@3sF>wq9cU0apwb{tWP{s{scdSy_@@^e|3LD z?^e^IbA_?J_{HR432ThY*7Ek(FN`j7A?&xYykYW{b*3*w0-rn{Vk4iMi2OygXIkt0 zhCSI6|xk$FSoyVrxGo2Uo#osV9Mk>GCnxo z!jK59WS@r{K2TOzied0&I`nd0da@(OUH>pEXT%?)FJ!sB{7E!8_kjGh`@Grc{f#+{ z&9(vN%}e;u$DE=@FTy6Z`txc~R(*6HzWdhmOu;YAq+yPd(msr4<1*MwF7TYW`K*M% zb}JjM`}7vKVs`U2VSAQ{K+GEN*f)_TAI4hVm^V3Kb)hB|XM9yN)lPB$&t}~}T(23DZ(*#Itg#q& zM{rI^U~Nk?$3H#qhg&OCai|iVBYFdJ{>)r zIV54ezagLqYYTqQ ziih;oTd<+E#gLUxN%{x)qENFshuU$0G;7TQ%J$*0r3L%rW^J}Cp+MkToh&jd;0bsq9%>^YtHO}e$ENTA=$!U$CC!U# z(F-Y&e|x@r$Q?G5Yc@XVK_?%ksIMEyF0WQGw&Zk2{*oqoZmp->`KaEzG%#-N^qvUR zY}TjoKgPOfDt%a9>X~QN8_jHTJcIxiHe~6Fg3}ubKy{wqXPiitdz*VBJ%ke?(>SzT zb(f2JC7H+6CU_o}imyXGLH?1(q_rn0YC!w8fdmPtQ~N49=AlRzu2 z&?W{FNY;^PsgJ~BdLhtTL-CN57k^$RU_nH#`H`&!_M(hW7=ID4Zhbg%vz3FjqulPy zuRq8`4v)3`LePW}s2U&nBj_bpArJ~#+S|#Zm0;D}+*;+vLr5#gX43v!8i-Z>f3;2&Z(Ig3=bSgTU^LwU6hkY{g(#nO zffrdGBrfIU*`#SH0e4%)4H_4JkWs_zX_$~7To4Y>UzN<^kCV2q>V@+~9A(H3w#NnV zui*4+VO^f1<#H~FpPlReDTK0(#ois7?TlgU)!*}Nwu6LZ-Ab1$xWAe{Go8NkmV_^I z(s7~6uQk3ShQw<^gikgzqrIhDCg55e+*rn^C0z)C$q5^$95sB-|F(g29V*3tCe!DO ztCW>G{kcvuw5(}1<*x`J=jk$hGKv1m@no+(Mv)7A)LWQF|0~A&By`HIyuYT_q=AHf zNhAi_yRLUU+0Bgm+0+xYBaIK{?Z5kr8222PKV>vXCSG5hvAIac98b!%>n zfUX!3)(hnSG~k$-V#lkpThDF&!iDPj3zsNbAbxc*ut;UC{!LTw(t{`_n(Db-uASI zb8M4X2;^qX0aV*-R}5#%UEnk>kFD-BM%|>oNkzcXBoGw)5}^7aD-gYOj_!VJYMd|jo+!LanaZ6}`tRRItphYb!)32~7tFB2$a4?Z z_rstL;t@Xl-ScoG6-DMOB}H_im*)U?#}L=9WYWd-U&D5|>yVAfl+XD4vGI7kNHaUK z`HhkfFE{Cn>8pb)^fXzl_CaPM&N%hBB&Y^;OpG2kB2zZ5C$LtbI%@@a! zuI(46uw&7=8x2zS$z0$joI}Ogq`WI5w8^v;AkH^8$bj1o0iw?e^|*c znld3JU}58Mp&G`f>3rXb;JByLPmbX>vn8KTtfjINJte__{M`3vBlj#=FZ$$Jiuk@y zG!^t_&YU%Yy2Zhcx0DVUWCjoT{&d~Us8#jBcNc_$vV8l(=p>!Wue;ym(!j{1>SvyQ zoe)R$VHb(3*FA%C+&LwDS>eqSaTS?mxAa$lC~(3tM0sqZ-NrHIKe0LSC0jJaySMN9 z>V1!xh8dEUJn2msZ~r%=S8ONB8xQHpO*tJ%UCO-jnoTLCBc|21sC(@r!g*Clu%B^r zRsOkwdwxQwC4tv3%c|V<^qFvh`0o!A^?m?T*v}GS+o$TF#M{`R#H!u^OKpno2glPaWh8~#5cL+C znb~~56ijx%M;VA%c%SFv7XDfIMsu1Qy|`y++j}KA5QxFyt+wQ9PL^{#wye>uqQQ$% z_~^4=Y0OzHq%5WzUR^t^Xl(|hU-&Z?c}9RnEuw68*E3yJ##+5p`VI1Vfk@hpH}y6W z@Qas)@|bnuwh1mGg_=PUa;s1cx?1zWuB4G!=O<=qyNIs?Nhc0T*6R@5GJI>W0i(=e zkNn$cWG^m``}upKmnFN*b|8rnQ@d58@Yj;~ORxRHH8q;AfkO*b@8I_g!CP$ml-&`8$Kon&B4?>lOw`$Jygw}vRVYziF z50EoMO#4GCF~sN%_6AHbD!W_UJr2FyL5E~QJ#SkLchKYG0h^iz79Uc0_Y3y&X(jF1 z7CeprZj}q5DPUc+3;USoX>zQ}vEu?-s>FK&I{!-9^rmAA0sbt=CH2^LJ&L$Kosi)K zG{m&BU!6+0(=wwLO!VSNQ@gn7q&qok@W{|KmwsJ+~|?9fLJ(liA&3UcZv~WOY42g{FY&9Sp1? zQZOUqArPlRx)FpUW;e4TXUK zqLZMUc(gJqZDU#X8Lg`DKS>FwNh{Qsmu+@{yfoz@D8I>W-J=UI?!XO@`=4ik?qoAg z1wHQr4!|yLP=YLcMO^1}wfc~4#zq?&SN^1B)f z0%_O-WRA2;Y8CDchK5F>}8& z|NcQ9ImpD0a}fh!XM4i~s;8qNSxFE?lel!EsYp3nqdn;ciqfSpzU(`NV=fNEMKLi@ z6x=X9*X1$+E?F~Uk^1QR8-^3?7JB?7M(cS!QHgPCl%x|CU@U|G1lTeix7*xC1{L$B zRPaOHv`t73{4+}8M72#yW3XxcuYR}Bz~AO>Ym86-in+O&p$gfLfUj~wYQa~JT4NHh za|3xv(#EOITCmQzm=dSkSy6Yv=olzrAX8fm9F;+s;^_X+h~@mgxFuOWYB$`i_g_2{ zW%pOSwXaHfyyd9q5I{q}frgk41&W^O{H@LJ_3&-V9t5+$l2Q@oUImK_A}Uk;BHqsN znpGm24UH-M1NhJXv6Q(+0u2~NG!T^Wf^V8_0bL=#O6WFzlY}!4(~t|AyJ+TcfnCR} zC1iU5nF*-Lp}Ji?4bK!MbUDz#^nk)U8=Euo_u%=VJ61Ea0V7KO?cleaee%oj>HpP| z>yW2nN2B z=KZWmDp!`P{MJD|X$g9Lm-h((JeukfDYUI+rs@`pGr*a8(=qj!Hyqy8} zWJel6_Wi$(a(XEmO%=x|X00@cC7BtgBGW=~8D65d?JIi%6}>z|R#k;8T^Y|`++z_K zwkCeI^gX4ZmYY6SzK2&WlPL{$zr6-=dQ^zcCl_&bNWYix9XH(i=0^D;O zS#6xtzJK1A4gy?dA2#5)zj{5bHcO8Ku#NC$_-I9*p^8+9kuVybv>^JJ2WiSazfA4H za_~E6?xB4$57>vSnOs27{EllX(_w+Vg}kgfFXK{+aNjG7fJFGrXnsoTT*GG~N>hP< z(8vV~>yMgV$|jLq`NxmL7ZM)9`6EhJLE;oWTbbd`lo0y}Ld&Ycwk^}>BvbRN@-gJ2 z&fCa5hrP+^eu&uLb2+dXJ@$hYS8);5h=1psu7|mKJg&e*8jU^tmk<&w05{*7{}tHa zT)QiBK&N|5=kM)2FMD3_lTNpE-Vc+o_hZpXXnQw@53DWXN9rO(Y3D&bDnBRq>^C*~ zQTRIRlN1F!H~8vA@yNozwDX{`zc6bhMI0y?p(nqWE(dK9k~*mQWsd(_spLNMwPDMn zI3!^-zihF~=D`8~*EstKVZa_;n7H>j`%Nc|(AO8=GuN|dVnbTug8EKCvqPVvw!GxP z+NGt;^R-1dM&Y)EE(0Z%YFT{!R!Ac%oHe5QBrfLC26(1-4Lz?c^gR3V+wJ`~U1!hg z{?8=LSsnetT=o&a$GR83<-?AA*BWmcw7?l=&ZFd;RIn>LYr|*c=%8mjpM zmS~C;0o^ zC|7um1?#MZ6KK~1J^lF2RT6b+Z38uGa~aprI`$n;?4^0RT=rNaCo~z0|F9`WA>G3R zMsGWQNa=#dM=H%?M?F=q;4u72JMDMs%iKoHKEWcii7JW8`|J3aEJR?uE^N~O2Un>< zV;MP*^T}l_-Y!ntN~G7B4Y9m#@e1qQjA;G4f-ih;aUkHzNWQULDxrVsCFzlH;d8wd zxT{MLrU+ZvNBdRZ(7S+FExwgD`LXW6?eQF3|T^ zrz>OHNAlA}9+ARXVsbT45$NE?*Zsv13f*mTlzBGADf+$F=# zR_}VnUEbzL!CK1Yh0|=EQQeIe<|1XydE7J~lW=|6F)Ji>X8AU+WHZ{%^{kpostGwe zTG$)6*ofn=6O8I+f z2641BiB{nSYXTR$;c^s_>~bV<)K%O1h?gfL${i1JVvzDcU}|YPciU;MR|15$sQLO< zd>Gy^c`L|;D2EQo{w<2^$s3Eg9@6dFTs`y0&4OR1lZN{v;8B{PD)KE?Vr%Gz4Dt&_2N@7RMmpN=p-YD}c z2;Dq~#N@ehbL=ruJF`><()#w1o+Q-T6L*SE0AQb7?U+ zE%im3&|ol${@ZP^ht+m{N3wB`#Q0&CU-%klPJxG{4_T-pS&>a@0gCZ)d?P)SCxezh z<3Z@y+npIm)$2f`n9f*7T%cN9y@BT~Z8Jy$z4rIfZz3EbU%ka5drY6)XDxa9^64q9 z8<{?EGsdUKbXsMz@auY)5p91Yl{7033YUwi=+lR`e$;-abVkgu6io*Ec5bO=&$cZM zEuVef7A9%H%xAQ7XJEx6d(4b~@E0Nd zh@>yeqF0#w(0t2Z6^0aDTX}){V#P{ZfVr1oKguhQQC0-9wDX0QqKwXyx60ko>vSFn ze37mYqe9-kz!{`#vDuL$W?9iWTXq#jg&@Q~ofm0YZ_$oOKnyL<_VG#a zuFzJ_bO^3KAf1-xD3;rMnE-9wxB+08X&R~91JoJc8O!s&%Ux1->$#w}YrS1uFT7aT z^CLZ2Ddl+OWp`AZRe^@`nCzH`oK)}~(zzS6rQ?h*PiHyIG+VV}ya+*c>=QlgccHg> zm(|GW0pR;j1%mQ*{1K`YBZW7}isI_+P-l7?d^)4C0$*fJjd(N|xN%aatWVKOFm919 z3T>mN1X4HsVqT&Ofs;-;e}q@j-SytC$nzxTvF=9v(gt~#@ipSfO3cmwYANYxoDsKZ z-XlID_5alioDtU1`^G{^r*Adg`Z(NlGZeTL7i$Dth#&pMVF~RwF52bP9d`j&iZZ z`fX|auh9~Fw-9-ZK0tWrne%Ib{dEU9n&7YPZW2nt=cgv&`2xGNkK6&q+b5h9Gc{P# zNb|KdQ`e}nnWxRXV($Xxv~Q2A6yU*US*KFuERHy^JmPV?x130(88s`#GunRzic$0g zA3_foMP4(rHTAj%I1eqN_@xVOR(1z=Q`D%mqMi?0&UW9UfXXoK1_V!*p<1`4#zjT&L3E%%;qqc zys(3w$TP0K?W)yFsguiQsphiWk%gOcH*Uj%_LGHgsIctWr5}<%U=M2D=-_>v7I z&~7cTn}rP*P>6C-8d_82c1!c~DXb;l3}_H3Tbg@Qtseei-%rN~V&cBm7{f-HU_3?c z)9a>Hrd@WLS_1ZDEapqbV#+V78h^H5z)QbvS1=Y!=C;n*w_-S=ez&46!Zvzqiyzp^l;!twCG7 z$*(^Gd(fofbEW<9Ej7cRmn%6eZrY9>jQun@IXtY}mn(gb9=SHznc!no=(A6&| zzhBEdwtW-myR7vx&7IM_M=W%3R%By&%>9eA&&2{u^Y!WRbbUbE8`^D;>!T+=AI+~u zD_BJ8psg4$R&xAGlTy`$h{o!ZYd;2j;lIqr|M?|$@6Yv{$v?*P8Ywyd8tXvyHEJH% GzWRSDp*6+; diff --git a/plugins/lancedb/assets/logo.png b/plugins/lancedb/assets/logo.png deleted file mode 100644 index de3e82aeff99fa85f609ac16b32eff999d6b7ed6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 36230 zcmcdz1y@yFx2C(hyQI6jq)SS=ySuv^5s+>XX%RRyNJxjg(j|>_H{9j-Bd$ZoP&}No z_u6aC`P3v{L+vd(3JD4n6coCmf~*!46g1@DA0!0u6@k%hLH!y0oY@5e6+dI65lF({FY#U#JplzEC+kJ1#aPI6|Y=!N1Xx zm5iY3Qiz2^s^YnQE!Ydbm!K)I&k^c54K)1_uCkWzduo5X;t3A}Cx!L@{yQx!1{;nj z3hQoM<^B7dv;CQ}@x>lpR$IGo5 zRqrZ=yUvLX+MmWoM?Zc1h-b4inknsf{F5@&>hIxU&T5Bmf9m-4aL<=7NG6PE{SB`v zD+@gO?Os)Gk2l9?!^ui!hw`^>0}JAAxLpRflInb_Fyv$C=hl$Dg|iW%Wy z!iS?>IhvP`wfsV*Ar)JdbABA=p%!tR9nn>qa;sSgRWB0nu&}WBYS8S^ zY+R*X__eC)&#SMZqGEinO_LCePdY!LIO&f4DGEeLZp=2?s!hIPPJ~u%iUHg z_S+P)8Rvxt>h^Enw1OY5>>*x8+6bqX%?49{uOCRNe+MuK3qLsJ@jKsOQi%GQT3Ky# zWsH2k9nax;l3@F`d|dkN8~0mH&2*l$G7-)@ENTuT2-dEj*loK~1&$HKP3pa=Y0=fg zVLcuE#_u z^ZH@JHy{dh?HgYF=-zjRX8V#Slaht7NSj#-;Q>`o^O4ycrsDfI%dQ+eB*~^vZ+sZ^@L1o4`uC+x(?HmUa|N**!*_q5{BOu%YIkhf_)acl}v^%7Rqo4^tEWyKrOT)``n>%8KbF|P{HoHBN!8rKy=c_V%c0FH? zieatpp?O-*j9up!-Rk$m%5)!khAFiy&s<58V~EgV0ul#3hQOyZ=(FN`v;`R}DUFhX zLp5bd$Zj-D6%}_sgmD6YqKHKmX8D!}Usdy)HgmL4+Qp>EDVnmnx+!a>Qs{pU%@T&J zSzT1h86#dMm9s)pLmq8U92bNr(Qvzn!<4&FL_$Qb1c}zMy49;r{CN^@n3)6WIy*Zh zs0WbL=rH-eS$+!3fkE0d=ncaoAc(MV)Ut|7E8Z&%JQ2^ExG}BOeIzBKFHoDO!ij(3 z4$m`A&TgxF5aB#mWq6l4W4BWM+hLvnAAf=>sywn%#awdc!Sf-81e;4j$?%)i$QKN9 z;qmMdD+$BeIa-9sKTkV&c1>gM#P=fgHzLKK&=F*kN353WwV7MJ4u0+Y=ID9)MoAr2 zZ$HSJe3YF_FhtXxa`LgpPe7vtL+v`_kd9MP$d)qyuhBiUm+ zD{P4g2? z{gKZ@gr?)r9H1T)^u*}ec|KI|G>$+b4A&N8UZ#}5hnGe`%w;iv%AEPv7hEcWmcax= z#TEj?xvFvJt*aKKSpPo|&$Zh>_P4_` z@^&b3+0YxQ){&yymlUwEtAA6pE+3nUpAX=sp3%e+7-LCEynQ#If}}V$Ir$=4t4lfK z(Cj^tWRPKg@%_n~n^@L&uSWNHAYu5%R@s2w&3{@?yX2ufM+Ba^_96 zNY&~VMKuJ@%fYcuO48`Qo8|NXBDQ&NZeS%FPyja$T6Jf2&n*7*ciFvx`*0>1wl?$i4AOE*-IZXe~XB|639 zB+d~E`KV-Ft5&&uJ!j~e%n&ua!P6Wijpq<2w8vfr_6H>sUc#u2{aqGSXskA~n7H|m zDEla^ItyHJy+n6jtbxo1Sju04m%9_BE=`L*V>=fJltusP73?=~y7H2!uLa+(PT@#z zcau$=&k4gPU)?Z3ZyRZoy0^)&)9+lP*}&MJoc@LFB4Uaj zC;qQX$8k$^6jpM*-#4QrjL`{P9Gnn>#6dQl9Ft3&#KDyR{`=1x^peq?P#;Qnb`_ae z3}d=N$yIdG)e4?cxag}{1=>38@z2RS(W)eTjOHQuB1HK?6Syj=@)Rd+3C zZ5vLlyDZvlaD4SM?vF#ZR+ZQ8_V)Pv;dS=#K!zms6vTZCAy0*2;U@v-w^-EO zAZ_jcPC-xoqm_lUNhzuGXWlfl0H1;)WO^BQA~73QshcwBtPk1DPLwGGAs=-iWTwuz z1G9K@7SZa@K_VXm)$7yK6MYmGpEJ)67cHV8k$f_VHzC_&j}0SvXjf@zsZYIOD|^8_ zI=qwtdqe%+^X>X+-R!~FPO-MmVB~1&7A3E%{h0f1>n4<6U1Sb_4ZX__+^}@(Ok}jEW5(;p5Mh zHqW2;kHY=QMgTF%y9~r(yLNc0!U!w%=FaBu*!}`n)bgu`ydfP{{iO!&!-o$oE=%9v z;3nmZEC+?tdj2H$9S?V%fjqx@VkHhHClYc{%+$p5M0`ggI-7hsPYq2fJ9G{`U?UnP zth9>7qaOfPFi#Szasql~RzAEMH} zeELMh&o;uT(px#mP8+Jr;L{Q8?d`i+$E>c>WV zQa-atgwv2QcNm&vM1~Yvg4-E;CG|7r%KO7fgci&1yz~(vB`4K+_-&fRAClGX*O$i; zY;5eujqgtR|IKICIfae3Kc4pV{H)c!Ip@c!_Vn-|n2t0tucsD|tsd*4xGAgn{JDFm zS+65nAp)9S%>Gw7v=@sc?C9%~C)742KK}LL#m<=Jy(O_!5Da@Ph9ic#x%slaCNlHf z;q3}38-el!&y;9}dq!$lMo$AciEcy;owmKl&Fwjf@@>}!wOM$0cuxhN6La#sc}+s@ zcT}1d$H~tUE_%B6HlmszK7IOB)W&CTy8jSKrK%eE$LyD8nS2*(_82vNWYq|%UQ5dN z@887)-oJknfwx!lzA1o#j;`0FKR^Z3wCAX*=C36HttUONFE5>2kuC}&(vP(f5fR>I zE1Z$;GL}VRN4gbS#$-G;<0^vaKeF?zXrbZqE#d8R^i2G%zsu58UH{qA33}KptzCBQ z2`-T?fw*91u`u6*^RRW~^N8@Z!F~03mzjk;Cntxr)n%2$llD;Rtj28BdAeB2^|FZG zL_qYV042KA2K0|D`x#7^k20Nz^PO2(I272}jjD7wCGH)3v_Iv$!6h)2(sXB~Z_TZK zeE>)p>z!wN=wJZ8i~9^1#FGVw#lyH*=eGPeAAzDAvX>COi` zlVS--9y;}zpRu>Q0;+{X#B{F~DTr@EB z|8q;!QtK8EB6j1lUnld@XSZvCZgQTS*z1F4As=s z6cMuO_sV1Iy=yp2Vo>=6RiNayy6F8LEmp0vI%p#t@nrLm1QcVhA2L@qNpW%dn0w-X z+9MCq$cAw+!i~EEyeaVgJ!yaH-uGDqxx1h9OiL2Kv#iUII5Lj(a(#Vyri?;g)>D4R zZrD-u;O^&UPF{laSeQ z0No|z$N67^dy#P)&)*A;mZ!1oj6{Rf6yeN<*wl3L0OS~Gsq)$V;b(ix+Xf)ZGT25jz*O#}W`i?6^^U2G;@)xU5rH-JRXa3Qg$U(wEtTzhDVO z$mjA(HU^d-FwZTEH=r2=sOfa;=TD1au^AzxUA~R_MvoH$>u53Fg6yiW2=#%tCmffw z=$%F!uxc%|@=1OPiJOqGqxdYkSCTm$zANs*+7mXH4$^V>DcJ-3CUMLAi%pei-56wo zXPVW&4f->$H)VYf(`i!f?(Q;!FmC`EQ&3e^6+@qd_ZfG4ZGrAs4S|%GN7a5QKk!%7 z()uOesGoFLc#_@I@6cR$IA6csMHQ5^iPgI^p+wF1dB%>U;Bw1 zXz%(dh#vD(;^X6m?l%)TZeqPP)Cj5LSkfg^2hPsU^ogugvb$1UEMiNI-JF} z%b!N~0%~{q}-ms(fGl|}{Vhhhn z-HKlS_s-2`6Z&h$^oYDs1YSGxr-@y?a;-Ozx&`eyR6;V8H`!y3UFWUm7PA8wRoW=% zwVD)#l(^{AAK00g>`0Da;R~YL#oXNAd&#k6k$_)UT2;Iy-Q5%({B;3=+X!yL1rbY2 z20qmYoBqWP-@t!h+{&E?61g$|{reZrp;@@Bu@PHs$*$L7w0F=N!R6pr#hHoK^TYKB z_`hGjPg7SozZj=Wf&#Pc;lKIKdhCN41s)+`8HKb<7ayUlQ|qeFa#V3K)s3XW%1ZJZ z5ta9wL}x?s>p&ZzW@NM#-Dg<2B8Nb@W0AbunrYJQvLvbe{`=$ByT-ygD~B~O%Zn5( z9WP&&qxtR~Pg{4liS!|K8dN`hiOBJzF5+Xow6ydlIR;`~4>i(ev$vprEC%>hUtJy9 zYM0nmEKnHV;llnYXf`GU6~V3EO6GVbK;Ztn5n%8H8S?+QQ<3?%C3 zl)AEJEs@0;sjgM)+q={`_AnD@;hy4JDa&TsDB zrv2{!t9s`oF|C@%Zw^No2C*tKkduQK@$)%Zu`l6}de43nCWAF#C5tfXRulr;B zT;Tbk>#x!R_65M~WZ$hrGs(3k)aEZdYoN9Hrz?2%WuC@UA$icc9ljdW-kgCZ{Tg;! ztII+Hff}GksH>?#ONl2$BjMfmjWNfV$#$0n@5mP={b$5wwY^~AEfxe)u0zOYlQd`{ z#7>Z?K0V*N--w7w1D+y^G?KPj!eoJnuOt=xMw7+E~kSW`V#ECD5Ze@dKXE%(DqBP1_=x32PV;AKuNTdzH*y~bE`F4x5zu=FrPht)v zxbSq^w4g@@;`q2;4bGr3!S? zi-A%%X#KpSR@^w)*ys5w46p@s^0BmT?g!$K4y(IQXz)jK)JGh`Gj0v*HIcg=rK`|dpx-kc@f zUgJLWP`l@UUo@M*&GX1IXBJ8=2J#0)W^`_CZH3Z-)~`krwULtzouo_|;_lAHx|?9l zy=dNS(4||Y{X-ZFgA)__z`V^Ugz3$jgG<`CDK(&}B@6b6Ax2?>4cg}R=SL`jzug{! zWJG=bNOAed)Gz?=bb_zzf&vk^K@}NAoCGzrGgMh#E~{Z`IwktBU$zd!z;|Z?ZfX8- z^6c3n9-f||)yoC3#z=4p6iZ0Z5KW`ozavxvoJ?lY?s2Z}M~Uj+cy zdS_t3Ocynbh)!}P(9RxZuOyHvQKF%bX! z)x79r+T!pVrNycD5=t%%B6AlystaU%uPCfUg4J8Q1KyL#9pCY!2ut_)!fd`j!hQdiw)2E zbm_lOxK?=|K6q?&Kb|DUN>jRIh>61bF(4x&8xC4>;DT|wj^eca<4;9%DURy+drPP?G@4)d<{`F zhh@7L$tr3ZE8{djhWi z4*MK0)rNme(O??TKCd04u+m=#@(McG?mkyLr2-U30sCJx%LpuUe>KnK0Y!|*dFgv& z!_CM6;5bY^9mXj3xj@zqD%NIh8-^`|7-}~VB<>JV%X-!xQ+TNp%mM>yIWjVGF-udIRmqZcNB{P@Pz2@CMP(5jCbXlD8`gj{r(a3ncQd3e))NZ?^Y^_&rWBe%C z6T%{Jn--r)ue+y*SD)Z)t#3zJ>hUzOdFJ1QDgx?4mC)-9%dVihbbMp$Uo~>5RRO3yU-TCGCMztB+Phr-D&+KRF7D&ML6 zWH2l|)J6T5FABrM!(rO=hE(AfJ?2{o+>YZD6VLVlMR5Vq6MF|`^~4oucCTmT_?<3- zduhX?)D)2N79y>`+yC3VQK^+n~E{gNq7~&>WYc^OF^gG*V!xFQ# zvDqvX7_i;=`mo*D*hqS=F`UQaf=a+T42iadx*%+EoIgW@t zW03~|H?fnyhc0v?B9D)`xw&>~G3=iZfBbtPN~VM`v7Wjr4tQ7(t?MCWLyTxZ3ge`r?wMJ@R1{G zN=gy4y?I*F&>=#CTQ`?e5|xojD|kX~j-{i39I-|5X|g`F4M2>aeoDM>rKjkqDATav z_b^!hm{(o3{9|T$aY3Od{mT$d{ybSKbA%y+uIEmSH;EGuh-~?Y@F#AqD93 zKyAzCJuTwf!{V|&lGaOLG4#aFa3u_(+s`y)1g*Av7XZc^qQNO%d?Xs8x#e>XOq%Ej z9F4E@T{(}s8{{8I@-j28a}?-M7PN_pJ^_)M1BtpMXc0m@IjjiGsaqH_Gtw_92;;%P zx!CJC?LI{3mfDKBgYU$-DTY8GY}`3Xq*pJ6+?EoQOuWqo!9GJt#By41NFn~;(Q>nT zP`!l)BU5n3<&Q<HVU^4;Ct^RhThO@?2O)}lyZIT;>qPkST* z-1<{0B*83gpRly;ai31FoV6k)Aub3ZYNLKZMRQxD!%PM$Q{``mdw8alte_P9AYdVq zgH9jFMd~*wPE=SDbq@5Nc>x z+iffE9JA4nZ!iJ8a3)C}n)!uBzTO};s#rEdb^x3|2}p}f8o||Iyy|?h{$YppSQbpv zVyArlyx#fFIu07S>5H2^Z*F2$RaKGGdbe0nh;}0f0Z;FzxWvSanbY3|!rlhuvj-T= zcnJjbp$}-e+x5EDCC77FwuSz?6m{2RC+;#ZIA8DRjWEYRZy%pK@WK}^sI&hut@~Du zlJ!0|(95lg2pGaNLPGarK-4hOw+;77;wY!9m($e5&T9eQVgo-f5Qyq|a#Vt35c5id zCl`xv|N9R?xqf~gtc>%&L){PL-Djui^fkhQ#4*`fC(9^M7p%U6v%g}-Nw!yc60G^+ zrN%#ETA|fPwlEKRP+YF+)s|w=Oq(066AFPikM9huXMMo=tHe`xed_ydgg>M((hC1X z9b3}mA?JXuwMCK`cXvDu{kx~hs&HdHGT z56)MsG<0s%|C$>dQeUV66`Ch3s*191#`zy`msQK;lXF#&?k}N{;IvGYkWEpESXLg2 zLB62#VwC0C($caAFmLhkYQdWavf_&#D~#SZXdnpS>*I4H0WN4cCWKDoLi}`Pl{uel zOKXxnB=9C!sBCZZR$dfcR3QW#ikhzcU8R~QfPMeM0Y9>DFb=$gaq#fI585<62fjSr zM_vWA2%@F6YUDAia*cs%sHKA&y@SLhZTuFx|r+aSw5UF)$o+7AEaeq@#%=g&KC zFk*iV*q<(O8$iE>iekGb<8t_DZ6w=e-XG%vI^L;%?c6g$WZ&UdVd(qXIfpKjo_3(X za9~USvY&%FyZ>^pyHS9Dm+g;%!Op6Bw9>}oHJL9I|NMCCnwOKaXi}x^Lx=>|#qK*e zIEYU`NN6kibk<+RqFWOekuhE}O4#zzXmaDe$qDxN^cw)IX3}-5uP=*>i^)lnKLb1+ zAZq=O@d7sBlPrJfY+|y88kNSh=A8IEXjx%mpHb3eP#b|M@zkIWNbn)JNz#bO$SFP^ zAGh#E#|_dhQm&wt*S#cSG3Y-Z*q_qAp`xRUnKv!YFP$Trf9ZN{5SRT*&e zBYkNA5&*6Xtm&kn?Fz;ex zW9#P*uU*Fr#X68~G%s9mX>6(_>Mp~cfDR9J;reY8+|o3*ofCK<20%j|vGmIaCPe`7 z-FBkVTGHez8a%H6eY-~8J7Jz#Dk9a7miALMG%#2a=H~XW14y(6hz`MdpFa6@zGuz} z4Nr*>>*3Rb)cNJ>czJnwgSVX$3%oJ<54282073%A|7ArmF^gDBrRyw7p<5ZQ{=`z+ ze0TWm;0NAR+07?gtx{yd|E2KL#`GF94UL5bo^3SRP?H5XSZ*n z-rTvh`$@h`C@(9kMTnk$XJ=tyL6b7%&iw15lS{j8=n_INpWH?W!rs4=>S_QSpqQJ# zza13=0v=MvthoMeoEZsPrkTuV{@CLtOv{W|4_~i{J@ZKB%w>;567fBG;^!o&25f{+TGpx_-4BX`6g8-dZ%jYKbO zf`WcFK=3aDTz7LgRpJFQdw;n%Tdc>Z{yCe7FEoqe*$KzwyV=1?+odxAvWYz0+&5C% zhsWnrwNkdWw)F?oCHj1gq1TB;{$C z$;B6BcJ=ojL7kPL-=63Z1qEgI`ee1^4s43V7$G7g;V*L1p0|L(U7xOpYJm9C5#ZYW zoroB)RTQG+t~C<9>*b7+0_eO7Q`XkjZ2znN#)RWH3$&jbL|9&OZe!NX6EIGAR7)c zayxIMmlY@e3?Qwu9xgO)2@a>vrvA*tM1(UtlT-|og0WUbFG?~g?z|6-*a$pXuQ&_+ z(;J?Z(^<4*4^@v(>;aS_V+o@+s%HS&;!y4uK%0h zqQAv>8g5lk0ouVXMn)@R02n^r$4tBxfS7R4*!RIX?z0l0DyphJ-@QDZayV24Zmz($ zhT{u-d+8B{IG7W$SOO?&)w)cbJf`>6B!14t0)v;h9n`E*kTVE2H-KYgUcU5HfCJRhKRS+C| zSEE-`bNM?_-rL*gj|NCzJlq^FOZ*V>?QW4s@1UHP0@+Ro2RPQYCbNeGm633v^4_Z0 z#vpvy2rjz~9Hit*N@D(`GK>ptr3;XE8c|kI2rGp>fxho-^(x57zb-G1-~=wjZxFTd zMQn|wPt(d8-ud%Yf|{J)dK7QL=K}W1wH)PZ9X<1$jc0MyEOPmKTwL7se`{d)aNgC; zKH!S!2ZEBiz_fb}r$-2QMSm%dBqGt2fjtF`+B;SBVi>F0U?L7B(+;v3sbadM*VbHLJf7+dk(@~B5a!|bi;<1U2jV-#^2`Oq7 zL|mZw#`zOSi>(sRSF^3NKWOTk3pX)dqS>i|1@?~%^ze3=hJNUYG!#Y#NQdvAj^n?K zGCkZzJCDAz4n&L`LJ%=Y5=SaBwS;6Q>KaEd9y+bIUuSEO$HKCjnP-lIV@;a*>C+v4 zO{SY=RCeKQb>gJ+oLd-|E7)vg?d;p44eX+Go?*RLUv+3ciFSGB?Bz5*xaC~w`~1)E zbK=hNnYEj6Eo*UPdT)0RpZrY^M;hloJ+otDDGpm&3oP%v$4{(#$Nv~0F&Hqkw#^2< zz!j;l*B&J}FHP@|+nQtM<^BHSU2SyG{pQy#;27*A5%VZXirZ~JtwY3s8+Hp6g{>zp ztYWRv06MppVc;0e%mA8U z`!76@P|fKb{q#)mwVb-LT1iFasZb*A{9z2r)6L{RP_R~F870cC`+XemHzF|u?3$O9 zcwO`g9*@Wx7M&c;`HWLNcu+0=M=L8zU|EVyh-wkl;4>O=epff&v z;QtX1xA3ca2WF-pY`z~LKhTCg@F}ZPO$@5i#Ma8H6GM30W+}j3XJq=j80e5GDh&PC zYJKQ@sf-5)2c#y!*E$Q;iMl5qLZ_iGmqq>F!sH#{IQ66%&}a=NT>)$r2{^NGY#*0F z@=c6saEPy!)b}Du-tzkDVD@b!S=&}*9bujOHSmm1L1@?s8(w}Yg47=YW4K*4m-m2j zq3NQ28T!-c=qPLA;E#fWDEsidD~t7j!`gKAxwbe&s7fo4Pf1m%(DLaa6!sJNErb2* z`Z477`L>f(=x?;}!ViFjcizg%9+gc@aRm^pG+=lPTYZc9$0nh9J-oDJ450WOTb!3~ zEbB-GOawS!b5wkw=eG>V&}upqD}H^pv^;BnL+sYYA`#vEbSU&aqvyu8QD3}-be~J? z4dkB7j+cZZ2p|Y#=pKrn71%?ml&|G#m0M~#a;Mh>_++&&Fr0*I(s3y%yQ4Gb?f%3K z?K1WA0vN>HR@@TTe)J$Yx==6*(&$snnWK{H1FA09o4?ut3teBg%U!77_=U*J=Z}?~ zcZfjz9XA(jZ&)f*R^jtt6aSse_=T#U)+kx3Y%wu0Cjb^12Bw{6YGtl0z51>PXM=!K zbN1__AF|8HaGzfxkfZ$Cy{XIuJo^uzDEpSMF_`Ann41>S3=vtq4xtDN?wEibWd3i% zxIcAtZ%~714Oz)KN}*xXA}a``QvO;;-R8F&0J1@)$m>qFsR6uroZ&k|fN#v^ z3SJ-Pdmcbu10oX~EcWprLIaCXQ%47%-)cCGP_hmb>Q7&<#PlmIHwWS?5HZN&u5Tvp za5XO07Z#X+(@p+Qx+W#6+kIwc1Th;45eBtm;XYF>o*jBvZwOSG02*i^9K@{_6uJGKW7EQmvf|IEGGk&nD z@u|PC0`C|L<4q}cq1@rvlFu>_Qy*x*j@)X@!MbNkA`cdyisTDc&kte z*^e;V_kh5aEqUd$9(;?g&4g#Xza(KJumW-{$-BUb35Mz!muxB8k2SH;(Oq&#(1@g7X@ab* zN6txWa1^AWfT4YmcTX~vcheZu27n zxICN_5)&8WEC9EJ-S!ZwyZ3|AKlBnVfT_^Rc?3TEE)rbCLo_O3%lv^?8&Q{k3dn6- zCvtQPo~TPqVFvC*@Vu}$Qilm|`9K(sfX@$kDJ!MXpcWs} zxXfc&^p~h|#L8iOY%CA$akI3n?6pp-YGEJ4JFVAJ7)-YuzwL1n?^|AA6Udt|{q-Ml z)=mJYYSoNg3a&JFZ`pMR^c>7a=9fxEx(`iHwvpM($z;`zKYsk^j+*TOO;zGE20uYI zlBn>D12Q#rw?-qg*UzDoDT!B6y~a*H`T2Q4{*?(2O*X47=gblb8ev6%1?yt+~$r}scuAqKq6cc%A<1II-mmnr2yv@^Q zwicMT4A9z`*@LPaq@$;=-TZY8BcZIG0ERdiwHGY{e)S_@bUQQ~?5i)L6egPbYp^kj z5i@3tsGSudn=nN}k;49tN~6l9zcN7Rw;px z{(ubJb560{#lMQs+Nbe@77KOZe$WAFZv+YAveU+P#zCla9nnb|aN02eHx|7*tM$Xv z(AU5`U>DHo!%D;Mxi5rk>*-a7fb-hkI|YuxOFE4m^wDZZb^$D~0*%T3rB3|0J`81i z?n<0J_!xXXNO(kICnpzeD!6!b69(`pcZC-6+(dYrYkfHanRLlCi0aIbS{)ImF39yq zI!+fGCChIih&HbszTxhKTg!m1kw8R5bPdl%)6XXGL)LpXZ_!kXPr(gQRiAH<(YFay0#MN8 zUSM#>ZNElV{g++a8>L*!XyRJ#92MbqF(}3sU$Y%{Fh~UMe>|#BS64SCn!)8Wh*E5; zrBF%~0tI=xQ3fu&E)pCMFMdUsqGdy4Rin~7&?zCV6KMVW`wyg>J7jmj4h{O+)GE=B zf7$tX($R2Id~x$k6^B`@|IJE~p$DqEf<*8p*d*Yf0`l}2e-EeejA`JU&0+&r&O>y{fow;%z2eP6e zPmt1*5~-8XTUi$rEmKpDg`UtJ{48lO*p+PI#e4w^hyf?S&+h@xfP~ZVZ$b)e z^z$b+-ol}Zojl;_X!7&(|LA7PUs;P5B*WN!y1!g8VI6=C<8cS|#>_w}o(dYBT2{l* z@bGuoPkLQ%5V|{h1j^y8*U5^|UCRu|6pVwpBp+okMuRnMQEXs1zjqo*Oqs{ZQzcfp zoZw;v$S60y83jbve}}<{gkM)rPbLAUdyx197CiPkBl4nH(vnG7L2sIP*$6{8EZH+# zI6Y(I+Uw7pMg@d}69eK=vj?*MyF!w4(&-9OwKG`TukLrr;bm|8X%%`S&@r$Ee4Qec z(aFl~jP65*YpL;2+*c<&Gl+&lERBr|=9h4&aFZr z%SxQ2#=Cc(n#`HsMhS~z-$n@R_r=-=z+od14bR0!MUg?9TiJX=S2gf~19KFl2RLx@ z7~)X-1_oD=Q~l2k7zMi3wK4Dbu;`}Ei4dHmy97@A=y|{(T|VghiEtA&)Uv(9poL#q5kwrmY2s zG!aC5hCsGxg|nst<+N8aJraBn4IavrWHRze_~nX?tAhGh?XMa7it%vm7!H8g5_}>A z?vqNQfExf_M+ozbML`#gz+*`37ElQoXyOEACJl^zkmnZI0Hb-x5>r!Oe|WTAuiiug zB=SCr;52}Af-O+(_ye1I2P#1Bs>z&*nvS2H-Gv-o^UwBM6>L92zT){q^kw%Lx}G~|cL^_={x&z1cv+9QSCzAid^DmMcdh5h>|RHN6Etes(_<2-Y-Wjl0o`}+ zX!k*u;sL}KIbCp!UeAL9xWQl&OFt*#kxz#gn2!3yeEIQ=IL6Ax=7+G6s*1`udjN0# zx?g=aMx`T|)oKKWwzF2%f7Q;VF!-QZ?yq${&ZG5fgF!yzE_>LhlZ7K;|BLOS9SOf?o=lj?mo&p{ZA}A-|Z3p;kLuaW9?|ng*R;gTR0CS(66S z)!!Vea0KddcMy=GY`uGSohT{!qF+Cc3j7m9=@Kk)vXj_Lvj8n%9lf-2y4i7w9W)C; z+2`m3>VYzAMWL$7A2x}Mg7QE}EsH};e9s?Do~;B|7>EHd(g&>4%jl!%F-%b)BmEd1 zRk8tk|N8q{T|rXiBzvW)3P!+LLF{R_VbvwuEC96pZ*~grP85}tmS_kPpMOSPySMc( zT7rltJ8%Ke@gN{$U*s)pOv^8Pc7zNA&a3exr;3ifebqdA{#Z$5d{uR|GBP^)s*)I! z&n1`1NoF_*pa6O1VHHab4TGjU{TR)~rfFa(=p&|J{>OebE2MILH7mVahtXppkHx=MDzJM8> zsA(an*&k~aAPWMbWE}tGhQqWLsTIV1g8fLxMtzKlB8k_cy{RHXpQ8nAj7Mt*)!gsE zmMJL3U)A^8kB zq!m5_@+6nZ@_BfLHd4OL=mZoRgBsv*mL(DGLTC0&yR>pZlSd^p!kr`)7Xb5?ms*zo zjC!R7nMmnB5bl-(3dZ|#FgVB{EXh7?b~*?BpO&F$aD_5}mMig6d537(jo-Tycc zac5cS6KNbxZ-y3gW&}_kr}UWc8io^1Y7)g51s8bf=&T66rl4H$%LLYQuXsNop##w^ z0y{sjR6wvxoS**&U2p=<3qt_W?}G5(3=aG&W}+&bOZ)~HU`fG|{ttR*cxEjKM_M6a z(P`~x^f$p7WBvyH_v{AW_c6}iGl9L#`xA+}2pI>2z|(LtyY%l>Vy1w_iAX^L!lKewzGAh|g?gHe19 z^FJHy;orjyYGc0l_G=f0=MmVIxJ@~Mg-HFP&CF`p;|}{4aI%!+)eZsj?S)Q<3j?>R z@xesGR&-2E309nV&JP4et?rTa*Ts=w=qjYn0mplK2LVi_^v5t~D#e1p90udO?aG2l z0QeyQIna;6oP3Ml$i?>O=Rqha^sI=@WL_=#4PL_KKR*F3n8Ecwh=!ti54HSAB8fWk%ZH{kUjH-J;99NtsyXjrAz07U0bf`LvY7W@hm6Af3a9$uYCxnxvUn7@!DeAuu!0{45RD>WrtEuQ!7kFU)av>= zn}E-v8 z`Gg_1;tj2v&)~{bVd*g~X~K4)NSi^XVoBt*vx!n$D1e)9ipS&YOxasZP|54iWXa35 znM*7J`K^9K+~ajJ*m*q~-dY3oI~oX+q+d3k1OBhKv+&9~>)t*k-7Q^$G$P$4pro{P zh;)a9bW4kfG=hNANOy`T(o%x7gmk0SZ{PF0f5SU#)|xfWD0iIiIcM+dx;|SibQXgQ zst>o-{^YZHG$eeDu^3~ zK1^YKF!rd8Rn&*d8UN*HOIZ+^^A+PL5765d6s3R2svEe3?}5H5Joxrr!TmoB!}vmK zj~|cj=#{4W-{o!(qUUC@kknI_huvy#0@ksAfF-lktsYUog}@6ZSFj4;Dx38*6UNa> zzeQEkeT9e<>~9n#;)nfUxT(3o)}-chU+t$8$}E2~o3>7HNHJChd8iP{$l>kzwpnb& zUlh3^9fvjp$Z%=T=>^1tbA@`b6`s6G_Uasy*oy`DC{Li@zvHpLDEr`OIF8}68p&=8 zcE2hcXXjl#u{Si_f*FguMyx5x2*V%`H#c4ws!D+8rSN7RDAiGkl=qgMuGeih#qM%) zZlyh`dFJ(-J60gzS#KCBZm@PTLhcn87CxhxXK^9YRX>)RiGhmpiSMxF*<6jwf|R5x z4UJC!$#>-a3hBSABu8L=cGH0PHoI6ol~FfM9+6RsQ|64fy2@zwaug7!VQ zKz63<9H#bsb1NS>I#}{d$QI`W{@c645#f{3 z`zHYK=;NOU6Lq-;RUIV6?uW0p1Qr-@~tLdjvQ*;yt&; z=;?0M&Qiez?*o>!=g>}(A4kzXR1@2n&^OZsZ&QmlJS8(i4y}=c>h!4{sDTJ4)XlV2 zqGY}8Xg)(l62^h7d6Lsy+9RJTsLL91t)pOB!x9^o<0=6U0|Y++V7)wL6bitpU*nn`rC8f z!{EPJm{toOhEuTRBpOv)etrv$+p27=RyB~s0|Ov=nsW`&yY{=hyp>V$Tj8BPII1#? zdkY=Xn`vf&)iTlji^_zd%o2gN1@Hto}0`SaVMd(0?A4;avCj#BV2@GC| zaumeVBHv;sQP6$xjl&P1k3EaqM9-1NOk*0S^<;W;VaojN2O*MYA--LP* zOusgqDO5@O&D*-)T>v4>;pNtGnYp*vR(Ma_VPjl{Z~G~$hyi4-m?Q4a(P)3vp#URA z`z0htX^zG!YQwSi$m zPmMbUWqPIEZ;|dl?SQob!NjKuOryRUXX+%7^0%*RMkLax!nzi@I60X?J|Rp(QDh!G5BoZ{V`R48lj0lrHcYB4SIvKhwKc-q5v*L4_?_Iw3cSLR!f{ z2(k-`{YEJyv54jRiAQb$OljZ-91l3s7uz)zVDeFQ6U(-o|99v$9Q!PR+GZ{bArAqg z=rjN<2}N*T1m!~;T>5m{YWoUJEHF7AYNwYv#pAy(fjLAX1+m~z2=|1KNA1-OV{GBW za^6DNRrDbMO3@RECyt6bv_Q(;kH~8tR|Z`TG=p380>LcG%g<+exQMEts7U9xnyge5 z5gB>SXFHPDmbZVUb}jILJ#gb)6brl>)CIuFLelBuiVq!{2OHKWCwcD~s#qjL_BawXd2IOE4*b9DmfcjMlN`?^aw!FT!Ar*cN z4Y*BTft0~2gHuMH!+%k8w3GX|`srx?gRk%?a)Zr~Ei=g3tQkB<&&4lu9D@;yWS_ zkiSio7G8IZU>}Fa6B4^;-xB3Ed&dwYCocYBQz(SH^&#Gc;|n);;na=3-d-9`ZfP00ETvbz^EM#I6ulAnY7yI0kSImPZ`m9D zIVtqFWY`;q8&-K}QFe{AAvQQU1vY!+Ll^tmland4%$yg8UppQsD!LOH$*W9n3}&Kk z8?fKKYj8HE!Yhk`=X*39!w@2;otXvBMkNAjp=~Gi>iR_?(W?F7)8Mf9Kj0bjL8inH zNgN1*z2qPGxBr=D4tnPVzInrOQ{;>wKjfh^Gje8A|e>C7d!kwy`vg2_xr|2Tl9%z`*R`h&;i`KKwD5%jAtAxMorKw1$q=23g2H#xI}| zf_&#S=?mdH|8#&f zM}zqX+<+>sdJJvFG8w3@QZt|7vUIYp)i*-aFMp^+IMst^F0x+*^_N?O+^A&&vRn15 zh|2AEFX2F0C^K!#nC0U>4!?vRl{vIBvwOO`Pe=SM3!;!(rj-G?_3R9Xw{;{+<+i`f z*H3#LP`&gbGGn`y>|Y&BMndu4Fn2a4(uf|i%VD_Sp}9&>+n86#0o?nLF6oe1-IYF6?!hD^CZlD;&^W%_r5bSwV?4Xag0Kl1RUs7a2tLZ zyGlv%Eq6!YdcTK2gCFj9GVco9S`@Cg_3%X;oDkap)YkeGIaPZ{U)ge>0+-3{KQm5b zf>%AnA#Q}SigpUS>Cu`3Z6h)aN++=Yoot=)2QjR8Su-nPVy!FqaIWByDm;5uqySMU z#3j=L{Gz0S&d86yyWUsif#Y!lJp0ZC-*mT8?hIJ-GKs8^_uDO%nq)asLI>rDH6><( z7T7hpg3fuyWY`hrWA7hYZ6Yat_Vc3Qfv-3lz<+1jzhC0_ zO~lh+5fChxnVROPoY}=Vd*#xQR(V2UFE8LcCE%{+G}#B*8&-*tY}C2@xO?v~WL+)l zdcf!s)s?QBBbHQMXqNSS0pJR^lQ`f(YyS9VyDAd7ZwHFhx~Ry=3fbR&R)>kuAG!i& zi&7Y_i??Jnog6z4xQE|(*LC&p{9_VDgoojd;26}-BTJYYEdInBGAf(kPqXovPoKh5 zR%vATrd2wz3P`(jH22oWw+6n_|I8(WO&=|@ag)`rGN}H|r`xxmzRAqISU5a%Us2Q3 z`(*J2KqB-Zl8JNmXss10=$bxqjzY85kN{>2^B{NDyvAJivmG+VwxNL@;;DbK@{iZv zom-Jl7csH0J{mWB+Rdx=(@*mJK(IBwISR?gRyE7aI{3sY;`cdb139uMiXiB%vqGfp zwxYXrHyruDAvA}>U1w28!K-JZ%tHJsIr)H=k>%|l((k%V^Qi8>A@*iI^(*f~xX{kY z#8D4mZAhW5ydaA?YO;4N5-pH-%Mc36Gw{-JXjXV?mrqG+t2BT3{zqP3os$-T2cw+${_wj&Da*)Hz=4K{;1I2xaOJK(!|)) z)+^_iU{IGtbsB+ZyVHfm`++rQSrk5<#QEmdT<&Lt)hJ>l6uUIiCEzkF3}j%2lmli) z7E)Xq1mXrYwlj%}8nyv}CS&}^sEW=!$8*562?8BT-`FwgAwiTcoO}0qrKGMYYh}8B zymuhw>W5Cw;W4bSTvYyctqj~8WXHXJ=#550>-FQK2)V}#&~UP2uqi81kigb$UWSf3 zGpB&SF;ZC@kZx4Qwba3fAO2Dz>G@GPs({}!@4b1aor%(^4%zF*^x2b--yo*b3iTk5 zEjDgsSyQT2B7+|Y@+!7<91u>u@9vl}^{i$GT;c|t{iGJUcb17dGojN;Dj)R^qGM-w zh_P@L=Z@AQ54~z;Uf}wjbO|8^k|KX27rOHtMDSiIBRW^ei?j!4&=&z zCLkyuMs1XXrMOL(gRFMB+X;C$2pta;q~?5xMi7xbNY6h)FoU9^cd@}NDJ3sU&3mGGN1MA=bd3Y z>#ic2*K}xoVvGu|2g{#%Am_~c?h*OHA~RApGkI(ZTq<56DN5hDb8EaO+F?-(1-4aQ za6ec4F2>(KjKj^#W8~nlH-lh;(Cdz=v8NX)DJelcJuljrf}*<2T_M5p2YLP#7I7Y5 zg{np zqf2HIr03g(dygTrw;dyh~9dMOcqEX~EItG;G=c9<(VM4F@jr;YbuTRWi zM9ZHmAf!~>7hKQ;%o?2UM6TWPfMg-fWk8Nrk)Up#dJh#hj$!5?Ic}xw=NQg;YFWZn z#YImIU=%2LdDUf*x4e_WMi5_o{ME{slB1o3VmBWmpeqe$dMv~dxnf=%xb3_=JbePz zKtzeUMwlYA)!DLQB7m%-OGQns2KPF?Wh+c$_%m{Xu6<7fqySa152PBQ2Qfr6p$zlE zDoUoUKBKMn6C9IEQf|v=MR!pN(-d8S_NO;BH8rr2D3S+=81%B;j};X{IyyQVOBc`! z%KP8z0+!5l7topL^K428J?sjm1A{MC<`4CibAc^7qY52@cwb~c(Bdk zeQ$e<`=1;6_?(N{I%Au-?+44m%ZMh-a!P%q8>PXBz}6H4feNmu+adCm@KY)~`EWNF zsz+@d9U-UU=2Ko(MR>M`j(C;iu@STqko^d<70B?gU4##YKMt6)2?+_$hIi%QrBXJ+ zwd<1^;6sLhIgE2`E#w4nnq>^#fs#_qzkd6=e8i`hkq@3fac=V1;pW5t5JYIZ zcj3TuYlhZA@ngS`SQT93Cr@r?=6@d=n*Z%7MlgmPNk@YC%7XEUu_KgfYHDs4DY_X$ zBBmo^o0-D8ToWwb)`SyMs%|?}_ynQJCT)G*^bFl)RD#CyT|!Lt5N2sWS8?$JLnu9; zG+WaD&FI$21^7h5T^n_gWC;`H8rWhc>;*~Fw?j*IK_K_6MI}wUjX=IA<0OIO#_apE zquc-H-;&Gx_aG1f7{ddk=lL@mz9=*fp8KwFVp%JVL7%QpsZfh{jogoD7&QT1jhcBr zMOy5+sc{e(P&*Ksc*{}*SQ)Z#qE)E4V=)=Av(?Y;oxK0Eso$!JE`sig+Zce$hl?uq z__bt0CXu)`XhQ)WYi9ia}Dv|(usOslYFqQCtM}CGpGw}!xWr<#j8{b6a_NZvy!@}bTdwRDrnzx50XPv-uKqz! z76PtZY;UEHUW2hBT8E4|1fd z`%68~!S5w&X~|TP%D{t)p7NG3f6TsaU{fyyU3JihMe@rV#et`vtiqG#K+cowQkgOL z8$spI`{WHfyaf#-iv|m^?z?Tt+#FmyJQGFC$6=^uhK4Vdd~Weo1fKUgH^^sv5)&2m zjW?}~3W;Jz8SVs6NJy8t2m>KzU`a)V>1}Fie-tgDw?)SWesT9Gak~-0i3l4)TG}g4 z36fr`LkfpF!#-O9XVMr23h=2=o^{+3;yH5$$z$3p3L5j}@SCD+b)xJZ5#(v!wcl;t zsz}TWb%*->f*-DL!Be**-F%k!F!&ifA}zw9V`Oj+;d41*`Y(v?A8G98q%N5`0{@q= zc&<*&z=@4LP1m`}gytrgRP-9{)~x^*QtYnAkkHQp>6zmx;6Y&$x?lc`43YQ)mPbU; z7lFcyaVytd%BHP~7WDq#?r%}$LUTtm-RU(2Ck=FTYQa*R!@{xWPi#Yc%O`8Z}~mAxMd9HeM$jH%~aMX=wP3?h8n2 zd${?JX{MNow5@qwg&1&o&wEXo@P=gpZ=2`i!}U|7a)WB7lBz0KLBYr}xz2$*3AZ>0 zKmtF3Vk#Qxi5aV4->Eny$Yhp=t`TWlSvY!Wz$Vg{f@ZFj%rrQhlJXS@6B!?W)Cq-e zJg(Aw-GGHrm-V**O5dKj<#udvRq<<`VTXBP?Z)A3*Q>&5UCtD&}Z^ldZc73o$}$ zz>sOz|1;g$hR^<;PSTGnq7KWTSmuHMz^D;wzdOjxE+lftI(_=O6~OjB{Pp8&&(zl>l@rheJ`O+w$eN9Xg=U2l zv(?$KNvvGY!2~?X;v8$hlR>BsDAv0fZpEXvSrD^(`*rFbP)Is!pe6|)Tu_CuZbNN1 zmUe2xn~WwP2$?W)&(H`3VBKN^w<{O;FZ1%;xOdlnn_)QQ{{8#+dADBN)(iCQo7p;t zv|pChS#r$JRr&@W3VQ|F^LLSUb`$pwj2wr!f>$vc>}eLxdCLkN2Uz&O9s>VAU>NVN z9*-`T?wd&-ljhg*x}1)EN`Dtzk0+5nZ2@Z`2$QjkVVv4&LmWXgNiyv_2+|(CU#q|j ziJ|{OFcKr|2;NIci97U@drthWZs}AAOLbY`6@$}H#YOSjxa1HN4%M&y{nMdaZo;O5 z4~He^Obrb)deb)XI>qiF^aE-J^OAEgX`I^&P?f?pPl{?aS~n$H1Nq~l4}Z3P)@@0^ znaOGQGB|4vESXz*_J_|Bk&z>~NU<$Y&z+#f;>EA|)l`4Av*JmHYEcO^hw+R2=chlM zE9N3gw7><<9zsVABWGVuMz;LX72auzKyH^D`T!z9#0_W+?YGJWtfp2z!C@P3gi+yO zS<}Z2<>x+LS&NC-Sq)F2-1hlq^&&kq8pyg9thZy+5WYQ zm!-#{FjaggaF5_=)jFrfp9>Fqu%1tp@#Ji4$_2ev0(GWokwFceX|uB9S`1A6|8rW1 z+%$0`C$%NH(!O$j3@sBWTO(Qv6BCn6c$#S6mNdB=emCdS0ZWVn3R$)atB~%<;w=X- zTs8wVMo#w*Ra3{e1;(_2cORZ&{n}gmrk($U8KH_XIjd2{&;8au0x(AhvD_<@Rbz(e zFL5+4)POMXJB~)tJ%~fBK5pSDzb;hzDT2-wIn%ZOa5*@20itIrH=KaVOtHWDh=&`i zuN+9Id!s2-l)^gOSY7>UITC-7;SQ5?vwiUIzI$wR^t3y)=(yU4WRl2{i}^bHBf`TS zy8;7(-sFcVBeXwgY`mU(S~u^7tVA_RuJi_mb+loXC!$DZtl`3??D_Hb%n_dboXC?V zDj^fxVmwv&2~tqoM$XGKxGcH4Cpd$e{7g=nxC5J7*3h1XA_WR`n$~BOiy`C>NAUK` z+!4kyf#$om(aHC>1wo(X6kS&%+q*#o@{RywH;Pqygy~H=X9ynFY5_Fg(oW>o{ z{uD?y__&~pqXH^yZMYw1t6@G4rD?5;A=Ao72??Iq1>$>vA|L{7U^2&fL4m9^j)M$L zmG}xH5B5M^n|kw7PSJWP^%>@VDxu|F4vq{uQc}<4d5`iAQL4GDqP9B?8tMGjcfEM_ z7qxmjgu{ByKst2HhEJgVv*i-&11pu>)!JM-hiM%SGOqWP@c({us&%WJ(&o>bMvRHD zzb&V%2|S7-xTs`1SG>MtuwN@VK7}^Pl^fsP{q&~cT{RJA3>$X1*n5{v*qdmS8qfH< zY$l*DG~r-ly92Miy$RHXp{7o?Ic4)K8JP|W=z$!C01I(&js?bncyYVEIwEs`)%F#T z&Y}pQD9zQhC4!TqTP`ag30}G`g!o-KYP%X|6rdtOn>FttnMNG>VdrCU&L6n~^xTpk z1y&)n1aLY%1e)z%8%IYj|2d*KMrEV1?)T)IbFx34HOvOl@|hzw%*X6BBz1 znq$yM^a~0KnpPC2zb*(-lo}pR z_zPO>dywSRy`@n-`M3F9!J*6QDuII&1TGz*owrv|{0^1h%$?^vf$sTax@jeaYNk+m z5JZ!|C>A7Nyuh1VDwVp%%`=Eel{SVY^<{Zw#mun%g=kC1pqf9f5zT&UrrCTuTkqgV z6xR~ACW2ij#m>&|0(z_75i61Eu_8Uccb*RI4rk4g)^CeNf7l9O4_KJ14(1dRs^^DJ>Jr#YMpHa?QOZxqMYNLGgK;K* zene$1NP8;2aFiiF6sa8T@v&P59$Dbbx zMa%09DtgWHc^lV$Pb4?bzR$_&5FjVlJr08jWYNnUkn^}++_P`Vsg+c?2q!cG8_+o{ zs^L84NVX_34%DcIII8l0j{h#;1NDc4Y%PIC)E%jkUyyLf-HKV8Px(iZ$;ql4;87t_ ziK09scZdB20WAB|Yx7HUuAT+EhyT!;`dEskIl;r~2TYhtMCum$=8GDQe(E#L1B-&0 zBXx6IReEpJ(|z+`iMgC?jH0r75z-vU+C6@Gf}Ma~`nD4%SNyrNH(aynfC_VSmxZO* zhAA5QsR*pWFnms|2u;R&s466FjyQjfQ}zqK_*?S@sD)VI?OFmS& z>;C)OC0J3K7GN>66%`k2z}<)!2QAbWnxV9%6aPZM3)S6xwg>`3Ez&hNT+gV=^wk0F zA#f?h$a2h2y%=GxY#08;=Tw{7`C~1bdDtPyKO|r@6|aTHr3W}njoi|Y*7EowGWQ)H zr4$imPgU~`713<&b?!|*4)cx~18a53A29ew!9^@l0(!$uRnDJVoPz902lmIG5srrB z1D5B~Qk0za`Ix;G7)6 z(Lv93_wG3pBjeJxwc$dS9;#6HN*rBV))duE7GpujfLP+?F|+ZaInYq9$6#}RF6Q+| z0KsB-7}9hbGZIgVLhZNk1G`0Na1tXNEX$Bg*tDCOwOSrzahY3aLpDlfT!J?W1H=MDs(9mnkZA_=-MY4AcJh2;;rhgRq zVSDv#`6bl~-P;=Y@yF%AoTU|wf=zbaHLY|#B5+#A1~`J@T!@5S3J<&zLHB`}_5#c~ zIE;oX4{)UPX*VC4AHo?(g|F(@Wl;S5)gNTKN5ILu}Y5_C+W0+aO0@Y81fS@6qz67gcU7FLRMGT$$ z#mHY?zj?zCy-w>58S}QEkPkS3T7vlWPidv0eueREVyGc2$2Yg(eZ+kzDZvI>*(kh? zNx$Qb$JOIlE8CSa_74iRbOGfh?J4%_F~o9ftE&$df$I^N000j}H-nZ|z;*-+d{$4) z2v+tr%(c?e(!$npP)93~tOYH)(GH;VNZqLOJO4rKKghbUk7taSCADa?qVj&fxX6yMgLa(H1P7#KtcC}267Vo`{%IYATYgbfkc0Em{WC)I!yk$-mts^eCJ96RD+L! z$XiuXVt)Y#?J1z%uQyb9+l~>u7$ z+|t68P)OT@(bWn10?El)S;nqS)x5+peqc)SR##EkLQwI`AOUm_YYqSXeAm9oGY6c^ z^8G2>^1qXK|2#?|m!=OSv=UGyN}jD$E%}XgHu$-*udXH6!^E{|$NE8tMAKivejITu z;5RgK%UEGOEi74h#^g$7=IrUMRBxC>vCP%@ktUJ{~Pd+1qLF zQ=xz@gwBsI1dc|k!?pj-ZwPMgh%Wva9;k3Y2dAdHqai*h72=*7`^__s*V$7;32JA} zvw0>f|6;3C9u@Lo;6oZaun`7Q;cIQ?o~Bof{yp))5ttrK@#MvRE>^SQ$FqBb@e^Iu z?3g(>7iCMgC}ot_8NWcCje2=A zd=f{7hN+`yY;(s6E_&p^Ae7WRA9ch(|1PE3RoFMwRX&xjS|ksLFuksh&gvL9X4aA- z+@Th}B6#)@P@0)-c#2)4Uy!?H;kSKZMRnw(9Qx^4zXy%g3^nPJZZn*aB%?5u-?EQR z!5z`6@=<4Zky^;ibGyQOGAEcytj#p&J(RpSi&a(?7!C}gyUM{mzFtXvFxM*wSiFfx zlhYZjDmX0}xU}0800vZoX)@2;3b!}DGU;zbWxj^O1ax%wC}a$8MDc@mx1nh<@sP4lKz?)Qh}*oQ6>LZZZ0cG4 z!NaO5?a4@yiu{fW(%>??fFvA!YnwgySQQqJ%Z7oH25XA0*UrxqZn@}>g|(IPNz{?# zCeh|Ar|=EY!If9++bq{MLFA5mWJ2~TI39k0%9s1zpK``DNF*GEfJY6()@_D5H-+3B4?TB zTWP>`dWIEH_i(prc4qwLM4J)NW=;z*GzY_XWhi-X1c^SGx@E*t?)ZpFAKP?;dy9KYfD5a%;PSfMK==4d2@%VNG}hWO1Mk6=C-RP z3PSc|5lO(3eL-9i#gIjo3fD8@U#&0uc77_hAwNxp=n&KMm;5}<4XTSxqaMslbA8#@ zwZ5~1`ph&;l5Werrk*&+q35gUdPUF`7`K&{G;<_Wc~NI~pT=;e(o9+;dGXazYZ7@{ z+sHJaj(jfW_KA%bXfUy{OZ>r-FjFCoxvWxE%%PDbQXK@0EIUK?=$x$+ut#wEgJgx^ zyIhQ@Z#U9Sxg*)2B}5T@2Kqzc&iY7GON?kzTH4tFBvdU=Pf;Hvu?~}w9wKrWh|Yh+ z?n(EL)j_gs5xDNPw1I(%te+I{EJJT70SNB{CTT?j2tT&d&`NZvS>HD(_5ojcl~O{v z+yg?F?n3ML;Ir`fm|yX^_WNLAVYnRQYFw>k#KFG9C&=44A=*hNo(f;#bLi^5Em3G~Nj{Oj`KzG?6&kN5UjNQc_tu)V zjP*3)jgJFqkjYk;j!KkXO-+u&7kupU;JW+FRkoe}biBI=gBFxrKEczeQD7&?#pTw9F+iRLE*e|9`g?~n-LKw8 zM`M1V>BEie3{WAt`8ymW=6jLOj9kyXSkba;pABApw0g9~NaraH`y}?VF9^&Ry>#FU za!IV)jKLX$=_UBi)rwIG z3xvU<{#~?Zx+pw_(7F1Te9M>23iy|=D`iF-TixQCwM0k~4s#t$QzaI;5pfvIGRSq$o0Y@?{#DbvI zA4!W`6D3kMLH}5-b7Qc^!41M*ApvexKNHZ0T2fO8+hzcSsXw+JHk#RabtJ<@KIJsu zD*9Q!{=4~u?3*t2U2vKAeu4)~d?QlN@oFcKg<%WwekTXAVd!?7;b$=q>1MB@_0t5G}ZWT#Mx0!8C*%!p48Q7g()|%p#Q-nx-Ady}y&-()+;2$EOmc zXbf-4eV||vj#&;t)wc`i2A{)fir^1Ruxb-mKq#)}NG;I@tj}GOXs%W_abyfICBPWH zMwj-#Ma+^PyGozn3bIr?6DzPjK5x5TH1k$G)CKtJJi^uU>CGwRExa@Gi}QvBhfYM=iAGJdp13>)pI0n z2f&%Gb3U3$mU@1Ch2c$j1$l~}&}2M)zlDGPLXu#1?l}za`U?xoX85JNL=T*2Uvjbz zj>k3FAYt33zK%A8%*&8A@W7?*M9;-_A8DIUh-yq9ls@G6X@kT$#s4 ze9CvQ(_&*osnd-NvRqhTys27DaFCuiiDHJGauYuawLq9a6Q(1%d*?_8nK}z)_Pl%b z>YXlIw0>Vl9soL?Xlq-A$3-?wE{$~lC4xXn)foqB`xlReR(x$EBkEX>?<;7KDd*e0 z?Q=cMOr!Nt2Z~Rgy8?_qkPk#`7cZlMqpS>B6sFBYk)}2b&I^#Qe*)MvmbzV12CNyJ zM-Z3{*VEPgJeu~n!Ho%=U3TxQu1xD}q;_4AI2PbC)z_CV{u<^1e-i_82eEKw| zV`i2}l!bwCeLcAaxdrl+o+YF&Z3%=-N4*P*6|GDD5b3MJ=WcXeLZK2_ot&<mJxo1$kZ6SVVnv6f3#?2tFDL&8B7xCC(bVbST10a`J;klsQDaIre>5HCDnesw zf-a95#o(;Kn)0sugaNwQ%+D4=eU1_fLgWdBL$N7jTQT$=GeuJ)5>*6w!9=~{=4k6m zU`Q9KHROH~J4}XEEAaLlK9?$jU6Biv-NRF%I0G(nIO=G^>7fJC=1%ef^9nQe^D>M@ znAkV2p7}Io0hlIc78bOra0yJB!&u2T0jQA{Xo>~Z#O?Z}6Q=1Hh($0mq8YttE(0_R zUb$=>U{6fTw*11kdBx~lR8^Ivn+Jt}E^7)_J6S=>dH|{oT=spB=nxAI8aZAdZee@~ z>FMtp0G*}=MnaD8V;>O0uTlWCAuA%fd2k>&42I1N`yJ7_5}sp}-J=$9H7}U3mqc4A zIQw(84q>N8#APtgkw_T)yid|8$jE4G47e^fOkF&AS}|!vW+9UWe&;Xac_By4a5w#f zhu#zTk6F=mJ}ea`#YWmvX}_lHbZ)5O--8FbQ0|?`*C71p=M3RL5LrRt>!Sk!c$=6_ z#-_kX3Jlq+e)+w$D&m1+ccE)c0y2y@LC56 zVCadl8ZdO2_K7LG{u1EQXfT4~1%Vvx;^42;(|ie3V)dyXKXgWS3=Agz+-}0*HEqSb zsKnnm@xx$5JIQ<=Y$F3Vu;beEaWUdGyWTJxHRDi$( zRI(Ru^N;gzMbd$n+Jwf8IjjYGw%B$!p#yM}i<3A|AH;gdEV|J$kYe*r!no+*n)RLg zON2Mbj|y&qrQE(y>!bbBrBc>hPWCiRNP@Sl1!Wag;@1N%on&l5Dm>E6?{aJ!i)8EM z`9kG-{xTfa!^Wq7?5NJVGf74g7 zzT9%j*<YH=054Qfv=2{B)w54!By#rk~z zuLK6A0ElS<07a&rrf{ME6O2A|V@`t~WezdO3$QB$g?z>Tc;98=bq6Yc6GzQ{`ugtrjJKjV(gkL^?F2~2h5>?`SIr{a85b|1=2y+j-LyfD4EJ)+85hHA) zHu8Ck*nj2bJQXIBJ|2;`s`eXek(or%0w044Fjj0tFwp2!GyvLP!fjN~(tUs5+mE;t zbLfV_({%zM3d7o3TISM(mvMAunR%bAAtI$t4=!b!4NG9;JOp#yZXI2NLcD+KIVCfce2pWkCa&qHJW>=B)O2 z?_xTB8yI-tiQmh{%6k3XX=(q|;NWZvz!*F0Dz|ZSn}~Y7g4cCmxdkt`fs(2Z3hGEO zd4Y(qq6_#)*=h}U{9#B|94+~&Px|t*r46j?jfP*33f!Ay`^y>i1Ve3M-}7pY1O?4ZUETwCz= z5)!F}dGMabJH@<+g>MCrW04-qIYQ~Gb>@pA5pijqWc)}^#Nhkx2z%*7a}&*GVMIYB z#{$Z|FY%b&oF9>C0}rb50GN6ZA**6HtA^pq&re`4&^w|bf$P)McVrk+-2$$2RTpUo zmSF0Up-f@kdyYgYnTtoE+vsK z)KObHvQ}MRxyj!EfrIN3ZfCkbJRa;#L?N>gv_q=6&t4#-&DakQFKe;rJ|!UicT@FE zH@E()=}L&lFcGLhN#G~zXDteMtRcnzfghYXS!qU(`jM9hFYY|BD+VTlRf14^#jZSM zRRZJQJc8q>1ns5D_N?sb4#=iCieVVUi5g&)@!9Z>MQByWjTd^+pG?5wqeIk>57~r@ zSdC0ewC2D*FAUPBgub$_rEcM3vvvv}1{K_J4_Dd)E<)R`REbvIbyHPAt0@}C!Z*Tj z4K-WHK&_Q#20o2nD2IxwT0Ng_?cn9Vt;#-VmJ7OyaC3Vpv1zylcyt1m8;&PEo%e4u zlwM%)WTR7eBIY0iY00^ZmhG?Z%SU;97%xc>Yy;w~2Bpt2AHTkl#Bc-}N2ng^@;Qa^ zY~$^CMSke263qujV!A(QR9`S(g?(0ch~4$rveHzC800-E(m#uDkZ$gZg$QnfPFkNj z@SCj(ZvY;8eSTLj814c$_xRTXzfGn4No6ZaH&)@;_zL&Q%uR;AZ{Iqog#Vi&tp;Wv z8dXOwj)Po1)2h!a+Z~XHk^3>cV$=z0BDM-4W4g7W=>c913G$!d8 zFFFAoSX1*0KFO^_)_(WAla-B-+iA1skj1|?B^<%UWDAS&Ap^Cl3VPqqc0W%DU%j$8COs_{}xJCxP*ouQu^@Z!^Wz~9OOg5XW$Yux8PWexQB%eOnz zXF$Pv1J@GLyrFE8wP4dq7aB0~v&^$PXQ4(fWHGXR@9+09;z`3WCN0+C$c9Guk?*I@ z7+P~pCEmM0;wpuKJOZdn(3~r|K5gj0i?Dx)cA!LQkd`SObo~L^%~ph?X#KrXQlMJj zt9^?$HH$(cr@Rm89Tiv7c@4bIQiyb>$UX=jqFtU^x5a|uEM)>>vZ?&( z-(8ISfYGP~LQXT>H-8^Wi-#ip2iXCh+WEVJ_0_mcz&cUGo+pjTxGjbB-IyWd$AK)o zo~v?IU@{*Rzs7q(UNCCl3$xB8dem&WSYqNpCr)krjSzG(}2t`{9ZtMLZJ131mBPkyt;CYq^TWOkCI4g97cCMKRl zJQ}o%HP+9bS?YVPzVry@?EVKAlt?J;uQ*`V4!0*hq5X8UUa2Isz(*(=Kg4IQV-mZ% z+KGSQx;$S=i~^knHu_J#qIJCL$3^}q!$u!%myKE< z=SsCc{;}2fHcQ{ww(Ggnc@Me^;FUVmvc*o2MSf)+8Ms+83wux@XQS4Go7YAzPUjxEphf{U>UNMK626isAX^XB{U^ zS51$tKu&91^$KoIn0S7a@V!b0;-kQ*fZVkX9K}KSZ?IdCL2K1-2ei-4avgW>V>IGp z1ES|;8soX2VPq9GG^YPX7?xj~z;bbUww-}X7j(JM`B+!&CYMg)o5`gpin>V{T#)ni zN`o?B^aH7!GA2b~m*IV}=a}xODXq1&I*tvqg{@OhtNJFOteb*k=5E75|t2I z)2+_vk(l|~hg7(O@LJq~V|=b)X}N6ls1QNm`ve}qZRl0l;GxTh>6KcuZT@DJrsNZO zO{P8uXZi%>YKVW{1%U)eppJ05^haq(9Q3}2Dw!Ov>DN0|XQ7dJ2emaYQL?kiQl8b8 zN(QqUki9MPk>F4hgv66oykgBL5a98EAlKt4lnb5W_$1$8x4@=0??uY)4jA17xZ7s) zI>SWJ6$AX*0&8?QuBsv1wChmWCIo)w3a^@7X066t86igl(XdAAd|s1g9Roc*){+k& z79}*{qvaCuJ$(8!AfU|+E~$2z!Y&CgllgVYr%zfn&-YA$J7Xj0nM-sb1x>Uv2x#5Q z9MlD)!Y_JaV)qKrAur&J3ItCp8z(2{-ykZchZc_?C)bpfeeY@`2=$?&Y~i~GnFzb@ zR`VfFsjcKSOWJ^9l1A6<+{CmC2 zf;!+@ryqE|2v=6|{AYd{HYyGt(i-2RXWnyg{295Hi<;NWEY{+H`!JLN@)rNU|7L0w ayTK48KYCGqTDOb@e?5Glu23Oo9{PWJ24)oi diff --git a/plugins/lancedb/skills/lancedb/SKILL.md b/plugins/lancedb/skills/lancedb/SKILL.md deleted file mode 100644 index 47537f31a..000000000 --- a/plugins/lancedb/skills/lancedb/SKILL.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -name: lancedb -description: Use when writing, reviewing, debugging, or documenting LanceDB pipelines in Python or TypeScript, especially code that should work across local LanceDB OSS tables and remote LanceDB Enterprise/Cloud tables. Helps avoid non-portable full-table materialization, choose idiomatic query/search patterns, apply LanceDB performance defaults for ingestion, indexing, filtering, and diagnostics, and resolve connections to the remote server for Enterprise-only operations such as jobs. ---- - -# Building LanceDB Pipelines - -Use this skill to produce LanceDB pipelines that are portable between local and remote tables (for LanceDB Enterprise/Cloud) and idiomatic for the selected SDK. - -## LanceDB Table Modes - -LanceDB has two common execution modes: - -- **Local table**: embedded, open source, in-process LanceDB. The client opens data from a local path or object storage URI and executes queries in the application process. -- **Remote table**: LanceDB Enterprise/Cloud table opened through a `db://...` URI. The data may be very large, commonly backed by object storage, and queried through a remote service. - -Do NOT assume local-only table helpers exist on remote tables. If the user asks for LanceDB Enterprise, Cloud, `db://...`, production remote access, or a remote table, focus on the remote table path: use `search()` / `query()`, keep reads bounded with `select()` and `limit()`, and avoid table-level full materialization APIs. - -## Workflow - -1. Identify the SDK: Python, TypeScript, or both. -2. Identify the table mode: local/embedded OSS, remote Enterprise/Cloud, or portable across both. If the user says "LanceDB Enterprise", choose the remote table path. If the task involves jobs in any way (listing, inspecting, creating, or canceling jobs), it is always the remote path and requires a remote server connection — see "Connecting to the LanceDB remote server" below before doing anything else. -3. Read the matching topic reference before writing or changing code: - - Column metadata authoring (both SDKs): `references/column_metadata.md` - - Branch operations (both SDKs): `references/branch_ops.md` - - Remote server connection resolution (jobs, raw REST): `references/remote_connect.md` - - Job operations REST API (list/describe/cancel/query_events): `references/remote_jobs.md` - - There is no bundled per-language guide. For exact method names, signatures, and options, look them up in the canonical sources instead of relying on memory: - - Python: `docs/src/python/python.md` (the hand-maintained API reference) and the source under `python/python/lancedb/` when working inside the LanceDB repo; otherwise . - - TypeScript: the generated typedoc under `docs/src/js/` and the source under `nodejs/lancedb/` when working inside the LanceDB repo; otherwise . -4. Apply the SDK invariants in "Per-SDK Invariants" below. Read `column_metadata.md` when the task is documenting, tagging, classifying, or grouping table columns (field descriptions, `lancedb:tag:*` tags, logical column families). Read `branch_ops.md` when the task involves branch lifecycle (list/create/delete), writing to a non-main branch, or verifying a change stayed off main. Read `remote_connect.md` when the task involves jobs or direct REST access to an Enterprise deployment, and `remote_jobs.md` for the job REST methods themselves (list, describe, cancel, query_events). -5. For Python schemas, favor Pydantic models and validate records before writing. Use PyArrow schemas when Arrow-native, streaming, or highly dynamic data makes them materially better suited. -6. Prefer `search()` or `query()` builders with explicit `select()` and `limit()` for reads. -7. Avoid table-level full materialization in remote or portable code. This is the main local-vs-remote read pitfall. -8. After a successful embedded OSS ingestion, call `table.optimize()`. Do not call it for Enterprise/Cloud; remote maintenance is automatic. -9. For remote Enterprise/Cloud writes, never drop-then-reuse or `mode="overwrite"` the same table name — see "Enterprise: never drop-then-reuse the same table name" below. This is the main local-vs-remote write pitfall. -10. If reviewing an existing file or repo, run `scripts/check_materialization.py` on the relevant paths and inspect each finding before editing. -11. Cross-check unfamiliar or non-trivial API claims against the source tree instead of relying on memory. - -## Core Portability Rule - -Do not write code that assumes a local table API will exist on a remote table. Remote tables can be very large, so whole-table materialization helpers are intentionally unavailable or unsafe. - -This does **not** mean result conversion is forbidden. Bounded query/search result collection is normal: - -- Python: `table.search(...).select([...]).limit(10).to_pandas()` -- TypeScript: `await table.search(...).select([...]).limit(10).toArray()` - -The unsafe pattern is table-level or unbounded collection, plus local-only dataset escape hatches in remote code: - -- Python: `table.to_pandas()`, `table.to_arrow()`, `table.to_polars()`; `table.to_lance()` is local/OSS-only dataset access, not materialization -- TypeScript: `await table.toArrow()`, `await table.query().toArray()` without `limit()` - -## Per-SDK Invariants - -Python: - -- Result collectors: default to `.to_list()` (plain dicts, no extra dependency) or `.to_arrow()` (PyArrow ships with LanceDB). Use `.to_pandas()` / `.to_polars()` only when the project already declares that dependency — do not assume pandas or polars is installed. -- Plain scans differ by client: the sync client has no `.query()` method — use `table.search()` with no argument; the async client uses `await async_table.query()`. - -TypeScript: - -- Collect bounded results with `.toArray()` (objects) or `.toArrow()` (Arrow) after `select()` and `limit()`. -- For large reads, stream batches instead of collecting: `for await (const batch of table.query().where(...).select(...).limit(...)) { ... }`. - -Both SDKs: - -- Ingest in bulk or in batches of thousands of rows; never write per-row in a loop — each write creates a version and fragment, slowing ingestion and later queries. -- Build a vector index once brute-force search is too slow (rule of thumb: beyond roughly 100K vectors locally), and scalar indexes for filtered columns and merge/upsert keys. Use index defaults unless the task states recall/latency requirements. - -## Enterprise: never drop-then-reuse the same table name - -LanceDB Enterprise/Cloud splits a **control plane** (DDL: create/drop/rename) from a **data plane** (query nodes that serve reads). Query nodes cache the resolved dataset for a table name for up to `table_cache_ttl` — **default 300 seconds (5 minutes)**. After you drop or overwrite a table, the control plane updates immediately but the data plane keeps serving the *old* dataset until that cache entry expires. During the window the two planes disagree. - -The failure this causes: you `drop_table("t")` then immediately `create_table("t", ...)` (or `create_table("t", ..., mode="overwrite")`). The DDL returns success, but every query against `t` returns **`500 Internal Server Error`** (the query node resolves the stale/deleted dataset), and a fresh `describe` may still show the *old* schema/version. It looks like your write silently failed; it didn't — the name is cached. - -**`mode="overwrite"` has the same problem** — it is a drop+create of the same name under the hood. - -Rules for portable Enterprise ingestion: - -1. **Never reuse a table name you just dropped/overwrote within the cache TTL.** Do not use `mode="overwrite"` to replace an existing Enterprise table in place. -2. To (re)load data, **write to a fresh table name** (e.g. `
_v2`, or a run-stamped suffix). A brand-new name has no cached data-plane entry, so writes and reads work immediately. -3. Before creating, `list_tables()` and **fail loudly if the name already exists** rather than overwriting — prompt for a new name. -4. To land on a specific final name that is currently occupied by an old table: drop the old table, **wait out the TTL (~5 min), then `rename_table(fresh_name, final_name)`**. Renaming onto a name whose old dataset is still cached hits the same race, so the wait is mandatory. `rename_table` is a supported control-plane op. -5. When you hand a table name back to a human, tell them which step still needs the propagation wait (usually: "the old `t` was dropped; run the rename in ~5 minutes"). - -This is Enterprise/Cloud-specific. Local/OSS tables have no separate data plane, so `mode="overwrite"` and immediate same-name reuse are fine there. - -## Connecting to the LanceDB remote server - -LanceDB Enterprise/Cloud deployments are served by a server implementing the lance-namespace OpenAPI spec (). Every remote (`db://...`) connection talks to such a server, and some operations exist only there. In particular, **all operations around jobs (listing, inspecting, creating, or canceling jobs) run server-side** — there is no local/OSS equivalent. Before any job work, or any direct REST call to an Enterprise deployment, read `references/remote_connect.md` to resolve the base URL, credentials, and database header and to validate the connection. Then use the four job REST methods documented in `references/remote_jobs.md` (list, describe, cancel, query_events). - -## Script - -Run the scanner when reviewing or modifying an existing codebase: - -```bash -python skills/lancedb/scripts/check_materialization.py path/to/file_or_dir -``` - -The script reports likely unsafe full-table materialization in Python and TypeScript. Treat results as review prompts, not automatic proof of a bug. diff --git a/plugins/lancedb/skills/lancedb/agents/openai.yaml b/plugins/lancedb/skills/lancedb/agents/openai.yaml deleted file mode 100644 index 5a5b2d5cd..000000000 --- a/plugins/lancedb/skills/lancedb/agents/openai.yaml +++ /dev/null @@ -1,6 +0,0 @@ -interface: - display_name: "LanceDB" - short_description: "Build LanceDB pipelines in Python and TypeScript" - default_prompt: "Use $lancedb to create a table, embed sample text, and run a vector search." - icon_small: "./assets/icon.png" - icon_large: "./assets/icon.png" diff --git a/plugins/lancedb/skills/lancedb/assets/icon.png b/plugins/lancedb/skills/lancedb/assets/icon.png deleted file mode 100644 index 94cdd637a6b890494db48c78876675f322ffdb4c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 23274 zcmced^-~Ug zm-nZhzv1~|t9Ey~duMuQrmDMN6RV-7h=)yu4FCY}K7Ewe0szp!|6MOIpWX(aErcg-*$-E-^5wT z)W>7g1FX>c!b5+{Xlk}!tlKfQAp_DMea1GwyQkzfKtvG;zcYq5+_5RCfZFc)%Er9?9!@O#V)kP(?CD8>h*g9>k}yFYTkT2aUDE&mrs!EIvHQK~ zTJen@+kFsZDbXwz(ZM<>=!5Q9XwNfydk4zA_MD&V0*)u|R}AlSGoDqm zzpk;)IN(WsRn89Z#SWbVaJ;lo1;n3PkNqq@gs-B*UIBd04-NqL)V62M;KP^zt!TbH_bd32_d33^ zI>SJ8$*2P0PsQ@47W6vSP-irWSdhOP?S%rC35b>xdUt)Uy10%3(_-t8eg^i(wH5yT zR^~vq8Pc<|l+=H*518N0=9Y`HGdt-=N8MwPlyf;Duuk-Y@3X^wf_J+v+|Ts>g(4oS zGFo^;%bqR9#!X#4Xx(QH!Flx@_~NT~iUfpcw-2Q(3R43kXa8WQqH5 zQEhTw41@_0Y@|ud9H1LyKl9>K5K4bD>F;UnCY|=fu&D>*L=un@g%n-|*1E)m*pt}Y z{jOV#hFHI3Yl@|qIB@5-c}u&qoO60A4zNeNR(KJ0>p|ySUcV7H^=M{|b^K`0FI!In z>68DOp`Uk%d$G5a<$i~?fP(7;ccZ$cv%#phn*XX`CiQJIe2%9j05fz8N$k0*_X!|j z>?xV51(XQXo?TOsV!nxRnG(=FNJ!woDg0^HmUM*{kVgQc1n3oLO#Pm)e7H-|c?SIy z79bR=U4C)@P$)xds#kBgh_nTGqt%fmh$S*iUf_OheY6f!61YCLvDwlAFoPcL5Q=eX zsj{z0b3t#{mYd}6T>t@m_Y~DS+_#zKvK$0fQHCU7CSMo3y+eKyu&Rb<-j?Uk)fWH= z&AAmb#Vy>peRlf47IS#_!u`g1C7Ij&wIxZzF(%IxfE+29b{}33xbkA%I>y%f!EP zGla2!s+anXHNVs1!LR|YXm$SOtJy40T32_MPz2&L<*t12czBGxhQ`p@QL0<5U+RY; zbBf@#WC%me;~T%mx3QAms64V~b@-u)XxG%C4-OU=Sd)!<35beUWN`+0NGw1L!8qs6 zgY+P_>co`UbC?_l;DE8tTwbms!s6(8-z^*Vd@KLR*3%>~jRP?R%w!Z6isSV@;-uMC z=r#E#eeD{lHsnO=0&+k!_C1&f2!sc|T!lG|-rfv&bJlvIOoiT?Zd^b$uTmLK8^7cNz@QFXQK#oVkhx1drx@ zWED+fXMMd}Ux(L29*UFozLkggi+6eBAW|~E{~t;89hv%`>-qN+e3Qp_e10vZu(s9n zrFmFeo6c7p_S{>(v`|W)@&c;~A}EqZPdb0<#Mbnzpb)dT3dTWmE((BR7i2PRa^hp5 zUB4U%)unT%`+P;U>z}7*Z7H@Vx)@DAv2f;ED+aQS^X9)w>EhC+TpF~m7m|bKTS1Bm z6Lf(G4VJg6u?Bw>h@$53?>l^|ue%nzuO&ij8}sYFL>ZG!@Z+MQ;<^~_*0>AcPI0ZA zi-sZ8=Z9nsB!zC+F6@9Fw7QqeAc9&+;@&<+b|1*T!RYY{0H3uWgi}xg>jIOleTZ!o z$7{d-p?qjA>VU`Q^VVgg!`JYYs3=?^qw;EB^kzn=w0N)Yug+lmeENF+CCnMJTF%XJ zo75p1`$mQy2S&Jbz$>!zz%03E*|c4m95#MJ@s5$@)#2x7XXs1ME3faY@n9ex9kBe% zAqFA5Eoz#Nre64!Ujm=!DiC)QSj30l?c563R5@=0*;)@{s)elluIbPh%l-+!{r71O zdwRgijx$7o7>{-Y$Z{bPMhrb4E=zWj-D!E*9afH%d}(@n-O30$APEq zI_`eQe++4$b|3OmSBTw8t^}i}8JP!rbxJf$z%`Iub<<&8UCNq3VdIx)9CEF7i_Dbi zP0)h6MdGX>@!h;>%PD1B%#V=N1>kn>1Ag`6U@KE#@^Ex&E=7z>)VQnPFBs$0i@%+Re`?w{&NIlBXB2g=M=k#(g$9%m_MlGE|`LOrpA?!c|IEgL6EjjA91@; zEp`Y%U4X%#iW+E&fylPm&-oCbztfsXoMch3F_T5i(U=5Cy( zzjkdR$qL>lk1^;Qo4~?NX@j@CaOGJ{4yT`E_y0E|RfnNCcH^ZOakwMJj#gb)eAE@q z@64G!FyXCV~9ttrB>51a&w|r95^c2H6ng zF^-yGQjjVbFFTcL9P?lFwlXjbkfsZ)$QG;ER|!8EJ|ZX`yN7ky^-tArziEd=aEHur5SYtFA}yh)5c&f6u^K7$vVzX@E}z6 zf0KKRK5a6tPK#GO(}lTP_Nooh+5gT>1FXHG$2!p@0;XoBV@+&U1OkIHEEIPBVGsc5w$7kM0}ezRxEXOSbRx-b-RVzLZRbqMcN|xw zF1IBbh)=b}h^-531do~ZyP5E3tuSLs!(1n6j_3Bfvg!+Dx`%k8h?ICS?!~Nh;@jJ0)RjvJ7^G$h@148$w=<3;YX& z)K0bzQ8dV-lHl> zBI44X2N@E?a`lR{_yq=hV=O_Sx?4xgvLV70&X)-NF*`1#>Hzbm)e2)c~~z_ zTmmyv)1+O!;&9Or)E0zzcKn2GOJ=y*ILXvL4SReDXLT}Qox_BM-AG9oKGhtW?K6ZFG zMNK-&zR<*&s87~vN|lgHwQ!3yREZ|ZB`m}?xsr&bOIGA$M4T-RQIrb&7r^Mk8b&&W zS;1r}t>MOza&}RKg-U^#HPowxQQJQv&NmvUT-YMZZ|$%m{eH%=G=J|T&1Lk$OWVPw zuN;i-raprief_Zbf*s+pL*~Ip1?G_m)^G~dv*nL!8rLIryofeyNZK!m~)jEQ0!Yn zhjssNP)u9_Dr9Tiet*r*@HM3Xu)f@oQbJjkCyD2<^hw7;1y7IZt_SqqgnJ`ur5Bov zJ|}Yja{<|TH(u{ipehFQlZ#Kr#}4-UhL%$Q6R$C9NbqDf*M5xspLZW!l4vr_i)kpw(VJfpjRdzx1UzGsL) z)v0yP660Qsh*DS$UTy4IJv!H~=BNKXH(M0u#u%!6osIh~J-IcUdUqQDH4xj|v4(6| zu8%QSZoJ|QEa98lp4L4K`?J_fmf}N~tFN6M-l6XYR>~xRB?3@`h#iFtPyjX=)t#ir zY~ku9-KIbZyDWnot%)-07qT6M->9=SE6NoA0VWyvs(0z$?7*D1C=kErIWRYxHdQT= zF5~xT%Kc~2-EMeLuYJA$ejvcuk;``9APlnKWW}jcq3k>{@Qy+n4cI0DR@!qvsx1>{ zMz0+rVZ1;5o53XySn*z(#}H0-OwIc%_r1yEIb~S-i>mBEp=zO zEx5-m0*(c9Cq%$3+!CS$y{9H2)S4HJloTbrvWXk)G-591J?3U6`$uT{f9g)`-x{g3 zzOi(aM!Eo`?doHRx`sB*mTLhf?>D|IMCJ~q;|0(vHIai5H#unc*-BG+W77MxpN}RC z9~HA6TOpNsBvEZAMI;T-XD6;x;q2A^XE<5SEx;+(K(fj`c6>UlOT%L%1s{K+5&f+d zC7vWW&gf}>&80gI*wZ!GQ;~EVn%&xv$~cf3zswtnle**Jt}#IL?b7B^bqc$Rpk5Bx zX}J&0+OFRS;0Nft#a?qOFj=m}i(~eB$(+PlT~o;M)8czXY{~-6i$L_;H58Dg`K#y0 z9yWPlk|~K3y)3H%9og$SsW~hPeV6^DV$fYryq(Rn5u$y2z%?a-5BHWrj_sW;ptTal z;Nx%Nq3tA%w@%Fmfnf;<$n!c=CjJi4o@?=?QOKC}H(xz%s?%vPp4^W1(VV>;d6{pj zq`q8M6(8u~YHlMFTPw<^G~L_i-7BpXc7r1~_ z&g~%YYQ2V<5{BeYA+br})Kqu;IDQ|PM)`ffS7c*^H?V+}vwP;KFU~t+Lys&2MGXtc=W7FKHGZgwvOfNU*gg@*(HxG(NBO z^8ehI;vZO8-d#JMpvhHWWzd#q#GbDG-Ig#HEW|uJ6P+tHe||N9hU3$@*caK$Ou^L% zFZe{DZ6E3AL!W?=zskR7*0MfBS5fIc9L2~aCpFYh#4of>8qcg@H#_n|cvCp5@w+j z@UnJP&ayw?@4R>?7^1G;cGO=t={essp|P_HQ}{TF-*S})351Zyr5IN6Y=#n=&EFD4 zLlJgcd*3#L^>ph#e(1Zg6x!%Crf_7yM6j>M+s^X)VO}*#jh$Up_`h+sMO*myT*&3_ zJhR4~kG?C>U#{${E^bdK=~87j3Gwf0o=NL>US?|SdbsIwcfib4sgz5^?_0_2tu7TH zJDso}UG|TiexRn?^dXhFcY-V;$qXnzn4mqnW?05*pa*;1g-8-V8GeAZ{eRW z8(5;>koHTXGClM;?5$u};slFFMu?q5keFXAUR@U9Pu4PL#+N!qiJYe!G{ z7Zr|)abe~Dp6PJjZ|EoZmv)l)$iLsX-?!OzrNkRtz?9S!2on9;YF4?pKZ3nQxG#YI z?$}+Dw8lBD8f~np>|aV?g&9^#$9StV&P?gDA>UGzb~FAi*eV^5r|Y-+)2AkG@a=dT zhUG;d9zpvhfue_DE!0#5?hopzKJ5Q0VVm@iRP4nZ!hiKv3m;iH7Y-wD3sYAK(^m5U zYOZd!CHf!ohMHNl+7e2(@on=r-*E~HpfF%*fNu63rhhe0>QA#@2>0dCtCIA+ zfNYXcIRZV-U@s2YdGQcEuBm7xWZn zK_JEIq{v41uR*E!?jkJ^G7E7F(s>K9yJ{qs#B{-N!40?qy zVQCWBqY?-cw1KlJ6s1_LoN{*h(X{PitnDlY9Zd$(6Fmncs2>l5{(*tsJF=bG@SVNRZuk9gln#*F9sgW2r{4T{IGc(pSZ@ss&TXAV5K`@pv}c*c ze4fn`U$8r7QU_u8MncX2>n~w9fO&$r>39aMN{M*AmL7<>h=V^@ngTO@t@B$uEXXdv z{|EImgSS;Z?1`yB3>bOWH2g=TxxFXgVp)s4ingUCajJr%1@1T6B3vw1yxjIJt(^`4 zBwy$m{|;ONe~oMSLfA%%EHnBPhcQ%1DlL2wZ?8lj z7+4a-O#h0cp1R`~Hv}kYcyi5D3J5i7`tAdu)4`F|FxQ>llIqaHmsqVbMgUn*huVfY}qZX(hjQMdD$bu_>G`*}jp zpR$S4yN+JORfZDko8kL!c4Ou-PPW}hRFnFJ0>DKYU0G={_UFlq0d1gYA{<4vD0(UM z2?(Y5x!r+1n!)SOmR&&^d?1w973uttW8TYIFx5dWH=e~SKs=g3uH~Kre}HhuHv)}g z$*Zu%pBmS)2++UD2;?uU%D%s+JyX+NvZ0PV&~) zqS#XnUEq#P=FSAXbLL2of32CU_I}z!>}4P3A(^vz@<{fOMModTV{7 z10mOLc+xf2b2n32D~9dP`rcl8z-dCsLO)AwLzm42Kpwiql8UBM(uLu!D>CYVr?dM- zl*W(#B<-oh4+YIch`W`q8(VV@o?jIwdu*cICN00&ulZje2;0w$lwFB# zcxZ65IS908AEFAN>>~PC$8PT6YRgWHU+BESh;w#fc=U2|dNO-+1IMBiX{GLN^%x%V z?u~DDrV0Y&W;GDV)LOSpfZMltzW5DmUDiQa^QBRyoh3>-0(;|bpI+iU_r?dKx{#ml z@d^7L;C0s22XYzVZF%w;oW<0FalAeH)QVLx6UTE}bGfi!UiSQlulQK%-N*8j+rw+x zH$KLT*ZYC^ub}aoLN}nJh0_?b0!40LZ&5q}-`c>ch~7X;T0@Zz}X8PL(Oj3OZ%~ zkgjH{Q&G=Xj*rcC)$Kf@+N{U|x=PZjp!ruHLsre+o?q7w!DL^kXRcuxX6O6NzO>#- zevaE24h=vxV!JxCf%UiIj-{r}n?-ZO zilxmzuW%RMw@LnJe8$N@OsDo*XwKkzatwn+2dfUY8BZf*JklA-BIJI`2XM9XVkkec zV+;(&8q4wb^YN?C-<*dzS!7o$I14eNL&3doF=knvv;nr7%{=Dyz{ z`_-QviR}JbXM&QHSY;R5dlOr+A#00AhDP&gN6%K*%uqL$`gD>`e3)aF51RPs!e1jT zx3jCjqnaYK2CG<>3ZV0Fr;fVNaQ?Jk2Oeo)aXpiYJZ>~cWx78LD)l|L1?>!%&HnNz zU|KF&ZLuwPfD^WrH~*yMVdPb!4|v`cTaf(djlgT9$Abb+T+B!Xm!DAzu*;8n+o7%Q z%3#i&xvDGl-RuUl{lYd+$x?!121c*F7{GwSnu2R*h^82KbItors&Fz$YTvM7>pKKR zV?t~+4Jo7Z0(iaohkXoCiP8Sf5u-n+MBbnFK5S(Zv5{u?orZ41MJ78E_#9H-Ep$)bJ8-6% z%wZQ(r>?N()>ZSJjtDI#(-^TcE|_%o%`5FD?((d+z|F0<9!pgW!ORPsqaG{i=i0&( zCZ~V(qQUEW1VEb52RshRHg(%;iB;8NJk-8~M zE43?ML6bsup7s&B@5E_2m%iaas9QNW`N|8r1aLwoQ{;ZwXy_9B7T)h)H8^hjY%O_u zbK!eA{E~*??{M8G;!}GE^!~(`q z3O{I)T!u)s%`r}#ULJ*28LU_^tGU-^mlFi7mjd~^JSlxs^240>$8PFCYWS+Fbe1xS z^C4$CzqP7rOv<<_irGkVK^WbnyZdwfRON(pLY>$nREDh091pj@cN!&rh<;l(7$n_1 zIM<@`=V$HTckk`5&m|%b>CRkCY3xry*d4E^q&Gl+8mrb~Te}WgT%)aqr+E{_U6zb& z(zE~6FmM8{I{M~ygCaF$LfpHv1)E&b`!b&e9l26 z6uA!M{V6nmar5ll&1m3u#&Z3r$m@_*NoB0M@6)@8^ox=Ch<7)S0j?RD>%O&#JaidP zG3$gX^c7XxPSE661<^|dv-d%D_LmdUxVY+JaF1ZePJ5Tanc|0z$B}&+=WGqF=RxB? zxyw59Cp3U^U(;NNZjxJOb^hfM735117CKil! z@e2>e?{7F>JFO=zC}F_kc?N;~l^b431g_|HxnHBV4WrtGlU%tR@YKRi7aHVky`L+> zNO@nCBzRumP^iH^eRKI#Qo_CI87P;ojSBz6^n*nwtA+3yV6PH)zZ4dwA3Shnu%DDM zyTVhvdR7FX$8ePi_f$SxU;o4{S5z9eVau^LcUuZVK9xY(ZfLe)t|Tv zGRPmhMl*)AaQnzF>(<;GRw|L3bliwS1Mh8mr1+qG^EIVGR0Q6IN}MtL)wd*nzmM_0 z=t!P-G!uN0tQh(;NLcQY}+_t1c z;|h$soPr#$;QUELxlOE=%(EA#BPPdT-70P5j5f4+a3`@o^XB)-dU_G^%~nlr+_)|! zZ}t!ZWC$x=HTLV|V&txgi4dO5OXYMBrL4^5AZtxew-D4ec8yS*Dq55qul782X?13a z$m>Jwbftkxitts2D)z~)`F*xnDi}~R=@#oNQle`ajCLPD=lISpg)ESA1NJ6#iIk#Z z0oMizm8;J0=E7=ye*Hf5MrzS<%Hw@q+qR-5W-l+l>;WOJ&tPL&_V41%eTeH;&aV*F z;43ZQP6MNTP2p$kY4%K&w(5-Y%QGvU&g{v25DU5a`2%Imr~YK;mt2nN8!u{A2X;ye zSNVYk*aOUQC$L_^zJJ*2>2bpI#zX7JPP2q_7SAq4iK!WcSZ(x0mHrEeZP zFd|<>8(LVgNEqTN|B2AcY%r0K@A*Jj^Q7H@qAfL-Zn7VZ;G+BW)4bpd;{xYTodqi> zJAtoa3JaIY=QNw>JeeE#SS9jrjppk-AL6;$0`fJ-tM{n0#OTqFN!@ct*}s!b z%?rsJZ8yRbA(fKvo3f;&YsWQ$YFV+TOP9F~n~j&l2eaqX#|#+*A9*z z@7{aNTRs}+NgJ!E&lu6_3`yc7*&t$6kx*N3~ z&p59Cl$F*wIC;ut2M|dcw>8P8&hfMBfdBcC#OI?4&f|oQthxLyCoG{S;KJ)PF@+T6 z(u!!ie0fE<$y;Sw!HcbS4*e|~SH0TYa?U`Y7Bf<}r)f=+`@GUY92)~CDMpQDvtK(2 zpQvT$^(K8ZD?IH&JgOXhKve@+Q-avE*VQWR8<4pk@8Gi6$>_h3g@p`XPN|;3Cc_1{ zMT?{I6i>lury4JNlw;a?dOp#vcHKt^j1?FKKDgFi2Q?+#T^oLgBJ2$Tzj$C`0k4#A zZ#ouIIX%=aG_rVgCFG3XrO7gcFdbK);d$bW-bf^$LrDG*H|gaCgzO4xehY6Dzm9Ye z#{rnkF%TRNSDI>_O4B|ECgdr6z7Fn*i#7{XjS=Fb>+Q+@3F~w}T-FdQ8ZhM~0DzOt ze>K$l2KJbj>7mi1^gSKa)Q?C_^54aAaCocxs-`B^-o0BjG3(}vGe^?<1F`?a3;iLW zAD^gn(jMo>g6mqFE&g2p_3uvo7?Z~syG94Yeq&6W4) zV3;T;Km47ooUxRSrv(72y+kx07w%jDO!{l@o}7qMG|1z0g#dhwU?VYOpprq<{*5)aqnV5NH zc9+M#BX5xZOOhvK?00R~p4+A|(K9y6B28egz!UDhU&T0g7 zb^m&ak~f-&bu*3Q;N7R2E4QU3*50TySST~A>4?4R&DRE}RFxc|l?k4<=W3cI0xduC zD2=AeNl)hAOG#o?2i;tNugV(9HB&pT%q%W#OO-bd3Td2R*OaWIKi^7#xgP7FzjJt^ zn7M0wB}lv(M-&Ww4X`@ed3Kr$RE$y^j|WmkLyF1Wc%>b$1KM)?Xgqf|Zr;+~e=KJ> zmx#po6E(2jfq?5t(ks4cN=0z*iKe#i4l4kH$7>-r0%P1oq(j!2!wXuJJerZ=2eZlT zab~&Colh@rP6@De18UCJD+k_DO5+yA$=8G5KZw7h@DPc=Ts={duV18k#OoE^xKr9E zGvRvB1w8I9Xn788(B`nWGE_02LhUVw@Cyw-?3b*4%-V9V9{BkC2li4%cr}thEBR7^ zRfJopO+be))~bFpneN;%%DS>l@!i&)Q)fn>=Dol1=UY0Kg-!)n6=B0)ewJ@iis-cD zZHTH zrvy@7P?P0SXaR?Sj&U2;h1EelAK)G;_iVzckGISG_k@aDqskv~2qHpVMgg`hl4$PSPmdqe#wf@ z?)!WR0`1znG)+zguU4ZgGc9Gzf6z8PwIlgXB!@fcUm=59{zlCLD?(5C*FxvF2$Ao4 z&%D13qSy}n?kJekakWGbY4f7kr2C8)x)R>II{M#W2tg9;f|@p_SdUlyf>XL#4OH ztR1Y2oGicY1GX64JWk~ad^7caUFuf2b+6xO=UksqO8pt@cigOR4)`9Wo8fl!q15ji zN`=xU;}2D`TtxL6$MH&S2~D+N_a*k6O64lP4J7d_eX5ro?eQfH4|hd*EWs5wB&Xj?DotCOx%NcU|F`)|QBBsi zkxa2N_dDLUKZMdVwWN-f^oH7# z&p%x|n^Oy)IB7wQ4KmZ=lqZf|hbXbB^V>0DW3niQKdlgKZ>gk80b#vC>mEwDp*Z_P6zV52BO(#0e5BQ(Q9LeQ%~Qpv^DjH-S?$qxVu#ML3+&%F&{0d#Jahc|H417|A}8zI{o-5PmY_Vt;oS)6{Z+d@@O=!)km!;`%?>|tDNV4rAq%k0$; zFu6C;OOX#W0O_p|c7Fej55sa!*2@vd>zmsJwO;kGn+=3Sc$Bcuf+=RnW}m1V{gHn> zxySmdlT_$zwAxk+a1@GmI4rS!-|ou6Yt7giiuV91(ie{RYb!m9)kJj-a4bN>$e%Di zenLFw6d4HYe$`N-wg``NH*0GDBew~4q;yAR&u)cDdWD9H2ffEqK>+x z6#@fd)CXS4K!QaxX%OwyNM?qdn(bM|i+TEQtNx@oQ#I-q6an{LyPC9^77IKwJ)aJs z1!pZepYk9bYgF$dwDf_mTV5^N`X4l~u9ElEc4H4E z&;XcHMn6xSUv)emqu6B($|&gjd)2dmnX5o~p<2^J{f4z`L1sTn{H*GWkNvuctE9`v z6G{QSz9Bi3I$OA8KTW&XRKvx|hYY1V9)IUD5D<{vP%qDQZMMhb^nl~<0jjTBdq?FZ zf*!2b#R2`=;e69-P|T#;M`b&c;4}_R(w2<=q8B=g!?#D9{iSO}to4 z(3G3jghG65m#U$VP+h&1-$i!^6#cv<5f1?6N8ydX=?8r2mRmye6!In8j>H7{AqF*G zw!ywu(o{UB10gOedyS_{acJ|F$N$3QktxzXIHyMhu+M<*A!Ph>C_;V^dGqGHNL+i? z^n1C)(aDzG6=}`H?#)Vnh%3jBHjg8t%H_uAp$Q_FTg|wyi+j_YbRHDse!VY?dtHim zT{T|))^}**jEPKBkXOYv}C4e61k|QE+nvH6IImF~MZ9m@qQbd3P$I_qHWTrbtw| zv7(3n=h+wSR0pMEgG>Gw>AgYp9^7U8&%bYyig%x;?+||ebtUnlH-(5)mUwoI;csh! zy+4yAJc`Kp(V+adwb~Vx6zK9s*yhpsH4vi(A8XTWoaw}tNY|wsmE%^MJAr~2L?$f< zaK-sb4LhcshCv<++z;?)*iwGCDaVPifWbGMJy)KzB=LgMjNp@ss}DDr$C~v)NgGk< zH$nG4tXuk-RfAGh(zA}=+J;jXpcvI_ZCAp8e6%{+fnTg_(H{d{TkO|gzyblF=&m%Q zoUgk zM^*Vw+c*DDbb#{hWkZ}l|C~B9gNiRem1GccZpjr2Aq44wt0wtEx zHb^3Ccf8LrwHeh&p;p;wF}0Zof96jdV!h{DL3sAds147J@KhbpDY<%bWV`ECN^JM} zTLa}%Kk}E&Qzi8elb{S~_55p=3nb2hSTSD#1GiX}gh_Ao%(?Hz{$X5dE_~KMm*r9u4MagcdA0DQ^cnc}pAeQp$tNoF_p=(;b%ZIRjV>3|?_-x3uRQ138#+$;Ai zIEGR17*BhJ_OD&f}9Mw*bm*i$)1>4?jvMkLvB)JFP`Fj`4n zoQdunzqU%b;lk45y3bbKaO?Y%l^Si|5LiH+2s@{) zya6X0=S0stMx3$UQaX*-ow(4Xt_*(Pw(&LajnsCK>Z`P773H<9)O(YMFpMT1A+XJ? z`P`OQ!3R31!^6m9Z&Q3qU&%#!NTxv6ZwHp+ z;49>HKej}^H6|w$YZv}gs>cT<(Gtgf;!t5mxxOYlneIp_-#(kf8X7)~@HPJdms#Fx zvpwzDOD`s`ceN{jpNF}=D`0b2Bk&_^WPW(%^VNnzU;K6_s&K=TIHolua=iM;Y(PG5 zQ0NJr#!I>~E7qLmz1INieH=gH4NOoOdp*UjarUq8B0PDH?|%tuh()Ai9bLH}L8(J* zxW~jHAbn`UkwRrGC~spTOK1Q;D&J3FM7p`+r@fexi^6(jr}OA5$aDQvvg{0Z>Pd=V zEV=y_6yKnHGWIma)%u}0-v)i3*kbn5!-yg5J<6UM2l~c!s}u+ofo#`q<3`%NJ>mz$^N6J^O8eJAD9PN zkDFROqdF^r%&NK4m94$?hk*D+p{aMPmBR}_N`E)yuiC&(=n4v2xQ$%22{g4o&3?_# zhf7JY8A8IjCxJN8GqVv%i|nLu3KG`=P9$u|Twe+spAFkkZ*uIU)5+l?yTjYwm?Jot zA``J8D%%mQCI&7ybwJl*!pD*)F4{+QX{bcJ!m3I`&*BLK$0p1_a;G74qUX~++KCSs z5TdyGxEonW4u`;cCspU(_FN+SCL#7wb;DD!kD5(_(&Hxy3E^5+T?SWWg&y2XU9p@7 zU6uXGRyb-cTaxbG$3IS>(3AmRLEdg$YTJ;buzRBzS<+nO-QhEs;TesRCF$-`XJos2 z;u9g|ioHgH_;ffFfM;ED&=)9V^k}u;&@={Dqv)VjEori5@w5aT#{{NXW=?& zY8erThZ2zu8`Z0j@pu;32StbNqdv&lrqL5dy)jk>)GO>^8Xx%Jek6xccF9c+JrL*h zx0KaO1yTQg0$>PwOOmCJN?%|Ij|Y>iSVVWWx}SIn5p1dgXt$BshZ^1CjsG?jN%J^f z*P5)ww1Ji7_6(Z7Z#q|+e`NFEe0&W)R zTAvvvl1+^*Q{sp#mTgT>DGNWRKn~wmoq5vB>-vdU3kHAt6C@wMw|nhDcA{2AdXwEL zOfOIB86Iw|(gi*$$vKZUlETeNdpet`!@8h{w?I-s*BZ6`Fp~k#d`ll$p3QtZ>@}-( zhO5~=R7_a%L_kaUH#zZuNj1OF`vm~w>-$z_qKRa6!Y1-cM3)rL%1b`9p5WZ!!acIqa z%OyejA1qx4`}>3!6TW?UruUKHyir1wULN}+S#xG5Nv^)?It1b!U&F>4MW{Q`;^+VT zh|!h61uXz(BlwcOvT!7w(UBC)*~w(|!3=v^7{Yn6`9GZ7if@k|K(NQ#l+h_EvZ6w8 z<`~8DWPwnd=?VO1a>ei=4-IffWy!waHTAQhD=gW5U3f1ZN`2idA@bxh@Zk-?pZ_Eo z)iHzzzxPV6S}6T{8o^IRN}J)UAE_QsO$-pi9YW%ch0{hOj7UP;KlT{5pjV8--3mDS zyPfriTUt+NIqm-+Hf@`zkbBx&JoNh91Dt zuUYe>SjbaEeE`>v*Je#mIQQxc&T{B8u>7+YqKz+qY}B3uOZxds_?2ppK!EQ4^Eczx zk#HD+z?n)ntLks7Gd&<}X%i(dWE=T~oCT{@rxpu{7Ha+{UM~|&b4!o(lgbaHq%6EY z+0GX&oaoli1P_tCD!jn6#XkNJ#i~4XmS1*8X;1+13pCYpI=%4C>mJ0kHa>6k9f)SJ ze-Ia7o5rn;CDV=!Kj+y&08C7JA>>;i=BY1|v1W~`sW&aSUw>2V_=!b8`nsjQ-MrB> zd%opPmbr-JJA69GpuqIns0O+lq{24GnU0SaPiOOi_ycAcIF@7c!Wg zpgy~tu`3D1f$3Mm$Q0P03LcGs+~IUIUB0xfuAuLbzwy*AMWJ38EOC~R2Pjs6uzkNZ zbG?Zv$y0(JL!go~yx@Tg+ZprtkE2M|5I)tKE-r1{jd!WwK>kr1pa#HWoF`BJ^>^kS z{{mH(J&-gMN`C%JfrYCraX6Q9Az82xh#}k`@wi3UqN#4e3r3R3^`VxS!~)ICObYHg z2Le~7vVxBDp`}(S{U<@euR?1l0*I4bKJnjl_uF)E{IZ(AKG>?Nm4=$vReF8v1h00r zijvgm=|riBtQ%uZMxZ`)_ZUSAF`Tb=6T7?d6)Uh}yKr!;ZO32I1pDU7(n_CrN6nsY z2=aQE_+=&EEj}lIxJ4?~0X}YnsEMVm*%)@8riksETAaTG<=i!d-wI*5P8`cixpkJ9 zpvd>Z&S=n$WvgT>Hk@}o(jX{1Ew}#RaHu+Fgxq=#i*8>+LvLTd2z1l2vT_pC!-M3X zO&AKE7?w7ggTxo9hvPV*$oNO(lBBH=IdSEK#4HC&X&5Axh@D&| zx%BzTvUCa8URt^QGa!A}iykd`6#`@^!LG)EOitVpv@1;*FJ^x$0O<)p6uK3}@)q)8 zz=xQ;d!+}z@JA8b4U7AF+`fq$U+5lKmv8i+V;2b85z2Wt8_YY@0X-BoQI&)AkZTVh z8+OtX@%dC7S@YhvhUX56l1%H-6lm;R)R`>9OMT0`VB6j;BqnOLMmOM!qYX>83M3lX zEBWNaU@`CUEzUcE4SWCbBTImXA*EAvcIm|vBYih-pRfHn)-O#}Js~)A9yltHzs7>m zuUpkA@J{Z@%Ff!cy(I)%TChq;)r%}h;{B07t0(dAoU>)vpf6Q6k=C08K>8X5s-82ZCKP{O$Hzn&% z=R$^|0u~sV@of`i3thSt|ZMcFtIb{^xTe&Oq{3}VhsNo|ys=yN#oN2t76)(8;Q=CEeMweVr1$ zGk*!}TwN+ZXS@4)rF~)=& z#-*Xr+9_cszH0EcHxBHEee@n+$pfSC$MhyY<13KJurN1G&oj)C?HzuBuiHxL?c_2V z!}!+yI#OG4@<((eT5|CVroC0XSlZR_x~L3Df(m_zQ@wDHJkmDp7457ep~jI&F02>6 z4qO_7WMQB46AiYeI)^8pt#e-Ft!mZ!lsrPwr7sQhb+u)w)o8Xltwufj@$@fUnyKk# zsAEA`T<#6?z#{zB&xHteIIj3>Ut^VHAOOyHWfjn6E9PD(8&5perJTcOw;cD(2D(i) zo|Q*=A7Bjh$%6h=m+V`(7zoRtq4pIqYk#YKt>ad74io?y-`u_lzU(7@2`;|q&C}wg zl#9HIbXMU0xPW$$MN5dhxE9U3*k1Ygizp%ZXd*rzdp;8s=5^`fPf4s$_fGG{hQ3S^ zSZ>t0pzujTTqP|>h&qkMa+Amlld3hcM>~QJ9EbR80VuL~v9;t2Zkcupv+c&gzpg~& z1|S(9M%<1lwWK2Zzs!vskDnRNo{O6!!JGFTEnt$lf{_cc(J*q;8wF!Kp>p}iNP1rj znX@zSY-d)(eSQW{aDFiNFL&kTp--yc%#vBaoa=0M}M_h_L+Efi?Ly0jcl5A7UcJ)d+a;V zFME^Wjm;swHIzq#-Y?lY%u-l zP-uE*%WE-%o`mw9_%ke-gs^iz=C_~YwCH{+1PvHkl%Ll*~a@Ss)bftR$n zM6kJPyFk@;?K+yyoB~~XPwIFQl9jOdz6ix~+G5qZwj~7hUI?;a`l=GDgA5iDnncsG z{cZeNI=b0@keVTqm^@he2CCYYVn@b3smaem5?Zj#ViN4{5x`ly4F_co>nIE zt^Y2LxV+;xyRpxrUxwRl;W1vSOLBFukcI(N>!a;BAk*FHGcqflcgp9-)x$yV4p#U; z1M=^-LQ-1JvAl>Fp7&@J?IlQ|XU=PSsWUqt6~Uot%f)qwD_`+wQM}Ig@+}cTd(qdKSG3cPqyp-ved`KM2`#|TtzGLXLMv7i z?en{*x9(rKZ=$#a9}r3OkZ*T4i-=D?9fRdD8M=J89u`9c6wZ@b(S;2SkTfK!4Lkv- zx(`@BhKihhm$$X$_xGw4vTT!=AT@`68ir+3H(lSuWA|^Fpu`tx&kQ>>K{)lj^L{ul z8qB{s%Qz4zWt`=0Y{x`9({wtDAG5Yh&CBJwa=ZtJq8&>3V{24_0#Ch&Z9zk&j#&Hy z_+5`Fmm#?a@^0(+SO3TqQceaXCp6)v{5&!Cl6SV^bR-6s$xkn)$m)X;zjj<Nwlo%cX*^4n5A+RA*7 z2E8GTXkkvCc1B_l2J|Ni^;#_1$@#vd3Ff29$1>NK&Cz$9(o8!@R~xlR;ce&A;J z_{u2q3n*l-ACgc!E(wz#W^Ai}jUDdRo8_YXt2&=(C0cew;ZEw0?|R-u(f89bHKGOB zE6Y?|75e(>&Bg;|jn-k=W|3s#l;&L`2&3m`#^2>wGEs$=gI-hmq@d{7W+rGlHOxg* z=|YtX;n!B^@gzZv3pSjVMk9l)1G)bQHgK%FD4YIHdIq@+I0<(v%y!LYs;`?$0SMT& ztCC02CPj>QPe+S@EeEsfW!C`ACduoxJCE$Q9lR-nT@bI+F8;|5Nq(VNoJpjpa!nC{ zzNJM~b)y?^15*@Vr-*QO*U20-E+Vp=+D?X?{bDIajY*V#!ntY}mH# z4GL_)df2z#)W-dTPl##JT6#DWQjD0g?y&k>v5)g~>m?~Xe5{RX3h^jN%3E$zfvEjH zmDvccD!*O)^|C7qQMkiIIMd^{B>IU&?jp-@DN{ED3az-W;%|PyQLKT82tXo`Q5c+F zKGs#n8ZTo!Bzf33-|4%^l)zHEWfUmw1z|W*jz3--3f-ux=ulTKN)lAVF4e)ZnASyg zq7xM_6jo7T$Jt^!bjz4!UQqq&D7G<>;x^v?3SM7oYNr9}SEQ!*e9BesfE5!_L!0DEysdTFRMqK+ zR+Hv6j~=fto&hW?Vy6OHo)yGWC4c!#Xx<~|PW&e5C+CgHWXs*f6P=DfNE0CZ*9|`` zq-*8d1Vlr(`!21H$+<*6e4;RGj|N#{v`ADD?BxvKg>Wy*5p=BUAa+( zOQr<0qFv6LWzzA@{aSXZIkO7EkLYdE;T1@)#wTXVlQ)i2X2U%3TjBtSz|%LRE#{e` zhX_+xHH#YgNqN$0SRf!YleaHdhS8w$bxbQ@cJA?yrT9POx+MB)J)%tT2nfjHW-^)^ zMNqw;3sG+XYE5Cv-;vRo!syvZOvm)dVD)f{g({2uoJ$9njo6EqO|aI&;FjzSXGhlY z^RlSt?3p#?^%4nBa)m0EyksHl|KvxNIio1d8Zm3G985kEz{^p4a&9H_jYU)w*Y|mT zidz)dK=l2~r;5OuD|)1-YXG*9F=a?Z^}hy+fBt;i1f7@zxECH#{SZoLEC9*r1s4&}8cMB{uPb(qSe2RIo*T1D)_F2Oz zeyoT9k2nuU_l`SbJvqMtV5kqu`M4&|9PKL6C`wCe46Mn%#9RD~c!$Any~2HulBzOMVvn<`MH-8qnj6Lq5XBG-@2Y$4Ik+09ab|$ zO5jZp#j+)bIUjZmZ_x-hhSzi`__e}(_x94+9#zx&E#k~;t(fjQhrHs^wc!cDVe!4b zty@oZ_|DgMYPR&|_Q-*Gq@4Pzi6!~gzXm~^ z7U7b$oCwoO-d|xeo2egSHD~R->baQUT|)w!dXNUX$Q_X3N(M9ToXkPCTYnLLgu{12 zU0GHN>1fYE&*~wOg67&p(QKURmm1u-a}0sx{8(0o!PVQQvWyviR9=NeOU?MTh=pi} z*A4}Ak@Mk3PNJoZ!6!y}E8!evhWkB#`zko@bGRJ-_6&n^R&@EPHJ7`P7BOQlldc2eES{1MMN2~XUlD5xJCu>&+Yot8`6U=)O z$3;klOkoDMvEQXKGk`g{H)f6P2`M0dm`GLG&3JK9pX3-4U`%O)f`pnpxtbM-IT_p* zDfld^hQu;}_oFt#x7E2zm_C7cxaET}7tN9m*yi`;pKOJ=iUwkK#+LIxJr%>SB~i7nxz? zMMiAkh;NTEX1>@hfBrhMndi83e1Y>-&`QVL%!5|wVy|CInca#(1{KeAyBIALE*EkKHB(_)rncY3xTA;u&_J_Abn$?c-#=N!x%8WQE< zRAdrG#$8j}{gJ`=16^G~LCjK!Im7-sTuWKTM{2o` z{`^DmifEok3* z8~w&-3zImPox(xhWTb@}9MJ@TS1M@RQ> z+!@V#tVu&2&C6oX>v)|=hW<%2RTkX2np7w0wZRiQ!V}q# z-R0w4omkF0_cZ80U29bkbWxDke7k{rHQ8GDuDPk>-k3X*;~8d~MO@e%_Qm&~TINW3 z&|EyDoSUs`lOJ}@nX%l)rgYV1qeG^hV>Mn&*#lNLe)j5HpSzN^-^R1SQUM!*Z3+$a zFM9+t{krlCw>}KL`Zg!Rfbt5YuboaI%Dbi&Z1s2?YN~s_LIhg!nIz4Z8xPDQaH0IF zk;vO(Td`)tTK_FS#oKv9XEatwvOyIklnW*6_b$e` zdKKpgD%fGTV%mu~GhnE99~xxmuOiQGX?qdsUd*A=)BHs?|1O;GUuPQjl2|=NhR{gJ zPnLIpQPU}_Doc#(wGUo=HM-O?~sOv??Gp6(%fk*{ze7<)jlmL?U!45V{?--2_{{Zm+9dkX6CAPPV} z0+at%mD76+C+Jq*3mhz@$O8xJVs1C|H8|$n6t??fh}35V*jPP#WG?s>xC3){0FcmX zKt8gGYKDYc;z>-dpCwiP{B+_EEAnkpJ96jpaeUKJn#GHDaF&nho8MWy7L@5%ApvxU_^EtBGhi7MO@LR`f%k4_*%;zXIs zIYkPu@j(_io9NwOz#IS~j*+b18d>CKtwWFN?p#NIx(*y|@ykz^g7I#BFRnV_<?395M7rLf&ug5lQ9ex z$=}SQ$9}u(RVl84n3_DvW0jhr*7UqDjXc@%%cb)L3c@q*CN-^?x%%R zrTJK-f3v6N=`p7$j6Q)Sv|soEX#~|j->*1$sAouj68YABy}!n?G;`O%stKh(`G8=I zCKDMR^M)n0>2Ym?B`PUPWRhlL)Uk{{)xM<=1*?ls5l4l{d^#da|LuA@d;fSXiuvPS ztR`!gVv0k-AQr*uW^f31XPKze0Y9Zo`EK5)7>f1IQ%3hcw70aTmdWp2s-xaDc9DU>K^NV$KxpeeUlUFNe zcaErDrhf=ZWZCJSfi0JpQdbv)+zoPHaBgm6JD0|-BU_>Sj#1jdXQ+Qn`6ot>tTe%- zu;3l;>kE<-$VQ>FDJgPzn+MXR;(qhCyK#(4^kM-;O3Bj-qr^;Wr&)BsMH=?hybO1B zgLz9vxU3$s@8!I*^l`cOUWqC0ys@nE$>V}&U`kguIzU(Kk~PHzy=7KT#hJbl+jr0R l!v8;6n*S$@E{M4e;p5L1-O=*+h;dj0RF$+8YhGK0{U6kFAS3_) diff --git a/plugins/lancedb/skills/lancedb/references/branch_ops.md b/plugins/lancedb/skills/lancedb/references/branch_ops.md deleted file mode 100644 index d79e5c8bc..000000000 --- a/plugins/lancedb/skills/lancedb/references/branch_ops.md +++ /dev/null @@ -1,16 +0,0 @@ -# Branch Operations - -Branches are isolated, writable lines of history forked from `main` by default (or from another branch/version via `create`'s `from_ref`/`from_version`). There is no global "switch branch" state: `branches.create(...)` / `branches.checkout(...)` return a **table handle scoped to that branch**, and every read/write on that handle lands on the branch while the original main handle is unaffected. Unpinned handles track the branch's latest version and are writable; `checkout(name, version=...)` pins the handle to that version and is read-only. - -Don't work from memory — read the public docs for the current API: - -- **Branching guide (concepts + Python/TypeScript examples):** — covers creating, writing to, reopening, and deleting branches; applying branch-tested changes back to main; diff/merge (Enterprise only); and building indexes on a branch. -- **How branches relate to versions and tags:** -- **Python API reference** (`Table.branches`, `Table.current_branch`, `Branches`/`AsyncBranches` with `list`/`create`/`checkout`/`delete`/`diff`/`merge`): -- **TypeScript API reference** (`Branches` class, same methods; `table.branches()` is async, `table.currentBranch()` returns `null` for main): - -Notes the docs may not state prominently: - -- Branch lifecycle works on local/OSS and remote Cloud/Enterprise tables; **merging into main is Enterprise-only** (others raise `NotSupported`). A rejected merge is not an exception — inspect the returned `status` and `diff.mergeBlockers`. -- To verify isolation after a branch write, read through both handles: the branch handle sees the change, the main handle must not. - diff --git a/plugins/lancedb/skills/lancedb/references/column_metadata.md b/plugins/lancedb/skills/lancedb/references/column_metadata.md deleted file mode 100644 index 2fe1c7c5d..000000000 --- a/plugins/lancedb/skills/lancedb/references/column_metadata.md +++ /dev/null @@ -1,183 +0,0 @@ -# Column Metadata Authoring - -Write column-level descriptions, tags, and logical groupings onto a LanceDB table's schema. Use this when the user wants to document, annotate, tag, or classify what their table columns ARE (embeddings vs labels vs eval metrics, model provenance, version families, etc.). - -Works on local/OSS and remote Enterprise/Cloud tables alike — read the schema through the table handle, write through `update_field_metadata` (Python) / `updateFieldMetadata` (TypeScript). - -## Metadata key conventions - -All metadata uses namespaced keys: - -| Key | Purpose | Example value | -|-----|---------|---------------| -| `lancedb:description` | Human-readable explanation of what the column contains | `"CLIP ViT-L/14 image embedding, L2-normalized (768-dim)"` | -| `lancedb:tag:` | Flexible key-value tag; the suffix names the tag category | `lancedb:tag:field_type: "embedding"`, `lancedb:tag:model: "clip"`, `lancedb:tag:project_id: "foo"` | -| `lancedb:logical-column` | Logical group/family this column belongs to | `"clip_features"` | - -Tags are open-ended — use whatever key suffix and value make sense given the user's intent. The tag suffix should describe *what is being classified* (e.g., `field_type`, `model`, `project_id`) and the value describes *how*. Multiple tags on the same column are fine — each is a separate key. All values are strings. - -## Step 1: Read the schema and existing metadata - -Read existing metadata before writing, to avoid redundant updates. - -Python — `table.schema` (sync property; async: `await table.schema()`) returns a `pyarrow.Schema`. **Arrow field metadata is bytes-keyed in Python**: - -```python -schema = table.schema -for field in schema: - meta = field.metadata or {} # dict[bytes, bytes], e.g. {b"lancedb:description": b"..."} - print(field.name, field.type, field.nullable, meta) -``` - -TypeScript — `await table.schema()` returns an Arrow `Schema`; field metadata is a `Map`: - -```typescript -const schema = await table.schema(); -for (const field of schema.fields) { - console.log(field.name, field.type, field.nullable, field.metadata); // Map - // field.metadata.get("lancedb:description") -} -``` - -For struct/nested fields, recurse into the field's children and address them as dot-paths (e.g., `parent.child`). - -If the user hasn't specified which columns to update, work with all columns. - -## Step 2: Generate metadata - -Decide what to generate based on the user's request. - -### Descriptions (`lancedb:description`) - -Base descriptions on: -- The column name and Arrow type (e.g., `FixedSizeList` of floats → likely an embedding) -- User-supplied context (upstream pipeline, sample values, domain knowledge) -- Name patterns: `_embedding`/`_vec`/`_embed` → vector; `_label`/`_class` → label; `_score`/`_eval`/`_metric` → evaluation metric - -Be specific and concise. Good: `"Sentence-BERT embedding of the query text (768-dim)."` Not: `"An embedding column."` - -### Tags (`lancedb:tag:`) - -Choose tag key names that match what the user asked to annotate. Common patterns: - -- Semantic field type → `lancedb:tag:field_type: "embedding"` / `"text"` / `"image"` / `"label"` / `"eval"` / `"id"` / `"metadata"` -- Model or source → `lancedb:tag:model: "clip"` / `"bert"` / `"vit"` -- Project affiliation → `lancedb:tag:project_id: ""` -- Version → `lancedb:tag:version: "v3"` (and `lancedb:tag:latest: "true"` for the newest) - -Use Arrow type as a hint: `FixedSizeList` + float → embedding; `Utf8`/`LargeUtf8` → text; `Binary` → image or blob. - -### Logical groupings (`lancedb:logical-column`) - -Look for naming patterns across columns: -- `clip_v1`, `clip_v2`, `clip_v3` → logical column `"clip"`, latest is `v3` -- `text_embed_20240101`, `text_embed_20240601` → logical column `"text_embed"`, latest is the most recent date suffix - -Write `lancedb:logical-column` on all members of a group. Mark the newest with `lancedb:tag:latest: "true"` (in addition to its version tag). - -## Step 3: Write the metadata - -Each update names a field by dot-path and carries a metadata map. Semantics (identical in both SDKs): - -- **Merge by default** (`replace` omitted/false) — preserves existing metadata the user didn't ask to change -- `replace: true` swaps the field's entire metadata map — only if the user explicitly asks to overwrite -- A value of `None`/`null` deletes that specific key -- Batch all field updates into a single call when possible -- Returns the new table version - -Python (sync and async take one dict per field, as varargs): - -```python -res = table.update_field_metadata( - { - "path": "clip_v3", - "metadata": { - "lancedb:description": "CLIP ViT-L/14 image embedding, L2-normalized (1024-dim).", - "lancedb:tag:field_type": "embedding", - "lancedb:tag:model": "clip", - "lancedb:tag:version": "v3", - "lancedb:tag:latest": "true", - "lancedb:logical-column": "clip", - }, - }, - { - "path": "clip_v2", - "metadata": { - "lancedb:description": "CLIP ViT-B/32 image embedding (768-dim), superseded by v3.", - "lancedb:tag:field_type": "embedding", - "lancedb:tag:model": "clip", - "lancedb:tag:version": "v2", - "lancedb:logical-column": "clip", - }, - }, -) -print(res.version) # new table version - -# merge semantics: add a key, delete one via None, keep the rest -table.update_field_metadata( - {"path": "clip_v2", "metadata": {"lancedb:tag:archived": "true", "lancedb:tag:latest": None}} -) -``` - -(`replace_field_metadata` is deprecated — use `update_field_metadata`.) - -TypeScript (takes an array of `FieldMetadataUpdate`): - -```typescript -const res = await table.updateFieldMetadata([ - { - path: "clip_v3", - metadata: { - "lancedb:description": "CLIP ViT-L/14 image embedding, L2-normalized (1024-dim).", - "lancedb:tag:field_type": "embedding", - "lancedb:tag:model": "clip", - "lancedb:tag:version": "v3", - "lancedb:tag:latest": "true", - "lancedb:logical-column": "clip", - }, - }, - { - path: "clip_v2", - metadata: { - "lancedb:description": "CLIP ViT-B/32 image embedding (768-dim), superseded by v3.", - "lancedb:tag:field_type": "embedding", - "lancedb:tag:model": "clip", - "lancedb:tag:version": "v2", - "lancedb:logical-column": "clip", - }, - }, -]); -console.log(res.version); // new table version - -// merge semantics: add a key, delete one via null, keep the rest -await table.updateFieldMetadata([ - { path: "clip_v2", metadata: { "lancedb:tag:archived": "true", "lancedb:tag:latest": null } }, -]); -``` - -## Step 4: Confirm - -Report back: -- Which columns were updated and what was written -- The new table version number (from the result) -- Any columns skipped (e.g., already had up-to-date metadata) - -## Quick examples - -**"Write descriptions for all columns in the `product_embeddings` table"** -1. Read `table.schema` → all fields + existing metadata -2. Generate a `lancedb:description` for each column based on name + type -3. One `update_field_metadata` call with all descriptions -4. Report - -**"Tag the columns in `model_outputs` with their field type and model"** -1. Read the schema -2. For each field, classify by name + Arrow type → set `lancedb:tag:field_type` and `lancedb:tag:model` where applicable -3. Write in one batched call -4. Report - -**"Group the feature columns in `training_features` into logical families and mark the latest version"** -1. Read the schema -2. Find version patterns → assign `lancedb:logical-column` and `lancedb:tag:version`; mark newest with `lancedb:tag:latest: "true"` -3. Write in one batched call -4. Show the grouping diff --git a/plugins/lancedb/skills/lancedb/references/remote_connect.md b/plugins/lancedb/skills/lancedb/references/remote_connect.md deleted file mode 100644 index 670242c94..000000000 --- a/plugins/lancedb/skills/lancedb/references/remote_connect.md +++ /dev/null @@ -1,45 +0,0 @@ -# Connecting to a LanceDB remote server - -LanceDB Enterprise/Cloud deployments are served by a server implementing the -lance-namespace OpenAPI spec -(). -Every remote (`db://...`) connection talks to such a server, and some operations -exist only there. In particular, all operations around jobs (listing, inspecting, -creating, or canceling jobs) run server-side — there is no local/OSS equivalent, so -resolve a server connection before attempting any job work. The job REST methods -themselves are documented in `references/remote_jobs.md`. - -Every request needs two things: - -1. **Base URL** — the server endpoint -2. **Credentials** — an API key (`x-api-key` header over REST), and usually a database name (`x-lancedb-database` header) - -## Resolution steps - -1. If the user already gave a URL and API key (or said which environment they're working against), use that. -2. Otherwise, look for credentials already available in the environment: - - Env vars like `LANCEDB_URI` / `LANCEDB_HOST` / `LANCEDB_API_KEY` - - A server endpoint already running or port-forwarded locally (the REST default port is 2333, i.e. `http://localhost:2333`) -3. If you didn't find both pieces, ask the user directly: **"What's your LanceDB endpoint's URL, and what's your API key?"** Also ask which database to use if it isn't obvious. Don't guess or probe further — the user knows their deployment. - -## Validating the connection - -Make a cheap authenticated request and check the status before starting real work: - -```bash -curl -s -w "\n%{http_code}" "{base_url}/v1/table/?limit=1" \ - -H "x-api-key: " \ - -H "x-lancedb-database: " -``` - -- `200` — connection, key, and database header all good -- `401` — API key missing or wrong -- `400` mentioning a database header — this deployment expects `x-lancedb-database` - -## Non-REST equivalents - -The same credentials work through the SDKs and CLI: - -- Python SDK: `lancedb.connect("db://", api_key="", host_override="")` -- TypeScript SDK: `await lancedb.connect("db://", { apiKey: "", hostOverride: "" })` -- `lancedb` CLI: a `[profiles.]` entry in `~/.lancedb/config.toml` with `http_server_url`, `api_key`, `database` diff --git a/plugins/lancedb/skills/lancedb/references/remote_jobs.md b/plugins/lancedb/skills/lancedb/references/remote_jobs.md deleted file mode 100644 index 175f0ce51..000000000 --- a/plugins/lancedb/skills/lancedb/references/remote_jobs.md +++ /dev/null @@ -1,151 +0,0 @@ -# Job operations over the LanceDB remote server REST API - -Jobs are server-side background operations on LanceDB Enterprise/Cloud — index builds, -column backfills, materialized view refreshes, and similar async work. Endpoints that -trigger async work (e.g. the column backfill or materialized view refresh endpoints) -return a `job_id`; these four methods are how you track and manage those jobs. - -Resolve the connection first — see `references/remote_connect.md`. All four methods -are **POST** requests under `{base_url}/v1/jobs/` with JSON bodies, and take the usual -`x-api-key` / `x-lancedb-database` headers. If every job call returns `501`, job APIs -are disabled on that deployment (the server has no job registry configured) — report -that rather than retrying. - -## 1. List jobs — `POST /v1/jobs/list` - -The body is optional; an empty body lists everything. All fields are filters: - -```json -{ - "limit": 100, - "table_name": "my_table", - "job_type": "...", - "job_subtype": "...", - "state": "...", - "page_token": "..." -} -``` - -```bash -curl -s -X POST "{base_url}/v1/jobs/list" \ - -H "x-api-key: " -H "x-lancedb-database: " \ - -H "content-type: application/json" \ - -d '{"table_name": "my_table"}' -``` - -Response: - -```json -{ - "jobs": [ - { - "job_id": "...", - "table": "my_table", - "job_type": "...", - "job_subtype": "...", - "state": "done", - "created_at_millis": 1720000000000 - } - ], - "page_token": "..." -} -``` - -A `page_token` in the response means there are more results — pass it back in the next -request to continue. Note list rows use a lowercase `state` string, while describe uses -an uppercase `job_state`. - -## 2. Describe a job — `POST /v1/jobs/describe` - -Body: `{"job_id": ""}`. Returns full detail for one job: - -```json -{ - "job_id": "...", - "job_type": "...", - "job_subtype": "...", - "job_state": "IN_PROGRESS", - "creation_ms": 1720000000000, - "spec": {}, - "status": {} -} -``` - -`job_state` is one of `IN_PROGRESS`, `CANCELLED`, `FAILED`, `DONE`. `spec` and `status` -are job-type-specific JSON objects (the job's input specification and its current -progress/status). Returns `404` for an unknown job id. - -## 3. Cancel a job — `POST /v1/jobs/cancel` - -Body: `{"job_id": ""}`; response echoes `{"job_id": ""}`. Cancellation is a -service-level operation requiring the same administrative authorization as the -`/admin` routes — a database-scoped API key that can list and describe jobs may still -get a permission error here. Other errors: `404` unknown job, `409` state conflict -(e.g. already in a terminal state), `429` too much write contention (safe to retry). - -## 4. Query job event history — `POST /v1/jobs/query_events` - -Returns the event history (state transitions, progress updates) for one or more jobs. -Body: `{"job_id": ""}` for one job, or `{"job_ids": ["", ...]}` for a batch. -Optional fields: `limit` (max event rows), `limit_per_job` (per job in a batch query), -and `filter` — a SQL-like expression over the columns `state`, `updated_by`, -`owner_component`, and `claim_entity`. (`full_text_search` is reserved and currently -rejected as not implemented.) - -The response is **not JSON** — it is an Arrow IPC stream -(`content-type: application/vnd.apache.arrow.stream`). Decode it, e.g. in Python: - -```python -import pyarrow.ipc -import requests - -resp = requests.post( - f"{base_url}/v1/jobs/query_events", - headers={"x-api-key": key, "x-lancedb-database": database}, - json={"job_id": job_id}, -) -resp.raise_for_status() -events = pyarrow.ipc.open_stream(resp.content).read_all() -``` - -## Feature engineering (Geneva) jobs - -Feature engineering jobs — UDF column backfills and materialized view refreshes run -through Geneva — are tracked **separately** from the `/v1/jobs` registry above. Their -records live in a `geneva_jobs` table inside the database itself (in the `__system` -namespace), and you access them through a Python `geneva` connection rather than the -REST endpoints above: - -```python -import geneva -from geneva.jobs import JobStateManager - -# Same credentials as lancedb.connect / the REST API -conn = geneva.connect("db://", api_key="", host_override="") -jsm = JobStateManager(conn) - -# List jobs. NOTE: status defaults to "RUNNING"; pass status=None for all jobs. -# Statuses: PENDING | RUNNING | DONE | FAILED | CANCELLED -jobs = jsm.list_jobs(table_name="my_table", status=None) - -# Fetch one job by id (returns a list of JobRecord) -records = jsm.get("") -``` - -Each `JobRecord` has `table_name`, `column_name`, `job_id`, `job_type`, `status`, -`launched_at`, `completed_at`, `config`, `launched_by`, `manifest_id`, `cluster_name`, -`metrics` (progress counters), `events` (human-readable history), and `updated_at`. -For filters `list_jobs` doesn't support (e.g. time ranges), query the underlying table -directly: `jsm.get_table(True).search().where("launched_at >= TIMESTAMP '...'")` — -pass `True` to check out the latest version, since other processes update job state. - -Stale-status caveat: nothing reaps dead Geneva jobs, so a job can sit in -`RUNNING`/`PENDING` forever if its worker died. Treat a job as effectively `FAILED` -when it has been running longer than ~36 hours, or its `updated_at` is more than ~2 -hours old (this matches the heuristic the Geneva console UI applies on read). - -## Workflow tips - -- To wait for async work (a backfill, an index build), poll `describe` until - `job_state` leaves `IN_PROGRESS`; on `FAILED`, pull `status` and `query_events` for - the failure detail. diff --git a/plugins/lancedb/skills/lancedb/scripts/check_materialization.py b/plugins/lancedb/skills/lancedb/scripts/check_materialization.py deleted file mode 100644 index 6b0f117a1..000000000 --- a/plugins/lancedb/skills/lancedb/scripts/check_materialization.py +++ /dev/null @@ -1,137 +0,0 @@ -#!/usr/bin/env python3 -"""Scan Python and TypeScript for likely unsafe LanceDB materialization.""" - -from __future__ import annotations - -import argparse -import re -import sys -from dataclasses import dataclass -from pathlib import Path - - -PY_FULL_TABLE = re.compile(r"\b\w+\.(to_pandas|to_arrow|to_polars)\s*\(") -TS_TABLE_TO_ARROW = re.compile(r"\b\w+\.toArrow\s*\(") -TS_QUERY_COLLECTOR = re.compile(r"\.query\s*\(\s*\)[\s\S]*?\.to(Array|Arrow)\s*\(") - - -@dataclass -class Finding: - path: Path - line: int - message: str - text: str - - -def iter_files(paths: list[Path]) -> list[Path]: - files: list[Path] = [] - for path in paths: - if path.is_dir(): - files.extend( - p - for p in path.rglob("*") - if p.suffix in {".py", ".ts", ".tsx"} and "node_modules" not in p.parts - ) - elif path.suffix in {".py", ".ts", ".tsx"}: - files.append(path) - return sorted(set(files)) - - -def line_number(text: str, offset: int) -> int: - return text.count("\n", 0, offset) + 1 - - -def scan_python(path: Path, text: str) -> list[Finding]: - findings: list[Finding] = [] - for match in PY_FULL_TABLE.finditer(text): - line_start = text.rfind("\n", 0, match.start()) + 1 - line_end = text.find("\n", match.start()) - if line_end == -1: - line_end = len(text) - line = text[line_start:line_end].strip() - if ".search(" in line or ".query(" in line: - continue - findings.append( - Finding( - path, - line_number(text, match.start()), - f"Review Python `{match.group(1)}()` call; table-level materialization is not portable to remote tables.", - line, - ) - ) - return findings - - -def statement_around(text: str, start: int, end: int) -> str: - before = max(text.rfind(";", 0, start), text.rfind("\n\n", 0, start)) - after_candidates = [ - pos for pos in (text.find(";", end), text.find("\n\n", end)) if pos != -1 - ] - after = min(after_candidates) if after_candidates else len(text) - return text[before + 1 : after].strip() - - -def scan_typescript(path: Path, text: str) -> list[Finding]: - findings: list[Finding] = [] - for match in TS_TABLE_TO_ARROW.finditer(text): - stmt = statement_around(text, match.start(), match.end()) - if ".query(" in stmt or ".search(" in stmt: - continue - findings.append( - Finding( - path, - line_number(text, match.start()), - "Review TypeScript `table.toArrow()`-style call; table-level materialization is not portable for large/remote tables.", - stmt.splitlines()[0].strip(), - ) - ) - - for match in TS_QUERY_COLLECTOR.finditer(text): - stmt = statement_around(text, match.start(), match.end()) - if ".limit(" in stmt: - continue - findings.append( - Finding( - path, - line_number(text, match.start()), - "Review unbounded TypeScript query collection; add `limit()` or stream batches.", - stmt.splitlines()[0].strip(), - ) - ) - return findings - - -def scan_file(path: Path) -> list[Finding]: - text = path.read_text(encoding="utf-8", errors="replace") - if path.suffix == ".py": - return scan_python(path, text) - if path.suffix in {".ts", ".tsx"}: - return scan_typescript(path, text) - return [] - - -def main() -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("paths", nargs="+", type=Path) - parser.add_argument( - "--no-fail", action="store_true", help="Always exit 0 after reporting findings." - ) - args = parser.parse_args() - - findings: list[Finding] = [] - for path in iter_files(args.paths): - findings.extend(scan_file(path)) - - for finding in findings: - print(f"{finding.path}:{finding.line}: {finding.message}") - print(f" {finding.text}") - - if findings: - print( - f"\n{len(findings)} finding(s). Review manually; bounded query result conversion may be OK." - ) - return 0 if args.no_fail or not findings else 1 - - -if __name__ == "__main__": - sys.exit(main()) From ecf4555cfde8103c143349bb27a6dd5813e3b674 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 22 Aug 2026 00:53:28 +0800 Subject: [PATCH 077/206] fix(remote): fence refresh submissions after add_columns (#4007) A remote backfill submission validates its target column against a table snapshot, but it did not carry the existing read-after-write freshness headers. Immediately after `add_columns`, a stale query node could therefore reject the newly committed column. Route backfill submission through the remote table read fence so it carries the version returned by the preceding write. The shared remote submission path gives synchronous and asynchronous client surfaces the same freshness guarantee. --- rust/lancedb/src/remote/table.rs | 42 ++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 1e5691554..14b869d90 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2866,8 +2866,7 @@ impl BaseTable for RemoteTable { let mut body = serde_json::json!({ "column": column }); self.apply_branch_body(&mut body); let request = self - .client - .post(&format!("/v1/table/{}/backfill_column", self.identifier)) + .post_read(&format!("/v1/table/{}/backfill_column", self.identifier)) .json(&body); let (request_id, response) = self.send(request, true).await?; let response = self.check_table_response(&request_id, response).await?; @@ -6823,6 +6822,45 @@ mod tests { ); } + #[tokio::test] + async fn test_refresh_submission_uses_add_columns_version_fence() { + let table = Table::new_with_handler("my_table", |request| match request.url().path() { + "/v1/table/my_table/describe/" => simple_describe_response(), + "/v1/table/my_table/add_columns/" => http::Response::builder() + .status(200) + .body(r#"{"version": 7}"#.to_string()) + .unwrap(), + "/v1/table/my_table/backfill_column" => { + let min_version = request + .headers() + .get("x-lancedb-min-version") + .and_then(|value| value.to_str().ok()); + if min_version != Some("7") { + return http::Response::builder() + .status(400) + .body(r#"{"error":"Column not found: doubled"}"#.to_string()) + .unwrap(); + } + http::Response::builder() + .status(202) + .body(r#"{"job_id": "j-43"}"#.to_string()) + .unwrap() + } + path => panic!("unexpected request: {path}"), + }); + + let result = table + .add_columns() + .computed("doubled", "a * 2") + .execute() + .await + .unwrap(); + assert_eq!(result.version, 7); + + let job = table.refresh_column_async("doubled").await.unwrap(); + assert_eq!(job.id(), Some("j-43")); + } + /// The gate's reproducer: after a successful wait, a same-handle read /// must carry a freshness baseline so a stale server cache cannot serve /// the pre-backfill snapshot. From 1baada89ef8809cccc45b1dc6360713d28f0db9a Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sat, 22 Aug 2026 02:01:45 +0800 Subject: [PATCH 078/206] feat(python): bind function versions to columns (#4012) A registered `FunctionVersion` has an exact identity and grouped output contract, but the Python SDK cannot currently bind it to table columns without manually constructing wire models. Calling a `FunctionVersion` with named `col(...)` references now returns one immutable `FunctionApplication` pinned to that exact version. The application preserves named-struct outputs as one sibling group, while `rename(columns=...)` defines the result-field to table-column mapping consumed by `Table.add_columns`. Derived expressions and incomplete or unknown input names fail before declaration. --- python/python/lancedb/expr.py | 5 +- python/python/lancedb/functions.py | 68 +++++++++++++++- .../tests/test_first_class_function_slice1.py | 78 +++++++++++++++++++ 3 files changed, 148 insertions(+), 3 deletions(-) diff --git a/python/python/lancedb/expr.py b/python/python/lancedb/expr.py index e8b2d63a4..d16ba95d7 100644 --- a/python/python/lancedb/expr.py +++ b/python/python/lancedb/expr.py @@ -85,8 +85,9 @@ class Expr: # for dict keys / set membership. __hash__ = None # type: ignore[assignment] - def __init__(self, inner: PyExpr) -> None: + def __init__(self, inner: PyExpr, *, column_path: str | None = None) -> None: self._inner = inner + self._column_path = column_path # ── comparisons ────────────────────────────────────────────────────────── @@ -273,7 +274,7 @@ def col(name: str) -> Expr: >>> col("age") > lit(18) Expr((age > 18)) """ - return Expr(expr_col(name)) + return Expr(expr_col(name), column_path=name) def lit(value: Union[bool, int, float, str, bytes, date, datetime, Decimal]) -> Expr: diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 1613e03b4..3b2d05951 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -20,6 +20,7 @@ import re import sys import textwrap import types +import uuid from collections.abc import Mapping from datetime import date, datetime from typing import ( @@ -265,6 +266,64 @@ class FunctionVersion(_RemoteValue): required_secrets: tuple[str, ...] = () created_at: str + def __call__(self, **inputs: Any) -> FunctionApplication: + """Bind this exact version to named table columns. + + Every input must be a direct [lancedb.col][lancedb.expr.col] + reference. The returned application is immutable and retains a + named-struct output as one sibling group, so every row's sibling values + come from one logical Function evaluation. Map result fields to table + columns with + [FunctionApplication.rename][lancedb.functions.FunctionApplication.rename], + then pass the application to + [Table.add_columns][lancedb.table.Table.add_columns]. + + Examples + -------- + >>> from lancedb import col + >>> application = function( + ... title=col("title"), + ... body=col("body"), + ... ).rename(columns={ + ... "normalized_text": "search_text", + ... "token_count": "search_token_count", + ... }) + >>> table.add_columns(application) # doctest: +SKIP + """ + from lancedb.expr import Expr + + parameters = tuple(parameter.name for parameter in self.signature.inputs) + missing = [parameter for parameter in parameters if parameter not in inputs] + unknown = sorted(set(inputs) - set(parameters)) + if missing or unknown: + details = [] + if missing: + details.append(f"missing inputs: {missing!r}") + if unknown: + details.append(f"unknown inputs: {unknown!r}") + raise TypeError("invalid Function inputs (" + "; ".join(details) + ")") + + bindings = [] + for parameter in parameters: + value = inputs[parameter] + if not isinstance(value, Expr) or value._column_path is None: + raise TypeError( + f"Function input {parameter!r} must be a direct col(...) reference" + ) + bindings.append( + ApplicationInput( + parameter=parameter, + kind="column", + value={"path": value._column_path}, + ) + ) + return FunctionApplication( + function=FunctionVersionRef(name=self.name, version=self.version), + inputs=tuple(bindings), + output=self.signature.output, + group_id=f"fg_{uuid.uuid4().hex}", + ) + class FunctionRegistrationRequest(_RemoteValue): """Stable remote registration envelope produced by :func:`udf`. @@ -304,7 +363,14 @@ class ApplicationInput(_OpenRemoteValue): class FunctionApplication(_OpenRemoteValue): - """Immutable pre-declaration application of an exact Function version.""" + """Immutable pre-declaration application of an exact Function version. + + A named-struct output remains one grouped application through table + declaration and execution. + [FunctionApplication.rename][lancedb.functions.FunctionApplication.rename] + records the result-field to table-column mapping without splitting sibling + outputs into separate UDF calls. + """ function: FunctionVersionRef inputs: tuple[ApplicationInput, ...] diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index fead28bc8..1bb8feaf4 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -6,6 +6,7 @@ from pathlib import Path import pytest +from lancedb import col import lancedb.functions as functions from lancedb.functions import ( FunctionApplication, @@ -120,6 +121,83 @@ def test_function_version_identity_is_immutable_and_exact(): assert FunctionVersion(**changed) != version +def test_function_version_binds_named_columns_as_one_immutable_group(): + version = FunctionVersion.from_json( + json.dumps(job_result("remote_function_job.json")) + ) + + application = version(text=col("documents.body")) + + assert application.function.name == version.name + assert application.function.version == version.version + assert application.output is version.signature.output + assert application.group_id.startswith("fg_") + assert [ + (value.parameter, value.kind, value.value["path"]) + for value in application.inputs + ] == [("text", "column", "documents.body")] + with pytest.raises((TypeError, ValueError)): + application.group_id = "fg_changed" + + +def test_function_version_binding_validates_names_and_direct_columns(): + version = FunctionVersion.from_json( + json.dumps(job_result("remote_function_job.json")) + ) + + with pytest.raises(TypeError, match=r"missing inputs: \['text'\]"): + version() + with pytest.raises(TypeError, match=r"unknown inputs: \['body'\]"): + version(text=col("text"), body=col("body")) + with pytest.raises(TypeError, match="direct col"): + version(text=col("text").lower()) + + +def test_function_version_keeps_named_struct_outputs_in_one_application(): + value = job_result("remote_function_job.json") + value["name"] = "text_features" + value["version"] = "fv_grouped" + value["signature"] = { + "inputs": [ + {"name": "title", "arrow_type": "utf8", "nullable": True}, + {"name": "body", "arrow_type": "utf8", "nullable": True}, + ], + "output": { + "kind": "named_struct", + "fields": [ + { + "name": "normalized_text", + "arrow_type": "utf8", + "nullable": False, + }, + { + "name": "token_count", + "arrow_type": "int64", + "nullable": False, + }, + ], + }, + } + version = FunctionVersion(**value) + + application = version(body=col("body"), title=col("title")).rename( + columns={ + "normalized_text": "search_text", + "token_count": "search_token_count", + } + ) + + assert [value.parameter for value in application.inputs] == ["title", "body"] + assert [field.name for field in application.output.fields] == [ + "normalized_text", + "token_count", + ] + assert dict(application.columns) == { + "normalized_text": "search_text", + "token_count": "search_token_count", + } + + def test_unknown_fields_and_discriminators_are_forward_decodable(): value = job_result("remote_function_job.json") value["future_version_metadata"] = {"retention_class": "catalog"} From f39a7a4dd9f788624f4f1e099f4a4d7765d8702d Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Fri, 21 Aug 2026 13:45:39 -0700 Subject: [PATCH 079/206] feat: support remote tables in the data loader (#3981) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `StreamingDataset`, `PermutationBuilder`, and `Permutation` now work against a `RemoteTable` (LanceDB Cloud and Enterprise), which unblocks benchmarking the loader against the enterprise cluster cache. ```python db = lancedb.connect("db://my-db", api_key=..., host_override=...) ds = StreamingDataset(db.open_table("training"), world_size=8, rank=r) ``` Rows are addressed by `_rowid` exactly as before — `PermutationReader::load_batch` already built the same `_rowid IN (...)` filter that `Table::take_row_ids` sends, so the loader's fetch was always the take path. It just was never allowed to run. ### The guard `PermutationBuilder.__init__` rejected anything without `_inner`, so a `RemoteTable` raised `TypeError` before reaching the PyO3 layer — which already unwraps one via `_table._inner`. ### A bounded schema lookup `PermutationReader::output_schema` reads the schema off a query plan, and building a plan on a remote table *executes* the query (`create_plan` → `execute_query`). With no limit that is `k = isize::MAX`, so asking a remote table for its output schema pulled the whole table over HTTP and threw it away — once per assigned split, on every epoch, since `StreamingDataset.__iter__` constructs a `Permutation` per split. One row rather than zero, deliberately: lance gates its limit node on `self.limit.unwrap_or(0) > 0`, so `Some(0)` means *no limit*. ### Tables with an LSM write spec are refused A permutation references rows by row id, and rows that have not been flushed to the base table do not have one yet. The loader could read around them, but they would then be missing from training with nothing said about it, so the build refuses such a table up front instead of half supporting it. ### Fallible identity construction `PermutationReader::identity` resolved `inner_new` with `unwrap`. That was near total against a local dataset, but construction counts the base table — an HTTP round trip for a remote one — so a transient network or auth failure became a panic across the PyO3 boundary. ### Tests End-to-end `permutation_builder` and `StreamingDataset` runs against a mock server, the former torch-free so it runs wherever the suite does, plus a test that a build succeeds without an LSM write spec and is refused once one is installed. --- python/python/lancedb/permutation.py | 18 +- .../python/tests/test_elastic_dataloader.py | 29 +++ python/python/tests/test_permutation.py | 59 +++++ python/python/tests/utils.py | 206 ++++++++++++++++++ python/src/permutation.rs | 4 +- .../src/dataloader/permutation/builder.rs | 104 ++++++++- .../src/dataloader/permutation/reader.rs | 22 +- rust/lancedb/src/remote/table.rs | 13 ++ rust/lancedb/src/table.rs | 13 ++ 9 files changed, 441 insertions(+), 27 deletions(-) diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index bcf84bf3a..5d7a685ef 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -41,21 +41,15 @@ class PermutationBuilder: The permutation is stored in memory and will be lost when the program exits. """ - def __init__(self, table: LanceTable): + def __init__(self, table: Table): """ Creates a new permutation builder for the given table. By default, the permutation builder will create a single split that contains all rows in the same order as the base table. + + Tables with an LSM write spec are rejected: unflushed rows have no row id. """ - if not hasattr(table, "_inner"): - raise TypeError( - f"PermutationBuilder requires a local LanceTable, " - f"got {type(table).__name__}. " - "The permutation API is not supported on remote tables. " - "Remote tables connect to LanceDB Cloud or Enterprise and do not have " - "direct access to the underlying Lance dataset needed for permutations." - ) self._async = async_permutation_builder(table) def split_random( @@ -231,7 +225,7 @@ class PermutationBuilder: return LOOP.run(do_execute()) -def permutation_builder(table: LanceTable) -> PermutationBuilder: +def permutation_builder(table: Table) -> PermutationBuilder: return PermutationBuilder(table) @@ -248,7 +242,7 @@ class Permutations: Attributes ---------- - base_table: LanceTable + base_table: Table The base table that the permutations are based on. permutation_table: LanceTable The permutation table that defines the splits. @@ -282,7 +276,7 @@ class Permutations: {'train': 0, 'test': 1} """ - def __init__(self, base_table: LanceTable, permutation_table: LanceTable): + def __init__(self, base_table: Table, permutation_table: LanceTable): self.base_table = base_table self.permutation_table = permutation_table diff --git a/python/python/tests/test_elastic_dataloader.py b/python/python/tests/test_elastic_dataloader.py index 734f835c6..0c1a70765 100644 --- a/python/python/tests/test_elastic_dataloader.py +++ b/python/python/tests/test_elastic_dataloader.py @@ -37,6 +37,11 @@ from unittest.mock import patch import lancedb import pyarrow as pa import pytest +from utils import ( + MockPermutationServer, + assert_server_safe_row_id_requests, + mock_remote_table, +) torch = pytest.importorskip("torch") streaming = pytest.importorskip("lancedb.streaming") @@ -2118,3 +2123,27 @@ def test_doc_example_checkpoint(lance_table): assert sorted(consumed + remaining_original) == list(range(NUM_ROWS)), ( "Consumed + remaining must cover every row exactly once" ) + + +# --------------------------------------------------------------------------- +# Remote tables (LanceDB Cloud / Enterprise) +# --------------------------------------------------------------------------- + + +def test_streaming_dataset_over_remote_table(): + """StreamingDataset reads a remote table, with server-safe requests. + + Builds a permutation over a remote table, then fetches batches from it by row id. + """ + server = MockPermutationServer() + + with mock_remote_table(server) as table: + ds = StreamingDataset(table, num_splits=2, shuffle_seed=SHUFFLE_SEED) + ids = [row["id"] for row in ds] + + assert sorted(ids) == list(range(server.num_rows)), ( + "Every row of the remote table must be yielded exactly once" + ) + assert len(server.scans) == 1, "the permutation is built with one row-id scan" + assert server.takes, "rows must be fetched with row-id takes" + assert_server_safe_row_id_requests(server) diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 6d8f6f431..135742c84 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -8,6 +8,11 @@ import pytest from lancedb import DBConnection, Table, connect from lancedb.background_loop import LOOP from lancedb.permutation import Permutation, Permutations, permutation_builder +from utils import ( + MockPermutationServer, + assert_server_safe_row_id_requests, + mock_remote_table, +) def test_split_random_ratios(mem_db): @@ -1214,3 +1219,57 @@ def test_remove_rowid_after_select(some_permutation: Permutation): perm_without_rowid = perm_with_rowid.remove_columns(["_rowid"]) assert "_rowid" not in perm_without_rowid.column_names assert perm_without_rowid.column_names == ["id"] + + +def test_permutation_is_stable_when_remote_scan_order_varies(): + """Splits are assigned by scan position, and every rank builds its own + permutation, so two ranks seeing different scan orders must still agree.""" + server = MockPermutationServer(num_rows=16, vary_scan_order=True) + + def split_of_each_row(permutation_tbl): + # Sequential splits are assigned by position, so a reversed scan would put + # the last rows in split 0. Compare the mapping rather than the table order, + # which the split-id sort does not pin down. + rows = permutation_tbl.search(None).to_arrow().to_pydict() + return dict(zip(rows["row_id"], rows["split_id"])) + + with mock_remote_table(server) as table: + first = split_of_each_row( + permutation_builder(table).split_sequential(fixed=2).execute() + ) + second = split_of_each_row( + permutation_builder(table).split_sequential(fixed=2).execute() + ) + + assert server.scan_calls == 2, "both builds must have scanned" + assert first == second + assert first[0] == 0 and first[server.num_rows - 1] == 1, first + + +def test_permutation_over_remote_table(): + """The permutation API accepts a remote table, addressing rows by `_rowid` just + as `take_row_ids` does. Also pins the request shapes sent to the server. + """ + server = MockPermutationServer() + + with mock_remote_table(server) as table: + permutation_tbl = permutation_builder(table).split_sequential(fixed=2).execute() + assert permutation_tbl.count_rows() == server.num_rows + + permutation = Permutation.from_tables(table, permutation_tbl, 0) + assert permutation.num_rows == server.num_rows // 2 + + # Compare against the permutation's own order; the split-id sort is not stable. + rows = permutation_tbl.search(None).to_arrow().to_pydict() + split0 = [ + row_id + for row_id, split in zip(rows["row_id"], rows["split_id"]) + if not split + ] + # The mock table's `id` equals its `_rowid`. + assert permutation.take_offsets([2, 0]) == [ + {"id": split0[2]}, + {"id": split0[0]}, + ] + + assert_server_safe_row_id_requests(server) diff --git a/python/python/tests/utils.py b/python/python/tests/utils.py index 62ec74497..4882f0c28 100644 --- a/python/python/tests/utils.py +++ b/python/python/tests/utils.py @@ -1,7 +1,17 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors +import contextlib +import http.server +import json +import re +import threading + +import lancedb +import pyarrow as pa import pytest +ARROW_FILE_CONTENT_TYPE = "application/vnd.apache.arrow.file" + def exception_output(e_info: pytest.ExceptionInfo): import traceback @@ -9,3 +19,199 @@ def exception_output(e_info: pytest.ExceptionInfo): # skip traceback part, since it's not worth checking in tests lines = traceback.format_exception_only(e_info.type, e_info.value) return "".join(lines).strip() + + +def parse_in_list(filter_sql: str) -> list[int]: + """Pull the integers out of a `IN (a, b, c)` predicate. + + Scoped to the parenthesised list so a cast in the SQL adds no phantom values. + """ + match = re.search(r"\bIN\s*\(([^)]*)\)", filter_sql, re.IGNORECASE) + assert match is not None, f"expected an IN list, got: {filter_sql}" + return [int(m) for m in re.findall(r"-?\d+", match.group(1))] + + +def is_row_id_take(body) -> bool: + """True when a query body fetches specific rows by row id.""" + return "_rowid" in (body.get("filter") or "") + + +def arrow_file_bytes(table: pa.Table) -> bytes: + """Serialize to the Arrow IPC *file* framing the /query/ route answers with.""" + sink = pa.BufferOutputStream() + with pa.ipc.new_file(sink, table.schema) as writer: + writer.write_table(table) + return sink.getvalue().to_pybytes() + + +class MockPermutationServer: + """A stand-in LanceDB server hosting one table whose ``id`` equals its ``_rowid``. + + Records every ``/query/`` body so tests can assert on the request shapes sent to + the server, which is the part that has to stay compatible. + """ + + def __init__(self, name="remote_data", num_rows=8, vary_scan_order=False): + self.name = name + self.num_rows = num_rows + self.query_bodies = [] + # Stand in for a distributed scan that answers in no fixed order. + self.vary_scan_order = vary_scan_order + self.scan_calls = 0 + + def __call__(self, request): + path = request.path + if path == f"/v1/table/{self.name}/describe/": + return self._json( + request, + { + "version": 1, + "schema": { + "fields": [ + {"name": "id", "type": {"type": "int64"}, "nullable": False} + ] + }, + }, + ) + if path == f"/v1/table/{self.name}/get_lsm_write_spec/": + self._read_body(request) + # Null spec: this table has no LSM write path. + return self._json(request, {"lsm_write_spec": None}) + if path == f"/v1/table/{self.name}/count_rows/": + self._read_body(request) + return self._json(request, self.num_rows) + if path == f"/v1/table/{self.name}/query/": + return self._query(request, self._read_body(request)) + + # Drain first, so an unexpected route cannot desync a keep-alive connection. + self._read_body(request) + request.send_response(404) + request.end_headers() + + @property + def scans(self): + """Bodies of the permutation build scan: the row id column, nothing else.""" + return [b for b in self.query_bodies if b.get("columns") == ["_rowid"]] + + @property + def takes(self): + """Bodies of the row-id takes the loader fetches batches with. + + Keyed on `_rowid`, not "has a filter": the schema probe also has a predicate. + """ + return [b for b in self.query_bodies if is_row_id_take(b)] + + @staticmethod + def _read_body(request): + content_len = int(request.headers.get("Content-Length") or 0) + return json.loads(request.rfile.read(content_len)) if content_len else {} + + @staticmethod + def _json(request, payload): + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(payload).encode()) + + @staticmethod + def _arrow(request, table): + body = arrow_file_bytes(table) + request.send_response(200) + request.send_header("Content-Type", ARROW_FILE_CONTENT_TYPE) + request.send_header("Content-Length", str(len(body))) + request.end_headers() + request.wfile.write(body) + + def _query(self, request, body): + self.query_bodies.append(body) + + if is_row_id_take(body): + # A row-id take. Answer ascending, so tests prove the client reorders. + row_ids = sorted(parse_in_list(body["filter"])) + return self._arrow( + request, + pa.table( + { + "id": pa.array(row_ids, pa.int64()), + "_rowid": pa.array(row_ids, pa.uint64()), + } + ), + ) + + if body.get("columns") == ["_rowid"]: + # The permutation build scan: row ids and nothing else. + row_ids = list(range(self.num_rows)) + if self.vary_scan_order and self.scan_calls % 2: + row_ids.reverse() + self.scan_calls += 1 + return self._arrow( + request, + pa.table({"_rowid": pa.array(row_ids, pa.uint64())}), + ) + + # The schema probe: filtered to nothing, so it carries schema and no rows. + return self._arrow(request, pa.table({"id": pa.array([], pa.int64())})) + + +def _make_handler(serve): + class MockLanceDBHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + serve(self) + + def do_POST(self): + serve(self) + + def log_message(self, *args): + pass # keep pytest output readable + + return MockLanceDBHandler + + +@contextlib.contextmanager +def mock_remote_table(server): + """Run ``server`` on a local port and yield an open remote table against it. + + Threading: the loader fans out fetch threads a single-threaded server would + serialize, hiding the prefetch overlap under test. + """ + with http.server.ThreadingHTTPServer( + ("localhost", 0), _make_handler(server) + ) as srv: + thread = threading.Thread(target=srv.serve_forever) + thread.start() + try: + db = lancedb.connect( + "db://dev", + api_key="fake", + host_override=f"http://localhost:{srv.server_address[1]}", + client_config={"timeout_config": {"connect_timeout": 5}}, + ) + yield db.open_table(server.name) + finally: + srv.shutdown() + thread.join() + + +def assert_server_safe_row_id_requests(server): + """Assert the loader fetched rows by row id and bounded everything else. + + `.get`, not `[...]`, so a dropped field reads as the assertion, not a KeyError. + """ + for body in server.takes: + # The fetch needs the row id back to restore the requested order. + assert body.get("with_row_id") is True, body + assert "_rowid" in body["filter"], body + + # Only the one-off permutation scan may scan the whole table; the schema probe is + # built once per split per epoch. `k == 0` counts as unbounded: lance reads a zero + # limit as "no limit". + def is_unbounded(body): + if is_row_id_take(body): + return False + k = body.get("k") + return k is None or k == 0 or k > server.num_rows + + unbounded = [b for b in server.query_bodies if is_unbounded(b)] + assert unbounded == server.scans, ( + f"only the permutation scan may be unbounded, got {unbounded}" + ) diff --git a/python/src/permutation.rs b/python/src/permutation.rs index 4dc49cfd3..24ca2b5a3 100644 --- a/python/src/permutation.rs +++ b/python/src/permutation.rs @@ -268,7 +268,9 @@ impl PyPermutationReader { .await .infer_error()? } else { - PermutationReader::identity(base_table).await + PermutationReader::identity(base_table) + .await + .infer_error()? }; Ok(Self::from_reader(reader)) }) diff --git a/rust/lancedb/src/dataloader/permutation/builder.rs b/rust/lancedb/src/dataloader/permutation/builder.rs index 6b4ae2303..a3700d0ef 100644 --- a/rust/lancedb/src/dataloader/permutation/builder.rs +++ b/rust/lancedb/src/dataloader/permutation/builder.rs @@ -160,9 +160,10 @@ impl PermutationBuilder { self } - async fn sort_by_split_id( + async fn sort_by_column( &self, data: SendableRecordBatchStream, + column: &str, ) -> Result { let memory_limit = std::env::var("LANCEDB_PERM_BUILDER_MEMORY_LIMIT") .unwrap_or_else(|_| DEFAULT_MEMORY_LIMIT.to_string()) @@ -188,25 +189,26 @@ impl PermutationBuilder { let df = ctx .read_one_shot(data.into_df_stream()) .map_err(|e| Error::Other { - message: format!("Failed to setup sort by split id: {}", e), + message: format!("Failed to setup sort by {}: {}", column, e), source: Some(e.into()), })?; let df_stream = df - .sort_by(vec![col(SPLIT_ID_COLUMN)]) + .sort_by(vec![col(column)]) .map_err(|e| Error::Other { - message: format!("Failed to plan sort by split id: {}", e), + message: format!("Failed to plan sort by {}: {}", column, e), source: Some(e.into()), })? .execute_stream() .await .map_err(|e| Error::Other { - message: format!("Failed to sort by split id: {}", e), + message: format!("Failed to sort by {}: {}", column, e), source: Some(e.into()), })?; + let column = column.to_string(); let schema = df_stream.schema(); - let stream = df_stream.map_err(|e| Error::Other { - message: format!("Failed to execute sort by split id: {}", e), + let stream = df_stream.map_err(move |e| Error::Other { + message: format!("Failed to execute sort by {}: {}", column, e), source: Some(e.into()), }); Ok(Box::pin(SimpleRecordBatchStream { schema, stream })) @@ -238,7 +240,25 @@ impl PermutationBuilder { /// Builds the permutation table and stores it in the given database. pub async fn build(self) -> Result
{ - // First pass, apply filter and load row ids + // Unflushed rows have no row id, so a permutation cannot address them. + match self.base_table.base_table().get_lsm_write_spec().await { + Ok(Some(_)) => { + return Err(Error::NotSupported { + message: "the data loader does not support tables with an LSM write \ + spec: rows that have not been flushed to the base table \ + have no row id, so a permutation cannot reference them" + .to_string(), + }); + } + Ok(None) => {} + // No LSM write path means no spec. + Err(Error::NotSupported { .. }) => {} + Err(err) => return Err(err), + } + + // First pass, apply filter and load row ids. `Shuffler` permutes positions, so + // every rank must scan the rows in the same order to build the same permutation. + // TODO: pin the version resolved here; remote does not implement Lazy. let mut rows = self.base_table.query().select(Select::columns(&[ROW_ID])); if let Some(filter) = &self.config.filter { @@ -263,6 +283,12 @@ impl PermutationBuilder { // Apply splits let rows = rows.execute().await?; + // Splits are assigned by position, so the scan has to arrive in a fixed order. + let rows = if self.base_table.base_table().scan_order_is_deterministic() { + rows + } else { + self.sort_by_column(rows, ROW_ID).await? + }; let split_data = splitter.apply(rows, num_rows).await?; // Shuffle data if requested @@ -284,7 +310,7 @@ impl PermutationBuilder { needs_sort |= !matches!(self.config.shuffle_strategy, ShuffleStrategy::None); let sorted = if needs_sort { - self.sort_by_split_id(shuffled).await? + self.sort_by_column(shuffled, SPLIT_ID_COLUMN).await? } else { shuffled }; @@ -367,6 +393,22 @@ mod tests { ); } + #[tokio::test] + async fn test_native_scan_order_is_deterministic() { + 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("t", data).execute().await.unwrap(); + + // Native tables skip the canonicalizing sort; remote does not. + assert!(table.base_table().scan_order_is_deterministic()); + } + #[tokio::test] async fn test_permutation_builder() { let temp_dir = tempfile::tempdir().unwrap(); @@ -416,4 +458,48 @@ mod tests { 283 ); } + + /// Rows that have not been flushed to the base table have no row id, so a + /// permutation cannot reference them. Reading the base table alone would drop + /// them from training without saying so, so the table is refused instead. + #[tokio::test] + async fn test_permutation_rejects_lsm_write_spec() { + use crate::table::LsmWriteSpec; + use arrow_array::{Int32Array, RecordBatchIterator}; + use arrow_schema::{DataType, Field, Schema}; + + // MemWAL needs a real dataset directory and a non-nullable primary key. + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("idx", DataType::Int32, false)])); + let batch = arrow_array::RecordBatch::try_new( + schema.clone(), + vec![Arc::new(Int32Array::from(vec![0, 1, 2, 3]))], + ) + .unwrap(); + let reader: Box = + Box::new(RecordBatchIterator::new(vec![Ok(batch)], schema.clone())); + let table = db.create_table("tbl", reader).execute().await.unwrap(); + + // Without a spec the build succeeds. + PermutationBuilder::new(table.clone()) + .build() + .await + .unwrap(); + + table.set_unenforced_primary_key(["idx"]).await.unwrap(); + table + .set_lsm_write_spec(LsmWriteSpec::unsharded()) + .await + .unwrap(); + + let err = PermutationBuilder::new(table).build().await.unwrap_err(); + assert!( + err.to_string().contains("LSM write spec"), + "expected the pre-check to refuse the table, got: {err}" + ); + } } diff --git a/rust/lancedb/src/dataloader/permutation/reader.rs b/rust/lancedb/src/dataloader/permutation/reader.rs index afe79b0ad..6da92e986 100644 --- a/rust/lancedb/src/dataloader/permutation/reader.rs +++ b/rust/lancedb/src/dataloader/permutation/reader.rs @@ -97,8 +97,10 @@ impl PermutationReader { Self::inner_new(base_table, Some(permutation_table), split).await } - pub async fn identity(base_table: Arc) -> Self { - Self::inner_new(base_table, None, 0).await.unwrap() + /// A reader over the base table in storage order, with no permutation. + /// Fallible because construction counts the base table. + pub async fn identity(base_table: Arc) -> Result { + Self::inner_new(base_table, None, 0).await } /// Validates the limit and offset and returns the number of rows that will be read @@ -487,7 +489,13 @@ impl PermutationReader { pub async fn output_schema(&self, selection: Select) -> Result { let table = Table::from(self.base_table.clone()); - table.query().select(selection).output_schema().await + // limit(1) because some table types execute the query to get its schema + table + .query() + .select(selection) + .limit(1) + .output_schema() + .await } pub fn count_rows(&self) -> u64 { @@ -779,7 +787,9 @@ mod tests { .into_mem_table("tbl", RowCount::from(10), BatchCount::from(1)) .await; - let reader = PermutationReader::identity(base_table.base_table().clone()).await; + let reader = PermutationReader::identity(base_table.base_table().clone()) + .await + .unwrap(); // With no permutation table, take_offsets uses the base table directly let offsets = vec![0, 2, 4, 6]; @@ -961,7 +971,9 @@ mod tests { .into_mem_table("tbl", RowCount::from(10), BatchCount::from(1)) .await; - let reader = PermutationReader::identity(base_table.base_table().clone()).await; + let reader = PermutationReader::identity(base_table.base_table().clone()) + .await + .unwrap(); let batch = reader.take_offsets(&[], Select::All).await.unwrap(); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 14b869d90..f98d4c8dd 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4303,6 +4303,19 @@ mod tests { write_ipc_stream_uncompressed(&one_row_blob_batch(column)) } + #[tokio::test] + async fn test_remote_scan_order_is_not_deterministic() { + // A distributed scan answers in no fixed order, so callers that assign meaning + // to row position have to sort for themselves. + let table = Table::new_with_handler("my_table", |_| { + http::Response::builder() + .status(200) + .body(Vec::new()) + .unwrap() + }); + assert!(!table.base_table().scan_order_is_deterministic()); + } + #[tokio::test] async fn test_fetch_blobs_sends_the_checked_out_version() { let ipc = one_row_blob_ipc_stream("image"); diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index e1dd942db..096d60345 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -789,6 +789,13 @@ 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<()>; + /// Whether repeated identical scans return rows in the same order. + /// + /// Callers that assign meaning to a row's position must order the results + /// themselves when this is false. Defaults to false so a table type opts in. + fn scan_order_is_deterministic(&self) -> bool { + false + } /// Restore the table to the currently checked out version. async fn restore(&self) -> Result<()>; /// List the versions of the table. @@ -2996,6 +3003,12 @@ 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. + fn scan_order_is_deterministic(&self) -> bool { + true + } + fn name(&self) -> &str { self.name.as_str() } From 29822306d2be9b1e8fe683b38b80d2440a708627 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Fri, 21 Aug 2026 14:20:03 -0700 Subject: [PATCH 080/206] fix(python): skip the unrunnable FunctionVersion doctest example (#4014) The example binds an undefined `function`; only its last line was skipped, so the doctest suite fails on main and on every PR. --- python/python/lancedb/functions.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 3b2d05951..9532ab8b9 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -281,7 +281,7 @@ class FunctionVersion(_RemoteValue): Examples -------- >>> from lancedb import col - >>> application = function( + >>> application = function( # doctest: +SKIP ... title=col("title"), ... body=col("body"), ... ).rename(columns={ From a35f7044ee8273d3746e7e1256449d6831f4518d Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 21 Aug 2026 15:43:04 -0700 Subject: [PATCH 081/206] test(rust): cover Azure table URI separators on Windows (#3810) ## Summary - add cross-platform regression coverage for Azure table URI construction - assert that az:// database paths always produce forward-slash blob keys ## Root cause ListingDatabase previously used the host filesystem Path join operation for object-store URIs, which inserted a backslash on Windows. The URI construction was corrected in #2575, but the original Azure report had no regression coverage and remained open. ## Validation - cargo fmt --all - cargo test --quiet --features remote -p lancedb test_table_uri_uses_forward_slashes_for_azure - cargo check --quiet --features remote --tests --examples - cargo clippy --quiet --features remote --tests --examples Fixes #2283 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- rust/lancedb/src/database/listing.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index 5ebbe6c5c..d8d687c7c 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -2569,6 +2569,21 @@ mod tests { } } + /// Regression test for https://github.com/lancedb/lancedb/issues/2283. + /// + /// Object-store URIs must use `/` on every platform. In particular, joining + /// with `std::path::Path` used to insert a `\\` into Azure blob keys on + /// Windows. + #[tokio::test] + async fn test_table_uri_uses_forward_slashes_for_azure() { + let (_tempdir, mut db) = setup_database().await; + db.uri = "az://test/db/test".to_string(); + + let uri = db.table_uri("test").unwrap(); + + assert_eq!(uri, "az://test/db/test/test.lance"); + } + /// Regression: connecting via a URL-style URI (which goes through /// `url::Url::parse` and the `query_pairs_mut()` path) must not /// append a trailing `?` to per-table URIs when the input URI has From c7cb0b9afa8f4807fb29c1af370348818416d231 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 21 Aug 2026 16:13:49 -0700 Subject: [PATCH 082/206] docs(python): clarify threading on two-CPU containers (#3807) ## Summary - document that current LanceDB releases use one compute worker without warning on two-vCPU containers - distinguish compute-worker tuning from storage I/O concurrency - direct users of affected LanceDB 0.21.1 installations to upgrade and link the current threading guidance ## Root cause The Lance version bundled with LanceDB 0.21.1 warned whenever the detected CPU count was less than or equal to its default two-core I/O reservation. A two-vCPU deployment therefore emitted the warning on every query even though falling back to one compute worker was the intended behavior. Lance fixed that warning condition upstream in lance-format/lance#3710, and LanceDB current main already pins a version containing the runtime fix; the Python package documentation did not explain the corrected behavior or the distinct thread controls. ## Validation - `git diff --check` - verified the linked Lance threading-model documentation returns HTTP 200 Fixes #2326 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/python/README.md b/python/README.md index 550698500..3a81c486a 100644 --- a/python/README.md +++ b/python/README.md @@ -38,6 +38,25 @@ Stable releases are created about every 2 weeks. For the latest features and bug pip install --pre --extra-index-url https://pypi.fury.io/lancedb/ lancedb ``` +### Threading in CPU-limited containers + +LanceDB uses separate pools for compute work and storage I/O. On a container with +two visible CPUs, current releases intentionally use one compute worker by default; +no manual configuration is needed. If every query logs an I/O core reservation +warning on a two-CPU container, upgrade from LanceDB 0.21.1 or earlier. + +The two commonly tuned environment variables control different resources: + +- `LANCE_CPU_THREADS` overrides the number of compute workers. One worker is the + appropriate setting for a two-CPU container when an explicit override is needed. +- `LANCE_IO_THREADS` controls concurrent storage operations, not reserved CPU + cores. Its default can be greater than the number of CPUs because I/O workers + spend much of their time waiting for storage. + +Keep the defaults unless measurements show that the workload benefits from an +override. See the [Lance threading model](https://lance.org/guide/performance/#threading-model) +for the current defaults and tuning guidance. + ## Usage ### Basic Example From 01679e37fdefcbf12ce42c7b2ac579ad6098d8fd Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Fri, 21 Aug 2026 16:17:03 -0700 Subject: [PATCH 083/206] feat: materialized view declarations on local tables (#3930) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A materialized view is a table whose contents are defined by a query over one source table and maintained by refresh rather than by writes. The declaration half: create_materialized_view(name, source) resolves a projected, filtered and limited definition against the source schema -- output types come from the DataFusion planner, never the caller -- and commits an empty table carrying it as kind-tagged JSON in schema metadata. The tag lets a kind added later read back as a view this version cannot refresh rather than as a plain table. Views open and list as ordinary tables. Sources must have stable row ids, checked here because the property cannot be enabled later: each view row records its source row in __source_row_id, and that provenance survives compactions, updates and deletes only when row ids are stable. A view inherits the metadata describing its columns and none governing how a table is written, so blob markers carry through while declarations its always-nullable fields would contradict are stripped. Embedding configuration is rewritten to the view's column names, and dropped where it does not project both ends of a function. Stack created with GitHub Stacks CLIGive Feedback 💬 --- rust/lancedb/src/connection.rs | 2 +- rust/lancedb/src/database/listing.rs | 302 +++- rust/lancedb/src/database/namespace.rs | 202 ++- rust/lancedb/src/error.rs | 2 + rust/lancedb/src/lib.rs | 2 + rust/lancedb/src/materialized_view.rs | 1992 ++++++++++++++++++++++++ rust/lancedb/src/remote/table.rs | 14 + rust/lancedb/src/table.rs | 5 + rust/lancedb/src/table/refresh.rs | 2 +- 9 files changed, 2406 insertions(+), 117 deletions(-) create mode 100644 rust/lancedb/src/materialized_view.rs diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 8935855a8..187e2df0e 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -41,7 +41,7 @@ use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider}; mod create_table; -fn merge_storage_options( +pub(crate) fn merge_storage_options( store_params: &mut ObjectStoreParams, pairs: impl IntoIterator, ) { diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index d8d687c7c..c9e9bcb22 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -765,60 +765,13 @@ impl ListingDatabase { } } - /// Extract storage option overrides from the request - fn extract_storage_overrides( - &self, - request: &CreateTableRequest, - ) -> Result<(Option, Option, Option)> { - let storage_options = request - .write_options - .lance_write_params - .as_ref() - .and_then(|p| p.store_params.as_ref()) - .and_then(|sp| sp.storage_options()); - - let storage_version_override = storage_options - .and_then(|opts| opts.get(OPT_NEW_TABLE_STORAGE_VERSION)) - .map(|s| s.parse::()) - .transpose()?; - - let v2_manifest_override = storage_options - .and_then(|opts| opts.get(OPT_NEW_TABLE_V2_MANIFEST_PATHS)) - .map(|s| s.parse::()) - .transpose() - .map_err(|_| Error::InvalidInput { - message: "enable_v2_manifest_paths must be a boolean".to_string(), - })?; - - let stable_row_ids_override = storage_options - .and_then(|opts| opts.get(OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS)) - .map(|s| s.parse::()) - .transpose() - .map_err(|_| Error::InvalidInput { - message: "enable_stable_row_ids must be a boolean".to_string(), - })?; - - Ok(( - storage_version_override, - v2_manifest_override, - stable_row_ids_override, - )) - } - /// Prepare write parameters for table creation fn prepare_write_params( &self, request: &CreateTableRequest, - storage_version_override: Option, - v2_manifest_override: Option, - stable_row_ids_override: Option, + mut write_params: lance::dataset::WriteParams, + overrides: NewTableConfig, ) -> lance::dataset::WriteParams { - let mut write_params = request - .write_options - .lance_write_params - .clone() - .unwrap_or_default(); - // Only modify the storage options if we actually have something to // inherit. There is a difference between storage_options=None and // storage_options=Some({}). Using storage_options=None will cause the @@ -842,18 +795,21 @@ impl ListingDatabase { store_params.storage_options_accessor = Some(Arc::new(accessor)); } - write_params.data_storage_version = storage_version_override + write_params.data_storage_version = overrides + .data_storage_version .or(write_params.data_storage_version) .or(self.new_table_config.data_storage_version); - if let Some(enable_v2_manifest_paths) = - v2_manifest_override.or(self.new_table_config.enable_v2_manifest_paths) + if let Some(enable_v2_manifest_paths) = overrides + .enable_v2_manifest_paths + .or(self.new_table_config.enable_v2_manifest_paths) { write_params.enable_v2_manifest_paths = enable_v2_manifest_paths; } let data_schema = request.data.arrow_schema(); - if let Some(enable_stable_row_ids) = stable_row_ids_override + if let Some(enable_stable_row_ids) = overrides + .enable_stable_row_ids .or(self.new_table_config.enable_stable_row_ids) .or(has_blob_columns(&data_schema).then_some(true)) { @@ -1048,15 +1004,13 @@ impl Database for ListingDatabase { .clone() .unwrap_or_else(|| self.table_uri(&request.name).unwrap()); - let (storage_version_override, v2_manifest_override, stable_row_ids_override) = - self.extract_storage_overrides(&request)?; - - let write_params = self.prepare_write_params( - &request, - storage_version_override, - v2_manifest_override, - stable_row_ids_override, - ); + let mut write_params = request + .write_options + .lance_write_params + .clone() + .unwrap_or_default(); + let overrides = take_request_creation_overrides(&mut write_params)?; + let write_params = self.prepare_write_params(&request, write_params, overrides); let data_schema = request.data.arrow_schema(); @@ -1288,8 +1242,232 @@ impl Database for ListingDatabase { } } +/// Parse the request-level `new_table_*` creation keys into overrides and +/// strip them from the store options in one step: every create path that +/// honors them must also keep them out of the object store. +pub(crate) fn take_request_creation_overrides( + params: &mut lance::dataset::WriteParams, +) -> Result { + let storage_options = params + .store_params + .as_ref() + .and_then(|sp| sp.storage_options()); + let overrides = NewTableConfig { + data_storage_version: storage_options + .and_then(|opts| opts.get(OPT_NEW_TABLE_STORAGE_VERSION)) + .map(|s| s.parse::()) + .transpose()?, + enable_v2_manifest_paths: storage_options + .and_then(|opts| opts.get(OPT_NEW_TABLE_V2_MANIFEST_PATHS)) + .map(|s| s.parse::()) + .transpose() + .map_err(|_| Error::InvalidInput { + message: "enable_v2_manifest_paths must be a boolean".to_string(), + })?, + enable_stable_row_ids: storage_options + .and_then(|opts| opts.get(OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS)) + .map(|s| s.parse::()) + .transpose() + .map_err(|_| Error::InvalidInput { + message: "enable_stable_row_ids must be a boolean".to_string(), + })?, + }; + if let Some(store_params) = params.store_params.as_mut() { + strip_new_table_creation_keys(store_params); + } + Ok(overrides) +} + +/// Strip the `new_table_*` creation keys from request store options: they are +/// creation config, not credentials, and left in place they fork a fresh +/// store connection for the request. +fn strip_new_table_creation_keys(store_params: &mut ObjectStoreParams) { + let mut options = store_params.storage_options().cloned().unwrap_or_default(); + let mut removed = false; + for key in [ + OPT_NEW_TABLE_STORAGE_VERSION, + OPT_NEW_TABLE_V2_MANIFEST_PATHS, + OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS, + ] { + removed |= options.remove(key).is_some(); + } + if !removed { + return; + } + let provider = store_params + .storage_options_accessor + .as_ref() + .and_then(|accessor| accessor.provider().cloned()); + store_params.storage_options_accessor = match (options.is_empty(), provider) { + (true, None) => None, + (true, Some(provider)) => Some(Arc::new(StorageOptionsAccessor::with_provider(provider))), + (false, Some(provider)) => Some(Arc::new( + StorageOptionsAccessor::with_initial_and_provider(options, provider), + )), + (false, None) => Some(Arc::new(StorageOptionsAccessor::with_static_options( + options, + ))), + }; +} + #[cfg(test)] mod tests { + #[tokio::test] + async fn request_level_creation_keys_do_not_fork_the_store() { + use crate::query::ExecutableQuery; + use futures::TryStreamExt; + + let db = crate::connect("memory://").execute().await.unwrap(); + let batch = arrow_array::record_batch!(("x", Int32, [1, 2])).unwrap(); + let store_params = ObjectStoreParams { + storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options( + HashMap::from([( + OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS.to_string(), + "true".to_string(), + )]), + ))), + ..Default::default() + }; + db.create_table("t", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(lance::dataset::WriteParams { + store_params: Some(store_params), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + + let table = db.open_table("t").execute().await.unwrap(); + let rows: usize = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + .iter() + .map(|b| b.num_rows()) + .sum(); + assert_eq!(rows, 2, "the table must live in the session's store"); + } + + mod strip_new_table_creation_keys { + use super::super::*; + + #[derive(Debug)] + struct EmptyProvider; + + #[async_trait::async_trait] + impl StorageOptionsProvider for EmptyProvider { + async fn fetch_storage_options( + &self, + ) -> lance_core::Result>> { + Ok(Some(HashMap::new())) + } + + fn provider_id(&self) -> String { + "empty-test-provider".into() + } + } + + fn params_with_static(options: &[(&str, &str)]) -> ObjectStoreParams { + ObjectStoreParams { + storage_options_accessor: Some(Arc::new( + StorageOptionsAccessor::with_static_options( + options + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(), + ), + )), + ..Default::default() + } + } + + #[test] + fn creation_keys_are_removed_and_store_keys_kept() { + let mut params = params_with_static(&[ + ("region", "us-west-2"), + (OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS, "true"), + ]); + strip_new_table_creation_keys(&mut params); + let options = params.storage_options().cloned().unwrap(); + assert_eq!(options.get("region").map(String::as_str), Some("us-west-2")); + assert!(!options.contains_key(OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS)); + + // Creation keys alone: no accessor survives to fork a store. + let mut params = params_with_static(&[(OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS, "true")]); + strip_new_table_creation_keys(&mut params); + assert!(params.storage_options_accessor.is_none()); + } + + /// A provider must survive every shape of strip: untouched accessors + /// keep their identity, emptied ones still fetch, and residual + /// statics ride along. + #[test] + fn provider_accessors_survive_the_strip() { + let accessor = Arc::new(StorageOptionsAccessor::with_provider(Arc::new( + EmptyProvider, + ))); + let mut params = ObjectStoreParams { + storage_options_accessor: Some(accessor.clone()), + ..Default::default() + }; + strip_new_table_creation_keys(&mut params); + assert!(Arc::ptr_eq( + params.storage_options_accessor.as_ref().unwrap(), + &accessor + )); + + let mut params = ObjectStoreParams { + storage_options_accessor: Some(Arc::new( + StorageOptionsAccessor::with_initial_and_provider( + HashMap::from([ + ("region".to_string(), "us-west-2".to_string()), + ( + OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS.to_string(), + "true".to_string(), + ), + ]), + Arc::new(EmptyProvider), + ), + )), + ..Default::default() + }; + strip_new_table_creation_keys(&mut params); + let accessor = params.storage_options_accessor.unwrap(); + assert!(accessor.has_provider()); + assert_eq!( + accessor + .initial_storage_options() + .and_then(|o| o.get("region").cloned()) + .as_deref(), + Some("us-west-2") + ); + + // Emptied entirely: a first-fetch accessor, not one caching {}. + let mut params = ObjectStoreParams { + storage_options_accessor: Some(Arc::new( + StorageOptionsAccessor::with_initial_and_provider( + HashMap::from([( + OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS.to_string(), + "true".to_string(), + )]), + Arc::new(EmptyProvider), + ), + )), + ..Default::default() + }; + strip_new_table_creation_keys(&mut params); + let accessor = params.storage_options_accessor.unwrap(); + assert!(accessor.has_provider()); + assert!(accessor.initial_storage_options().is_none()); + } + } + use super::*; use crate::Table; use crate::arrow::{SendableRecordBatchStream, SimpleRecordBatchStream}; diff --git a/rust/lancedb/src/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index 740e11645..250d933f6 100644 --- a/rust/lancedb/src/database/namespace.rs +++ b/rust/lancedb/src/database/namespace.rs @@ -26,10 +26,7 @@ use lance_table::io::commit::external_manifest::ExternalManifestCommitHandler; use crate::blob::{ensure_blob_storage_version, has_blob_columns}; use crate::connection::NamespaceClientPushdownOperation; use crate::database::ReadConsistency; -use crate::database::listing::{ - NewTableConfig, OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS, OPT_NEW_TABLE_STORAGE_VERSION, - OPT_NEW_TABLE_V2_MANIFEST_PATHS, -}; +use crate::database::listing::{NewTableConfig, take_request_creation_overrides}; use crate::database::read_freshness::{ FreshnessBaselines, ReadFreshnessContextProvider, TableFreshness, }; @@ -197,69 +194,28 @@ impl LanceNamespaceDatabase { TableFreshness::new(self.freshness_baselines.clone(), key) } - fn extract_storage_overrides( - &self, - request: &DbCreateTableRequest, - ) -> Result<( - Option, - Option, - Option, - )> { - let storage_options = request - .write_options - .lance_write_params - .as_ref() - .and_then(|p| p.store_params.as_ref()) - .and_then(|sp| sp.storage_options()); - - let storage_version_override = storage_options - .and_then(|opts| opts.get(OPT_NEW_TABLE_STORAGE_VERSION)) - .map(|s| s.parse::()) - .transpose()?; - - let v2_manifest_override = storage_options - .and_then(|opts| opts.get(OPT_NEW_TABLE_V2_MANIFEST_PATHS)) - .map(|s| s.parse::()) - .transpose() - .map_err(|_| Error::InvalidInput { - message: "enable_v2_manifest_paths must be a boolean".to_string(), - })?; - - let stable_row_ids_override = storage_options - .and_then(|opts| opts.get(OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS)) - .map(|s| s.parse::()) - .transpose() - .map_err(|_| Error::InvalidInput { - message: "enable_stable_row_ids must be a boolean".to_string(), - })?; - - Ok(( - storage_version_override, - v2_manifest_override, - stable_row_ids_override, - )) - } - fn apply_new_table_config( &self, params: &mut lance::dataset::WriteParams, request: &DbCreateTableRequest, ) -> Result<()> { - let (storage_version_override, v2_manifest_override, stable_row_ids_override) = - self.extract_storage_overrides(request)?; + let overrides = take_request_creation_overrides(params)?; - params.data_storage_version = storage_version_override + params.data_storage_version = overrides + .data_storage_version .or(params.data_storage_version) .or(self.new_table_config.data_storage_version); - if let Some(enable_v2_manifest_paths) = - v2_manifest_override.or(self.new_table_config.enable_v2_manifest_paths) + if let Some(enable_v2_manifest_paths) = overrides + .enable_v2_manifest_paths + .or(self.new_table_config.enable_v2_manifest_paths) { params.enable_v2_manifest_paths = enable_v2_manifest_paths; } let data_schema = request.data.schema(); - if let Some(enable_stable_row_ids) = stable_row_ids_override + if let Some(enable_stable_row_ids) = overrides + .enable_stable_row_ids .or(self.new_table_config.enable_stable_row_ids) .or(has_blob_columns(data_schema.as_ref()).then_some(true)) { @@ -644,6 +600,146 @@ mod tests { RecordBatch::try_new(schema, vec![Arc::new(id_array), Arc::new(name_array)]).unwrap() } + /// The shared parse-and-sanitize boundary is wired into this path: the + /// request-level creation key must act as an override (the strip itself + /// is covered by the listing tests). + #[tokio::test] + async fn request_level_creation_keys_are_taken_as_overrides() { + use crate::database::listing::OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS; + + let tmp_dir = tempdir().unwrap(); + let mut properties = HashMap::new(); + properties.insert( + "root".to_string(), + tmp_dir.path().to_str().unwrap().to_string(), + ); + let db = connect_namespace("dir", properties) + .execute() + .await + .unwrap(); + + let store_params = ObjectStoreParams { + storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options( + HashMap::from([( + OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS.to_string(), + "true".to_string(), + )]), + ))), + ..Default::default() + }; + let table = db + .create_table("t", create_test_data()) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(lance::dataset::WriteParams { + store_params: Some(store_params), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let native = table.as_native().unwrap(); + assert!( + native + .dataset + .get() + .await + .unwrap() + .manifest + .uses_stable_row_ids(), + "the creation key must be honored as an override" + ); + + let table = db.open_table("t").execute().await.unwrap(); + let rows: usize = table + .query() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap() + .iter() + .map(|b| b.num_rows()) + .sum(); + assert_eq!(rows, 5); + } + + /// Sanitation on this path: apply must strip the creation keys from the + /// store options while genuine options and the provider survive. + #[tokio::test] + async fn apply_new_table_config_sanitizes_request_store_options() { + use crate::database::listing::OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS; + use lance_io::object_store::StorageOptionsProvider; + + #[derive(Debug)] + struct EmptyProvider; + + #[async_trait::async_trait] + impl StorageOptionsProvider for EmptyProvider { + async fn fetch_storage_options( + &self, + ) -> lance_core::Result>> { + Ok(Some(HashMap::new())) + } + + fn provider_id(&self) -> String { + "empty-test-provider".into() + } + } + + let tmp_dir = tempdir().unwrap(); + let mut properties = HashMap::new(); + properties.insert( + "root".to_string(), + tmp_dir.path().to_str().unwrap().to_string(), + ); + let db = LanceNamespaceDatabase::connect_with_new_table_config( + "dir", + properties, + HashMap::new(), + None, + None, + HashSet::new(), + NewTableConfig::default(), + ) + .await + .unwrap(); + + let request = DbCreateTableRequest::new("t".to_string(), Box::new(create_test_data())); + let mut params = lance::dataset::WriteParams { + store_params: Some(ObjectStoreParams { + storage_options_accessor: Some(Arc::new( + StorageOptionsAccessor::with_initial_and_provider( + HashMap::from([ + ("region".to_string(), "us-west-2".to_string()), + ( + OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS.to_string(), + "true".to_string(), + ), + ]), + Arc::new(EmptyProvider), + ), + )), + ..Default::default() + }), + ..Default::default() + }; + db.apply_new_table_config(&mut params, &request).unwrap(); + + assert!(params.enable_stable_row_ids); + let store_params = params.store_params.unwrap(); + let options = store_params.storage_options().cloned().unwrap(); + assert!(!options.contains_key(OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS)); + assert_eq!(options.get("region").map(String::as_str), Some("us-west-2")); + assert!( + store_params + .storage_options_accessor + .unwrap() + .has_provider() + ); + } + #[tokio::test] async fn test_namespace_connection_simple() { // Test that namespace connections work with simple connect_namespace(impl_type, properties) diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 6bd1ffa2b..be4641388 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -77,6 +77,8 @@ pub enum Error { ColumnAlreadyExists { name: String }, #[snafu(display("Column '{name}' is not a computed column"))] NotAComputedColumn { name: String }, + #[snafu(display("Table '{name}' is not a materialized view"))] + NotAMaterializedView { name: String }, #[snafu(display("Invalid expression for column '{column}': {message}"))] InvalidExpression { column: String, message: String }, diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index 291dcaf65..3a937db5b 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -186,6 +186,7 @@ pub mod index; pub mod io; pub mod ipc; pub mod job; +pub mod materialized_view; #[cfg(feature = "metrics-otel")] pub mod metrics_otel; #[cfg(feature = "polars")] @@ -210,6 +211,7 @@ pub use function::FunctionVersion; pub use job::Job; use lance_index::vector::ApproxMode as LanceApproxMode; use lance_linalg::distance::DistanceType as LanceDistanceType; +pub use materialized_view::{MaterializedView, MaterializedViewDefinition}; /// Re-export of the [`metrics`](https://docs.rs/metrics) crate facade. Enable /// the `metrics` feature to publish LanceDB's internal metrics; install any /// `metrics`-compatible recorder to collect them. See also [`metrics_otel`] for diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs new file mode 100644 index 000000000..f1eddf9da --- /dev/null +++ b/rust/lancedb/src/materialized_view.rs @@ -0,0 +1,1992 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Materialized views. +//! +//! A materialized view is a table whose contents are defined by a query over +//! one source table and maintained by refresh rather than by writes. Creation +//! commits an empty table carrying the kind-tagged definition in schema +//! metadata; a kind added later reads back as unrefreshable, not as a plain +//! table. Queries, indexes and search work on the view unchanged. + +use std::collections::HashMap; +use std::sync::Arc; + +use arrow_schema::{DataType, Field as ArrowField, FieldRef, Schema as ArrowSchema, SchemaRef}; +use datafusion_common::ScalarValue; +use lance_core::ROW_ID; +use lance_datafusion::planner::Planner; +use serde::{Deserialize, Serialize}; + +use crate::connection::Connection; +use crate::database::listing::OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS; +use crate::database::{CreateTableRequest, Database, OpenTableRequest}; +use crate::embeddings::EmbeddingDefinition; +use crate::table::Table; +use crate::table::refresh::quote_identifier; +use crate::table::{ColumnDefinition, ColumnKind}; +use crate::{Error, Result}; + +/// Schema metadata key holding the view definition, as kind-tagged JSON. +pub const DEFINITION_META_KEY: &str = "mv.definition"; + +/// Schema metadata key holding the source table version the view was last +/// refreshed to. Absent until the first refresh. +pub const SOURCE_VERSION_META_KEY: &str = "mv.source_version"; + +/// Schema metadata key holding the wall-clock time of the last refresh, +/// in milliseconds since the epoch. +pub const REFRESHED_AT_MS_META_KEY: &str = "mv.refreshed_at_ms"; + +/// Column recording which source row produced each view row: the source's +/// stable `_rowid` at refresh time, which is why sources must keep stable +/// row ids. +pub const SOURCE_ROW_ID_COLUMN: &str = "__source_row_id"; + +/// Field metadata namespace for declarations about schema structure, such as +/// an unenforced primary key. +const SCHEMA_DECLARATION_META_PREFIX: &str = "lance-schema:"; + +/// A field's identity in its own schema, which is not the view's. +const LANCE_FIELD_ID_KEY: &str = "lance:field_id"; + +/// Schema metadata key holding embedding-function configuration. It describes +/// columns rather than storage, so a view carries it through. +const EMBEDDING_FUNCTIONS_META_KEY: &str = "embedding_functions"; + +/// Schema metadata key holding lancedb's own column definitions, one per +/// field in schema order. It marks which columns an embedding function +/// produces, which is what lets a query embed its own text. +const COLUMN_DEFINITIONS_META_KEY: &str = "lancedb::column_definitions"; + +/// Value of the definition's `kind` tag for the projected `select` form. +pub const SELECT_KIND: &str = "select"; + +/// Which view outputs each source column is projected to directly. A column +/// may be projected more than once, so each carries every name the view gives +/// it, in projection order. +type Lineage = HashMap>; + +/// One projected output column of a view. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ViewProjection { + /// Name of the column in the view. + pub output: String, + /// SQL expression over the source table that computes it. + pub expression: String, +} + +/// The query that defines a materialized view. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct MaterializedViewDefinition { + /// Name of the source table, in the same database as the view. + pub source_table: String, + /// The projected output columns, in view schema order. + pub projections: Vec, + /// SQL predicate selecting the source rows the view holds. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub filter: Option, + /// Cap on the number of rows the view holds, in materialization order. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub limit: Option, + /// Source columns the projections and filter read, derived at creation. + #[serde(default)] + pub inputs: Vec, +} + +/// A view definition as read back from schema metadata. Non-exhaustive so a +/// kind added later is additive. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum MaterializedViewKind { + /// The projected `select` form. + Select(MaterializedViewDefinition), + /// A kind written by a newer version, reported so a caller can tell an + /// unrefreshable view apart from a plain table. Nothing produces this. + Unrecognized { + /// The kind as it was found in the metadata. + kind: String, + }, +} + +/// Serialize `definition` into the kind-tagged form stored under +/// [`DEFINITION_META_KEY`]. +pub(crate) fn definition_to_metadata(definition: &MaterializedViewDefinition) -> Result { + let mut value = serde_json::to_value(definition).map_err(|e| Error::Runtime { + message: format!("failed to serialize view definition: {e}"), + })?; + value["kind"] = serde_json::Value::String(SELECT_KIND.to_string()); + Ok(value.to_string()) +} + +/// Read a view declaration off a schema metadata map, if it carries one. +/// `Ok(None)` for a plain table; a declaration that does not parse is an +/// error, because treating a view as plain would let it be rewritten. +pub fn materialized_view_kind( + metadata: &HashMap, +) -> Result> { + let Some(raw) = metadata.get(DEFINITION_META_KEY) else { + return Ok(None); + }; + let unreadable = |e: &dyn std::fmt::Display| Error::Runtime { + message: format!("unreadable materialized view definition: {e}"), + }; + let value: serde_json::Value = serde_json::from_str(raw).map_err(|e| unreadable(&e))?; + let kind = value + .get("kind") + .and_then(|k| k.as_str()) + .ok_or_else(|| unreadable(&"missing kind tag"))?; + if kind != SELECT_KIND { + return Ok(Some(MaterializedViewKind::Unrecognized { + kind: kind.to_string(), + })); + } + let definition = serde_json::from_value(value).map_err(|e| unreadable(&e))?; + Ok(Some(MaterializedViewKind::Select(definition))) +} + +/// Resolve a definition against the source schema into the view's projected +/// fields, with `inputs` filled in. Everything statically checkable is +/// checked here rather than at refresh time. Empty `projections` selects +/// every source column as the schema stands now. +pub(crate) fn plan( + source_schema: SchemaRef, + source_table: &str, + projections: &[(String, String)], + filter: Option<&str>, + limit: Option, +) -> Result<(MaterializedViewDefinition, Vec, Lineage)> { + let projections: Vec<(String, String)> = if projections.is_empty() { + source_schema + .fields() + .iter() + // A source that is itself a view carries its own provenance + // column; the new view records its own, not a copy. + .filter(|f| f.name() != SOURCE_ROW_ID_COLUMN) + .map(|f| (f.name().clone(), quote_identifier(f.name()))) + .collect() + } else { + projections.to_vec() + }; + + // A scan takes the cap as i64. Rejecting it here keeps creation and + // refresh from disagreeing about whether a view is valid. + if let Some(limit) = limit + && i64::try_from(limit).is_err() + { + return Err(Error::InvalidInput { + message: format!("view limit {limit} exceeds the maximum of {}", i64::MAX), + }); + } + + let planner = Planner::new(source_schema.clone()); + let mut fields = Vec::with_capacity(projections.len()); + let mut inputs = Vec::new(); + let mut declared: Vec<&str> = Vec::with_capacity(projections.len()); + let mut lineage: Lineage = HashMap::new(); + + for (output, expression) in &projections { + if declared.contains(&output.as_str()) { + return Err(Error::ColumnAlreadyExists { + name: output.clone(), + }); + } + if output == SOURCE_ROW_ID_COLUMN || output == ROW_ID { + return Err(Error::InvalidInput { + message: format!("view column name '{output}' is reserved"), + }); + } + + let parsed = planner + .parse_expr(expression) + .map_err(|e| Error::InvalidExpression { + column: output.clone(), + message: e.to_string(), + })?; + // Before optimization: the simplifier folds a stable-but-not-immutable + // call like now() into a literal, hiding it from the check while the + // stored definition keeps the call. + ensure_immutable(&parsed, |message| Error::InvalidExpression { + column: output.clone(), + message, + })?; + let expr = planner + .optimize_expr(parsed) + .map_err(|e| Error::InvalidExpression { + column: output.clone(), + message: e.to_string(), + })?; + let expr_inputs = + resolve_inputs(&source_schema, &expr, |message| Error::InvalidExpression { + column: output.clone(), + message, + })?; + + // Physical expressions address columns by position, so the planner + // that types the expression is built on the projected schema. + let read_schema = project_schema(&source_schema, &expr_inputs); + let physical = Planner::new(read_schema.clone()) + .create_physical_expr(&expr) + .map_err(|e| Error::InvalidExpression { + column: output.clone(), + message: e.to_string(), + })?; + let data_type = + physical + .data_type(read_schema.as_ref()) + .map_err(|e| Error::InvalidExpression { + column: output.clone(), + message: e.to_string(), + })?; + + // Always nullable: what a refresh appends must fit the declared field + // whatever nullability the evaluator reports for a given batch. + let mut field = ArrowField::new(output, data_type, true); + // Identity projections keep descriptive field metadata (blob markers); + // computed values carry none. Structural declarations never come along. + if let Some(source_field) = projected_field(&expr, &source_schema) { + field = field.with_metadata(source_field.metadata().clone()); + } + if let Some(path) = projected_path(&expr) + && let [column] = path.as_slice() + { + lineage + .entry(column.clone()) + .or_default() + .push(output.clone()); + } + fields.push(without_declarations(&field)); + inputs.extend(expr_inputs); + declared.push(output); + } + + if let Some(filter) = filter { + let expr = planner + .parse_filter(filter) + .map_err(|e| Error::InvalidInput { + message: format!("invalid view filter: {e}"), + })?; + ensure_immutable(&expr, |message| Error::InvalidInput { + message: format!("invalid view filter: {message}"), + })?; + let filter_inputs = resolve_inputs(&source_schema, &expr, |message| Error::InvalidInput { + message: format!("invalid view filter: {message}"), + })?; + // A committed filter has to be usable as a predicate. + let read_schema = project_schema(&source_schema, &filter_inputs); + let data_type = Planner::new(read_schema.clone()) + .create_physical_expr(&expr) + .map_err(|e| Error::InvalidInput { + message: format!("invalid view filter: {e}"), + })? + .data_type(read_schema.as_ref()) + .map_err(|e| Error::InvalidInput { + message: format!("invalid view filter: {e}"), + })?; + if data_type != DataType::Boolean { + return Err(Error::InvalidInput { + message: format!("view filter must be a boolean predicate, not {data_type}"), + }); + } + inputs.extend(filter_inputs); + } + + inputs.sort(); + inputs.dedup(); + + let definition = MaterializedViewDefinition { + source_table: source_table.to_string(), + projections: projections + .into_iter() + .map(|(output, expression)| ViewProjection { output, expression }) + .collect(), + filter: filter.map(String::from), + limit, + inputs, + }; + Ok((definition, fields, lineage)) +} + +/// Reject any function that is not immutable: a view definition has to +/// evaluate identically across refreshes, or incremental maintenance would +/// mix rows from different evaluations of the same definition. +fn ensure_immutable(expr: &datafusion_expr::Expr, error: impl Fn(String) -> Error) -> Result<()> { + use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion}; + use datafusion_expr::Volatility; + + // Labeled immutable but not determined by row values alone: version() + // depends on the build, the arrow_* introspectors on schema state. + const NOT_VALUE_DETERMINED: &[&str] = + &["version", "arrow_typeof", "arrow_field", "arrow_metadata"]; + + let mut offending: Option = None; + expr.apply(|node| { + if let datafusion_expr::Expr::ScalarFunction(function) = node { + let name = function.func.name(); + if function.func.signature().volatility != Volatility::Immutable + || NOT_VALUE_DETERMINED.contains(&name) + { + offending = Some(name.to_string()); + return Ok(TreeNodeRecursion::Stop); + } + } + Ok(TreeNodeRecursion::Continue) + }) + .map_err(|e| error(e.to_string()))?; + match offending { + Some(name) => Err(error(format!( + "function '{name}' is not immutable and would evaluate differently \ + across refreshes" + ))), + None => Ok(()), + } +} + +/// The root of a possibly-dotted column path: `metadata.age` -> `metadata`. +fn root(path: &str) -> &str { + path.split('.').next().unwrap_or(path) +} + +/// The columns `expr` reads, kept as the planner reports them (a nested +/// reference stays a dotted path) but resolved by root field. +/// Embedding configuration rewritten for the view: entries whose columns the +/// view projects directly are kept under the view's names; the rest describe +/// a table that does not exist and are dropped. +fn embedding_config_for_view(raw: &str, lineage: &Lineage) -> Option { + // Every representation the writers use: the Python bindings name the + // destination `vector_column`, the Rust definition `dest_column`, and the + // Node bindings spell both halves in camelCase. + const SOURCE_KEYS: [&str; 2] = ["source_column", "sourceColumn"]; + const DEST_KEYS: [&str; 4] = ["vector_column", "dest_column", "vectorColumn", "destColumn"]; + + let entries: Vec = serde_json::from_str(raw).ok()?; + let mut kept = Vec::new(); + for entry in &entries { + let Some(object) = entry.as_object() else { + continue; + }; + let named = |keys: &[&str]| { + let key = keys.iter().find(|key| object.contains_key(**key))?; + let outputs = lineage.get(object.get(*key)?.as_str()?)?; + Some(((*key).to_string(), outputs)) + }; + let (Some((source_key, sources)), Some((dest_key, dests))) = + (named(&SOURCE_KEYS), named(&DEST_KEYS)) + else { + continue; + }; + // A projection may give one source column several names, and every + // pairing of the two is a real relationship in the view. + for source in sources { + for dest in dests { + let mut object = object.clone(); + object.insert(source_key.clone(), source.clone().into()); + object.insert(dest_key.clone(), dest.clone().into()); + kept.push(serde_json::Value::Object(object)); + } + } + } + (!kept.is_empty()).then(|| serde_json::Value::Array(kept).to_string()) +} + +/// Lancedb's column definitions rewritten for the view: positional, one per +/// view field. Directly projected embedding columns keep their definition +/// under the view's names; everything else is physical. `None` = no key. +fn column_definitions_for_view( + raw: &str, + source_schema: &ArrowSchema, + view_fields: &[ArrowField], + lineage: &Lineage, +) -> Option { + let source_definitions: Vec = serde_json::from_str(raw).ok()?; + // The definition sits on the column the function writes, so the source + // schema's field name at that position is the embedding's destination. + let embeddings: HashMap<&str, &EmbeddingDefinition> = source_schema + .fields() + .iter() + .zip(&source_definitions) + .filter_map(|(field, definition)| match &definition.kind { + ColumnKind::Embedding(embedding) => Some((field.name().as_str(), embedding)), + ColumnKind::Physical => None, + }) + .collect(); + let sources: HashMap<&str, &str> = lineage + .iter() + .flat_map(|(source, outputs)| outputs.iter().map(move |o| (o.as_str(), source.as_str()))) + .collect(); + + let mut kept = false; + let definitions: Vec = view_fields + .iter() + .map(|field| { + let kind = embedding_for_output(field.name(), &embeddings, &sources, lineage) + .map(|embedding| { + kept = true; + ColumnKind::Embedding(embedding) + }) + .unwrap_or(ColumnKind::Physical); + ColumnDefinition { kind } + }) + .collect(); + kept.then(|| serde_json::to_string(&definitions).ok())? +} + +/// The embedding `output` inherits, renamed to the view's columns. `None` +/// unless the view projects both the function's input and its output +/// directly: anything else advertises a column the view cannot recompute. +fn embedding_for_output( + output: &str, + embeddings: &HashMap<&str, &EmbeddingDefinition>, + sources: &HashMap<&str, &str>, + lineage: &Lineage, +) -> Option { + let embedding = embeddings.get(sources.get(output)?)?; + // The input may be projected several times; the first name the view gives + // it is the one this column is defined against. + let input = lineage.get(&embedding.source_column)?.first()?; + Some(EmbeddingDefinition { + source_column: input.clone(), + dest_column: Some(output.to_string()), + embedding_name: embedding.embedding_name.clone(), + }) +} + +/// The source field a projection reads directly, if it reads one: a bare +/// column, or a path of struct field accesses over one. Anything computed +/// produces a new value and has no source field. +fn projected_field<'a>( + expr: &datafusion_expr::Expr, + schema: &'a ArrowSchema, +) -> Option<&'a ArrowField> { + let path = projected_path(expr)?; + let mut segments = path.iter(); + let mut field = schema.field_with_name(segments.next()?).ok()?; + for segment in segments { + let DataType::Struct(children) = field.data_type() else { + return None; + }; + field = children.iter().find(|c| c.name() == segment)?; + } + Some(field) +} + +/// The dotted path a projection reads directly, root first. +fn projected_path(expr: &datafusion_expr::Expr) -> Option> { + let mut path = Vec::new(); + let mut node = expr; + loop { + match node { + datafusion_expr::Expr::Column(column) => { + path.push(column.name.clone()); + break; + } + // `a.b` parses to get_field(a, "b"), nested for deeper paths. + datafusion_expr::Expr::ScalarFunction(call) if call.func.name() == "get_field" => { + let [ + inner, + datafusion_expr::Expr::Literal(ScalarValue::Utf8(Some(name)), _), + ] = call.args.as_slice() + else { + return None; + }; + path.push(name.clone()); + node = inner; + } + _ => return None, + } + } + + path.reverse(); + Some(path) +} + +/// `field` without the metadata that declares how a column is written, at +/// every depth; descriptive metadata (blob markers) stays. A view is written +/// by refresh alone, and its always-nullable fields contradict declarations. +fn is_declaration(key: &str) -> bool { + key.starts_with(SCHEMA_DECLARATION_META_PREFIX) + || key == LANCE_FIELD_ID_KEY + || crate::table::computed_columns::is_declaration_key(key) +} + +fn without_declarations(field: &ArrowField) -> ArrowField { + let metadata: HashMap = field + .metadata() + .iter() + .filter(|(key, _)| !is_declaration(key)) + .map(|(key, value)| (key.clone(), value.clone())) + .collect(); + let strip = |child: &FieldRef| Arc::new(without_declarations(child)); + // Every Arrow variant that carries a field carries that field's metadata + // with it, so all of them are descended. + let data_type = match field.data_type() { + DataType::Struct(children) => DataType::Struct(children.iter().map(strip).collect()), + DataType::List(child) => DataType::List(strip(child)), + DataType::ListView(child) => DataType::ListView(strip(child)), + DataType::LargeList(child) => DataType::LargeList(strip(child)), + DataType::LargeListView(child) => DataType::LargeListView(strip(child)), + DataType::Map(entries, sorted) => DataType::Map(strip(entries), *sorted), + DataType::FixedSizeList(child, len) => DataType::FixedSizeList(strip(child), *len), + DataType::Union(variants, mode) => DataType::Union( + variants + .iter() + .map(|(id, child)| (id, strip(child))) + .collect(), + *mode, + ), + DataType::RunEndEncoded(run_ends, values) => { + DataType::RunEndEncoded(strip(run_ends), strip(values)) + } + other => other.clone(), + }; + ArrowField::new(field.name(), data_type, field.is_nullable()).with_metadata(metadata) +} + +fn resolve_inputs( + schema: &ArrowSchema, + expr: &datafusion_expr::Expr, + error: impl Fn(String) -> Error, +) -> Result> { + let mut inputs = Planner::column_names_in_expr(expr); + inputs.sort(); + inputs.dedup(); + for input in &inputs { + if schema.field_with_name(root(input)).is_err() { + return Err(error(format!("unknown column '{input}'"))); + } + } + Ok(inputs) +} + +/// Project the root fields of `columns`, deduplicated, in schema order. +fn project_schema(schema: &ArrowSchema, columns: &[String]) -> SchemaRef { + let roots: std::collections::HashSet<&str> = columns.iter().map(|c| root(c)).collect(); + let fields: Vec = schema + .fields() + .iter() + .filter(|f| roots.contains(f.name().as_str())) + .map(|f| f.as_ref().clone()) + .collect(); + Arc::new(ArrowSchema::new(fields)) +} + +/// A validated view declaration, ready to become a table: the projected +/// fields plus [`SOURCE_ROW_ID_COLUMN`], definition stamped in metadata. +/// Produced only by [`prepare_declaration`]. +#[derive(Clone)] +pub struct PreparedDeclaration { + schema: SchemaRef, + definition: MaterializedViewDefinition, + /// The source's own database: the only place + /// [`PreparedDeclaration::create`] will put the view, because refresh + /// resolves the recorded source name through the view's database. + database: Arc, +} + +impl std::fmt::Debug for PreparedDeclaration { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PreparedDeclaration") + .field("definition", &self.definition) + .finish_non_exhaustive() + } +} + +impl PreparedDeclaration { + /// The query the declaration records. + pub fn definition(&self) -> &MaterializedViewDefinition { + &self.definition + } + + /// Create the view table and verify it, consuming the declaration. + /// + /// The view goes in the source's own database, where refresh resolves the + /// recorded source name. Stable row ids are requested at both levels and + /// verified rather than trusted; nothing is rolled back on failure. + pub async fn create(self, name: &str) -> Result { + let empty: Vec> = + vec![]; + let reader: Box = + Box::new(arrow_array::RecordBatchIterator::new(empty, self.schema)); + let mut request = CreateTableRequest::new(name.to_string(), Box::new(reader)); + let write_params = request + .write_options + .lance_write_params + .get_or_insert_with(Default::default); + write_params.enable_stable_row_ids = true; + let store_params = write_params + .store_params + .get_or_insert_with(Default::default); + crate::connection::merge_storage_options( + store_params, + [( + OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS.to_string(), + "true".to_string(), + )], + ); + let table = self.database.clone().create_table(request).await?; + let table = Table::new(table, self.database); + let stable = match table.as_native() { + Some(native) => native.dataset.get().await?.manifest.uses_stable_row_ids(), + None => false, + }; + if !stable { + return Err(Error::Runtime { + message: format!( + "view '{name}' was created without stable row ids: the database \ + ignored the creation option; the table remains and is not \ + usable as a materialized view" + ), + }); + } + Ok(MaterializedView { + table, + definition: self.definition, + }) + } +} + +/// Validate a view declaration against its live source and hold what its +/// creation needs. The declaration is canonicalized through the coordinate a +/// refresh will resolve, so a handle that does not resolve back to itself is +/// rejected, as is a namespaced source. Same creation-time checks as +/// [`Connection::create_materialized_view`]. +/// +/// ```no_run +/// # #![recursion_limit = "256"] +/// # use lancedb::materialized_view::prepare_declaration; +/// # async fn declare(source: &lancedb::Table) -> Result<(), Box> { +/// let prepared = prepare_declaration( +/// source, +/// &[("id".into(), "id".into()), ("double".into(), "value * 2".into())], +/// Some("value > 0"), +/// None, +/// ) +/// .await?; +/// let view = prepared.create("doubles").await?; +/// # Ok(()) +/// # } +/// ``` +pub async fn prepare_declaration( + source: &Table, + projections: &[(String, String)], + filter: Option<&str>, + limit: Option, +) -> Result { + let Some(caller_native) = source.as_native() else { + return Err(Error::NotSupported { + message: "materialized views are supported only on local databases".into(), + }); + }; + // The definition records the source by bare name; any other source + // form would be recorded as a name its refresh cannot resolve. + if !source.namespace().is_empty() { + return Err(Error::NotSupported { + message: format!( + "a namespaced source cannot be recorded in a view definition; \ + '{}' must be a root-namespace table", + source.name() + ), + }); + } + let database = source + .database_opt() + .ok_or_else(|| Error::InvalidInput { + message: "the source was not opened through a database connection".into(), + })? + .clone(); + + // Canonicalize: resolve the recorded coordinate exactly the way a + // refresh will, and plan from what it reaches. A handle that does not + // resolve back to itself must not be declared under this name. + let resolved = database + .open_table(OpenTableRequest { + name: source.name().to_string(), + namespace_path: vec![], + index_cache_size: None, + lance_read_params: None, + location: None, + namespace_client: None, + managed_versioning: None, + }) + .await?; + let resolved = Table::new(resolved, database.clone()); + let Some(native) = resolved.as_native() else { + return Err(Error::NotSupported { + message: "materialized views are supported only on local databases".into(), + }); + }; + let caller_uri = caller_native.dataset.get().await?.uri().to_string(); + let resolved_uri = native.dataset.get().await?.uri().to_string(); + if caller_uri != resolved_uri { + return Err(Error::InvalidInput { + message: format!( + "the source handle does not resolve to itself through its \ + database: '{}' resolves to '{resolved_uri}', but the handle \ + reads '{caller_uri}'", + source.name() + ), + }); + } + if !native.dataset.get().await?.manifest.uses_stable_row_ids() { + return Err(Error::InvalidInput { + message: format!( + "materialized views require stable row ids on the source table; \ + create '{}' with storage option new_table_enable_stable_row_ids=true", + source.name() + ), + }); + } + let source_schema = resolved.schema().await?; + let source_metadata = source_schema.metadata().clone(); + let (definition, mut fields, lineage) = plan( + source_schema.clone(), + resolved.name(), + projections, + filter, + limit, + )?; + fields.push(ArrowField::new( + SOURCE_ROW_ID_COLUMN, + DataType::UInt64, + false, + )); + // Only column-describing metadata comes along: structural declarations + // describe how a table is written, and a view is written by refresh alone. + let mut metadata: HashMap = HashMap::new(); + if let Some(raw) = source_metadata.get(EMBEDDING_FUNCTIONS_META_KEY) + && let Some(rewritten) = embedding_config_for_view(raw, &lineage) + { + metadata.insert(EMBEDDING_FUNCTIONS_META_KEY.to_string(), rewritten); + } + if let Some(raw) = source_metadata.get(COLUMN_DEFINITIONS_META_KEY) + && let Some(rewritten) = column_definitions_for_view(raw, &source_schema, &fields, &lineage) + { + metadata.insert(COLUMN_DEFINITIONS_META_KEY.to_string(), rewritten); + } + metadata.insert( + DEFINITION_META_KEY.to_string(), + definition_to_metadata(&definition)?, + ); + Ok(PreparedDeclaration { + schema: Arc::new(ArrowSchema::new_with_metadata(fields, metadata)), + definition, + database, + }) +} + +/// One row of [`Connection::list_materialized_views`]: a view's name and its +/// definition kind, which may be one this version cannot refresh. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MaterializedViewEntry { + /// Name of the view's table. + pub name: String, + /// The view's definition as stored. + pub kind: MaterializedViewKind, +} + +/// Materialized views are local-only; refuse a remote connection before any +/// request is made. +fn ensure_local(connection: &Connection) -> Result<()> { + if connection.uri().starts_with("db://") { + return Err(Error::NotSupported { + message: "materialized views are supported only on local databases".into(), + }); + } + Ok(()) +} + +/// Builds a materialized view. Created by +/// [`Connection::create_materialized_view`]. +pub struct CreateMaterializedViewBuilder { + connection: Connection, + name: String, + source: String, + projections: Vec<(String, String)>, + filter: Option, + limit: Option, +} + +impl CreateMaterializedViewBuilder { + pub(crate) fn new(connection: Connection, name: String, source: String) -> Self { + Self { + connection, + name, + source, + projections: Vec::new(), + filter: None, + limit: None, + } + } + + /// The view's columns, as `(name, SQL expression)` pairs. Not calling + /// this selects every source column, expanded at creation time. + pub fn select( + mut self, + columns: impl IntoIterator, impl Into)>, + ) -> Self { + self.projections = columns + .into_iter() + .map(|(output, expression)| (output.into(), expression.into())) + .collect(); + self + } + + /// Only source rows matching the SQL predicate appear in the view. + pub fn only_if(mut self, filter: impl Into) -> Self { + self.filter = Some(filter.into()); + self + } + + /// Cap the view at `limit` rows, in materialization order. + pub fn limit(mut self, limit: u64) -> Self { + self.limit = Some(limit); + self + } + + /// Create the view: an empty table carrying the definition; refresh + /// computes the rows. The source must keep stable row ids -- they hold + /// provenance across compaction, and cannot be enabled later. + pub async fn execute(self) -> Result { + ensure_local(&self.connection)?; + let source = self.connection.open_table(&self.source).execute().await?; + let prepared = prepare_declaration( + &source, + &self.projections, + self.filter.as_deref(), + self.limit, + ) + .await?; + prepared.create(&self.name).await + } +} + +/// A handle on a materialized view: the view table plus its parsed definition. +#[derive(Debug, Clone)] +pub struct MaterializedView { + table: Table, + definition: MaterializedViewDefinition, +} + +impl MaterializedView { + /// Interpret `table` as a materialized view: [`Error::NotAMaterializedView`] + /// for a plain table, [`Error::NotSupported`] for a kind this version + /// cannot refresh. + pub async fn from_table(table: Table) -> Result { + // Same local-only boundary the connection-level entry points hold, + // applied before the schema read so a remote table costs no request. + if table.as_native().is_none() { + return Err(Error::NotSupported { + message: "materialized views are supported only on local databases".into(), + }); + } + let schema = table.schema().await?; + match materialized_view_kind(schema.metadata())? { + Some(MaterializedViewKind::Select(definition)) => Ok(Self { table, definition }), + Some(MaterializedViewKind::Unrecognized { kind }) => Err(Error::NotSupported { + message: format!( + "materialized view '{}' is defined by '{kind}', which this version of \ + lancedb cannot refresh", + table.name() + ), + }), + None => Err(Error::NotAMaterializedView { + name: table.name().to_string(), + }), + } + } + + /// The view, as the table it is. Queries, indexes and search all apply. + pub fn table(&self) -> &Table { + &self.table + } + + /// The view's table name. + pub fn name(&self) -> &str { + self.table.name() + } + + /// The query that defines the view. + pub fn definition(&self) -> &MaterializedViewDefinition { + &self.definition + } +} + +impl Connection { + /// Define a materialized view named `name` over `source`. + /// + /// The view is created empty, with the definition recorded in its schema + /// metadata; refresh computes the rows. Local databases only. + /// + /// ```no_run + /// # use lancedb::Connection; + /// # async fn create(conn: &Connection) -> Result<(), Box> { + /// let view = conn + /// .create_materialized_view("loud_adults", "people") + /// .select([("name", "upper(name)"), ("age", "age")]) + /// .only_if("age >= 18") + /// .execute() + /// .await?; + /// println!("{}", view.definition().source_table); + /// # Ok(()) + /// # } + /// ``` + pub fn create_materialized_view( + &self, + name: impl Into, + source: impl Into, + ) -> CreateMaterializedViewBuilder { + CreateMaterializedViewBuilder::new(self.clone(), name.into(), source.into()) + } + + /// Open the materialized view named `name`. + pub async fn open_materialized_view( + &self, + name: impl Into, + ) -> Result { + ensure_local(self)?; + let table = self.open_table(name).execute().await?; + MaterializedView::from_table(table).await + } + + /// The materialized views in this database, unrefreshable kinds included. + /// Costs a table open per table; one that cannot be opened is skipped + /// rather than failing the listing. + pub async fn list_materialized_views(&self) -> Result> { + ensure_local(self)?; + let names = self.table_names().execute().await?; + let mut views = Vec::new(); + for name in names { + let Ok(table) = self.open_table(&name).execute().await else { + continue; + }; + let schema = table.schema().await?; + if let Some(kind) = materialized_view_kind(schema.metadata())? { + views.push(MaterializedViewEntry { name, kind }); + } + } + Ok(views) + } +} + +#[cfg(test)] +mod tests { + use arrow_array::record_batch; + + use super::*; + use crate::connect; + use crate::table::WriteOptions; + + async fn people_db() -> Connection { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!( + ("name", Utf8, ["ada", "grace", "alan"]), + ("age", Int32, [36, 85, 41]) + ) + .unwrap(); + conn.create_table("people", batch) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + conn + } + + /// Sources must keep stable row ids; see the create-time gate. + pub(super) fn stable_row_ids() -> WriteOptions { + WriteOptions { + lance_write_params: Some(lance::dataset::WriteParams { + enable_stable_row_ids: true, + ..Default::default() + }), + } + } + + /// The error a doomed declaration against `people` produces. + async fn declare_err( + cfg: impl FnOnce(CreateMaterializedViewBuilder) -> CreateMaterializedViewBuilder, + ) -> Error { + let conn = people_db().await; + cfg(conn.create_materialized_view("bad", "people")) + .execute() + .await + .unwrap_err() + } + + #[tokio::test] + async fn test_create_records_the_definition() { + let conn = people_db().await; + let view = conn + .create_materialized_view("adults", "people") + .select([("name", "name"), ("shout", "upper(name)")]) + .only_if("age >= 18") + .limit(10) + .execute() + .await + .unwrap(); + + assert_eq!(view.name(), "adults"); + assert_eq!( + view.definition(), + &MaterializedViewDefinition { + source_table: "people".into(), + projections: vec![ + ViewProjection { + output: "name".into(), + expression: "name".into() + }, + ViewProjection { + output: "shout".into(), + expression: "upper(name)".into() + }, + ], + filter: Some("age >= 18".into()), + limit: Some(10), + inputs: vec!["age".into(), "name".into()], + } + ); + + // The definition round-trips off the stored schema, not the handle. + let reopened = conn.open_materialized_view("adults").await.unwrap(); + assert_eq!(reopened.definition(), view.definition()); + } + + #[tokio::test] + async fn test_view_schema_is_derived_from_the_query() { + let conn = people_db().await; + let view = conn + .create_materialized_view("shapes", "people") + .select([("shout", "upper(name)"), ("next_age", "age + 1")]) + .execute() + .await + .unwrap(); + + let schema = view.table().schema().await.unwrap(); + assert_eq!( + schema.field_with_name("shout").unwrap().data_type(), + &DataType::Utf8 + ); + assert_eq!( + schema.field_with_name("next_age").unwrap().data_type(), + &DataType::Int32 + ); + assert_eq!( + schema + .field_with_name(SOURCE_ROW_ID_COLUMN) + .unwrap() + .data_type(), + &DataType::UInt64 + ); + assert_eq!(view.table().count_rows(None).await.unwrap(), 0); + } + + /// No projection selects every source column, expanded now: the schema + /// captured at creation is the definition. + #[tokio::test] + async fn test_default_projection_captures_the_source_schema() { + let conn = people_db().await; + let view = conn + .create_materialized_view("copy", "people") + .execute() + .await + .unwrap(); + assert_eq!( + view.definition() + .projections + .iter() + .map(|p| p.output.as_str()) + .collect::>(), + vec!["name", "age"] + ); + assert_eq!(view.definition().inputs, vec!["age", "name"]); + } + + #[tokio::test] + async fn test_unknown_column_fails_at_create_time() { + let conn = people_db().await; + let err = conn + .create_materialized_view("bad", "people") + .select([("x", "missing + 1")]) + .execute() + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidExpression { column, .. } if column == "x")); + let names = conn.table_names().execute().await.unwrap(); + assert!(!names.contains(&"bad".to_string())); + } + + #[tokio::test] + async fn test_unknown_filter_column_fails_at_create_time() { + let err = declare_err(|b| b.only_if("missing > 1")).await; + assert!(matches!(err, Error::InvalidInput { message } if message.contains("missing"))); + } + + #[tokio::test] + async fn test_duplicate_output_is_rejected() { + let err = declare_err(|b| b.select([("dup", "age"), ("dup", "age + 1")])).await; + assert!(matches!(err, Error::ColumnAlreadyExists { name } if name == "dup")); + } + + #[tokio::test] + async fn test_reserved_output_name_is_rejected() { + let err = declare_err(|b| b.select([(SOURCE_ROW_ID_COLUMN, "age")])).await; + assert!(matches!(err, Error::InvalidInput { message } if message.contains("reserved"))); + } + + #[tokio::test] + async fn test_missing_source_fails() { + let conn = connect("memory://").execute().await.unwrap(); + let err = conn + .create_materialized_view("v", "nope") + .execute() + .await + .unwrap_err(); + assert!(matches!(err, Error::TableNotFound { .. })); + } + + /// Provenance has to survive source compactions and updates, and stable + /// row ids cannot be enabled after a table exists -- so the requirement + /// is checked at the last moment the caller can still act on it. + #[tokio::test] + async fn test_source_without_stable_row_ids_is_refused() { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!(("x", Int32, [1, 2])).unwrap(); + conn.create_table("plain", batch).execute().await.unwrap(); + + let err = conn + .create_materialized_view("v", "plain") + .execute() + .await + .unwrap_err(); + assert!( + matches!(err, Error::InvalidInput { message } if message.contains("stable row ids")) + ); + assert!( + !conn + .table_names() + .execute() + .await + .unwrap() + .contains(&"v".to_string()) + ); + } + + #[tokio::test] + async fn test_name_collision_fails() { + let conn = people_db().await; + let err = conn + .create_materialized_view("people", "people") + .execute() + .await + .unwrap_err(); + assert!(matches!(err, Error::TableAlreadyExists { .. })); + } + + #[tokio::test] + async fn test_a_plain_table_is_not_a_view() { + let conn = people_db().await; + let table = conn.open_table("people").execute().await.unwrap(); + let err = MaterializedView::from_table(table).await.unwrap_err(); + assert!(matches!(err, Error::NotAMaterializedView { name } if name == "people")); + + let err = conn.open_materialized_view("people").await.unwrap_err(); + assert!(matches!(err, Error::NotAMaterializedView { .. })); + } + + /// The reason the kind is tagged: a definition written by a newer version + /// reads back as a view this one cannot refresh, not as a plain table. + #[tokio::test] + async fn test_unrecognized_kind_is_refused_by_name() { + let conn = people_db().await; + conn.create_materialized_view("v", "people") + .execute() + .await + .unwrap(); + let table = conn.open_table("v").execute().await.unwrap(); + table + .as_native() + .unwrap() + .replace_schema_metadata(HashMap::from([( + DEFINITION_META_KEY.to_string(), + r#"{"kind": "join"}"#.to_string(), + )])) + .await + .unwrap(); + + let err = conn.open_materialized_view("v").await.unwrap_err(); + assert!(matches!(err, Error::NotSupported { message } if message.contains("join"))); + } + + #[tokio::test] + async fn test_list_reports_views_and_only_views() { + let conn = people_db().await; + conn.create_materialized_view("adults", "people") + .only_if("age >= 18") + .execute() + .await + .unwrap(); + + let views = conn.list_materialized_views().await.unwrap(); + assert_eq!( + views.iter().map(|v| v.name.as_str()).collect::>(), + vec!["adults"] + ); + let MaterializedViewKind::Select(definition) = &views[0].kind else { + panic!("expected a select view"); + }; + assert_eq!(definition.filter.as_deref(), Some("age >= 18")); + } + + /// The creation option outranks a connection configured to create + /// unstable tables: the view still gets stable row ids, on the same + /// store (no fork -- the table must be reachable through the + /// connection afterwards). + #[tokio::test] + async fn test_view_is_stable_despite_connection_override() { + let conn = connect("memory://") + .storage_options([("new_table_enable_stable_row_ids", "false")]) + .execute() + .await + .unwrap(); + let batch = record_batch!(("x", Int32, [1])).unwrap(); + conn.create_table("src", batch) + .storage_option("new_table_enable_stable_row_ids", "true") + .execute() + .await + .unwrap(); + + let view = conn + .create_materialized_view("v", "src") + .execute() + .await + .unwrap(); + let stable = view + .table() + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .manifest + .uses_stable_row_ids(); + assert!(stable); + conn.open_materialized_view("v").await.unwrap(); + } + + /// A committed filter has to be usable as a predicate. + #[tokio::test] + async fn test_non_boolean_filter_is_rejected() { + let err = declare_err(|b| b.only_if("age + 1")).await; + assert!(matches!(err, Error::InvalidInput { message } if message.contains("boolean"))); + } + + /// Nested references stay dotted paths; resolution is by root field. + #[tokio::test] + async fn test_struct_columns_can_be_declared() { + use arrow_array::{ArrayRef, Int32Array, StructArray}; + + let conn = connect("memory://").execute().await.unwrap(); + let ages = StructArray::from(vec![( + Arc::new(ArrowField::new("age", DataType::Int32, false)), + Arc::new(Int32Array::from(vec![36, 17])) as ArrayRef, + )]); + let batch = + arrow_array::RecordBatch::try_from_iter(vec![("metadata", Arc::new(ages) as ArrayRef)]) + .unwrap(); + conn.create_table("people", batch) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + + let view = conn + .create_materialized_view("ages", "people") + .select([("age", "metadata.age")]) + .only_if("metadata.age >= 18") + .execute() + .await + .unwrap(); + assert_eq!(view.definition().inputs, vec!["metadata.age"]); + let schema = view.table().schema().await.unwrap(); + assert_eq!( + schema.field_with_name("age").unwrap().data_type(), + &DataType::Int32 + ); + } + + /// A newer-kind view must not disappear from the listing. + #[tokio::test] + async fn test_unrecognized_kind_is_listed_with_its_kind() { + let conn = people_db().await; + conn.create_materialized_view("v", "people") + .execute() + .await + .unwrap(); + let table = conn.open_table("v").execute().await.unwrap(); + table + .as_native() + .unwrap() + .replace_schema_metadata(HashMap::from([( + DEFINITION_META_KEY.to_string(), + r#"{"kind": "join"}"#.to_string(), + )])) + .await + .unwrap(); + + let views = conn.list_materialized_views().await.unwrap(); + assert_eq!(views.len(), 1); + assert_eq!(views[0].name, "v"); + assert_eq!( + views[0].kind, + MaterializedViewKind::Unrecognized { + kind: "join".into() + } + ); + } + + /// Remote connections are refused before any request is made. + #[cfg(feature = "remote")] + #[tokio::test] + async fn test_remote_connection_is_refused_up_front() { + let conn = connect("db://nowhere") + .api_key("sk_test") + .region("us-east-1") + .execute() + .await + .unwrap(); + let err = conn + .create_materialized_view("v", "src") + .execute() + .await + .unwrap_err(); + assert!(matches!(err, Error::NotSupported { .. })); + let err = conn.open_materialized_view("v").await.unwrap_err(); + assert!(matches!(err, Error::NotSupported { .. })); + let err = conn.list_materialized_views().await.unwrap_err(); + assert!(matches!(err, Error::NotSupported { .. })); + } + + /// A definition must evaluate identically across refreshes; anything + /// less makes incremental maintenance a mix of evaluations. + #[tokio::test] + async fn test_volatile_and_unstable_expressions_are_rejected() { + let conn = people_db().await; + for expression in [ + "random()", + "now()", + "version()", + "arrow_typeof(age)", + "arrow_metadata(age, 'k')", + ] { + let err = conn + .create_materialized_view("bad", "people") + .select([("x", expression)]) + .execute() + .await + .unwrap_err(); + assert!( + matches!(err, Error::InvalidExpression { message, .. } + if message.contains("not immutable")), + "{expression} was not rejected" + ); + } + for filter in ["age > random() * 100", "age >= 0 and now() is not null"] { + let err = conn + .create_materialized_view("bad", "people") + .only_if(filter) + .execute() + .await + .unwrap_err(); + assert!( + matches!(err, Error::InvalidInput { message } if message.contains("not immutable")), + "{filter} was not rejected" + ); + } + } + + /// A column projected as itself stays the column it was: blob discovery + /// and the blob APIs key off field metadata, which a bare rebuild of the + /// field would drop. + #[tokio::test] + async fn test_identity_projection_keeps_field_metadata() { + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(ArrowSchema::new_with_metadata( + vec![ + ArrowField::new("id", DataType::Int32, true), + crate::blob("payload", true), + ], + HashMap::new(), + )); + conn.create_empty_table("src", schema) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + + let view = conn + .create_materialized_view("v", "src") + .execute() + .await + .unwrap(); + let view_schema = view.table().schema().await.unwrap(); + + let payload = view_schema.field_with_name("payload").unwrap(); + assert!( + crate::blob::is_blob(payload), + "default projection dropped the blob marker: {:?}", + payload.metadata() + ); + assert_eq!( + view.table().blob_columns().await.unwrap(), + vec!["payload".to_string()], + "blob discovery no longer finds the projected column" + ); + assert!(view_schema.metadata().contains_key(DEFINITION_META_KEY)); + // Structural declarations describe how a table is written; a view is + // written by refresh, and its fields are always nullable. + assert!(!view_schema.metadata().contains_key("lance:primary_key")); + + // A computed column is a new value and carries no source metadata. + let computed = conn + .create_materialized_view("c", "src") + .select([("payload", "payload"), ("n", "id + 1")]) + .execute() + .await + .unwrap(); + let computed_schema = computed.table().schema().await.unwrap(); + assert!(crate::blob::is_blob( + computed_schema.field_with_name("payload").unwrap() + )); + assert!( + computed_schema + .field_with_name("n") + .unwrap() + .metadata() + .is_empty() + ); + } + + /// A nested column projected straight through is still that column, and a + /// declaration buried in a struct child binds as hard as one on top. + #[tokio::test] + async fn test_nested_projection_metadata_and_declarations() { + let conn = connect("memory://").execute().await.unwrap(); + let payload = crate::blob("payload", true).with_metadata(HashMap::from([ + ("lance-encoding:blob".to_string(), "true".to_string()), + ( + "lance-schema:unenforced-primary-key".to_string(), + "0".to_string(), + ), + ])); + let schema = Arc::new(ArrowSchema::new(vec![ + ArrowField::new("id", DataType::Int32, true), + ArrowField::new("meta", DataType::Struct(vec![payload].into()), true), + ])); + conn.create_empty_table("src", schema) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + + // A nested path is a direct projection: the leaf's metadata comes with + // it, so the blob stays a blob rather than a plain struct. + let lifted = conn + .create_materialized_view("lifted", "src") + .select([("payload", "meta.payload")]) + .execute() + .await + .unwrap(); + let field = lifted.table().schema().await.unwrap(); + let field = field.field_with_name("payload").unwrap().clone(); + assert_eq!( + field.metadata().get("lance-encoding:blob"), + Some(&"true".to_string()), + "nested projection lost the leaf's metadata" + ); + assert!( + !field + .metadata() + .contains_key("lance-schema:unenforced-primary-key"), + "a structural declaration rode along" + ); + + // Projecting the struct whole must not carry the child's declaration + // out to a view whose fields are nullable. + let whole = conn + .create_materialized_view("whole", "src") + .select([("meta", "meta")]) + .execute() + .await + .unwrap(); + let schema = whole.table().schema().await.unwrap(); + let DataType::Struct(children) = schema.field_with_name("meta").unwrap().data_type() else { + panic!("meta is not a struct"); + }; + let child = children.iter().find(|c| c.name() == "payload").unwrap(); + assert!( + !child + .metadata() + .contains_key("lance-schema:unenforced-primary-key"), + "a nested declaration survived: {:?}", + child.metadata() + ); + assert_eq!( + child.metadata().get("lance-encoding:blob"), + Some(&"true".to_string()) + ); + } + + /// A map's entries are fields like any other, and a declaration on one + /// binds the view's writes just as hard as one on top. + #[tokio::test] + async fn test_map_declarations_are_stripped() { + let conn = connect("memory://").execute().await.unwrap(); + let value = + ArrowField::new("value", DataType::Utf8, false).with_metadata(HashMap::from([( + "lance-schema:unenforced-clustering-key:position".to_string(), + "1".to_string(), + )])); + let entries = ArrowField::new( + "entries", + DataType::Struct(vec![ArrowField::new("key", DataType::Utf8, false), value].into()), + false, + ); + let schema = Arc::new(ArrowSchema::new(vec![ArrowField::new( + "props", + DataType::Map(Arc::new(entries), false), + true, + )])); + conn.create_empty_table("src", schema) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + + let view = conn + .create_materialized_view("view", "src") + .execute() + .await + .unwrap(); + let schema = view.table().schema().await.unwrap(); + let DataType::Map(entries, _) = schema.field_with_name("props").unwrap().data_type() else { + panic!("props is not a map"); + }; + let DataType::Struct(children) = entries.data_type() else { + panic!("map entries are not a struct"); + }; + let value = children.iter().find(|c| c.name() == "value").unwrap(); + assert!( + !value + .metadata() + .contains_key("lance-schema:unenforced-clustering-key:position"), + "a declaration survived inside a map: {:?}", + value.metadata() + ); + } + + /// A computed column is declared by field metadata. Projecting one -- + /// as itself or under an alias -- must carry its description without its + /// declaration, which the target table would reject as foreign. + #[tokio::test] + async fn test_view_over_a_computed_column() { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!(("id", Int32, [1, 2])).unwrap(); + let source = conn + .create_table("src", batch) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + source + .add_columns() + .computed("doubled", "id * 2") + .execute() + .await + .unwrap(); + + // Default projection reaches the computed column too. + let whole = conn + .create_materialized_view("whole", "src") + .execute() + .await + .unwrap(); + let schema = whole.table().schema().await.unwrap(); + let field = schema.field_with_name("doubled").unwrap(); + assert!( + !field + .metadata() + .keys() + .any(|k| k.starts_with("computed_column")), + "a computed-column declaration rode along: {:?}", + field.metadata() + ); + + // And under an alias. + conn.create_materialized_view("aliased", "src") + .select([("twice", "doubled")]) + .execute() + .await + .unwrap(); + } + + /// Embedding configuration names columns. It comes along only for the + /// columns a view actually projects, under the names the view gives them. + #[tokio::test] + async fn test_embedding_config_follows_the_projection() { + let config = r#"[{"name":"f","model":{},"source_column":"text","vector_column":"vec"}]"#; + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(ArrowSchema::new_with_metadata( + vec![ + ArrowField::new("text", DataType::Utf8, true), + ArrowField::new("vec", DataType::Float32, true), + ], + HashMap::from([("embedding_functions".to_string(), config.to_string())]), + )); + conn.create_empty_table("src", schema) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + + let carried = |view: &MaterializedView| { + let view = view.table().clone(); + async move { + view.schema() + .await + .unwrap() + .metadata() + .get("embedding_functions") + .cloned() + } + }; + + // Both columns projected as themselves: kept as it stands. + let whole = conn + .create_materialized_view("whole", "src") + .execute() + .await + .unwrap(); + let kept = carried(&whole).await.expect("config dropped"); + assert!(kept.contains(r#""source_column":"text""#), "{kept}"); + assert!(kept.contains(r#""vector_column":"vec""#), "{kept}"); + + // Only the source column: the configuration names a vector column the + // view does not have, so it describes nothing and goes. + let partial = conn + .create_materialized_view("partial", "src") + .select([("text", "text")]) + .execute() + .await + .unwrap(); + assert_eq!(carried(&partial).await, None); + + // Renamed: the configuration follows the names the view uses. + let renamed = conn + .create_materialized_view("renamed", "src") + .select([("body", "text"), ("embedding", "vec")]) + .execute() + .await + .unwrap(); + let remapped = carried(&renamed).await.expect("config dropped"); + assert!(remapped.contains(r#""source_column":"body""#), "{remapped}"); + assert!( + remapped.contains(r#""vector_column":"embedding""#), + "{remapped}" + ); + + // The Node bindings spell the same configuration in camelCase, and + // the Rust definition names the destination `dest_column`. + for (config, source_key, dest_key) in [ + ( + r#"[{"name":"f","model":{},"sourceColumn":"text","vectorColumn":"vec"}]"#, + "sourceColumn", + "vectorColumn", + ), + ( + r#"[{"name":"f","model":{},"source_column":"text","dest_column":"vec"}]"#, + "source_column", + "dest_column", + ), + ] { + let schema = Arc::new(ArrowSchema::new_with_metadata( + vec![ + ArrowField::new("text", DataType::Utf8, true), + ArrowField::new("vec", DataType::Float32, true), + ], + HashMap::from([("embedding_functions".to_string(), config.to_string())]), + )); + let name = format!("src_{source_key}"); + conn.create_empty_table(&name, schema) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + let view = conn + .create_materialized_view(format!("v_{source_key}"), &name) + .select([("body", "text"), ("embedding", "vec")]) + .execute() + .await + .unwrap(); + let carried = carried(&view).await.expect("config dropped"); + assert!( + carried.contains(&format!(r#""{source_key}":"body""#)), + "{carried}" + ); + assert!( + carried.contains(&format!(r#""{dest_key}":"embedding""#)), + "{carried}" + ); + } + + // A computed column is not the source column under another name. + let computed = conn + .create_materialized_view("computed", "src") + .select([("body", "upper(text)"), ("embedding", "vec")]) + .execute() + .await + .unwrap(); + assert_eq!(carried(&computed).await, None); + + // One column projected twice is two columns in the view, and the + // configuration has to describe both rather than whichever came last. + let twice = conn + .create_materialized_view("twice", "src") + .select([("body", "text"), ("a", "vec"), ("b", "vec")]) + .execute() + .await + .unwrap(); + let carried = carried(&twice).await.expect("config dropped"); + let entries: Vec = serde_json::from_str(&carried).unwrap(); + let mut vectors: Vec<&str> = entries + .iter() + .filter_map(|e| e["vector_column"].as_str()) + .collect(); + vectors.sort_unstable(); + assert_eq!(vectors, ["a", "b"], "{carried}"); + } + + /// The native Rust producer records embeddings as column definitions + /// rather than as `embedding_functions`, and a query embeds its own text + /// through them. They are positional, so the view's list covers every one + /// of its fields. + #[tokio::test] + async fn test_native_column_definitions_follow_the_projection() { + let conn = connect("memory://").execute().await.unwrap(); + let rich = crate::table::TableDefinition::new( + Arc::new(ArrowSchema::new(vec![ + ArrowField::new("text", DataType::Utf8, true), + ArrowField::new("vector", DataType::Float32, true), + ])), + vec![ + ColumnDefinition { + kind: ColumnKind::Physical, + }, + ColumnDefinition { + kind: ColumnKind::Embedding(EmbeddingDefinition::new( + "text", + "model", + Some("vector"), + )), + }, + ], + ) + .into_rich_schema(); + conn.create_empty_table("src", rich) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + + let view = conn + .create_materialized_view("view", "src") + .select([("body", "text"), ("embedding", "vector")]) + .execute() + .await + .unwrap(); + let schema = view.table().schema().await.unwrap(); + let raw = schema + .metadata() + .get(COLUMN_DEFINITIONS_META_KEY) + .expect("the view dropped the native column definitions"); + let definitions: Vec = serde_json::from_str(raw).unwrap(); + assert_eq!( + definitions.len(), + schema.fields().len(), + "column definitions are positional" + ); + let ColumnKind::Embedding(embedding) = &definitions[1].kind else { + panic!("the embedding column came back physical: {raw}"); + }; + assert_eq!(embedding.source_column, "body"); + assert_eq!(embedding.dest_column.as_deref(), Some("embedding")); + assert_eq!(embedding.embedding_name, "model"); + assert!(matches!(definitions[0].kind, ColumnKind::Physical)); + assert!(matches!(definitions[2].kind, ColumnKind::Physical)); + + // Without the column the function reads, the view cannot recompute + // the embedding, so it carries no definition for it. + let partial = conn + .create_materialized_view("partial", "src") + .select([("embedding", "vector")]) + .execute() + .await + .unwrap(); + assert_eq!( + partial + .table() + .schema() + .await + .unwrap() + .metadata() + .get(COLUMN_DEFINITIONS_META_KEY), + None + ); + } + + /// A scan takes the cap as i64, so a larger one is refused where it is + /// declared rather than at the refresh that cannot run it. What a cap of + /// zero means is a refresh question, tested there. + #[tokio::test] + async fn test_limit_above_i64_max_is_refused_at_creation() { + let conn = people_db().await; + let err = conn + .create_materialized_view("too_big", "people") + .limit(i64::MAX as u64 + 1) + .execute() + .await + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("exceeds the maximum")), + "got {err:?}" + ); + + // The boundary itself is accepted. + conn.create_materialized_view("at_max", "people") + .limit(i64::MAX as u64) + .execute() + .await + .unwrap(); + } + + #[tokio::test] + async fn test_drop_is_drop_table() { + let conn = people_db().await; + conn.create_materialized_view("v", "people") + .execute() + .await + .unwrap(); + conn.drop_table("v", &[]).await.unwrap(); + assert!(conn.list_materialized_views().await.unwrap().is_empty()); + } + + /// The public declaration contract: prepare validates the source and + /// create consumes the declaration into a verified view table; a + /// source that cannot anchor refresh and a target outside the + /// source's database are both refused. + #[tokio::test] + async fn prepare_and_create_bind_the_declaration_lifecycle() { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!(("id", Int32, [1, 2]), ("value", Int32, [3, 4])).unwrap(); + let source = conn + .create_table("src", batch.clone()) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + + let projections = [ + ("id".to_string(), "id".to_string()), + ("double".to_string(), "value * 2".to_string()), + ]; + let prepared = prepare_declaration(&source, &projections, Some("value > 0"), None) + .await + .unwrap(); + assert_eq!(prepared.definition().source_table, "src"); + + let view = prepared.create("v").await.unwrap(); + let schema = view.table().schema().await.unwrap(); + let names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect(); + assert_eq!(names, ["id", "double", SOURCE_ROW_ID_COLUMN]); + assert!(schema.metadata().contains_key(DEFINITION_META_KEY)); + + // The same call rejects a source without stable row ids, so an + // external creation path cannot skip the check. + conn.create_table("plain", batch).execute().await.unwrap(); + let plain = conn.open_table("plain").execute().await.unwrap(); + let err = prepare_declaration(&plain, &[], None, None) + .await + .unwrap_err(); + assert!(err.to_string().contains("stable row ids"), "{err}"); + + // A handle whose location does not resolve back through its name is + // refused: the definition would record a name reaching other data. + let plain_uri = plain + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .uri() + .to_string(); + let masquerade = conn + .open_table("src") + .location(plain_uri) + .execute() + .await + .unwrap(); + let err = prepare_declaration(&masquerade, &[], None, None) + .await + .unwrap_err(); + assert!( + err.to_string().contains("does not resolve to itself"), + "{err}" + ); + + // A table created at a custom location is refused outright: its + // recorded name reaches nothing at the database root, so the + // canonical reopen fails before any URI comparison. + let custom = conn + .create_table( + "custom_loc", + record_batch!(("id", Int32, [1, 2]), ("value", Int32, [3, 4])).unwrap(), + ) + .location("memory://elsewhere/custom_loc") + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + let err = prepare_declaration(&custom, &[], None, None) + .await + .unwrap_err(); + assert!(err.to_string().contains("custom_loc"), "{err}"); + + // A namespaced source cannot be recorded in the definition: the + // bare name refresh resolves would reach a different table or none. + let namespaced = crate::table::NativeTable::create( + "memory://ns_src", + "ns_src", + vec!["ns".to_string()], + Box::new(arrow_array::RecordBatchIterator::new( + vec![], + std::sync::Arc::new(arrow_schema::Schema::new(vec![arrow_schema::Field::new( + "id", + arrow_schema::DataType::Int32, + true, + )])), + )) as Box, + None, + None, + None, + None, + std::collections::HashSet::new(), + ) + .await + .unwrap(); + let namespaced = Table::new(std::sync::Arc::new(namespaced), conn.database().clone()); + let err = prepare_declaration(&namespaced, &[], None, None) + .await + .unwrap_err(); + assert!(err.to_string().contains("namespaced source"), "{err}"); + } +} diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index f98d4c8dd..6c446907d 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -10410,6 +10410,20 @@ mod tests { ); } + #[tokio::test] + async fn test_materialized_view_refused_without_a_request() { + // Materialized views are local-only. The table-level entry the + // bindings use must refuse a remote table before reading its schema, + // so the panicking handler is the assertion. + let table = Table::new_with_handler("my_table", |request| -> http::Response { + panic!("unexpected request: {}", request.url().path()) + }); + let err = crate::MaterializedView::from_table(table) + .await + .unwrap_err(); + assert!(matches!(err, Error::NotSupported { .. }), "got {err:?}"); + } + #[tokio::test] async fn test_create_branch_empty_name_rejected_client_side() { use lance::dataset::refs::Ref; diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 096d60345..ca9ed8f26 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1066,6 +1066,11 @@ impl Table { self.database.as_ref().unwrap() } + /// The database this handle was opened through, when it was. + pub fn database_opt(&self) -> Option<&Arc> { + self.database.as_ref() + } + pub fn embedding_registry(&self) -> &Arc { &self.embedding_registry } diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index a3f3da92f..2715a163c 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -193,7 +193,7 @@ fn declared_expression(dataset: &Dataset, column: &str) -> Result { /// /// Lance's dialect delimits with backticks, so a double-quoted name would /// parse as a string literal rather than a column. -fn quote_identifier(name: &str) -> String { +pub(crate) fn quote_identifier(name: &str) -> String { format!("`{}`", name.replace('`', "``")) } From 9e8f1c1a6dffeafcdebf218d4f9e7212f90917f6 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 21 Aug 2026 16:31:34 -0700 Subject: [PATCH 084/206] fix(python): expose FTS build memory limits (#3796) ## Summary - expose `memory_limit` and `num_workers` on the Python FTS configuration for local builds - forward both build-only settings to the Lance inverted-index builder - add an end-to-end regression proving the configured memory budget reaches the native build ## Root cause LanceDB 0.26.1 pinned Lance 1.0.1. That Lance version used an FTS partition-merge path whose retained data made memory grow with merge progress on very large indexes. Upstream Lance [#5754](https://github.com/lance-format/lance/pull/5754) changed partition merging to stream its inputs, reducing peak memory by about 25%. Lance [#6174](https://github.com/lance-format/lance/pull/6174) then removed the old merge phase, compressed posting lists during construction, reduced indexing memory by about 60%, and introduced a total build `memory_limit` for bounded workers. Current `main` pins Lance 11.0.0-beta.3, which contains those architectural fixes. This PR does not duplicate or claim the upstream leak fix; it addresses the remaining Python API gap. ## This repair LanceDB Python did not expose the native FTS builder resource controls. `memory_limit` now sets the total local-build budget in MiB, divided among effective workers, and `num_workers` controls build parallelism. Both are build-only settings and do not affect remote builds or persisted index configuration. ## Validation - `cargo check --quiet --features remote --tests --examples` - `cargo fmt --all` - `uv run --project python --extra tests --extra dev ruff check .` - `uv run --project python --extra tests --extra dev ruff format --check python/python/lancedb/index.py python/python/tests/test_fts.py` - `uv run --project python --extra tests pytest python/tests/test_fts.py -q` (51 passed) Fixes #2923 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- python/Cargo.toml | 9 +++-- python/pyproject.toml | 2 +- python/python/lancedb/index.py | 11 +++++++ python/python/tests/test_fts.py | 8 +++++ python/src/index.rs | 58 ++++++++++++++++++++++++++++++++- 5 files changed, 81 insertions(+), 7 deletions(-) diff --git a/python/Cargo.toml b/python/Cargo.toml index 6181f704f..ddc13b69f 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -26,7 +26,9 @@ lance-namespace-impls.workspace = true lance-io.workspace = true env_logger.workspace = true log.workspace = true -pyo3 = { version = "0.28", features = ["extension-module", "abi3-py310", "chrono"] } +# Maturin enables extension-module mode for Python builds. Keeping it out of +# Cargo features lets Rust unit tests link against libpython. +pyo3 = { version = "0.28", features = ["abi3-py310", "chrono"] } chrono.workspace = true pyo3-async-runtimes = { version = "0.28", features = [ "attributes", @@ -41,10 +43,7 @@ tokio.workspace = true libc = "0.2" [build-dependencies] -pyo3-build-config = { version = "0.28", features = [ - "extension-module", - "abi3-py310", -] } +pyo3-build-config = { version = "0.28", features = ["abi3-py310"] } [features] default = ["remote", "lancedb/aws", "lancedb/gcs", "lancedb/azure", "lancedb/dynamodb", "lancedb/oss", "lancedb/huggingface", "lancedb/cos", "lancedb/goosefs", "lancedb/metrics-otel"] diff --git a/python/pyproject.toml b/python/pyproject.toml index ae42172c0..fad3b1001 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -103,7 +103,7 @@ python-source = "python" module-name = "lancedb._lancedb" [build-system] -requires = ["maturin>=1.4"] +requires = ["maturin>=1.9.4"] build-backend = "maturin" [tool.ruff.lint] diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py index aa7846892..d2b63baf6 100644 --- a/python/python/lancedb/index.py +++ b/python/python/lancedb/index.py @@ -163,6 +163,15 @@ class FTS: The number of documents per compressed posting block. Supported values are 128 and 256. A value of 256 uses the experimental FTS V3 format and may introduce breaking changes. + memory_limit : int, optional + The total memory limit in MiB for the local FTS build stage. The limit + is divided evenly among indexing workers. This build-only setting is + not persisted with the index and does not apply to remote tables. + num_workers : int, optional + The number of workers for a local FTS build. By default Lance uses + roughly half of the available CPU cores. The effective value is + limited by the available compute capacity. This build-only setting is + not persisted with the index and does not apply to remote tables. Notes ----- @@ -185,6 +194,8 @@ class FTS: prefix_only: bool = False block_size: int = 128 custom_stop_words: Optional[List[str]] = None + memory_limit: Optional[int] = None + num_workers: Optional[int] = None @dataclass diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index f791f9886..625198d92 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -245,6 +245,14 @@ def test_create_inverted_index_rejects_invalid_block_size(table): table.create_index("text", config=FTS(block_size=129)) +def test_create_inverted_index_respects_build_memory_limit(table): + with pytest.raises(ValueError, match="exceeds worker memory limit"): + table.create_index( + "text", + config=FTS(memory_limit=0, num_workers=1), + ) + + def test_custom_stop_words_list(table): table.create_index( "text", diff --git a/python/src/index.rs b/python/src/index.rs index dd362373e..a5ca63c68 100644 --- a/python/src/index.rs +++ b/python/src/index.rs @@ -42,7 +42,7 @@ pub fn extract_index_params(source: &Option>) -> PyResult Ok(LanceDbIndex::Fm(FmIndexBuilder::default())), "FTS" => { let params = source.extract::()?; - let inner_opts = FtsIndexBuilder::default() + let mut inner_opts = FtsIndexBuilder::default() .base_tokenizer(params.base_tokenizer) .language(¶ms.language) .map_err(|_| { @@ -61,6 +61,12 @@ pub fn extract_index_params(source: &Option>) -> PyResult, + num_workers: Option, } #[derive(FromPyObject)] @@ -444,3 +452,51 @@ impl IndexConfig { } } } + +#[cfg(test)] +mod tests { + use super::*; + use pyo3::types::{PyDict, PyDictMethods}; + use serde_json::json; + + #[test] + fn fts_build_controls_are_forwarded() { + Python::initialize(); + Python::attach(|py| { + let locals = PyDict::new(py); + py.run( + c"class FTS: + with_position = True + base_tokenizer = 'simple' + language = 'English' + max_token_length = None + lower_case = True + stem = False + remove_stop_words = False + custom_stop_words = None + ascii_folding = False + ngram_min_length = 3 + ngram_max_length = 3 + prefix_only = False + block_size = 128 + memory_limit = 2048 + num_workers = 7 + +config = FTS()", + None, + Some(&locals), + ) + .unwrap(); + + let config = locals.get_item("config").unwrap().unwrap(); + let index = extract_index_params(&Some(config)).unwrap(); + let LanceDbIndex::FTS(params) = index else { + panic!("expected FTS index parameters"); + }; + let training_json = params.to_training_json().unwrap(); + + assert_eq!(training_json.get("memory_limit"), Some(&json!(2048))); + assert_eq!(training_json.get("num_workers"), Some(&json!(7))); + }); + } +} From c0df2c63b6f14c29bef699f93b33153c39dfbc96 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 21 Aug 2026 16:39:13 -0700 Subject: [PATCH 085/206] test(rust): cover fixed-size-list merge overflow (#3907) ## Summary - add a merge-insert regression test whose fixed-size-list child count crosses `u32::MAX` - verify delete-by-source updates the matching row, deletes every other row, and completes without an Arrow panic - use a null child array so the boundary case avoids allocating a real vector payload ## Root cause and fix The affected Lance merge fallback carried the target payload through a full outer hash join. Arrow's fixed-size-list take kernel uses `u32` child indices, so taking a target row whose child offset crossed `u32::MAX` wrapped the offset and produced child data shorter than the parent array, triggering the reported `ArrayData::slice` assertion. The projection-aware merge path in the Lance version now used by `main` avoids materializing the target fixed-size-list payload in that join. This regression test locks in that production behavior at the exact child-index boundary. ## Validation - `cargo fmt --all` - `cargo test --quiet --features remote -p lancedb test_merge_insert_fixed_size_list_above_u32_child_count` - `cargo check --quiet --features remote --tests --examples` - `cargo clippy --quiet --features remote --tests --examples` Fixes #2874 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- rust/lancedb/src/table/merge.rs | 71 ++++++++++++++++++++++++++++++++- 1 file changed, 70 insertions(+), 1 deletion(-) diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index ea68e99df..b9dd5732b 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -321,7 +321,8 @@ pub(crate) async fn execute_merge_insert( mod tests { use arrow_array::builder::FixedSizeBinaryBuilder; use arrow_array::{ - Int32Array, RecordBatch, RecordBatchIterator, RecordBatchReader, StringArray, UInt64Array, + FixedSizeListArray, Int32Array, NullArray, RecordBatch, RecordBatchIterator, + RecordBatchReader, StringArray, UInt32Array, UInt64Array, }; use arrow_schema::{DataType, Field, Schema}; use std::sync::Arc; @@ -529,6 +530,74 @@ mod tests { assert_eq!(result.num_deleted_rows, 5); assert_eq!(table.count_rows(None).await.unwrap(), 5); } + + #[tokio::test] + async fn test_merge_insert_fixed_size_list_above_u32_child_count() { + // Arrow's FixedSizeList take kernel uses u32 child indices. Previously, + // delete-by-source materialized the target payload in a full outer join, + // causing the final list below to overflow those indices and panic. + // A Null child keeps this boundary test small in memory. + const LIST_SIZE: i32 = 65_536; + const ROW_COUNT: usize = (u32::MAX as usize / LIST_SIZE as usize) + 1; + const BATCH_SIZE: usize = 8_192; + + let item = Arc::new(Field::new("item", DataType::Null, true)); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::UInt32, false), + Field::new( + "vector", + DataType::FixedSizeList(item.clone(), LIST_SIZE), + false, + ), + ])); + let batch = |start: usize, len: usize| { + RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(UInt32Array::from_iter_values( + start as u32..(start + len) as u32, + )), + Arc::new(FixedSizeListArray::new( + item.clone(), + LIST_SIZE, + Arc::new(NullArray::new(len * LIST_SIZE as usize)), + None, + )), + ], + ) + .unwrap() + }; + + let target_batches = (0..ROW_COUNT) + .step_by(BATCH_SIZE) + .map(|start| { + let len = (ROW_COUNT - start).min(BATCH_SIZE); + Ok(batch(start, len)) + }) + .collect::>(); + let target_data: Box = + Box::new(RecordBatchIterator::new(target_batches, schema.clone())); + let conn = connect("memory://").execute().await.unwrap(); + let table = conn + .create_table("fixed_size_list_overflow", target_data) + .execute() + .await + .unwrap(); + + let source = batch(ROW_COUNT - 1, 1); + let mut merge = table.merge_insert(&["id"]); + merge + .when_matched_update_all(None) + .when_not_matched_by_source_delete(None); + let result = merge + .execute(Box::new(RecordBatchIterator::new([Ok(source)], schema))) + .await + .unwrap(); + + assert_eq!(result.num_updated_rows, 1); + assert_eq!(result.num_deleted_rows, (ROW_COUNT - 1) as u64); + assert_eq!(table.count_rows(None).await.unwrap(), 1); + } } #[cfg(test)] From 5468f3d490229ab0dc18e4dd3e6639779f377ad3 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Fri, 21 Aug 2026 16:44:21 -0700 Subject: [PATCH 086/206] fix(rust): reject bitmap indexes on JSON fields (#3895) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - reject whole-document `lance.json` fields during native BITMAP index preparation - preserve BITMAP support for raw `LargeBinary` fields - return guidance to use a JSON-path scalar index or FTS instead - add regression coverage for the logical JSON type while retaining the existing raw binary coverage ## Root cause Native scalar-index validation resolved the complete Arrow field but checked BITMAP compatibility only against its physical data type. Because `lance.json` is stored as `LargeBinary`, it was incorrectly accepted under the raw binary compatibility rule. The fix reuses Lance’s `lance_arrow::json::is_json_field` helper before physical type validation. Remote serialization is unchanged, so remote clients continue to send the requested BITMAP type for server-side validation. ## Validation - `cargo fmt --all -- --check` - `cargo test --quiet --features remote -p lancedb test_create_bitmap_index -- --nocapture` - `cargo check --quiet --features remote --tests --examples` - `cargo clippy --quiet --features remote --tests --examples` - `cargo test --quiet --features remote --tests` Fixes #3889 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- rust/lancedb/src/table/create_index.rs | 38 ++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs index 144c6dbfb..e373522bc 100644 --- a/rust/lancedb/src/table/create_index.rs +++ b/rust/lancedb/src/table/create_index.rs @@ -12,6 +12,7 @@ use arrow_schema::{DataType, Field}; use lance::index::DatasetIndexExt; use lance::index::vector::VectorIndexParams; use lance::index::vector::utils::infer_vector_dim; +use lance_arrow::json::is_json_field; use lance_index::IndexType; use lance_index::scalar::{BuiltinIndexType, ScalarIndexParams}; use lance_index::vector::bq::RQBuildParams; @@ -219,6 +220,14 @@ impl NativeTable { ))) } Index::Bitmap(_) => { + if is_json_field(field) { + return Err(Error::Schema { + message: format!( + "A BITMAP index cannot be created on the whole-document lance.json field `{}`. Create a JSON-path scalar index for structured equality or range predicates, or use FTS for document search", + field.name() + ), + }); + } Self::validate_index_type(field, "Bitmap", supported_bitmap_data_type)?; Ok(Box::new(ScalarIndexParams::for_builtin( BuiltinIndexType::Bitmap, @@ -1465,6 +1474,35 @@ mod tests { assert_eq!(stats.distance_type, None); } + #[tokio::test] + async fn test_create_bitmap_index_rejects_lance_json() { + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![lance_arrow::json::json_field( + "metadata", true, + )])); + let table = conn + .create_empty_table("json_bitmap", schema) + .execute() + .await + .unwrap(); + + let err = table + .create_index(&["metadata"], Index::Bitmap(Default::default())) + .execute() + .await + .expect_err("a whole-document lance.json field must not support a bitmap index"); + let message = err.to_string(); + assert!( + message.contains("lance.json"), + "unexpected error: {message}" + ); + assert!( + message.contains("JSON-path scalar index"), + "unexpected error: {message}" + ); + assert!(message.contains("FTS"), "unexpected error: {message}"); + } + #[tokio::test] async fn test_create_label_list_index() { let conn = connect("memory://").execute().await.unwrap(); From 7801e2746aae9438b7c87e814fe52d5631d0fd9c Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Fri, 21 Aug 2026 21:43:45 -0700 Subject: [PATCH 087/206] chore: update lance dependency to v11.0.0-beta.19 (#4025) Updates the Lance dependencies and Java lance-core dependency to v11.0.0-beta.19. No compatibility fixes were required; workspace clippy with all features passes. Triggering tag: https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.19 --- Cargo.lock | 84 ++++++++++++++++++++++++++-------------------------- Cargo.toml | 28 +++++++++--------- java/pom.xml | 2 +- 3 files changed, 57 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 73f5923fe..5947187cc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow", "arrow-array", @@ -5013,8 +5013,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow", "arrow-array", @@ -5031,8 +5031,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "proc-macro2", "quote", @@ -5041,8 +5041,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow-arith", "arrow-array", @@ -5075,8 +5075,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow-arith", "arrow-array", @@ -5107,8 +5107,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arc-swap", "arrow", @@ -5172,8 +5172,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow-array", "arrow-schema", @@ -5195,8 +5195,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow", "arrow-array", @@ -5232,8 +5232,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow-array", "arrow-schema", @@ -5247,8 +5247,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow", "async-trait", @@ -5260,8 +5260,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow", "arrow-ipc", @@ -5314,8 +5314,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow-array", "arrow-buffer", @@ -5329,8 +5329,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow", "arrow-array", @@ -5370,8 +5370,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "arrow-array", "arrow-schema", @@ -5384,8 +5384,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.18" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.18#7b6e2d3586e9c1b99326313533aba2150557ed65" +version = "11.0.0-beta.19" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 9aeccd76f..c147b06db 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.18", default-features = false, "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.18", default-features = false, "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.18", default-features = false, "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.18", "tag" = "v11.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.19", default-features = false, "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.19", default-features = false, "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.19", default-features = false, "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index 978f7c7c7..36ec01d9e 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.18 + 11.0.0-beta.19 false 2.30.0 1.7 From a578e9ff7f63f0ef534b088c2f9fc9c4deaa0cb6 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Fri, 21 Aug 2026 22:39:47 -0700 Subject: [PATCH 088/206] feat: refresh materialized views (#4010) A declared view holds no rows; refresh computes them. It pins one source version, brings the view to exactly the definition's result at that version, and records the version as a watermark in the view's schema metadata. It is incremental when it can reconcile what changed: appended rows are computed and appended, and rows the source deleted or updated are found by the lance delta and evicted by their __source_row_id provenance, the updated ones recomputed in the same commit. Compaction rearranges rows without changing them, so its outputs cost nothing -- which is what keeps routine background compaction from rebuilding the view. A vacuumed watermark, a delta the transaction-log walk cannot classify, a Legacy-storage source, or more staged ids than a fixed cap all fall back to a rebuild; rebuilding an indexed view swaps every fragment in one Update, so readers never see it unindexed or empty. Concurrent refreshes serialize at commit -- each carries the same sentinel row id in its inserted-rows filter, so the loser lands nothing. On the append path the watermark moves in a follow-up commit, so a crash between the two re-appends those rows. Bumps lance to v11.0.0-beta.19 for the delta reader. --- rust/lancedb/src/lib.rs | 4 +- rust/lancedb/src/materialized_view.rs | 60 +- rust/lancedb/src/materialized_view/refresh.rs | 2719 +++++++++++++++++ rust/lancedb/src/table/merge/lsm.rs | 7 + rust/lancedb/src/table/refresh.rs | 2 +- 5 files changed, 2789 insertions(+), 3 deletions(-) create mode 100644 rust/lancedb/src/materialized_view/refresh.rs diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index 3a937db5b..9c3c199ff 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -211,7 +211,9 @@ pub use function::FunctionVersion; pub use job::Job; use lance_index::vector::ApproxMode as LanceApproxMode; use lance_linalg::distance::DistanceType as LanceDistanceType; -pub use materialized_view::{MaterializedView, MaterializedViewDefinition}; +pub use materialized_view::{ + MaterializedView, MaterializedViewDefinition, RefreshMaterializedViewResult, RefreshMode, +}; /// Re-export of the [`metrics`](https://docs.rs/metrics) crate facade. Enable /// the `metrics` feature to publish LanceDB's internal metrics; install any /// `metrics`-compatible recorder to collect them. See also [`metrics_otel`] for diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index f1eddf9da..8b553165b 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -9,6 +9,7 @@ //! metadata; a kind added later reads back as unrefreshable, not as a plain //! table. Queries, indexes and search work on the view unchanged. +pub mod refresh; use std::collections::HashMap; use std::sync::Arc; @@ -27,6 +28,8 @@ use crate::table::refresh::quote_identifier; use crate::table::{ColumnDefinition, ColumnKind}; use crate::{Error, Result}; +pub use refresh::{RefreshMaterializedViewResult, RefreshMode}; + /// Schema metadata key holding the view definition, as kind-tagged JSON. pub const DEFINITION_META_KEY: &str = "mv.definition"; @@ -736,6 +739,12 @@ pub async fn prepare_declaration( ), }); } + refresh::ensure_no_mem_wal( + native.dataset.get().await?.as_ref(), + "source table", + resolved.name(), + ) + .await?; let source_schema = resolved.schema().await?; let source_metadata = source_schema.metadata().clone(); let (definition, mut fields, lineage) = plan( @@ -909,6 +918,54 @@ impl MaterializedView { pub fn definition(&self) -> &MaterializedViewDefinition { &self.definition } + + /// Recompute the view from its source. + /// + /// By default the refresh is incremental when the source's changes can be + /// reconciled into the view, and otherwise rebuilds; see + /// [`RefreshMaterializedViewBuilder`]. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # use lancedb::materialized_view::MaterializedView; + /// # async fn refresh(view: &MaterializedView) -> Result<(), Box> { + /// let result = view.refresh().execute().await?; + /// println!("{:?}: {} rows", result.mode, result.rows_written); + /// # Ok(()) + /// # } + /// ``` + pub fn refresh(&self) -> RefreshMaterializedViewBuilder { + RefreshMaterializedViewBuilder { + view: self.clone(), + full: false, + source_version: None, + } + } +} + +/// Builds a refresh. Created by [`MaterializedView::refresh`]. +pub struct RefreshMaterializedViewBuilder { + view: MaterializedView, + full: bool, + source_version: Option, +} + +impl RefreshMaterializedViewBuilder { + /// Rebuild the view even where an incremental refresh would do. + pub fn full(mut self, full: bool) -> Self { + self.full = full; + self + } + + /// Refresh to this source table version instead of the latest. + pub fn source_version(mut self, version: u64) -> Self { + self.source_version = Some(version); + self + } + + pub async fn execute(self) -> Result { + refresh::execute_refresh(&self.view.table, self.full, self.source_version).await + } } impl Connection { @@ -918,6 +975,7 @@ impl Connection { /// metadata; refresh computes the rows. Local databases only. /// /// ```no_run + /// # #![recursion_limit = "256"] /// # use lancedb::Connection; /// # async fn create(conn: &Connection) -> Result<(), Box> { /// let view = conn @@ -926,7 +984,7 @@ impl Connection { /// .only_if("age >= 18") /// .execute() /// .await?; - /// println!("{}", view.definition().source_table); + /// view.refresh().execute().await?; /// # Ok(()) /// # } /// ``` diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs new file mode 100644 index 000000000..7ac39a9f5 --- /dev/null +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -0,0 +1,2719 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Refreshing materialized views. +//! +//! A refresh pins one source version and brings the view to exactly the +//! definition's result at that version: added rows are computed and appended, +//! removed or changed rows are evicted by provenance id and recomputed in the +//! same pass. Compaction outputs cost nothing, which is only sound while +//! [`SOURCE_ROW_ID_COLUMN`] stays valid across the rewrite. Anything the +//! classifier cannot prove intact rebuilds; an indexed rebuild swaps all +//! fragments in one commit that retains index definitions. +//! +//! The watermark ([`SOURCE_VERSION_META_KEY`]) lands in a follow-up commit; a +//! crash or race between the two leaves the view visibly unstamped and the +//! next refresh rebuilds. In-process refreshes serialize on a per-view lock; +//! across processes the commit's inserted-rows filter carries a shared token, +//! so two refreshes of one view conflict and only one lands. + +use std::collections::{HashMap, HashSet}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex as StdMutex, OnceLock}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use arrow_array::cast::AsArray; +use arrow_array::types::UInt64Type; +use arrow_array::{RecordBatch, UInt64Array}; +use arrow_schema::{Schema as ArrowSchema, SchemaRef}; +use datafusion::common::ScalarValue; +use datafusion::error::DataFusionError; +use datafusion::physical_plan::SendableRecordBatchStream; +use datafusion::physical_plan::stream::RecordBatchStreamAdapter; +use datafusion::prelude::{col, lit}; +use futures::{StreamExt, TryStreamExt}; +use lance::Dataset; +use lance::dataset::mem_wal::DatasetMemWalExt; +use lance::dataset::transaction::{Operation, Transaction}; +use lance::dataset::write::delete::DeleteBuilder; +use lance::dataset::write::merge_insert::inserted_rows::{ + KeyExistenceFilter, KeyExistenceFilterBuilder, KeyValue, +}; +use lance::dataset::{CommitBuilder, InsertBuilder, WriteDestination, WriteMode, WriteParams}; +use lance_core::{ROW_CREATED_AT_VERSION, ROW_ID, ROW_LAST_UPDATED_AT_VERSION}; +use lance_file::version::ConcreteFileVersion; +use lance_table::format::Fragment; +use serde::{Deserialize, Serialize}; + +use super::{ + MaterializedViewDefinition, REFRESHED_AT_MS_META_KEY, SOURCE_ROW_ID_COLUMN, + SOURCE_VERSION_META_KEY, +}; +use crate::database::OpenTableRequest; +use crate::table::{NativeTable, NativeTableExt, Table}; +use crate::{Error, Result}; + +/// How a refresh brought the view up to date. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RefreshMode { + /// The view was recomputed from scratch. + Rebuild, + /// Rows from source fragments added since the last refresh were appended. + Incremental, + /// The view was already at the requested source version. + NoOp, +} + +/// The result of refreshing a materialized view. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RefreshMaterializedViewResult { + /// How the view was brought up to date. + pub mode: RefreshMode, + /// Rows written to the view: everything on a rebuild, and on an + /// incremental refresh both the rows added and the rows recomputed in + /// place of ones the source changed. + pub rows_written: u64, + /// The source table version the view now reflects. + pub source_version: u64, + /// The view table version after the refresh. + pub version: u64, +} + +/// Schema metadata key holding the view table version a successful refresh +/// left behind. Any other commit on the view is drift, and refresh rebuilds. +pub const VIEW_VERSION_META_KEY: &str = "mv.view_version"; + +/// Schema metadata key holding the commit timestamp of the watermark's source +/// manifest. A dropped and recreated source reuses version numbers but never +/// their timestamps, so a mismatch means the watermark describes a different +/// incarnation and refresh rebuilds. +pub const SOURCE_VERSION_TS_META_KEY: &str = "mv.source_version_ts"; + +/// One refresh per view at a time within this process. +fn refresh_lock(uri: &str) -> Arc> { + static LOCKS: OnceLock>>>> = + OnceLock::new(); + LOCKS + .get_or_init(Default::default) + .lock() + .expect("refresh lock registry poisoned") + .entry(uri.to_string()) + .or_default() + .clone() +} + +/// Internal implementation of the refresh logic. +pub(crate) async fn execute_refresh( + view: &Table, + full: bool, + pinned: Option, +) -> Result { + let view_native = view.as_native().ok_or_else(|| Error::NotSupported { + message: "materialized views are supported only on local tables".into(), + })?; + view_native.dataset.ensure_mutable()?; + let lock = refresh_lock(view_native.dataset.get().await?.uri()); + let _guard = lock.lock().await; + // Force-load the latest view state under the lock: each handle caches + // lazily, and a second handle would otherwise plan from a snapshot taken + // before another handle's commit -- appending the same rows again or + // reporting NoOp over a mutated view. + view_native.dataset.reload().await?; + let view_ds = view_native.dataset.get().await?.as_ref().clone(); + + // The definition a handle cached at open may since have been replaced; + // what refresh executes and what it stamps must be one generation. + let definition = match super::materialized_view_kind(&view_ds.schema().metadata)? { + Some(super::MaterializedViewKind::Select(definition)) => definition, + Some(super::MaterializedViewKind::Unrecognized { kind }) => { + return Err(Error::NotSupported { + message: format!( + "materialized view '{}' is defined by '{kind}', which this \ + version of lancedb cannot refresh", + view.name() + ), + }); + } + None => { + return Err(Error::NotAMaterializedView { + name: view.name().to_string(), + }); + } + }; + let definition = &definition; + ensure_no_mem_wal(&view_ds, "materialized view", view.name()).await?; + + let source_ds = open_source(view, definition).await?; + let source_ds = match pinned { + Some(version) => source_ds.checkout_version(version).await?, + None => source_ds, + }; + ensure_no_mem_wal(&source_ds, "source table", &definition.source_table).await?; + let source_version = source_ds.version().version; + let source_ts = source_ds.manifest.timestamp_nanos; + + // Re-plan the persisted definition against the current source schema and + // require its planned output to be exactly the view's physical schema: a + // definition the stored table cannot represent must not be certified. + let source_schema = Arc::new(ArrowSchema::from(source_ds.schema())); + let projections: Vec<(String, String)> = definition + .projections + .iter() + .map(|p| (p.output.clone(), p.expression.clone())) + .collect(); + validate_inputs(&source_ds, definition)?; + let (replanned, mut planned_fields, _renames) = super::plan( + source_schema, + &definition.source_table, + &projections, + definition.filter.as_deref(), + definition.limit, + )?; + planned_fields.push(arrow_schema::Field::new( + SOURCE_ROW_ID_COLUMN, + arrow_schema::DataType::UInt64, + false, + )); + let physical = ArrowSchema::from(view_ds.schema()); + let planned_shape: Vec<_> = planned_fields + .iter() + .map(|f| (f.name().clone(), f.data_type().clone(), f.is_nullable())) + .collect(); + let physical_shape: Vec<_> = physical + .fields() + .iter() + .map(|f| (f.name().clone(), f.data_type().clone(), f.is_nullable())) + .collect(); + if planned_shape != physical_shape { + return Err(Error::Schema { + message: format!( + "the stored definition of view '{}' does not produce this \ + view's schema; recreate the view", + view.name() + ), + }); + } + let definition = &replanned; + + let metadata = &view_ds.schema().metadata; + let watermark: Option = metadata + .get(SOURCE_VERSION_META_KEY) + .and_then(|raw| raw.parse().ok()); + let recorded_ts: Option = metadata + .get(SOURCE_VERSION_TS_META_KEY) + .and_then(|raw| raw.parse().ok()); + // The watermark speaks only for the view state its refresh left behind; + // any other commit on the view since then is drift. + let view_intact = metadata + .get(VIEW_VERSION_META_KEY) + .and_then(|raw| raw.parse::().ok()) + == Some(view_ds.version().version); + + if !full && watermark == Some(source_version) && view_intact && recorded_ts == Some(source_ts) { + return Ok(RefreshMaterializedViewResult { + mode: RefreshMode::NoOp, + rows_written: 0, + source_version, + version: view_ds.version().version, + }); + } + + let watermark = watermark.filter(|_| view_intact); + match plan_increment( + &source_ds, + source_version, + watermark, + recorded_ts, + full, + definition, + ) + .await + { + Some(increment) => { + let reconciled = incremental( + view_native, + &view_ds, + &source_ds, + source_version, + source_ts, + increment, + definition, + watermark, + ) + .await?; + match reconciled { + Some(result) => Ok(result), + // The delta was too large to reconcile in bounded memory. + None => { + rebuild( + view_native, + &view_ds, + &source_ds, + source_version, + source_ts, + definition, + ) + .await + } + } + } + None => { + rebuild( + view_native, + &view_ds, + &source_ds, + source_version, + source_ts, + definition, + ) + .await + } + } +} + +/// The source fragments whose rows are new since the watermark, or `None` +/// where the view has to rebuild. Two tiers: the transaction walk is exact +/// where it applies; the fragment-signature check is the fallback for deltas +/// the walk cannot read, and under it any fragment churn rebuilds. +async fn plan_increment( + source_ds: &Dataset, + source_version: u64, + watermark: Option, + recorded_ts: Option, + full: bool, + definition: &MaterializedViewDefinition, +) -> Option { + if full { + return None; + } + let watermark = watermark?; + if watermark > source_version { + return None; + } + let old = source_ds.checkout_version(watermark).await.ok()?; + // A recreated source reuses version numbers, never their timestamps: a + // mismatch means the watermark describes a different incarnation. + if recorded_ts != Some(old.manifest.timestamp_nanos) { + return None; + } + let old_ids: HashSet = old.get_fragments().iter().map(|f| f.id() as u64).collect(); + let live: Vec = source_ds + .get_fragments() + .iter() + .map(|f| f.metadata().clone()) + .collect(); + + if let Some(delta) = appends_and_rewrites(source_ds, watermark, source_version).await { + // A rewrite that consumed a fragment neither present at the watermark + // nor produced by an earlier rewrite swallowed a mid-delta append; + // its rows cannot be told apart from already-materialized ones. + let folded = delta + .rewritten + .iter() + .any(|id| !old_ids.contains(id) && !delta.produced.contains(id)); + if folded { + return None; + } + // An update rewrites a whole fragment. If it touched one the watermark + // never saw, that fragment holds rows appended since -- new rows the + // update did not change, which the recompute does not cover and which + // this fragment's exclusion from the append set would drop. + if delta + .updated_in_place + .iter() + .any(|id| !old_ids.contains(id)) + { + return None; + } + // Rows past the cap left every delta when the watermark advanced, so + // a capped view cannot reconcile a removal incrementally. The rebuild + // is cheap for the same reason it is capped: the scan stops there. + if definition.limit.is_some() && (delta.deleted_rows || delta.updated_rows) { + return None; + } + // Legacy storage cannot serve the row-version columns update + // discovery scans; deletes and appends need none of them. + if delta.updated_rows + && source_ds.manifest.data_storage_format.lance_file_format() == ConcreteFileVersion::V1 + { + return None; + } + // Every other fragment new at head is an append: appends and rewrites + // are the only operations in the delta that add fragments, and the + // rewrite outputs are already-materialized rows rearranged. + return Some(Increment { + appended: live + .into_iter() + .filter(|f| !old_ids.contains(&f.id) && !delta.produced.contains(&f.id)) + .collect(), + evict_deleted: delta.deleted_rows, + replace_updated: delta.updated_rows, + }); + } + + is_pure_append(&old, source_ds, &relevant_field_ids(source_ds, definition)).then(|| Increment { + appended: live + .into_iter() + .filter(|f| !old_ids.contains(&f.id)) + .collect(), + evict_deleted: false, + replace_updated: false, + }) +} + +/// Version gap beyond which per-version transaction reads stop being cheaper +/// than one fragment scan. +const MAX_TRANSACTION_WALK: u64 = 512; + +/// Fragment ids moved by the `Rewrite` operations of the delta. Only rewrite +/// ids are real in transaction files (an Append's are placeholders assigned +/// at commit), so appends are derived as new-at-head minus rewrite outputs. +/// What an incremental refresh must do to bring the view up to date. +struct Increment { + /// Source fragments whose rows are not in the view yet. + appended: Vec, + /// Source rows left the range, so the view holds rows to evict. + evict_deleted: bool, + /// Source rows changed in the range, so the view holds rows to replace. + replace_updated: bool, +} + +struct TxnDelta { + /// Fragments consumed by `Rewrite` operations. + rewritten: HashSet, + /// Fragments produced by `Rewrite` operations. + produced: HashSet, + /// The delta removed source rows, so the view holds rows to evict. + deleted_rows: bool, + /// The delta changed source rows in place, so the view holds rows to + /// recompute. + updated_rows: bool, + /// Fragments an update modified in place, as opposed to produced. + updated_in_place: HashSet, +} + +/// Read the delta from the transaction log, `None` where it holds anything +/// but appends and rewrites or cannot be read; `None` only sends the caller +/// to a slower check. `ReserveFragments` moves no rows and rides along. +async fn appends_and_rewrites(cur: &Dataset, from: u64, to: u64) -> Option { + if to <= from || to - from > MAX_TRANSACTION_WALK { + return None; + } + let mut delta = TxnDelta { + rewritten: HashSet::new(), + produced: HashSet::new(), + deleted_rows: false, + updated_rows: false, + updated_in_place: HashSet::new(), + }; + for version in (from + 1)..=to { + let Ok(Some(txn)) = cur.read_transaction_by_version(version).await else { + return None; + }; + match txn.operation { + Operation::Append { .. } | Operation::ReserveFragments { .. } => {} + // A delete removes source rows without changing the ones that + // remain, so the view's other rows stay valid: the refresh + // evicts exactly the ids that left. + Operation::Delete { .. } => delta.deleted_rows = true, + // Update outputs carry no new rows, so they are excluded from + // the append set like rewrite outputs; the changed rows are + // replaced individually below. + Operation::Update { + removed_fragment_ids, + new_fragments, + updated_fragments, + .. + } => { + delta.updated_rows = true; + // merge_insert reaches here too, and its by-source arm deletes + // rows rather than changing them. + delta.deleted_rows = true; + delta.rewritten.extend(removed_fragment_ids.iter().copied()); + // Only pre-existing fragment ids are real here; created ones + // are placeholders. Rewritten rows are excluded by creation + // version below, not by fragment identity. + delta + .produced + .extend(updated_fragments.iter().map(|f| f.id)); + delta + .updated_in_place + .extend(updated_fragments.iter().map(|f| f.id)); + let _ = new_fragments; + } + Operation::Rewrite { groups, .. } => { + for group in groups { + delta + .rewritten + .extend(group.old_fragments.iter().map(|f| f.id)); + delta + .produced + .extend(group.new_fragments.iter().map(|f| f.id)); + } + } + _ => return None, + } + } + Some(delta) +} + +/// Fallback pure-append check: every old fragment still present with an +/// identical signature over the columns the view reads. Compaction, deletes +/// and updates each break it and force a rebuild; a change to a column the +/// view does not read leaves it alone, which is what lets this tier pass +/// deltas the transaction walk cannot. +fn is_pure_append(old: &Dataset, cur: &Dataset, relevant: &HashSet) -> bool { + let signature = |fragment: &lance::dataset::fragment::FileFragment| { + fragment_signature(fragment.metadata(), relevant) + }; + let current: HashSet<(u64, String)> = cur.get_fragments().iter().map(signature).collect(); + old.get_fragments() + .iter() + .all(|fragment| current.contains(&signature(fragment))) +} + +/// A fragment's identity as the view observes it: data files and overlays +/// touching the columns it reads, plus the deletion file. Overlays change no +/// file path, so they must be part of the signature. +fn fragment_signature(metadata: &Fragment, relevant: &HashSet) -> (u64, String) { + let touches_relevant = + |fields: &[i32]| relevant.is_empty() || fields.iter().any(|id| relevant.contains(id)); + let mut files: Vec<&str> = metadata + .files + .iter() + .filter(|file| touches_relevant(&file.fields)) + .map(|file| file.path.as_str()) + .collect(); + files.sort_unstable(); + let mut overlays: Vec = metadata + .overlays + .iter() + .filter(|overlay| touches_relevant(&overlay.data_file.fields)) + .map(|overlay| format!("{}@{}", overlay.data_file.path, overlay.committed_version)) + .collect(); + overlays.sort_unstable(); + ( + metadata.id, + format!( + "{}|{}|{:?}", + files.join(","), + overlays.join(","), + metadata.deletion_file + ), + ) +} + +/// Field ids (with struct descendants) of the source columns the view reads. +fn relevant_field_ids(source: &Dataset, definition: &MaterializedViewDefinition) -> HashSet { + fn collect(field: &lance_core::datatypes::Field, ids: &mut HashSet) { + ids.insert(field.id); + for child in &field.children { + collect(child, ids); + } + } + let mut ids = HashSet::new(); + for input in &definition.inputs { + if let Some(field) = source.schema().field(input) { + collect(field, &mut ids); + } + } + ids +} + +/// Error if a column the view reads no longer exists in the source. +fn validate_inputs(source: &Dataset, definition: &MaterializedViewDefinition) -> Result<()> { + for input in &definition.inputs { + if source.schema().field(input).is_none() { + return Err(Error::Schema { + message: format!( + "source column '{input}' read by the view no longer exists \ + (dropped or renamed in '{}')", + definition.source_table + ), + }); + } + } + Ok(()) +} + +/// Reject MemWAL/LSM state on a refresh participant: un-compacted tiers are +/// invisible to the fragment-planned refresh scan. An active write spec and +/// retained rows both disqualify; shard directories on storage are the +/// durable evidence of the latter. +pub(crate) async fn ensure_no_mem_wal(dataset: &Dataset, role: &str, name: &str) -> Result<()> { + let retained = !dataset.list_mem_wal_latest_shard_ids().await?.is_empty(); + if retained || dataset.mem_wal_index_details().await?.is_some() { + return Err(Error::NotSupported { + message: format!( + "{role} '{name}' has an LSM write spec or retained un-compacted \ + rows: rows in un-compacted tiers are invisible to refresh" + ), + }); + } + Ok(()) +} + +async fn open_source(view: &Table, definition: &MaterializedViewDefinition) -> Result { + let database = view.database_opt().ok_or_else(|| Error::InvalidInput { + message: "the view was not opened through a database connection".into(), + })?; + let source = database + .open_table(OpenTableRequest { + name: definition.source_table.clone(), + namespace_path: Vec::new(), + index_cache_size: None, + lance_read_params: None, + location: None, + namespace_client: None, + managed_versioning: None, + }) + .await?; + let native = source.as_native().ok_or_else(|| Error::NotSupported { + message: "materialized views are supported only on local tables".into(), + })?; + let dataset = native.dataset.get().await?.as_ref().clone(); + if !dataset.manifest.uses_stable_row_ids() { + return Err(Error::InvalidInput { + message: format!( + "source table '{}' does not have stable row ids; it is not the \ + table this view was declared over", + definition.source_table + ), + }); + } + Ok(dataset) +} + +#[allow(clippy::too_many_arguments)] +async fn incremental( + view_native: &NativeTable, + view_ds: &Dataset, + source_ds: &Dataset, + source_version: u64, + source_ts: u128, + increment: Increment, + definition: &MaterializedViewDefinition, + watermark: Option, +) -> Result> { + let new_fragments = increment.appended; + let watermark_version = watermark.unwrap_or(0); + // Provenance ids this refresh removes: dropped rows, plus changed rows + // recomputed in the same commit. One view row per source row makes the + // eviction exact. Staged, not committed: removals ride with the rows + // that replace them, so a reader never sees the view without either. + let mut eviction = Eviction::new(view_ds, EVICTION_CHUNK); + let mut updated_rows = false; + if (increment.evict_deleted || increment.replace_updated) + && let Some(watermark) = watermark + { + let delta = source_ds + .delta() + .with_begin_version(watermark) + .with_end_version(source_version) + .build()?; + // Reconciling holds the delta's provenance ids in staged deletion + // vectors; past the cap, the streamed rebuild is the bounded path. + let cap = eviction_rebuild_cap(); + let mut evicted = 0usize; + if increment.evict_deleted { + let mut stream = delta.get_deleted_row_ids().await?; + while let Some(batch) = stream.try_next().await? { + let ids = row_ids_of(&batch)?; + evicted += ids.len(); + if evicted > cap { + return Ok(None); + } + eviction.push(ids).await?; + } + } + if increment.replace_updated { + // Ids only: `get_updated_rows` carries every column of every + // updated row, and discovery needs none of them. + let mut scanner = source_ds.scan(); + scanner.with_row_id().project(&[ROW_CREATED_AT_VERSION])?; + // A fixed bound: the configured default could make one discovery + // batch arbitrarily large before the fallback cap is consulted. + scanner.batch_size(8192); + scanner.filter(&format!( + "{ROW_CREATED_AT_VERSION} <= {watermark} + AND {ROW_LAST_UPDATED_AT_VERSION} > {watermark} + AND {ROW_LAST_UPDATED_AT_VERSION} <= {source_version}" + ))?; + let mut stream = scanner.try_into_stream().await?; + while let Some(batch) = stream.try_next().await? { + let ids = row_ids_of(&batch)?; + evicted += ids.len(); + if evicted > cap { + return Ok(None); + } + updated_rows |= !ids.is_empty(); + eviction.push(ids).await?; + } + } + } + let eviction = eviction.finish().await?; + + // The cap counts rows already materialized, in first-materialized order. + let remaining = match definition.limit { + Some(limit) => { + let held = view_ds.count_rows(None).await? as u64; + Some(limit.saturating_sub(held)) + } + None => None, + }; + + let mut result = RefreshMaterializedViewResult { + mode: RefreshMode::Incremental, + rows_written: 0, + source_version, + version: view_ds.version().version, + }; + let nothing_to_add = (new_fragments.is_empty() && !updated_rows) || remaining == Some(0); + if nothing_to_add && eviction.is_none() { + result.version = + stamp_watermark(view_native, view_ds.clone(), source_version, source_ts).await?; + return Ok(Some(result)); + } + // Rows left but none arrive: the removals still have to be published. + if nothing_to_add { + let filter = refresh_filter(&empty_keys(view_ds)?)?; + let published = publish(view_ds, eviction, Vec::new(), Some(filter)).await?; + result.version = stamp_watermark(view_native, published, source_version, source_ts).await?; + return Ok(Some(result)); + } + + // Appends carry the view's schema as it stands; the watermark moves in a + // follow-up commit (see the module docs for the crash window). + let schema = Arc::new(ArrowSchema::from(view_ds.schema())); + let rows_written = Arc::new(AtomicU64::new(0)); + // compute_stream counts what it produces; the truncation below can drop + // some of that, so the written count comes from the tee instead. + let computed = Arc::new(AtomicU64::new(0)); + let mut stream = compute_stream( + source_ds, + definition, + RowScope { + fragments: Some(new_fragments), + // An update rewrites whole fragments, so a fragment new at head + // can hold rows the view already has. Their creation version + // does not change, so it -- not fragment identity -- says which + // rows are new. + created_after: increment.replace_updated.then_some(watermark_version), + limit: remaining, + ..Default::default() + }, + schema.clone(), + computed.clone(), + ) + .await?; + + // The updated rows' current values, computed the same way and appended + // in the same commit as the new fragments' rows. + if updated_rows { + let recomputed = compute_stream( + source_ds, + definition, + RowScope { + updated_between: Some((watermark_version, source_version)), + ..Default::default() + }, + schema.clone(), + computed.clone(), + ) + .await?; + stream = Box::pin(RecordBatchStreamAdapter::new( + schema.clone(), + recomputed.chain(stream), + )); + } + + // Nothing survived the filter: the watermark still has to advance or the + // same fragments would be rescanned forever, but any removals still do. + let Some(first) = stream.try_next().await? else { + let published = if eviction.is_some() { + publish( + view_ds, + eviction, + Vec::new(), + Some(refresh_filter(&empty_keys(view_ds)?)?), + ) + .await? + } else { + view_ds.clone() + }; + result.version = stamp_watermark(view_native, published, source_version, source_ts).await?; + return Ok(Some(result)); + }; + let stream: SendableRecordBatchStream = Box::pin(RecordBatchStreamAdapter::new( + schema, + futures::stream::iter([Ok(first)]).chain(stream), + )); + + // Any two refreshes of one view must not both commit: the filter's + // shared token makes lance reject the loser on key overlap however + // their planned rows relate. + let keys = Arc::new(StdMutex::new(KeyExistenceFilterBuilder::new(vec![ + source_row_id_field_id(view_ds)?, + ]))); + let stream = collect_source_row_ids(stream, keys.clone(), rows_written.clone()); + + let ds = Arc::new(view_ds.clone()); + let write_txn = InsertBuilder::new(WriteDestination::Dataset(ds.clone())) + .with_params(&WriteParams { + mode: WriteMode::Append, + ..Default::default() + }) + .execute_uncommitted_stream(stream) + .await?; + let Operation::Append { + fragments: new_fragments, + } = write_txn.operation + else { + return Err(Error::Runtime { + message: "expected an append when staging the view's new rows".into(), + }); + }; + let filter = refresh_filter(&keys)?; + let appended = publish(view_ds, eviction, new_fragments, Some(filter)).await?; + result.rows_written = rows_written.load(Ordering::Relaxed); + result.version = stamp_watermark(view_native, appended, source_version, source_ts).await?; + Ok(Some(result)) +} + +async fn rebuild( + view_native: &NativeTable, + view_ds: &Dataset, + source_ds: &Dataset, + source_version: u64, + source_ts: u128, + definition: &MaterializedViewDefinition, +) -> Result { + let rows_written = Arc::new(AtomicU64::new(0)); + let schema = Arc::new(ArrowSchema::from(view_ds.schema())); + let stream = compute_stream( + source_ds, + definition, + RowScope { + limit: definition.limit, + ..Default::default() + }, + schema, + rows_written.clone(), + ) + .await?; + let keys = Arc::new(StdMutex::new(KeyExistenceFilterBuilder::new(vec![ + source_row_id_field_id(view_ds)?, + ]))); + let stream = collect_source_row_ids(stream, keys.clone(), Arc::new(AtomicU64::new(0))); + // Every rebuild is one fragment swap, indexed or not: an Update commit + // carries no schema metadata, so it cannot erase a definition update + // that raced in the way an overwrite (which adopts its stream's schema) + // durably would -- and it must land on the planned generation or abort. + let replaced = replace_retaining_indices(view_ds.clone(), stream, keys).await?; + let version = stamp_watermark(view_native, replaced, source_version, source_ts).await?; + Ok(RefreshMaterializedViewResult { + mode: RefreshMode::Rebuild, + rows_written: rows_written.load(Ordering::Relaxed), + source_version, + version, + }) +} + +/// Replace all of the view's data in one commit that retains its index +/// definitions: new fragments staged uncommitted, one `Update` removing every +/// old fragment. `Update` prunes index bitmaps only for modified fields and +/// none are modified here, so readers never see the view unindexed or empty. +async fn replace_retaining_indices( + view_ds: Dataset, + stream: SendableRecordBatchStream, + keys: Arc>, +) -> Result { + let ds = Arc::new(view_ds); + let read_version = ds.version().version; + #[cfg(test)] + tests::hold_before_publish(ds.uri()).await; + let removed_fragment_ids: Vec = ds.get_fragments().iter().map(|f| f.id() as u64).collect(); + + let write_txn = InsertBuilder::new(WriteDestination::Dataset(ds.clone())) + .with_params(&WriteParams { + mode: WriteMode::Append, + ..Default::default() + }) + .execute_uncommitted_stream(stream) + .await?; + let Operation::Append { + fragments: new_fragments, + } = write_txn.operation + else { + return Err(Error::Runtime { + message: "expected an append when staging the view's replacement rows".into(), + }); + }; + + // Built only now: the tee fills as the staging drains the stream. + let filter = refresh_filter(&keys)?; + let transaction = Transaction::new( + read_version, + Operation::Update { + removed_fragment_ids, + updated_fragments: Vec::new(), + new_fragments, + fields_modified: Vec::new(), + compacted_sstables: Vec::new(), + fields_for_preserving_frag_bitmap: Vec::new(), + update_mode: None, + // Two refreshes that materialized the same source rows must not + // both land -- a raced first rebuild would double the view. + inserted_rows_filter: Some(filter), + updated_fragment_offsets: None, + }, + None, + ); + let committed = CommitBuilder::new(WriteDestination::Dataset(ds)) + .execute(transaction) + .await?; + if committed.version().version != read_version + 1 { + return Err(Error::Runtime { + message: format!( + "a concurrent commit raced this refresh (view version {}); the + refresh is unrecorded and the next one will rebuild", + committed.version().version + ), + }); + } + Ok(committed) +} + +/// Record that the view now reflects `source_version`, including the view +/// version this very commit produces. The version is predicted and then +/// verified; on a mismatch another commit raced in between, and the stamp +/// ABORTS rather than certify that commit as the refresh's own generation. +/// The view is left visibly unstamped, so the next refresh rebuilds. +async fn stamp_watermark( + view_native: &NativeTable, + mut dataset: Dataset, + source_version: u64, + source_ts: u128, +) -> Result { + let predicted = dataset.version().version + 1; + dataset + .update_schema_metadata([ + ( + SOURCE_VERSION_META_KEY.to_string(), + Some(source_version.to_string()), + ), + ( + SOURCE_VERSION_TS_META_KEY.to_string(), + Some(source_ts.to_string()), + ), + ( + REFRESHED_AT_MS_META_KEY.to_string(), + Some(now_ms().to_string()), + ), + ( + VIEW_VERSION_META_KEY.to_string(), + Some(predicted.to_string()), + ), + ]) + .await?; + let actual = dataset.version().version; + if actual != predicted { + return Err(Error::Runtime { + message: format!( + "a concurrent commit raced this refresh (view version {actual}, \ + expected {predicted}); the refresh is unrecorded and the next \ + one will rebuild" + ), + }); + } + view_native.dataset.update(dataset); + Ok(predicted) +} + +fn now_ms() -> u128 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() +} + +/// Evaluate the definition over `source`, restricted to `fragments` when +/// given, as batches in the view's schema. The filter is pushed into the +/// scan; projections are `(name, expression)` pairs, never spliced into SQL; +/// [`SOURCE_ROW_ID_COLUMN`] is filled by the scan's row id. +/// Which source rows a compute pass reads. +#[derive(Default)] +struct RowScope { + /// Read only these fragments. + fragments: Option>, + /// Read only rows created after this version. + created_after: Option, + /// Read only rows changed in place after the first version and no later + /// than the second. + updated_between: Option<(u64, u64)>, + /// Stop after this many rows. + limit: Option, +} + +async fn compute_stream( + source: &Dataset, + definition: &MaterializedViewDefinition, + scope: RowScope, + schema: SchemaRef, + rows_written: Arc, +) -> Result { + let RowScope { + fragments, + created_after, + updated_between, + limit, + } = scope; + let mut scanner = source.scan(); + if let Some(fragments) = fragments { + scanner.with_fragments(fragments); + } + scanner.with_row_id(); + // Narrowing keeps the definition's filter, so a row updated out of the + // view simply does not come back. Changed rows are named by the predicate + // `DatasetDelta::get_updated_rows` uses, not its streamed ids: an id list + // grows with the delta, this does not. + let updated_filter = updated_between.map(|(from, to)| { + format!( + "{ROW_CREATED_AT_VERSION} <= {from} \ + AND {ROW_LAST_UPDATED_AT_VERSION} > {from} \ + AND {ROW_LAST_UPDATED_AT_VERSION} <= {to}" + ) + }); + let created_filter = + created_after.map(|version| format!("{ROW_CREATED_AT_VERSION} > {version}")); + let clauses: Vec = definition + .filter + .clone() + .map(|f| format!("({f})")) + .into_iter() + .chain(updated_filter) + .chain(created_filter) + .collect(); + if !clauses.is_empty() { + scanner.filter(&clauses.join(" AND "))?; + } + let transforms: Vec<(&str, &str)> = definition + .projections + .iter() + .map(|p| (p.output.as_str(), p.expression.as_str())) + .collect(); + scanner.project_with_transform(&transforms)?; + // A scan reads a limit of zero as no limit at all, so a view capped at + // nothing is answered without one. + if limit == Some(0) { + return Ok(Box::pin(RecordBatchStreamAdapter::new( + schema.clone(), + futures::stream::empty(), + ))); + } + if let Some(limit) = limit { + let limit = i64::try_from(limit).map_err(|_| Error::InvalidInput { + message: format!("view limit {limit} exceeds the maximum of {}", i64::MAX), + })?; + scanner.limit(Some(limit), None)?; + } + + let out_schema = schema.clone(); + let mapped = scanner.try_into_stream().await?.map(move |batch| { + let batch = batch.map_err(|e| DataFusionError::External(Box::new(e)))?; + let mut columns = Vec::with_capacity(out_schema.fields().len()); + for field in out_schema.fields() { + let name = if field.name() == SOURCE_ROW_ID_COLUMN { + ROW_ID + } else { + field.name() + }; + let column = batch.column_by_name(name).ok_or_else(|| { + DataFusionError::Internal(format!( + "view column '{}' is not produced by the view's definition", + field.name() + )) + })?; + columns.push(column.clone()); + } + rows_written.fetch_add(batch.num_rows() as u64, Ordering::Relaxed); + Ok(RecordBatch::try_new(out_schema.clone(), columns)?) + }); + Ok(Box::pin(RecordBatchStreamAdapter::new(schema, mapped))) +} + +/// Commit the view's removals and additions as one change, on the exact +/// generation the refresh planned from. Lance rejects an overlapping +/// provenance key, but an unrelated write to the view is not a key conflict, +/// so the generation is checked here too. +async fn publish( + view_ds: &Dataset, + eviction: Option<(Vec, Vec)>, + new_fragments: Vec, + keys: Option, +) -> Result { + let planned = view_ds.version().version; + #[cfg(test)] + tests::hold_before_publish(view_ds.uri()).await; + let (updated_fragments, removed_fragment_ids) = eviction.unwrap_or_default(); + let committed = CommitBuilder::new(WriteDestination::Dataset(Arc::new(view_ds.clone()))) + .execute(Transaction::new( + planned, + Operation::Update { + removed_fragment_ids, + updated_fragments, + new_fragments, + fields_modified: Vec::new(), + compacted_sstables: Vec::new(), + fields_for_preserving_frag_bitmap: Vec::new(), + update_mode: None, + inserted_rows_filter: keys, + updated_fragment_offsets: None, + }, + None, + )) + .await?; + if committed.version().version != planned + 1 { + return Err(Error::Runtime { + message: format!( + "a concurrent commit raced this refresh (view version {}); + the refresh is unrecorded and the next one will rebuild", + committed.version().version + ), + }); + } + Ok(committed) +} + +/// A delta batch's row id column, borrowed: a delta batch is as large as one +/// fragment's deletions, so copying it out would be the unbounded step the +/// chunking exists to avoid. +fn row_ids_of(batch: &RecordBatch) -> Result<&UInt64Array> { + let column = batch.column_by_name(ROW_ID).ok_or_else(|| Error::Runtime { + message: format!("'{ROW_ID}' is missing from a delta batch"), + })?; + column + .as_primitive_opt::() + .ok_or_else(|| Error::Runtime { + message: "row ids are not UInt64".into(), + }) +} + +/// A provenance id no source row can hold, carried in every refresh's +/// inserted-rows filter: any two refreshes of one view overlap on it, so +/// the loser of a race conflicts at commit whatever rows each planned. +const REFRESH_TOKEN_ID: u64 = u64::MAX; + +/// A builder with no collected keys, for publishes that only remove rows. +fn empty_keys(view_ds: &Dataset) -> Result>> { + Ok(Arc::new(StdMutex::new(KeyExistenceFilterBuilder::new( + vec![source_row_id_field_id(view_ds)?], + )))) +} + +/// An inserted-rows filter holding the refresh token plus whatever the +/// tee collected. +fn refresh_filter(keys: &Arc>) -> Result { + let mut keys = keys.lock().map_err(|_| Error::Runtime { + message: "the provenance key filter was poisoned mid-refresh".into(), + })?; + keys.insert(KeyValue::UInt64(REFRESH_TOKEN_ID)) + .map_err(|e| Error::Runtime { + message: format!("failed to mark the refresh's filter: {e}"), + })?; + Ok(keys.build()) +} + +/// Reconciled ids past this fall back to the streamed rebuild, whose memory +/// does not grow with the delta. +fn eviction_rebuild_cap() -> usize { + #[cfg(test)] + if let Some(cap) = tests::eviction_cap_override() { + return cap; + } + 4 * 1024 * 1024 +} + +/// Provenance ids per staged eviction: the delete predicate carries one +/// literal per id, so a whole delta at once is unbounded. Each chunk costs a +/// pass over the view's provenance column, which is why it is not smaller. +const EVICTION_CHUNK: usize = 64 * 1024; + +/// Accumulates the view's removals from bounded chunks of provenance ids into +/// the one set of fragment changes the refresh publishes. +struct Eviction { + /// The view as the chunks staged so far leave it. A chunk's delete has to + /// see the deletion vectors the earlier ones wrote, or it stages a + /// fragment that drops them. + snapshot: Dataset, + chunk: usize, + updated: HashMap, + removed: Vec, + pending: Vec, + staged: bool, + /// Largest the buffer ever got, which is the bound under test. + #[cfg(test)] + peak: usize, +} + +impl Eviction { + fn new(view_ds: &Dataset, chunk: usize) -> Self { + Self { + snapshot: view_ds.clone(), + chunk, + updated: HashMap::new(), + removed: Vec::new(), + pending: Vec::with_capacity(chunk), + staged: false, + #[cfg(test)] + peak: 0, + } + } + + /// Fill a chunk at a time. Taking the batch whole and splitting it would + /// hold a fragment's worth of ids and recopy the tail per chunk. + async fn push(&mut self, ids: &UInt64Array) -> Result<()> { + for id in ids.values() { + self.pending.push(*id); + #[cfg(test)] + { + self.peak = self.peak.max(self.pending.len()); + } + if self.pending.len() == self.chunk { + self.flush().await?; + } + } + Ok(()) + } + + /// Stage what is buffered, keeping the buffer's allocation. + async fn flush(&mut self) -> Result<()> { + let mut chunk = std::mem::take(&mut self.pending); + let staged = self.stage(&chunk).await; + chunk.clear(); + self.pending = chunk; + staged + } + + /// The staged fragment changes, or `None` where nothing was evicted. + async fn finish(mut self) -> Result, Vec)>> { + if !self.pending.is_empty() { + self.flush().await?; + } + if !self.staged { + return Ok(None); + } + let mut updated: Vec = self.updated.into_values().collect(); + updated.sort_unstable_by_key(|f| f.id); + Ok(Some((updated, self.removed))) + } + + async fn stage(&mut self, ids: &[u64]) -> Result<()> { + let (updated, removed) = stage_eviction(&self.snapshot, ids).await?; + self.snapshot = advance(&self.snapshot, &updated); + for fragment in updated { + self.updated.insert(fragment.id, fragment); + } + self.removed.extend(removed); + self.staged = true; + Ok(()) + } +} + +/// The view as staged removals leave it, without committing them. Fragments +/// are replaced in place so the fragment bitmap stays in step; an emptied one +/// is left alone, since the delta names each provenance id only once. +fn advance(view_ds: &Dataset, updated: &[Fragment]) -> Dataset { + if updated.is_empty() { + return view_ds.clone(); + } + let by_id: HashMap = updated.iter().map(|f| (f.id, f)).collect(); + let fragments = view_ds + .manifest + .fragments + .iter() + .map(|f| by_id.get(&f.id).map_or_else(|| f.clone(), |u| (*u).clone())) + .collect(); + let mut manifest = view_ds.manifest.as_ref().clone(); + manifest.fragments = Arc::new(fragments); + let mut snapshot = view_ds.clone(); + snapshot.manifest = Arc::new(manifest); + snapshot +} + +/// The fragment changes that remove the view's rows for `ids`, staged rather +/// than committed so they can ride in the refresh's single data commit. +async fn stage_eviction(view_ds: &Dataset, ids: &[u64]) -> Result<(Vec, Vec)> { + // An expression rather than SQL text: the id list is a value here, not a + // predicate string that grows with the delta and has to be parsed. + let predicate = col(SOURCE_ROW_ID_COLUMN).in_list( + ids.iter() + .map(|id| lit(ScalarValue::UInt64(Some(*id)))) + .collect(), + false, + ); + let staged = DeleteBuilder::from_expr(Arc::new(view_ds.clone()), predicate) + .execute_uncommitted() + .await?; + let Operation::Delete { + updated_fragments, + deleted_fragment_ids, + .. + } = staged.transaction.operation + else { + return Err(Error::Runtime { + message: "expected a delete when staging the view's evictions".into(), + }); + }; + Ok((updated_fragments, deleted_fragment_ids)) +} + +fn source_row_id_field_id(view_ds: &Dataset) -> Result { + view_ds + .schema() + .field(SOURCE_ROW_ID_COLUMN) + .map(|f| f.id) + .ok_or_else(|| Error::Runtime { + message: format!("the view has no '{SOURCE_ROW_ID_COLUMN}' column"), + }) +} + +/// Tee the provenance ids of everything written into `keys`. +fn collect_source_row_ids( + stream: SendableRecordBatchStream, + keys: Arc>, + written: Arc, +) -> SendableRecordBatchStream { + let schema = stream.schema(); + let mapped = stream.map(move |batch| { + let batch = batch?; + let column = batch + .column_by_name(SOURCE_ROW_ID_COLUMN) + .ok_or_else(|| { + DataFusionError::Internal(format!( + "'{SOURCE_ROW_ID_COLUMN}' is missing from the rows being written" + )) + })? + .as_primitive_opt::() + .ok_or_else(|| { + DataFusionError::Internal(format!("'{SOURCE_ROW_ID_COLUMN}' is not a uint64")) + })?; + let mut keys = keys + .lock() + .map_err(|_| DataFusionError::Internal("provenance key filter poisoned".into()))?; + for id in column.values() { + keys.insert(KeyValue::UInt64(*id)) + .map_err(|e| DataFusionError::Internal(e.to_string()))?; + } + written.fetch_add(batch.num_rows() as u64, Ordering::Relaxed); + Ok(batch) + }); + Box::pin(RecordBatchStreamAdapter::new(schema, mapped)) +} + +#[cfg(test)] +mod tests { + + /// Park a refresh between planning and publication so a test can move + /// the view underneath it. Inert unless [`DRIFT_TARGET`] names this view. + pub(super) async fn hold_before_publish(uri: &str) { + { + let mut target = DRIFT_TARGET.lock().unwrap(); + if target.as_deref() != Some(uri) { + return; + } + // Take it: memory:// uris are relative and repeat across tests, so + // leaving it armed would park an unrelated refresh forever. + *target = None; + } + DRIFT_PLANNED.notify_one(); + DRIFT_RELEASED.notified().await; + } + + /// The rendezvous below is one global pair, so the cases that use it run + /// one at a time rather than trading each other's signals. + pub(super) static EVICTION_CAP: StdMutex> = StdMutex::new(None); + pub(super) fn eviction_cap_override() -> Option { + *EVICTION_CAP.lock().unwrap() + } + + pub(super) static DRIFT_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + pub(super) static DRIFT_TARGET: StdMutex> = StdMutex::new(None); + pub(super) static DRIFT_PLANNED: tokio::sync::Notify = tokio::sync::Notify::const_new(); + pub(super) static DRIFT_RELEASED: tokio::sync::Notify = tokio::sync::Notify::const_new(); + use arrow_array::{Int32Array, record_batch}; + use futures::TryStreamExt; + use lance::dataset::NewColumnTransform; + use lance_file::version::LanceFileVersion; + + use super::*; + use crate::connect; + use crate::connection::Connection; + use crate::index::Index; + use crate::index::scalar::BTreeIndexBuilder; + use crate::materialized_view::MaterializedView; + use crate::query::{ExecutableQuery, QueryBase, Select}; + use crate::table::{CompactionOptions, OptimizeAction}; + + async fn db_with_source(values: Vec) -> (Connection, Table) { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!(("x", Int32, values)).unwrap(); + let table = conn + .create_table("src", batch) + .write_options(crate::materialized_view::tests::stable_row_ids()) + .execute() + .await + .unwrap(); + (conn, table) + } + + async fn doubled_view(conn: &Connection) -> MaterializedView { + conn.create_materialized_view("doubled", "src") + .select([("x", "x"), ("twice", "x * 2")]) + .execute() + .await + .unwrap() + } + + /// A refreshed doubled view over a source holding `values`. + async fn refreshed_doubled(values: Vec) -> (Connection, Table, MaterializedView) { + let (conn, source) = db_with_source(values).await; + let view = doubled_view(&conn).await; + view.refresh().execute().await.unwrap(); + (conn, source, view) + } + + async fn read(table: &Table, column: &str) -> Vec { + let batches = table + .query() + .select(Select::columns(&[column])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let mut values: Vec = batches + .iter() + .flat_map(|batch| { + batch[column] + .as_any() + .downcast_ref::() + .unwrap() + .iter() + .flatten() + .collect::>() + }) + .collect(); + values.sort(); + values + } + + async fn append(table: &Table, values: Vec) { + let batch = record_batch!(("x", Int32, values)).unwrap(); + table.add(batch).execute().await.unwrap(); + } + + #[tokio::test] + async fn test_first_refresh_materializes_the_view() { + let (conn, _) = db_with_source(vec![1, 2, 3]).await; + let view = doubled_view(&conn).await; + + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Rebuild); + assert_eq!(result.rows_written, 3); + assert_eq!(read(view.table(), "twice").await, vec![2, 4, 6]); + + // The watermark survives on the stored schema, not just the handle. + let reopened = conn.open_materialized_view("doubled").await.unwrap(); + let again = reopened.refresh().execute().await.unwrap(); + assert_eq!(again.mode, RefreshMode::NoOp); + assert_eq!(again.rows_written, 0); + } + + #[tokio::test] + async fn test_filter_selects_the_source_rows() { + let (conn, _) = db_with_source(vec![1, 20, 3, 40]).await; + let view = conn + .create_materialized_view("big", "src") + .select([("x", "x")]) + .only_if("x > 10") + .execute() + .await + .unwrap(); + + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.rows_written, 2); + assert_eq!(read(view.table(), "x").await, vec![20, 40]); + } + + #[tokio::test] + async fn test_append_refreshes_incrementally() { + let (_conn, source, view) = refreshed_doubled(vec![1, 2]).await; + + append(&source, vec![5]).await; + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(result.rows_written, 1); + assert_eq!(read(view.table(), "twice").await, vec![2, 4, 10]); + } + + #[tokio::test] + async fn test_incremental_applies_the_filter() { + let (conn, source) = db_with_source(vec![1, 20]).await; + let view = conn + .create_materialized_view("big", "src") + .select([("x", "x")]) + .only_if("x > 10") + .execute() + .await + .unwrap(); + view.refresh().execute().await.unwrap(); + + append(&source, vec![3, 30]).await; + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(result.rows_written, 1); + assert_eq!(read(view.table(), "x").await, vec![20, 30]); + } + + /// The watermark has to advance even when no appended row matches, or the + /// same fragments would be rescanned by every later refresh. + #[tokio::test] + async fn test_incremental_with_nothing_matching_advances_the_watermark() { + let (conn, source) = db_with_source(vec![20]).await; + let view = conn + .create_materialized_view("big", "src") + .select([("x", "x")]) + .only_if("x > 10") + .execute() + .await + .unwrap(); + view.refresh().execute().await.unwrap(); + + append(&source, vec![1, 2]).await; + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(result.rows_written, 0); + + let again = view.refresh().execute().await.unwrap(); + assert_eq!(again.mode, RefreshMode::NoOp); + } + + /// Unlike a computed column, a view reflects source mutation: an update + /// rebuilds rather than going stale. + #[tokio::test] + async fn test_update_replaces_the_rows_it_changed() { + let (_conn, source, view) = refreshed_doubled(vec![1, 2, 3]).await; + + // An update changes rows in place, so the view replaces exactly + // those rows and leaves the rest of what it holds alone. + source + .update() + .column("x", "20") + .only_if("x = 2") + .execute() + .await + .unwrap(); + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(result.rows_written, 1, "only the changed row is recomputed"); + assert_eq!(read(view.table(), "twice").await, vec![2, 6, 40]); + } + + /// Legacy storage cannot serve the row-version columns update discovery + /// scans; appends stay incremental, updates rebuild rather than fail. + #[tokio::test] + async fn test_a_legacy_storage_source_is_reconciled() { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!(("x", Int32, [1, 2, 3])).unwrap(); + let source = conn + .create_table("legacy_src", batch) + .write_options(crate::table::WriteOptions { + lance_write_params: Some(lance::dataset::WriteParams { + enable_stable_row_ids: true, + data_storage_version: Some(LanceFileVersion::Legacy), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + let view = conn + .create_materialized_view("legacy_doubled", "legacy_src") + .select([("x", "x"), ("twice", "x * 2")]) + .execute() + .await + .unwrap(); + view.refresh().execute().await.unwrap(); + + source + .add(record_batch!(("x", Int32, [4])).unwrap()) + .execute() + .await + .unwrap(); + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(read(view.table(), "twice").await, vec![2, 4, 6, 8]); + + source + .update() + .column("x", "20") + .only_if("x = 2") + .execute() + .await + .unwrap(); + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Rebuild); + assert_eq!(read(view.table(), "twice").await, vec![2, 6, 8, 40]); + } + + #[tokio::test] + async fn test_delete_evicts_the_view_rows_it_removed() { + let (_conn, source, view) = refreshed_doubled(vec![1, 2, 3]).await; + + // A delete removes source rows without changing the ones that + // remain, so the view evicts exactly those rows and keeps the rest + // rather than recomputing every row it already held. + source.delete("x = 2").await.unwrap(); + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(read(view.table(), "twice").await, vec![2, 6]); + + // A delete and an append in one span: both are applied. + source.delete("x = 1").await.unwrap(); + source + .add(record_batch!(("x", Int32, vec![4])).unwrap()) + .execute() + .await + .unwrap(); + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(read(view.table(), "twice").await, vec![6, 8]); + } + + /// merge_insert commits an `Update`, and its by-source arm removes rows + /// rather than changing them, so the classifier must treat that + /// transaction form as a source of deletions. + #[tokio::test] + async fn test_merge_insert_by_source_delete_evicts_the_view_rows() { + let (_conn, source, view) = refreshed_doubled(vec![1, 2, 3]).await; + + let batch = record_batch!(("x", Int32, vec![1, 3])).unwrap(); + let reader = arrow_array::RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema()); + let mut merge = source.merge_insert(&["x"]); + merge.when_not_matched_by_source_delete(None); + merge.execute(Box::new(reader)).await.unwrap(); + + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(read(view.table(), "twice").await, vec![2, 6]); + } + + /// A refresh may only certify the generation it planned from. A write + /// that lands between planning and publication is drift the refresh did + /// not account for, so it aborts rather than stamp it as materialized. + #[tokio::test(flavor = "multi_thread")] + async fn test_refresh_aborts_rather_than_certify_view_drift() { + let _serial = DRIFT_LOCK.lock().await; + let (conn, source) = db_with_source(vec![1, 2, 3]).await; + let view = conn + .create_materialized_view("drifting_view", "src") + .select([("x", "x"), ("twice", "x * 2")]) + .execute() + .await + .unwrap(); + view.refresh().execute().await.unwrap(); + let certified = source_version_of(view.table()).await; + + // The source loses a row, so the next refresh plans an eviction. + source.delete("x = 2").await.unwrap(); + + let uri = view + .table() + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .uri() + .to_string(); + *DRIFT_TARGET.lock().unwrap() = Some(uri); + let refreshing = tokio::spawn(async move { view.refresh().execute().await }); + + // Move the view once the refresh has planned against it. + tokio::time::timeout(std::time::Duration::from_secs(30), DRIFT_PLANNED.notified()) + .await + .expect("the refresh never reached the publication boundary"); + let drifted = conn.open_table("drifting_view").execute().await.unwrap(); + drifted.delete("twice = 6").await.unwrap(); + DRIFT_RELEASED.notify_one(); + + // Publishing removals and additions as one change makes the drift a + // conflict lance itself rejects; a pure append, which touches no + // existing fragment, still relies on the generation check. + let err = refreshing.await.unwrap().unwrap_err(); + let message = err.to_string(); + assert!( + message.contains("raced this refresh") || message.contains("preempted by concurrent"), + "got {err:?}" + ); + // The watermark still names the generation that was actually proven. + assert_eq!(source_version_of(&drifted).await, certified); + } + + async fn source_version_of(table: &Table) -> Option { + table + .schema() + .await + .unwrap() + .metadata() + .get(SOURCE_VERSION_META_KEY) + .cloned() + } + + /// A transaction file carries placeholder ids for the fragments it + /// creates. Into an empty source those collide with the ids the commit + /// assigns, so treating them as already-materialized drops the very + /// first rows while the watermark still advances past them. + #[tokio::test] + async fn test_merge_into_an_empty_source_is_materialized() { + let (_conn, source, view) = refreshed_doubled(vec![]).await; + assert_eq!(read(view.table(), "twice").await, Vec::::new()); + + let batch = record_batch!(("x", Int32, vec![1, 2])).unwrap(); + let reader = arrow_array::RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema()); + let mut merge = source.merge_insert(&["x"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + merge.execute(Box::new(reader)).await.unwrap(); + + view.refresh().execute().await.unwrap(); + assert_eq!(read(view.table(), "twice").await, vec![2, 4]); + // A second refresh must not double them either. + view.refresh().execute().await.unwrap(); + assert_eq!(read(view.table(), "twice").await, vec![2, 4]); + } + + /// A refresh publishes what it removes and what it adds as one change, + /// so an update never exposes the view without the rows it is replacing. + #[tokio::test(flavor = "multi_thread")] + async fn test_an_update_is_never_visible_as_a_gap() { + let _serial = DRIFT_LOCK.lock().await; + let (conn, source) = db_with_source(vec![1, 2, 3]).await; + let view = conn + .create_materialized_view("atomic_view", "src") + .select([("x", "x"), ("twice", "x * 2")]) + .execute() + .await + .unwrap(); + view.refresh().execute().await.unwrap(); + + source + .update() + .column("x", "x + 10") + .execute() + .await + .unwrap(); + + let uri = view + .table() + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .uri() + .to_string(); + *DRIFT_TARGET.lock().unwrap() = Some(uri); + let refreshing = tokio::spawn(async move { view.refresh().execute().await }); + + // Read the view while the refresh is staged but not yet published. + tokio::time::timeout(std::time::Duration::from_secs(30), DRIFT_PLANNED.notified()) + .await + .expect("the refresh never reached the publication boundary"); + let midway = conn.open_table("atomic_view").execute().await.unwrap(); + assert_eq!( + read(&midway, "twice").await, + vec![2, 4, 6], + "the pre-refresh rows must still be there in full" + ); + DRIFT_RELEASED.notify_one(); + + refreshing.await.unwrap().unwrap(); + let after = conn.open_table("atomic_view").execute().await.unwrap(); + assert_eq!(read(&after, "twice").await, vec![22, 24, 26]); + } + + async fn provenance_by_x(table: &Table) -> HashMap { + let batches = table + .query() + .select(Select::columns(&["x", SOURCE_ROW_ID_COLUMN])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + batches + .iter() + .flat_map(|batch| { + let xs = batch["x"].as_any().downcast_ref::().unwrap(); + let ids = batch[SOURCE_ROW_ID_COLUMN].as_primitive::(); + (0..batch.num_rows()) + .map(|i| (xs.value(i), ids.value(i))) + .collect::>() + }) + .collect() + } + + /// One delta batch is as large as a fragment's deletions, so it arrives + /// well past a chunk: it has to be drained a chunk at a time without ever + /// holding the batch, and the passes' deletion vectors have to accumulate + /// rather than replace each other. + #[tokio::test] + async fn test_a_chunked_eviction_removes_every_row_it_names() { + let (_conn, _, view) = refreshed_doubled(vec![1, 2, 3, 4, 5, 6]).await; + + let native = view.table().as_native().unwrap(); + let view_ds = native.dataset.get().await.unwrap().as_ref().clone(); + let provenance = provenance_by_x(view.table()).await; + + let mut eviction = Eviction::new(&view_ds, 2); + let batch = UInt64Array::from_iter_values([1, 2, 3, 4].map(|x| provenance[&x])); + eviction.push(&batch).await.unwrap(); + assert_eq!( + eviction.peak, 2, + "a batch past the chunk was buffered whole" + ); + let staged = eviction.finish().await.unwrap(); + assert!(staged.is_some(), "four ids over a chunk of two stage twice"); + publish(&view_ds, staged, Vec::new(), None).await.unwrap(); + native.dataset.reload().await.unwrap(); + + assert_eq!(read(view.table(), "x").await, vec![5, 6]); + } + + /// Two first rebuilds materialize the same source rows; the loser must + /// key-conflict at commit and land nothing, or the view doubles. + #[tokio::test] + async fn test_a_raced_first_rebuild_lands_nothing() { + let _guard = DRIFT_LOCK.lock().await; + let (conn, _) = db_with_source(vec![1, 2, 3]).await; + let view = conn + .create_materialized_view("raced_rebuild", "src") + .select([("x", "x"), ("twice", "x * 2")]) + .execute() + .await + .unwrap(); + let native = view.table().as_native().unwrap(); + let view_ds = native.dataset.get().await.unwrap().as_ref().clone(); + let uri = view_ds.uri().to_string(); + *DRIFT_TARGET.lock().unwrap() = Some(uri); + let racing = tokio::spawn(async move { view.refresh().execute().await }); + tokio::time::timeout(std::time::Duration::from_secs(30), DRIFT_PLANNED.notified()) + .await + .expect("the rebuild never reached the publication boundary"); + + // The other process's first rebuild, reduced to its commit. Its + // source rows are DISJOINT from ours -- the sentinel alone must make + // the two rebuilds conflict. + let batch = record_batch!( + ("x", Int32, [8, 9]), + ("twice", Int32, [16, 18]), + ("__source_row_id", UInt64, [7u64, 8]) + ) + .unwrap(); + let schema = Arc::new(ArrowSchema::from(view_ds.schema())); + let batch = RecordBatch::try_new( + schema.clone(), + schema + .fields() + .iter() + .map(|f| batch.column_by_name(f.name()).unwrap().clone()) + .collect(), + ) + .unwrap(); + let stream: SendableRecordBatchStream = Box::pin(RecordBatchStreamAdapter::new( + schema.clone(), + futures::stream::iter([Ok(batch)]), + )); + let keys = Arc::new(StdMutex::new(KeyExistenceFilterBuilder::new(vec![ + source_row_id_field_id(&view_ds).unwrap(), + ]))); + let stream = collect_source_row_ids(stream, keys.clone(), Arc::new(AtomicU64::new(0))); + let write_txn = InsertBuilder::new(WriteDestination::Dataset(Arc::new(view_ds.clone()))) + .with_params(&WriteParams { + mode: WriteMode::Append, + ..Default::default() + }) + .execute_uncommitted_stream(stream) + .await + .unwrap(); + let Operation::Append { fragments } = write_txn.operation else { + panic!("expected an append"); + }; + let filter = { + let mut keys = keys.lock().unwrap(); + keys.insert(KeyValue::UInt64(super::REFRESH_TOKEN_ID)) + .unwrap(); + keys.build() + }; + CommitBuilder::new(WriteDestination::Dataset(Arc::new(view_ds.clone()))) + .execute(Transaction::new( + view_ds.version().version, + Operation::Update { + removed_fragment_ids: Vec::new(), + updated_fragments: Vec::new(), + new_fragments: fragments, + fields_modified: Vec::new(), + compacted_sstables: Vec::new(), + fields_for_preserving_frag_bitmap: Vec::new(), + update_mode: None, + inserted_rows_filter: Some(filter), + updated_fragment_offsets: None, + }, + None, + )) + .await + .unwrap(); + DRIFT_RELEASED.notify_one(); + + let err = racing.await.unwrap().unwrap_err(); + // The loser lands nothing: only the winner's rows remain. + let raced = conn.open_table("raced_rebuild").execute().await.unwrap(); + assert_eq!( + read(&raced, "twice").await, + vec![16, 18], + "the losing rebuild must not union with the winner ({err})" + ); + } + + /// An incremental refresh racing any other refresh must land nothing, + /// even when their planned rows are disjoint: the shared token makes the + /// commits conflict. + #[tokio::test] + async fn test_a_raced_incremental_lands_nothing() { + let _guard = DRIFT_LOCK.lock().await; + let (conn, source) = db_with_source(vec![1, 2, 3]).await; + let view = conn + .create_materialized_view("raced_incremental", "src") + .select([("x", "x"), ("twice", "x * 2")]) + .execute() + .await + .unwrap(); + view.refresh().execute().await.unwrap(); + append(&source, vec![4]).await; + + let native = view.table().as_native().unwrap(); + native.dataset.reload().await.unwrap(); + let view_ds = native.dataset.get().await.unwrap().as_ref().clone(); + *DRIFT_TARGET.lock().unwrap() = Some(view_ds.uri().to_string()); + let racing = tokio::spawn(async move { view.refresh().execute().await }); + tokio::time::timeout(std::time::Duration::from_secs(30), DRIFT_PLANNED.notified()) + .await + .expect("the refresh never reached the publication boundary"); + + // The concurrent refresh, reduced to its commit: disjoint rows, the + // shared token alone must collide. + let batch = record_batch!( + ("x", Int32, [9]), + ("twice", Int32, [18]), + ("__source_row_id", UInt64, [8u64]) + ) + .unwrap(); + let schema = Arc::new(ArrowSchema::from(view_ds.schema())); + let batch = RecordBatch::try_new( + schema.clone(), + schema + .fields() + .iter() + .map(|f| batch.column_by_name(f.name()).unwrap().clone()) + .collect(), + ) + .unwrap(); + let stream: SendableRecordBatchStream = Box::pin(RecordBatchStreamAdapter::new( + schema.clone(), + futures::stream::iter([Ok(batch)]), + )); + let keys = empty_keys(&view_ds).unwrap(); + let stream = collect_source_row_ids(stream, keys.clone(), Arc::new(AtomicU64::new(0))); + let write_txn = InsertBuilder::new(WriteDestination::Dataset(Arc::new(view_ds.clone()))) + .with_params(&WriteParams { + mode: WriteMode::Append, + ..Default::default() + }) + .execute_uncommitted_stream(stream) + .await + .unwrap(); + let Operation::Append { fragments } = write_txn.operation else { + panic!("expected an append"); + }; + let filter = refresh_filter(&keys).unwrap(); + CommitBuilder::new(WriteDestination::Dataset(Arc::new(view_ds.clone()))) + .execute(Transaction::new( + view_ds.version().version, + Operation::Update { + removed_fragment_ids: Vec::new(), + updated_fragments: Vec::new(), + new_fragments: fragments, + fields_modified: Vec::new(), + compacted_sstables: Vec::new(), + fields_for_preserving_frag_bitmap: Vec::new(), + update_mode: None, + inserted_rows_filter: Some(filter), + updated_fragment_offsets: None, + }, + None, + )) + .await + .unwrap(); + DRIFT_RELEASED.notify_one(); + + let err = racing.await.unwrap().unwrap_err(); + let raced = conn + .open_table("raced_incremental") + .execute() + .await + .unwrap(); + assert_eq!( + read(&raced, "twice").await, + vec![2, 4, 6, 18], + "the losing increment must not land its rows ({err})" + ); + } + + /// Past the eviction cap the refresh falls back to the streamed rebuild, + /// and the result is identical either way. + #[tokio::test] + async fn test_oversized_delta_falls_back_to_rebuild() { + let (conn, source) = db_with_source((1..=20).collect()).await; + let view = doubled_view(&conn).await; + view.refresh().execute().await.unwrap(); + + source.delete("x <= 10").await.unwrap(); + *tests::EVICTION_CAP.lock().unwrap() = Some(4); + let result = view.refresh().execute().await; + *tests::EVICTION_CAP.lock().unwrap() = None; + let result = result.unwrap(); + assert_eq!( + result.mode, + RefreshMode::Rebuild, + "ten evictions, cap of four" + ); + assert_eq!(read(view.table(), "x").await, (11..=20).collect::>()); + + // Under the cap the same shape stays incremental. + source.delete("x = 11").await.unwrap(); + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(read(view.table(), "x").await, (12..=20).collect::>()); + } + + /// A cap of zero is a view that holds nothing, not a view without a cap. + #[tokio::test] + async fn test_zero_limit_holds_no_rows() { + let (conn, source) = db_with_source(vec![1, 2, 3]).await; + let view = conn + .create_materialized_view("empty", "src") + .select([("x", "x")]) + .limit(0) + .execute() + .await + .unwrap(); + + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.rows_written, 0); + assert_eq!(view.table().count_rows(None).await.unwrap(), 0); + + // Still nothing after the source grows, and the watermark advances. + append(&source, vec![4]).await; + view.refresh().execute().await.unwrap(); + assert_eq!(view.table().count_rows(None).await.unwrap(), 0); + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::NoOp + ); + } + + /// An update rewrites a whole fragment. When it lands on one appended + /// since the watermark, that fragment also holds rows the update never + /// touched -- rows the recompute does not cover and the append set no + /// longer reaches. + #[tokio::test] + async fn test_update_touching_a_new_fragment_keeps_its_untouched_rows() { + let (_conn, source, view) = refreshed_doubled(vec![1, 2]).await; + + // One fragment, appended after the watermark, holding both a row the + // update will change and a row it will not. + append(&source, vec![3, 40]).await; + source + .update() + .column("x", "99") + .only_if("x = 3") + .execute() + .await + .unwrap(); + + view.refresh().execute().await.unwrap(); + assert_eq!( + read(view.table(), "twice").await, + vec![2, 4, 80, 198], + "a row appended into the updated fragment went missing" + ); + } + + async fn compact(source: &Table) { + source + .optimize(OptimizeAction::Compact { + options: CompactionOptions::default(), + remap_options: None, + }) + .await + .unwrap(); + } + + /// A compaction rearranges rows without changing them, so it costs the + /// view nothing: the watermark advances and no row is recomputed. + #[tokio::test] + async fn test_compaction_alone_refreshes_incrementally() { + let (_conn, source, view) = refreshed_doubled(vec![1, 2]).await; + append(&source, vec![3]).await; + view.refresh().execute().await.unwrap(); + + compact(&source).await; + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(result.rows_written, 0); + assert_eq!(read(view.table(), "twice").await, vec![2, 4, 6]); + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::NoOp + ); + } + + /// Rows appended after a compaction are separable through the transaction + /// log: only the appended fragments are computed. + #[tokio::test] + async fn test_append_after_compaction_stays_incremental() { + let (_conn, source, view) = refreshed_doubled(vec![1]).await; + append(&source, vec![2]).await; + view.refresh().execute().await.unwrap(); + + compact(&source).await; + append(&source, vec![3]).await; + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(result.rows_written, 1); + assert_eq!(read(view.table(), "twice").await, vec![2, 4, 6]); + } + + /// An append swallowed by a later compaction cannot be told apart from + /// the rows the view already holds, so the refresh rebuilds -- once -- + /// rather than duplicate or drop. + #[tokio::test] + async fn test_append_folded_into_compaction_rebuilds() { + let (_conn, source, view) = refreshed_doubled(vec![1]).await; + + append(&source, vec![2]).await; + compact(&source).await; + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Rebuild); + assert_eq!(read(view.table(), "twice").await, vec![2, 4]); + } + + /// The create-time gate holds across a drop-and-recreate of the source + /// under the same name. + #[tokio::test] + async fn test_refresh_refuses_a_recreated_source_without_stable_row_ids() { + let (conn, _, view) = refreshed_doubled(vec![1]).await; + + conn.drop_table("src", &[]).await.unwrap(); + let batch = record_batch!(("x", Int32, [9])).unwrap(); + conn.create_table("src", batch).execute().await.unwrap(); + + let err = view.refresh().execute().await.unwrap_err(); + assert!( + matches!(err, Error::InvalidInput { message } if message.contains("stable row ids")) + ); + } + + /// A change to a column the view does not read is not a reason to + /// rebuild: the exact signature check is scoped to the view's inputs. + #[tokio::test] + async fn test_unrelated_column_change_does_not_rebuild() { + let (_conn, source, view) = refreshed_doubled(vec![1, 2]).await; + + source + .add_columns() + .transform(NewColumnTransform::AllNulls(Arc::new(ArrowSchema::new( + vec![arrow_schema::Field::new( + "unrelated", + arrow_schema::DataType::Int32, + true, + )], + )))) + .execute() + .await + .unwrap(); + + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(result.rows_written, 0); + assert_eq!(read(view.table(), "twice").await, vec![2, 4]); + } + + #[tokio::test] + async fn test_full_forces_a_rebuild() { + let (_conn, source, view) = refreshed_doubled(vec![1]).await; + + append(&source, vec![2]).await; + let result = view.refresh().full(true).execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Rebuild); + assert_eq!(result.rows_written, 2); + assert_eq!(read(view.table(), "twice").await, vec![2, 4]); + } + + /// A cap and incremental reconciliation do not compose: rows skipped at + /// the cap fall behind the watermark, so room freed later cannot be + /// refilled from any delta. A capped view rebuilds instead, which its + /// own cap keeps cheap. + #[tokio::test] + async fn test_limited_view_rebuilds_rather_than_reconcile() { + let (conn, source) = db_with_source(vec![1, 2]).await; + let view = conn + .create_materialized_view("capped", "src") + .select([("x", "x")]) + .limit(2) + .execute() + .await + .unwrap(); + view.refresh().execute().await.unwrap(); + assert_eq!(read(view.table(), "x").await, vec![1, 2]); + + append(&source, vec![3, 4]).await; + source + .update() + .column("x", "11") + .only_if("x = 1") + .execute() + .await + .unwrap(); + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Rebuild); + let held = read(view.table(), "x").await; + assert_eq!(held.len(), 2, "the cap holds: {held:?}"); + let selectable = read(&source, "x").await; + assert!( + held.iter().all(|x| selectable.contains(x)), + "{held:?} is not a subset of {selectable:?}" + ); + } + + #[tokio::test] + async fn test_limit_caps_the_view() { + let (conn, source) = db_with_source(vec![1, 2, 3]).await; + let view = conn + .create_materialized_view("capped", "src") + .select([("x", "x")]) + .limit(4) + .execute() + .await + .unwrap(); + + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.rows_written, 3); + + // The cap counts already-held rows, so only one appended row lands. + append(&source, vec![4, 5, 6]).await; + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(result.rows_written, 1); + assert_eq!(view.table().count_rows(None).await.unwrap(), 4); + + // At the cap, later appends only move the watermark. + append(&source, vec![7]).await; + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.rows_written, 0); + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::NoOp + ); + } + + /// The whole point of the fragment-swap commit: a rebuild must never + /// leave the view without its index definitions. + #[tokio::test] + async fn test_rebuild_retains_indexes() { + let (_conn, source, view) = refreshed_doubled(vec![1, 2, 3]).await; + + view.table() + .create_index(&["twice"], Index::BTree(BTreeIndexBuilder::default())) + .execute() + .await + .unwrap(); + assert_eq!(view.table().list_indices().await.unwrap().len(), 1); + + source + .update() + .column("x", "x + 10") + .execute() + .await + .unwrap(); + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Rebuild); + assert_eq!(view.table().list_indices().await.unwrap().len(), 1); + assert_eq!(read(view.table(), "twice").await, vec![22, 24, 26]); + + // The swapped-in rows are reachable through an indexed query. + let batches = view + .table() + .query() + .only_if("twice = 24") + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 1); + } + + #[tokio::test] + async fn test_rebuild_of_an_empty_result_is_an_empty_view() { + let (conn, _) = db_with_source(vec![1, 2]).await; + let view = conn + .create_materialized_view("none", "src") + .select([("x", "x")]) + .only_if("x > 100") + .execute() + .await + .unwrap(); + + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Rebuild); + assert_eq!(result.rows_written, 0); + assert_eq!(view.table().count_rows(None).await.unwrap(), 0); + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::NoOp + ); + } + + /// Provenance: every view row records the source row that produced it. + #[tokio::test] + async fn test_source_row_ids_are_recorded() { + let (_conn, _, view) = refreshed_doubled(vec![1, 2, 3]).await; + + let batches = view + .table() + .query() + .select(Select::columns(&[SOURCE_ROW_ID_COLUMN])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let total: usize = batches.iter().map(|b| b.num_rows()).sum(); + assert_eq!(total, 3); + for batch in &batches { + assert_eq!(batch[SOURCE_ROW_ID_COLUMN].null_count(), 0); + } + } + + #[tokio::test] + async fn test_dropping_a_source_input_fails_the_refresh() { + let (conn, source) = db_with_source(vec![1]).await; + let view = conn + .create_materialized_view("v", "src") + .select([("twice", "x * 2")]) + .execute() + .await + .unwrap(); + view.refresh().execute().await.unwrap(); + + append(&source, vec![2]).await; + source + .add_columns() + .transform(NewColumnTransform::AllNulls(Arc::new(ArrowSchema::new( + vec![arrow_schema::Field::new( + "y", + arrow_schema::DataType::Int32, + true, + )], + )))) + .execute() + .await + .unwrap(); + source.drop_columns(&["x"]).await.unwrap(); + + let err = view.refresh().execute().await.unwrap_err(); + assert!(matches!(err, Error::Schema { message } if message.contains("'x'"))); + } + + /// A pinned refresh materializes the source as of `version`; catching up + /// to the appends beyond it stays incremental. + #[tokio::test] + async fn test_pinned_refresh_and_catch_up() { + let (conn, source) = db_with_source(vec![1]).await; + let view = doubled_view(&conn).await; + let pinned = source.version().await.unwrap(); + + append(&source, vec![2]).await; + let result = view + .refresh() + .source_version(pinned) + .execute() + .await + .unwrap(); + assert_eq!(result.source_version, pinned); + assert_eq!(read(view.table(), "twice").await, vec![2]); + + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(read(view.table(), "twice").await, vec![2, 4]); + } + + /// Views chain: a view's stable row ids and provenance column make it a + /// source like any other, and the default projection takes its declared + /// columns without copying its provenance. + #[tokio::test] + async fn test_a_view_can_source_another_view() { + let (conn, source) = db_with_source(vec![1, 2, 30]).await; + let first = doubled_view(&conn).await; + first.refresh().execute().await.unwrap(); + + let second = conn + .create_materialized_view("second", "doubled") + .only_if("twice > 10") + .execute() + .await + .unwrap(); + assert!( + second + .definition() + .projections + .iter() + .all(|p| p.output != SOURCE_ROW_ID_COLUMN) + ); + let result = second.refresh().execute().await.unwrap(); + assert_eq!(result.rows_written, 1); + assert_eq!(read(second.table(), "twice").await, vec![60]); + + append(&source, vec![50]).await; + first.refresh().execute().await.unwrap(); + let result = second.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(read(second.table(), "twice").await, vec![60, 100]); + } + + /// The watermark speaks only for the state a refresh left behind: a + /// direct write to the view is drift, and the next refresh rebuilds + /// rather than preserving it as current. + #[tokio::test] + async fn test_direct_view_mutation_forces_a_rebuild() { + let (_conn, _, view) = refreshed_doubled(vec![1, 2]).await; + + view.table().delete("x = 1").await.unwrap(); + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Rebuild); + assert_eq!(read(view.table(), "twice").await, vec![2, 4]); + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::NoOp + ); + } + + /// A dropped and recreated source reuses version numbers but never their + /// timestamps; the watermark must not vouch for the replacement's rows. + #[tokio::test] + async fn test_source_recreation_forces_a_rebuild() { + let (conn, _, view) = refreshed_doubled(vec![1]).await; + + conn.drop_table("src", &[]).await.unwrap(); + let batch = record_batch!(("x", Int32, [7])).unwrap(); + conn.create_table("src", batch) + .write_options(crate::materialized_view::tests::stable_row_ids()) + .execute() + .await + .unwrap(); + + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Rebuild); + assert_eq!(read(view.table(), "twice").await, vec![14]); + } + + /// In-process refreshes of one view serialize: the loser of the race + /// observes the winner's watermark instead of appending the same rows. + #[tokio::test(flavor = "multi_thread")] + async fn test_concurrent_refreshes_do_not_duplicate() { + let (_conn, source, view) = refreshed_doubled(vec![1]).await; + + append(&source, vec![2, 3]).await; + let (a, b) = tokio::join!(view.refresh().execute(), view.refresh().execute()); + let (a, b) = (a.unwrap(), b.unwrap()); + assert_eq!(read(view.table(), "twice").await, vec![2, 4, 6]); + let modes = [a.mode, b.mode]; + assert!(modes.contains(&RefreshMode::Incremental)); + assert!(modes.contains(&RefreshMode::NoOp)); + } + + /// A second handle's lazy cache must not defeat the lock: after another + /// handle's refresh commits, the stale handle plans from the reloaded + /// state and no-ops instead of appending the same fragments again. + #[tokio::test] + async fn test_a_second_handle_does_not_double_append() { + let (conn, source, view) = refreshed_doubled(vec![1, 2, 3]).await; + let stale = conn.open_materialized_view("doubled").await.unwrap(); + + append(&source, vec![4]).await; + view.refresh().execute().await.unwrap(); + + let result = stale.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::NoOp); + assert_eq!(read(view.table(), "twice").await, vec![2, 4, 6, 8]); + } + + /// A commit racing between a refresh's data commit and its stamp must + /// not be certified as the refresh's generation: the stamp aborts, and + /// the next refresh rebuilds from the drifted state. + #[tokio::test] + async fn test_stamp_aborts_on_a_racing_commit() { + let (_conn, _, view) = refreshed_doubled(vec![1, 2]).await; + + let view_native = view.table().as_native().unwrap(); + let stale = view_native.dataset.get().await.unwrap().as_ref().clone(); + view.table().delete("x = 1").await.unwrap(); + + let err = stamp_watermark(view_native, stale, 99, 99).await; + assert!(err.is_err()); + + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Rebuild); + assert_eq!(read(view.table(), "twice").await, vec![2, 4]); + } + + /// What refresh executes and what it stamps must be one generation: a + /// replaced definition wins over whatever a stale handle cached. + #[tokio::test] + async fn test_refresh_uses_the_latest_persisted_definition() { + let (_conn, _, view) = refreshed_doubled(vec![1, 2]).await; + + let replacement = crate::materialized_view::MaterializedViewDefinition { + source_table: "src".into(), + projections: vec![ + crate::materialized_view::ViewProjection { + output: "x".into(), + expression: "x".into(), + }, + crate::materialized_view::ViewProjection { + output: "twice".into(), + expression: "x * 3".into(), + }, + ], + filter: None, + limit: None, + inputs: vec!["x".into()], + }; + let mut metadata = HashMap::new(); + metadata.insert( + crate::materialized_view::DEFINITION_META_KEY.to_string(), + crate::materialized_view::definition_to_metadata(&replacement).unwrap(), + ); + view.table() + .as_native() + .unwrap() + .replace_schema_metadata(metadata) + .await + .unwrap(); + + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Rebuild); + assert_eq!(read(view.table(), "twice").await, vec![3, 6]); + } + + /// A persisted definition that does not produce this view's schema must + /// not refresh at all, let alone be certified. + #[tokio::test] + async fn test_definition_view_schema_mismatch_is_refused() { + let (_conn, _, view) = refreshed_doubled(vec![1, 2]).await; + + let narrower = crate::materialized_view::MaterializedViewDefinition { + source_table: "src".into(), + projections: vec![crate::materialized_view::ViewProjection { + output: "x".into(), + expression: "x".into(), + }], + filter: None, + limit: None, + inputs: vec!["x".into()], + }; + let mut metadata = HashMap::new(); + metadata.insert( + crate::materialized_view::DEFINITION_META_KEY.to_string(), + crate::materialized_view::definition_to_metadata(&narrower).unwrap(), + ); + view.table() + .as_native() + .unwrap() + .replace_schema_metadata(metadata) + .await + .unwrap(); + + let err = view.refresh().execute().await.unwrap_err(); + assert!(matches!(err, Error::Schema { message } if message.contains("does not produce")),); + } + + /// An overlay replaces cell values without changing any file path; the + /// signature must see it, scoped to the columns the view reads like + /// data files are. + #[test] + fn test_fragment_signature_sees_overlays() { + use lance_file::version::ConcreteFileVersion; + use lance_table::format::DataFile; + use lance_table::format::overlay::{DataOverlayFile, OverlayCoverage}; + + let base = Fragment::new(7); + let mut file = DataFile::new_unstarted("f0.lance", ConcreteFileVersion::V2_1); + file.fields = vec![0, 1].into(); + let mut with_file = base.clone(); + with_file.files.push(file.clone()); + + let overlay = |field: i32| { + let mut data_file = DataFile::new_unstarted("o0.lance", ConcreteFileVersion::V2_1); + data_file.fields = vec![field].into(); + DataOverlayFile { + data_file, + coverage: OverlayCoverage::PerField(Vec::new()), + committed_version: 9, + } + }; + let relevant: HashSet = [0].into_iter().collect(); + + let mut overlaid_relevant = with_file.clone(); + overlaid_relevant.overlays.push(overlay(0)); + assert_ne!( + fragment_signature(&with_file, &relevant), + fragment_signature(&overlaid_relevant, &relevant), + ); + + let mut overlaid_unrelated = with_file.clone(); + overlaid_unrelated.overlays.push(overlay(5)); + assert_eq!( + fragment_signature(&with_file, &relevant), + fragment_signature(&overlaid_unrelated, &relevant), + ); + } + + /// An output whose name needs quoting flows through as a projection + /// alias, never spliced into SQL text. + #[tokio::test] + async fn test_output_names_needing_quotes() { + let (conn, _) = db_with_source(vec![1, 2]).await; + let view = conn + .create_materialized_view("v", "src") + .select([("double value", "x * 2")]) + .execute() + .await + .unwrap(); + + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.rows_written, 2); + assert_eq!(read(view.table(), "double value").await, vec![2, 4]); + } + + /// MemWAL tiers are visible to reads but not to the refresh scan, so LSM + /// state disqualifies every participant: the source at create, either + /// side at refresh, and the view can never accept a spec. Retained + /// un-compacted rows (the catch-up flag outlives unset) count as state. + #[tokio::test] + async fn lsm_state_disqualifies_source_and_view() { + use crate::table::LsmWriteSpec; + use arrow_array::RecordBatchIterator; + + let tmp_dir = tempfile::tempdir().unwrap(); + let conn = connect(tmp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + // Hand-rolled: the LSM primary key must be non-nullable, which + // record_batch! cannot express. + let schema = Arc::new(ArrowSchema::new(vec![ + arrow_schema::Field::new("id", arrow_schema::DataType::Int64, false), + arrow_schema::Field::new("x", arrow_schema::DataType::Int32, false), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(arrow_array::Int64Array::from(vec![1, 2])) as _, + Arc::new(Int32Array::from(vec![1, 2])) as _, + ], + ) + .unwrap(); + let table = conn + .create_table("src", batch.clone()) + .write_options(crate::materialized_view::tests::stable_row_ids()) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["id"]).await.unwrap(); + table + .set_lsm_write_spec(LsmWriteSpec::unsharded()) + .await + .unwrap(); + + // An active-LSM source is refused at create. + let err = conn + .create_materialized_view("v", "src") + .execute() + .await + .unwrap_err(); + assert!(err.to_string().contains("un-compacted"), "{err}"); + + // Unset with nothing written clears the state: the view creates, + // and a spec can never be installed over it. + table.unset_lsm_write_spec().await.unwrap(); + let view = conn + .create_materialized_view("v", "src") + .execute() + .await + .unwrap(); + let err = view + .table() + .set_lsm_write_spec(LsmWriteSpec::unsharded()) + .await + .unwrap_err(); + assert!(err.to_string().contains("materialized view"), "{err}"); + + // A source that acquires a spec after create fails refresh. + table + .set_lsm_write_spec(LsmWriteSpec::unsharded()) + .await + .unwrap(); + let err = view.refresh().execute().await.unwrap_err(); + assert!(err.to_string().contains("source table 'src'"), "{err}"); + + // Retained rows outlive unset: write through the WAL, unset, and + // refresh still refuses. + let mut merge = table.merge_insert(&["id"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all() + .use_lsm(true); + merge + .execute(Box::new(RecordBatchIterator::new( + vec![Ok(batch.clone())], + batch.schema(), + ))) + .await + .unwrap(); + table.unset_lsm_write_spec().await.unwrap(); + let err = view.refresh().execute().await.unwrap_err(); + assert!(err.to_string().contains("source table 'src'"), "{err}"); + } +} diff --git a/rust/lancedb/src/table/merge/lsm.rs b/rust/lancedb/src/table/merge/lsm.rs index 44a2874de..a06507ba0 100644 --- a/rust/lancedb/src/table/merge/lsm.rs +++ b/rust/lancedb/src/table/merge/lsm.rs @@ -104,6 +104,13 @@ pub(crate) async fn set_lsm_write_spec(table: &NativeTable, spec: LsmWriteSpec) .into(), }); } + if crate::materialized_view::materialized_view_kind(&dataset.schema().metadata)?.is_some() { + return Err(Error::NotSupported { + message: "an LSM write spec cannot be installed on a materialized view: \ + rows in un-compacted tiers are invisible to refresh" + .into(), + }); + } let mut builder = dataset.initialize_mem_wal(); let writer_config_defaults = match spec { LsmWriteSpec::Bucket { diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 2715a163c..7d74bbae7 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -597,7 +597,7 @@ mod tests { /// A fragment spanning several scan batches exercises the streamed fill: /// the probe buffers only until the first gained value and the rest flows - /// through write_column a batch at a time. + /// through write_columns a batch at a time. #[tokio::test] async fn test_refresh_streams_a_multi_batch_fragment() { let values: Vec = (0..20_000).collect(); From d04ac7ed202181049cb871c2d6b97e5e5d9d54f0 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Fri, 21 Aug 2026 23:04:04 -0700 Subject: [PATCH 089/206] test: differential refresh harness for materialized views (#3932) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Example tests pin behaviors; the refresh contract is a property: after any sequence of source mutations, a view maintained by default refreshes equals the definition evaluated against the source directly, and so does a forced rebuild. This drives every mutation sequence up to length three -- appends, deletes, updates crossing the filter, compactions, unrelated column adds -- over an identity and a filtered view shape, checking against an oracle that shares nothing with the refresh path: a plain column scan with the filter applied in Rust. The oracle runs after every step because a later rebuild-forcing mutation silently heals an incremental error; end-state checks miss exactly the transient bugs that matter. A length-four sweep runs behind ignore. Named regressions additionally assert the refresh mode, which value comparison cannot: a wrongly rebuilding classifier still matches the oracle, so the append, unrelated-column and compaction cases pin that the incremental path actually ran. Stack created with GitHub Stacks CLIGive Feedback 💬 --- rust/lancedb/src/materialized_view.rs | 4 + .../src/materialized_view/differential.rs | 730 ++++++++++++++++++ rust/lancedb/src/materialized_view/refresh.rs | 38 + 3 files changed, 772 insertions(+) create mode 100644 rust/lancedb/src/materialized_view/differential.rs diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 8b553165b..1d7cbb5e7 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -10,6 +10,10 @@ //! table. Queries, indexes and search work on the view unchanged. pub mod refresh; + +#[cfg(test)] +mod differential; + use std::collections::HashMap; use std::sync::Arc; diff --git a/rust/lancedb/src/materialized_view/differential.rs b/rust/lancedb/src/materialized_view/differential.rs new file mode 100644 index 000000000..396b4e65b --- /dev/null +++ b/rust/lancedb/src/materialized_view/differential.rs @@ -0,0 +1,730 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Differential refresh testing. +//! +//! The refresh contract is a property: after any sequence of source +//! mutations, a view maintained by default (incremental-where-possible) +//! refreshes equals the definition evaluated against the source directly, +//! and so does a forced rebuild. The oracle is an independent read of the +//! source -- plain column scan, filter applied in Rust -- so it shares +//! nothing with the refresh path it checks. +//! +//! The oracle runs after every step, not just at the end: a later mutation +//! that forces a rebuild would silently heal an incremental error, and those +//! transient errors are exactly the bugs this exists to catch. + +use arrow_array::{Float32Array, Int32Array, RecordBatch}; +use arrow_schema::{DataType, Field as ArrowField, Schema as ArrowSchema}; +use futures::{StreamExt, TryStreamExt}; +use lance::dataset::NewColumnTransform; +use std::sync::Arc; + +use super::MaterializedView; +use super::refresh::RefreshMode; +use crate::connect; +use crate::connection::Connection; +use crate::query::{ExecutableQuery, QueryBase, Select}; +use crate::table::{CompactionOptions, OptimizeAction, Table}; + +/// One source mutation, one per correctness-relevant class. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum SrcOp { + /// Fresh non-colliding ids of both parities, so every other op has + /// view-resident rows to act on: the only op that should refresh + /// incrementally. + AppendNew, + /// Deletion in surviving fragments must break the pure-append check. + DeleteEven, + /// An in-place update; on the filtered shape it crosses the predicate, + /// so rows must leave the view. + UpdateOddScore, + /// Fragment rewrite/renumber must break the pure-append check. + Compact, + /// A column the view does not read must NOT force a rebuild. + AddColumn, + /// merge_insert commits an Update whose by-source arm deletes rows, so a + /// classifier that reads Update as "changed only" loses those deletions. + MergeDropLargest, + /// merge_insert that both changes existing rows and inserts new ones in + /// one transaction. + MergeUpsert, +} + +const ALL_OPS: [SrcOp; 7] = [ + SrcOp::AppendNew, + SrcOp::DeleteEven, + SrcOp::UpdateOddScore, + SrcOp::Compact, + SrcOp::AddColumn, + SrcOp::MergeDropLargest, + SrcOp::MergeUpsert, +]; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Shape { + /// SELECT id, score. + Identity, + /// SELECT id, score WHERE score > 50: additionally sensitive to rows + /// crossing the predicate. + Filtered, + /// SELECT id, score LIMIT 4. Which rows are held depends on the order + /// they were first materialized, so the oracle checks containment and + /// the cap rather than equality. + Limited, +} + +impl Shape { + fn filter(&self) -> Option<&'static str> { + match self { + Self::Identity | Self::Limited => None, + Self::Filtered => Some("score > 50"), + } + } + + fn matches(&self, score: f32) -> bool { + match self { + Self::Identity | Self::Limited => true, + Self::Filtered => score > 50.0, + } + } + + fn limit(&self) -> Option { + match self { + Self::Limited => Some(4), + _ => None, + } + } +} + +struct Case { + conn: Connection, + source: Table, + view: MaterializedView, + shape: Shape, + next_id: i32, + added_columns: u32, +} + +fn rows_batch(ids: &[i32]) -> RecordBatch { + let scores: Vec = ids.iter().map(|id| (*id * 10) as f32).collect(); + RecordBatch::try_new( + Arc::new(ArrowSchema::new(vec![ + ArrowField::new("id", DataType::Int32, true), + ArrowField::new("score", DataType::Float32, true), + ])), + vec![ + Arc::new(Int32Array::from(ids.to_vec())), + Arc::new(Float32Array::from(scores)), + ], + ) + .unwrap() +} + +fn merge_batch(ids: &[i32]) -> RecordBatch { + let scores: Vec = ids.iter().map(|id| (*id * 10 + 5) as f32).collect(); + RecordBatch::try_new( + Arc::new(ArrowSchema::new(vec![ + ArrowField::new("id", DataType::Int32, true), + ArrowField::new("score", DataType::Float32, true), + ])), + vec![ + Arc::new(Int32Array::from(ids.to_vec())), + Arc::new(Float32Array::from(scores)), + ], + ) + .unwrap() +} + +impl Case { + async fn new(shape: Shape) -> Self { + let conn = connect("memory://").execute().await.unwrap(); + let source = conn + .create_table("src", rows_batch(&[1, 2, 3, 4])) + .write_options(crate::materialized_view::tests::stable_row_ids()) + .execute() + .await + .unwrap(); + let mut builder = conn + .create_materialized_view("view", "src") + .select([("id", "id"), ("score", "score")]); + if let Some(filter) = shape.filter() { + builder = builder.only_if(filter); + } + if let Some(limit) = shape.limit() { + builder = builder.limit(limit as u64); + } + let view = builder.execute().await.unwrap(); + Self { + conn, + source, + view, + shape, + next_id: 100, + added_columns: 0, + } + } + + async fn apply(&mut self, op: SrcOp) { + match op { + SrcOp::AppendNew => { + // Mixed parity: the middle id is odd, so UpdateOddScore always + // has a filter-matching appended row to evict. + let ids = vec![self.next_id, self.next_id + 101, self.next_id + 202]; + self.next_id += 303; + self.source.add(rows_batch(&ids)).execute().await.unwrap(); + } + SrcOp::DeleteEven => { + self.source.delete("id % 2 = 0").await.unwrap(); + } + SrcOp::UpdateOddScore => { + self.source + .update() + .column("score", "-1.0") + .only_if("id % 2 = 1") + .execute() + .await + .unwrap(); + } + SrcOp::Compact => { + self.source + .optimize(OptimizeAction::Compact { + options: CompactionOptions::default(), + remap_options: None, + }) + .await + .unwrap(); + } + SrcOp::MergeDropLargest => { + let mut ids = self.source_ids().await; + ids.sort_unstable(); + ids.pop(); + if ids.is_empty() { + return; + } + let batch = rows_batch(&ids); + let reader = + arrow_array::RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema()); + let mut merge = self.source.merge_insert(&["id"]); + merge.when_not_matched_by_source_delete(None); + merge.execute(Box::new(reader)).await.unwrap(); + } + SrcOp::MergeUpsert => { + let mut ids = self.source_ids().await; + ids.sort_unstable(); + // One row that exists (updated in place) and one that does not. + let existing = ids.first().copied().unwrap_or(self.next_id); + let fresh = self.next_id; + self.next_id += 1; + let batch = merge_batch(&[existing, fresh]); + let reader = + arrow_array::RecordBatchIterator::new(vec![Ok(batch.clone())], batch.schema()); + let mut merge = self.source.merge_insert(&["id"]); + merge + .when_matched_update_all(None) + .when_not_matched_insert_all(); + merge.execute(Box::new(reader)).await.unwrap(); + } + SrcOp::AddColumn => { + self.added_columns += 1; + let field = ArrowField::new( + format!("extra_{}", self.added_columns), + DataType::Int32, + true, + ); + self.source + .add_columns() + .transform(NewColumnTransform::AllNulls(Arc::new(ArrowSchema::new( + vec![field], + )))) + .execute() + .await + .unwrap(); + } + } + } + + async fn source_ids(&self) -> Vec { + read_rows( + self.source + .query() + .select(Select::columns(&["id", "score"])), + ) + .await + .into_iter() + .map(|(id, _)| id) + .collect() + } + + /// The definition's result, read independently of the refresh path: + /// plain column scan, filter applied here, sorted. + async fn oracle(&self) -> Vec<(i32, i32)> { + let mut rows = read_rows( + self.source + .query() + .select(Select::columns(&["id", "score"])), + ) + .await + .into_iter() + .filter(|(_, score)| self.shape.matches(*score as f32)) + .collect::>(); + rows.sort_unstable(); + rows + } + + async fn view_rows(&self) -> Vec<(i32, i32)> { + let mut rows = read_rows( + self.view + .table() + .query() + .select(Select::columns(&["id", "score"])), + ) + .await; + rows.sort_unstable(); + rows + } + + async fn check(&self, label: &str) -> Result<(), String> { + let expected = self.oracle().await; + let actual = self.view_rows().await; + let Some(cap) = self.shape.limit() else { + if expected != actual { + return Err(format!( + "{label}: view diverged from oracle\n expected: {expected:?}\n actual: {actual:?}" + )); + } + return Ok(()); + }; + // A capped view holds some subset of the definition's result, never + // more than the cap, and never the same row twice. + if actual.len() > cap { + return Err(format!( + "{label}: view holds {} rows, over its cap of {cap}: {actual:?}", + actual.len() + )); + } + let mut unique = actual.clone(); + unique.dedup(); + if unique.len() != actual.len() { + return Err(format!("{label}: view holds a row twice: {actual:?}")); + } + if let Some(stray) = actual.iter().find(|row| !expected.contains(row)) { + return Err(format!( + "{label}: view holds {stray:?}, which the definition does not select: {expected:?}" + )); + } + // Below the cap the view must be complete, or a row was lost. + if actual.len() < cap.min(expected.len()) { + return Err(format!( + "{label}: view holds {} of {} selectable rows under a cap of {cap}: {actual:?}", + actual.len(), + expected.len() + )); + } + Ok(()) + } +} + +async fn read_rows(query: impl ExecutableQuery) -> Vec<(i32, i32)> { + let batches = query + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + batches + .iter() + .flat_map(|batch| { + let ids = batch["id"].as_any().downcast_ref::().unwrap(); + let scores = batch["score"] + .as_any() + .downcast_ref::() + .unwrap(); + // Scores are integer-valued by construction; compare exactly. + (0..batch.num_rows()) + .map(|i| (ids.value(i), scores.value(i) as i32)) + .collect::>() + }) + .collect() +} + +/// Drive one mutation sequence: refresh + oracle-check after every step, +/// then a forced rebuild checked against the same oracle. +async fn run_sequence(ops: &[SrcOp], shape: Shape) -> Result<(), String> { + let label = format!("{shape:?} {ops:?}"); + let mut case = Case::new(shape).await; + case.view + .refresh() + .execute() + .await + .map_err(|e| format!("{label}: initial refresh failed: {e}"))?; + case.check(&format!("{label} (initial)")).await?; + + for (step, op) in ops.iter().enumerate() { + case.apply(*op).await; + case.view + .refresh() + .execute() + .await + .map_err(|e| format!("{label}: refresh at step {step} failed: {e}"))?; + case.check(&format!("{label} (step {step}, {op:?})")) + .await?; + } + + case.view + .refresh() + .full(true) + .execute() + .await + .map_err(|e| format!("{label}: final full refresh failed: {e}"))?; + case.check(&format!("{label} (final rebuild)")).await?; + // Silence the unused-connection lint without dropping it mid-case. + let _ = &case.conn; + Ok(()) +} + +/// Every op sequence up to `max_len`. +fn all_sequences(max_len: u32) -> Vec> { + let mut sequences = Vec::new(); + for len in 1..=max_len { + for mut index in 0..ALL_OPS.len().pow(len) { + let mut ops = Vec::with_capacity(len as usize); + for _ in 0..len { + ops.push(ALL_OPS[index % ALL_OPS.len()]); + index /= ALL_OPS.len(); + } + sequences.push(ops); + } + } + sequences +} + +async fn run_exhaustive(max_len: u32) { + let mut cases = Vec::new(); + for shape in [Shape::Identity, Shape::Filtered, Shape::Limited] { + for ops in all_sequences(max_len) { + cases.push((ops, shape)); + } + } + let failures: Vec = futures::stream::iter(cases) + .map(|(ops, shape)| async move { run_sequence(&ops, shape).await.err() }) + .buffer_unordered(8) + .filter_map(|failure| async move { failure }) + .collect() + .await; + assert!( + failures.is_empty(), + "{} sequences diverged; first: {}", + failures.len(), + failures[0] + ); +} + +#[tokio::test(flavor = "multi_thread")] +async fn differential_exhaustive() { + run_exhaustive(3).await; +} + +#[tokio::test(flavor = "multi_thread")] +#[ignore = "longer sweep; run manually"] +async fn differential_exhaustive_deep() { + run_exhaustive(4).await; +} + +/// Named interleavings that double as repro handles. The mode assertions pin +/// the classifier, which value comparison alone cannot: a wrongly rebuilt +/// view still matches the oracle. +#[tokio::test(flavor = "multi_thread")] +async fn differential_named_regressions() { + // An append is the one op that must stay incremental. + let mut case = Case::new(Shape::Identity).await; + case.view.refresh().execute().await.unwrap(); + case.apply(SrcOp::AppendNew).await; + let result = case.view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + case.check("append stays incremental").await.unwrap(); + + // A column the view does not read must not force a rebuild. + let mut case = Case::new(Shape::Identity).await; + case.view.refresh().execute().await.unwrap(); + case.apply(SrcOp::AddColumn).await; + let result = case.view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(result.rows_written, 0); + + // Compaction rearranges rows without changing them: the watermark + // advances and nothing rebuilds. + let mut case = Case::new(Shape::Identity).await; + case.view.refresh().execute().await.unwrap(); + case.apply(SrcOp::AppendNew).await; + case.view.refresh().execute().await.unwrap(); + case.apply(SrcOp::Compact).await; + let result = case.view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(result.rows_written, 0); + case.check("compaction alone").await.unwrap(); + + // Fragment bookkeeping stays coherent across the compaction: the next + // append is separable and computed alone. + case.apply(SrcOp::AppendNew).await; + let result = case.view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(result.rows_written, 3); + case.check("compact then append").await.unwrap(); + + // A row updated to no longer match the filter must leave the view -- + // and the fixture must prove the eviction happened, not merely that the + // end state matches: an update that never touched a view-resident row + // would also "match". + let mut case = Case::new(Shape::Filtered).await; + case.apply(SrcOp::AppendNew).await; + case.view.refresh().execute().await.unwrap(); + let before = case.view_rows().await.len(); + case.apply(SrcOp::UpdateOddScore).await; + case.view.refresh().execute().await.unwrap(); + let after = case.view_rows().await.len(); + assert!( + after < before, + "no view-resident row was evicted ({before} -> {after}); the fixture \ + no longer exercises the filtered-update transition" + ); + case.check("update crosses the filter").await.unwrap(); +} + +// --------------------------------------------------------------------------- +// Concurrency +// --------------------------------------------------------------------------- +// +// The sequential cases above cannot observe a cross-process race: the +// per-view refresh lock is process-local, so a second refresh in this +// process queues behind the first. What is missing is not more op +// sequences but a second process. These cases add one, and assert the same +// property the harness always asserts -- the view holds each row once. + +/// Rows the definition selects from the source: every id but the first, +/// read straight from the source, sharing nothing with the refresh path. +async fn concurrency_oracle(conn: &Connection) -> Vec { + let batches: Vec = conn + .open_table("src") + .execute() + .await + .unwrap() + .query() + .select(Select::columns(&["id"])) + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + let mut ids = Vec::new(); + for batch in &batches { + let column = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + for i in 0..batch.num_rows() { + if column.value(i) > 1 { + ids.push(column.value(i)); + } + } + } + ids.sort_unstable(); + ids +} + +/// The view's ids, sorted. +async fn concurrency_view_ids(conn: &Connection) -> Vec { + let batches: Vec = conn + .open_table("mv") + .execute() + .await + .unwrap() + .query() + .select(Select::columns(&["id"])) + .execute() + .await + .unwrap() + .try_collect() + .await + .unwrap(); + let mut ids = Vec::new(); + for batch in &batches { + let column = batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + for i in 0..batch.num_rows() { + ids.push(column.value(i)); + } + } + ids.sort_unstable(); + ids +} + +/// One refresh of the view at `MV_RACE_DIR`, in its own process. +/// +/// Setup happens before the start barrier so warm-up does not stagger the +/// two processes. What makes the race certain rather than likely is the +/// second barrier inside `refresh()` itself, which holds every participant +/// between staging and commit. +#[tokio::test] +#[ignore = "spawned as a child process by the concurrency cases"] +async fn cross_process_refresh_child() { + let Ok(dir) = std::env::var("MV_RACE_DIR") else { + return; + }; + let dir = std::path::PathBuf::from(dir); + let tag = std::env::var("MV_RACE_TAG").unwrap(); + + let conn = connect(dir.to_str().unwrap()).execute().await.unwrap(); + let table = conn.open_table("mv").execute().await.unwrap(); + let _ = table.schema().await.unwrap(); + let _ = table.count_rows(None).await.unwrap(); + let source = conn.open_table("src").execute().await.unwrap(); + let _ = source.count_rows(None).await.unwrap(); + let view = MaterializedView::from_table(table).await.unwrap(); + + std::fs::write(dir.join(format!("ready-{tag}")), b"1").unwrap(); + while !dir.join("START").exists() { + std::thread::sleep(std::time::Duration::from_millis(2)); + } + + let outcome = match view.refresh().execute().await { + Ok(result) => format!("committed rows={}", result.rows_written), + Err(err) if is_commit_conflict(&err) => "conflicted".to_string(), + Err(err) => format!("failed {err}"), + }; + std::fs::write(dir.join(format!("outcome-{tag}")), outcome).unwrap(); +} + +/// Whether a refresh lost its commit to a concurrent one, as opposed to +/// failing for any other reason. +fn is_commit_conflict(err: &crate::Error) -> bool { + let text = err.to_string(); + text.contains("Retryable commit conflict") || text.contains("preempted by concurrent") +} + +/// Two processes refreshing one view concurrently must leave the view +/// equal to the oracle: each selected row present exactly once. +/// +/// Both plan the same incremental delta from one watermark. A refresh is +/// meant to land on the generation it planned or leave nothing behind, so +/// at most one of them may write. +#[tokio::test] +async fn concurrent_refreshes_hold_each_row_once() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().to_str().unwrap().to_string(); + let conn = connect(&path).execute().await.unwrap(); + conn.create_table("src", rows_batch(&[1, 2, 3, 4])) + .write_options(crate::materialized_view::tests::stable_row_ids()) + .execute() + .await + .unwrap(); + let view = conn + .create_materialized_view("mv", "src") + .select([("id", "id"), ("score", "score")]) + .only_if("id > 1") + .execute() + .await + .unwrap(); + // Seed the watermark so the racing refreshes are both incremental. + view.refresh().execute().await.unwrap(); + + // Large enough that a refresh is real work rather than a formality. + let ids: Vec = (100..200_100).collect(); + conn.open_table("src") + .execute() + .await + .unwrap() + .add(rows_batch(&ids)) + .execute() + .await + .unwrap(); + + let tags = ["a", "b"]; + let exe = std::env::current_exe().unwrap(); + let children: Vec = tags + .iter() + .map(|tag| { + std::process::Command::new(&exe) + .args([ + "--exact", + "materialized_view::differential::cross_process_refresh_child", + "--ignored", + "--nocapture", + ]) + .env("MV_RACE_DIR", dir.path()) + .env("MV_RACE_SYNC", dir.path()) + .env("MV_RACE_PEERS", "2") + .env("MV_RACE_TAG", tag) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .unwrap() + }) + .collect(); + + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(180); + while tags + .iter() + .any(|tag| !dir.path().join(format!("ready-{tag}")).exists()) + { + assert!( + std::time::Instant::now() < deadline, + "children never became ready" + ); + std::thread::sleep(std::time::Duration::from_millis(10)); + } + std::fs::write(dir.path().join("START"), b"1").unwrap(); + for (tag, mut child) in tags.iter().zip(children) { + let status = loop { + match child.try_wait().unwrap() { + Some(status) => break status, + None if std::time::Instant::now() >= deadline => { + child.kill().unwrap(); + panic!("child {tag} never finished"); + } + None => std::thread::sleep(std::time::Duration::from_millis(10)), + } + }; + assert!(status.success(), "child {tag} exited {status}"); + } + + // Both refreshes reached the commit boundary before either committed -- + // the in-refresh barrier guarantees it -- so exactly one may win. + let outcomes: Vec = tags + .iter() + .map(|tag| { + std::fs::read_to_string(dir.path().join(format!("outcome-{tag}"))) + .unwrap_or_else(|_| panic!("child {tag} recorded no outcome")) + }) + .collect(); + for tag in tags { + assert!( + dir.path().join(format!("planned-{tag}")).exists(), + "child {tag} never reached the commit boundary, so nothing was synchronized" + ); + } + let committed = outcomes.iter().filter(|o| o.contains("committed")).count(); + let conflicted = outcomes.iter().filter(|o| o.contains("conflicted")).count(); + assert_eq!( + (committed, conflicted), + (1, 1), + "exactly one refresh may win the generation both planned: {outcomes:?}" + ); + + let expected = concurrency_oracle(&conn).await; + let actual = concurrency_view_ids(&conn).await; + assert_eq!( + actual.len(), + expected.len(), + "the view holds {} rows, the oracle {}: a losing refresh left rows behind", + actual.len(), + expected.len() + ); + assert_eq!(actual, expected, "the view does not match the oracle"); +} diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index 7ac39a9f5..24d828e01 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -1056,6 +1056,8 @@ async fn publish( let planned = view_ds.version().version; #[cfg(test)] tests::hold_before_publish(view_ds.uri()).await; + #[cfg(test)] + tests::hold_until_peers_planned(); let (updated_fragments, removed_fragment_ids) = eviction.unwrap_or_default(); let committed = CommitBuilder::new(WriteDestination::Dataset(Arc::new(view_ds.clone()))) .execute(Transaction::new( @@ -1342,6 +1344,42 @@ mod tests { pub(super) static DRIFT_TARGET: StdMutex> = StdMutex::new(None); pub(super) static DRIFT_PLANNED: tokio::sync::Notify = tokio::sync::Notify::const_new(); pub(super) static DRIFT_RELEASED: tokio::sync::Notify = tokio::sync::Notify::const_new(); + + /// Block until every participant in a cross-process race has planned and + /// staged its write, so the commits they then attempt genuinely contend + /// rather than depending on the scheduler to overlap them. Inert unless + /// `MV_RACE_SYNC` names a directory shared by the participants. + pub(super) fn hold_until_peers_planned() { + let (Ok(dir), Ok(tag), Ok(peers)) = ( + std::env::var("MV_RACE_SYNC"), + std::env::var("MV_RACE_TAG"), + std::env::var("MV_RACE_PEERS"), + ) else { + return; + }; + let dir = std::path::PathBuf::from(dir); + let peers: usize = peers.parse().unwrap(); + std::fs::write(dir.join(format!("planned-{tag}")), b"1").unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); + while planned_count(&dir) < peers { + assert!( + std::time::Instant::now() < deadline, + "peers never reached the commit boundary" + ); + std::thread::sleep(std::time::Duration::from_millis(2)); + } + } + + fn planned_count(dir: &std::path::Path) -> usize { + std::fs::read_dir(dir) + .map(|entries| { + entries + .filter_map(|e| e.ok()) + .filter(|e| e.file_name().to_string_lossy().starts_with("planned-")) + .count() + }) + .unwrap_or(0) + } use arrow_array::{Int32Array, record_batch}; use futures::TryStreamExt; use lance::dataset::NewColumnTransform; From 851fa16b47ecdde2b9aa116ad4100adfaf68279c Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Fri, 21 Aug 2026 23:08:41 -0700 Subject: [PATCH 090/206] feat(python): materialized view bindings (#3933) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Exposes materialized views to Python in both the async and sync clients: create_materialized_view / open_materialized_view / list_materialized_views on the connections, and MaterializedView / AsyncMaterializedView handles carrying the parsed definition and refresh(full=, source_version=), which returns the typed refresh result. select accepts column names, (alias, expression) pairs, or a dict of the same; the definition reads back off the stored schema, so a reopened handle needs no side channel. Remote connections raise NotImplementedError up front rather than failing deep in a request, matching the computed-column convention. Stack created with GitHub Stacks CLIGive Feedback 💬 --- docs/src/python/python.md | 10 + python/python/lancedb/__init__.py | 8 + python/python/lancedb/_lancedb.pyi | 18 ++ python/python/lancedb/db.py | 166 +++++++++++ python/python/lancedb/materialized_view.py | 178 ++++++++++++ python/python/lancedb/namespace.py | 68 +++++ python/python/lancedb/remote/db.py | 27 ++ .../python/tests/test_materialized_views.py | 268 ++++++++++++++++++ python/src/connection.rs | 34 +++ python/src/lib.rs | 5 +- python/src/table.rs | 55 ++++ 11 files changed, 835 insertions(+), 2 deletions(-) create mode 100644 python/python/lancedb/materialized_view.py create mode 100644 python/python/tests/test_materialized_views.py diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 70b2a7207..8a24ea199 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -102,6 +102,12 @@ listing a storage directory. ::: lancedb.job.AsyncJob +## Materialized Views (Synchronous) + +::: lancedb.materialized_view.MaterializedView + +::: lancedb.materialized_view.MaterializedViewDefinition + ## Expressions Type-safe expression builder for filters and projections. Use these instead @@ -295,6 +301,10 @@ Table hold your actual data as a collection of records / rows. ::: lancedb.table.AsyncBranches +## Materialized Views (Asynchronous) + +::: lancedb.materialized_view.AsyncMaterializedView + ## Indices (Asynchronous) Indices can be created on a table to speed up queries. This section diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 0ceda4558..aa473c5f8 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -32,6 +32,11 @@ from .functions import ( UdfDefinition as UdfDefinition, udf as udf, ) +from .materialized_view import ( + AsyncMaterializedView, + MaterializedView, + MaterializedViewDefinition, +) from .table import AsyncTable, Table from .types import BaseTokenizerType from ._lancedb import Session @@ -506,6 +511,9 @@ async def connect_async( __all__ = [ + "AsyncMaterializedView", + "MaterializedView", + "MaterializedViewDefinition", "connect", "connect_async", "tokenize", diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 59537f45a..b23d79c85 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -197,6 +197,15 @@ class Connection(object): cur_namespace_path: Optional[List[str]] = None, new_namespace_path: Optional[List[str]] = None, ) -> None: ... + async def create_materialized_view( + self, + name: str, + source: str, + projections: Optional[List[Tuple[str, str]]] = None, + filter: Optional[str] = None, + limit: Optional[int] = None, + ) -> Table: ... + async def list_materialized_views(self) -> List[str]: ... async def drop_table( self, name: str, namespace_path: Optional[List[str]] = None ) -> None: ... @@ -355,6 +364,9 @@ class Table: ) -> AddColumnsResult: ... async def refresh_column(self, column: str) -> RefreshColumnResult: ... async def refresh_column_async(self, column: str) -> Job: ... + async def refresh_materialized_view( + self, full: bool = False, source_version: Optional[int] = None + ) -> RefreshMaterializedViewResult: ... async def add_columns_with_schema(self, schema: pa.Schema) -> AddColumnsResult: ... async def alter_columns( self, columns: list[dict[str, Any]] @@ -704,6 +716,12 @@ class RefreshColumnResult: rows_filled: int version: int +class RefreshMaterializedViewResult: + mode: str + rows_written: int + source_version: int + version: int + class AlterColumnsResult: version: int diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index af18b6944..7ad749920 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -47,6 +47,12 @@ from . import __version__ from ._lancedb import connect as lancedb_connect # type: ignore from .functions import FunctionVersion, UdfDefinition from .job import AsyncJob, Job, _function_job +from .materialized_view import ( + AsyncMaterializedView, + MaterializedView, + SelectArg, + normalize_select, +) from .table import ( AsyncTable, LanceTable, @@ -510,6 +516,70 @@ class DBConnection(EnforceOverrides): """ raise NotImplementedError + def create_materialized_view( + self, + name: str, + source: str, + *, + select: SelectArg = None, + where: Optional[str] = None, + limit: Optional[int] = None, + ) -> MaterializedView: + """Define a materialized view named ``name`` over the table ``source``. + + The view is created empty, with the query recorded in its schema + metadata; ``view.refresh()`` computes the rows. The view is a normal + table: it can be queried, indexed and searched, and it appears in + ``table_names``. Local databases only. + + The source table must have stable row ids (create it with the + ``new_table_enable_stable_row_ids`` storage option): they keep the + view's provenance valid across source compactions, and cannot be + enabled after a table exists. + + Parameters + ---------- + name: str + The name of the view. + source: str + The name of the source table, in this database. + 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 + column, expanded against the source schema at creation time. + where: str, optional + SQL predicate; only matching source rows appear in the view. + limit: int, optional + Cap the view at this many rows, in materialization order. + + Returns + ------- + MaterializedView + """ + raise NotImplementedError( + "materialized views are not supported on this connection type" + ) + + def open_materialized_view(self, name: str) -> MaterializedView: + """Open the materialized view named ``name``. + + Raises ``ValueError`` if the table exists but is not a materialized + view. + """ + raise NotImplementedError( + "materialized views are not supported on this connection type" + ) + + def list_materialized_views(self) -> List[str]: + """The names of the materialized views in this database. + + Found by reading every table's schema, so this costs an open per + table. + """ + raise NotImplementedError( + "materialized views are not supported on this connection type" + ) + def drop_table(self, name: str, namespace_path: Optional[List[str]] = None): """Drop a table from the database. @@ -1136,6 +1206,58 @@ class LanceDBConnection(DBConnection): tbl.checkout(version) return tbl + @override + def create_materialized_view( + self, + name: str, + source: str, + *, + select: SelectArg = None, + where: Optional[str] = None, + limit: Optional[int] = None, + ) -> MaterializedView: + """Define a materialized view named ``name`` over the table ``source``. + See + [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. + + Examples + -------- + >>> import lancedb + >>> db = lancedb.connect( + ... "./.lancedb", + ... storage_options={"new_table_enable_stable_row_ids": "true"}, + ... ) + >>> data = [{"name": "ada", "age": 36}, {"name": "kid", "age": 7}] + >>> table = db.create_table("people", data) + >>> view = db.create_materialized_view( + ... "adults", + ... "people", + ... select=["name", ("shout", "upper(name)")], + ... where="age >= 18", + ... ) + >>> result = view.refresh() + >>> result.rows_written + 1 + """ + LOOP.run( + self._conn.create_materialized_view( + name, source, select=select, where=where, limit=limit + ) + ) + return MaterializedView(self.open_table(name)) + + @override + def open_materialized_view(self, name: str) -> MaterializedView: + """Open the materialized view named ``name``.""" + view = MaterializedView(self.open_table(name)) + view.definition + return view + + @override + def list_materialized_views(self) -> List[str]: + """The names of the materialized views in this database.""" + return LOOP.run(self._conn.list_materialized_views()) + def clone_table( self, target_table_name: str, @@ -1906,6 +2028,50 @@ class AsyncConnection(object): await tbl.checkout(version) return tbl + async def create_materialized_view( + self, + name: str, + source: str, + *, + select: SelectArg = None, + where: Optional[str] = None, + limit: Optional[int] = None, + ) -> AsyncMaterializedView: + """Define a materialized view named ``name`` over the table ``source``. + See + [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. + """ + inner = await self._inner.create_materialized_view( + name, + source, + projections=normalize_select(select), + filter=where, + limit=limit, + ) + return AsyncMaterializedView(AsyncTable(inner)) + + async def open_materialized_view(self, name: str) -> AsyncMaterializedView: + """Open the materialized view named ``name``. + + Raises ``ValueError`` if the table exists but is not a materialized + view. + """ + if self.uri.startswith("db://"): + raise NotImplementedError( + "materialized views are supported only on local databases" + ) + view = AsyncMaterializedView(await self.open_table(name)) + await view.definition() + return view + + async def list_materialized_views(self) -> List[str]: + """The names of the materialized views in this database. + + Found by reading every table's schema, so this costs an open per + table. + """ + return await self._inner.list_materialized_views() + async def clone_table( self, target_table_name: str, diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py new file mode 100644 index 000000000..5abb44dc0 --- /dev/null +++ b/python/python/lancedb/materialized_view.py @@ -0,0 +1,178 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Materialized views: tables defined by a query over a source table and +maintained by refresh. See ``DBConnection.create_materialized_view``.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Dict, List, Optional, Sequence, Tuple, Union + +from .background_loop import LOOP + +if TYPE_CHECKING: + import pyarrow as pa + + from ._lancedb import RefreshMaterializedViewResult + from .table import AsyncTable, LanceTable + +DEFINITION_META_KEY = b"mv.definition" + +SelectArg = Union[ + str, + Sequence[Union[str, Tuple[str, str]]], + Dict[str, str], + None, +] + + +@dataclass +class MaterializedViewDefinition: + """The query that defines a materialized view.""" + + source_table: str + """Name of the source table, in the same database as the view.""" + projections: List[Tuple[str, str]] + """``(output column, SQL expression)`` pairs, in view schema order.""" + filter: Optional[str] = None + """SQL predicate selecting the source rows the view holds.""" + limit: Optional[int] = None + """Cap on the number of rows the view holds.""" + inputs: List[str] = field(default_factory=list) + """Source columns the projections and filter read.""" + + +def _definition_from_schema( + schema: "pa.Schema", name: str +) -> MaterializedViewDefinition: + metadata = schema.metadata or {} + raw = metadata.get(DEFINITION_META_KEY) + if raw is None: + raise ValueError(f"Table '{name}' is not a materialized view") + value = json.loads(raw) + kind = value.get("kind") + if kind != "select": + raise NotImplementedError( + f"materialized view '{name}' is defined by '{kind}', which this " + "version of lancedb cannot refresh" + ) + return MaterializedViewDefinition( + source_table=value["source_table"], + projections=[ + (p["output"], p["expression"]) for p in value.get("projections", []) + ], + filter=value.get("filter"), + limit=value.get("limit"), + inputs=value.get("inputs", []), + ) + + +def _quote_identifier(name: str) -> str: + """Quote a column name as a Lance SQL identifier (backticks).""" + escaped = name.replace("`", "``") + return f"`{escaped}`" + + +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 + valid column name works; dict and pair entries are kept verbatim because + their right side is an expression. + + A lone string is one column, not a sequence of its characters.""" + if select is None: + return None + if isinstance(select, str): + select = [select] + if isinstance(select, dict): + return list(select.items()) + normalized = [] + for item in select: + if isinstance(item, str): + normalized.append((item, _quote_identifier(item))) + else: + alias, expression = item + normalized.append((alias, expression)) + return normalized + + +class AsyncMaterializedView: + """A handle on a materialized view: its table plus its definition. + + Obtained from ``AsyncConnection.create_materialized_view`` or + ``AsyncConnection.open_materialized_view``. + """ + + def __init__(self, table: "AsyncTable"): + self._table = table + + def __repr__(self) -> str: + return f"AsyncMaterializedView(name={self.name!r})" + + @property + def name(self) -> str: + return self._table.name + + @property + def table(self) -> "AsyncTable": + """The view, as the table it is. Queries, indexes and search all + apply; writes are not blocked, but a rebuild replaces them.""" + return self._table + + async def definition(self) -> MaterializedViewDefinition: + """The query that defines the view, read from its stored schema.""" + return _definition_from_schema(await self._table.schema(), self.name) + + async def refresh( + self, *, full: bool = False, source_version: Optional[int] = None + ) -> "RefreshMaterializedViewResult": + """Recompute the view from its source. + + The refresh is incremental when the source's changes can be + reconciled into the view -- rows added, changed or removed since the + last one -- and otherwise rebuilds. ``full=True`` forces a rebuild; + ``source_version`` refreshes to that source version instead of the + latest. + + Concurrent refreshes of one view do not duplicate its rows. Two that + plan the same source rows conflict on commit, and the loser raises + rather than writing them a second time. + """ + return await self._table._inner.refresh_materialized_view( + full=full, source_version=source_version + ) + + +class MaterializedView: + """Synchronous variant of + [AsyncMaterializedView][lancedb.materialized_view.AsyncMaterializedView].""" + + def __init__(self, table: "LanceTable"): + self._table = table + self._async = AsyncMaterializedView(table._table) + + def __repr__(self) -> str: + return f"MaterializedView(name={self.name!r})" + + @property + def name(self) -> str: + return self._table.name + + @property + def table(self) -> "LanceTable": + """The view, as the table it is.""" + return self._table + + @property + def definition(self) -> MaterializedViewDefinition: + """The query that defines the view, read from its stored schema.""" + return _definition_from_schema(self._table.schema, self.name) + + def refresh( + self, *, full: bool = False, source_version: Optional[int] = None + ) -> "RefreshMaterializedViewResult": + """Recompute the view from its source. See + [AsyncMaterializedView.refresh][lancedb.materialized_view.AsyncMaterializedView.refresh].""" + return LOOP.run(self._async.refresh(full=full, source_version=source_version)) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 0e60bd218..f2e553321 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -61,6 +61,11 @@ from lance_namespace import ( NamespaceExistsRequest, TableExistsRequest, ) +from lancedb.materialized_view import ( + AsyncMaterializedView, + MaterializedView, + SelectArg, +) from lancedb.table import AsyncTable, LanceTable, Table from lancedb.util import validate_table_name from lancedb.common import DATA @@ -619,6 +624,42 @@ class LanceNamespaceDBConnection(DBConnection): tbl.checkout(version) return tbl + @override + def create_materialized_view( + self, + name: str, + source: str, + *, + select: "SelectArg" = None, + where: Optional[str] = None, + limit: Optional[int] = None, + ) -> "MaterializedView": + """Define a materialized view over a table in the root namespace. + See + [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. + """ + return MaterializedView( + self.open_table( + LOOP.run( + self._inner.create_materialized_view( + name, source, select=select, where=where, limit=limit + ) + ).name + ) + ) + + @override + def open_materialized_view(self, name: str) -> "MaterializedView": + """Open the materialized view named ``name``.""" + view = MaterializedView(self.open_table(name)) + view.definition + return view + + @override + def list_materialized_views(self) -> List[str]: + """The names of the materialized views in the root namespace.""" + return LOOP.run(self._inner.list_materialized_views()) + @override def drop_table(self, name: str, namespace_path: Optional[List[str]] = None): if namespace_path is None: @@ -1141,6 +1182,33 @@ class AsyncLanceNamespaceDBConnection: route_pushdown_to_rust=self._route_pushdown_to_rust, ) + async def create_materialized_view( + self, + name: str, + source: str, + *, + select: "SelectArg" = None, + where: Optional[str] = None, + limit: Optional[int] = None, + ) -> "AsyncMaterializedView": + """Define a materialized view over a table in the root namespace.""" + view = await self._inner.create_materialized_view( + name, source, select=select, where=where, limit=limit + ) + # Reopen through the namespace so the view's table carries the + # namespace client and pushdown configuration a bare inner table lacks. + return AsyncMaterializedView(await self.open_table(view.name)) + + async def open_materialized_view(self, name: str) -> "AsyncMaterializedView": + """Open the materialized view named ``name``.""" + view = AsyncMaterializedView(await self.open_table(name)) + await view.definition() + return view + + async def list_materialized_views(self) -> List[str]: + """The names of the materialized views in the root namespace.""" + return await self._inner.list_materialized_views() + async def drop_table(self, name: str, namespace_path: Optional[List[str]] = None): """Drop a table from the namespace.""" if namespace_path is None: diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 822756a34..b228cfb5b 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -25,6 +25,7 @@ from ..common import DATA from ..db import DBConnection, LOOP from ..functions import FunctionVersion, UdfDefinition from ..job import AsyncJob, Job +from ..materialized_view import MaterializedView, SelectArg if TYPE_CHECKING: from .._lancedb import JobDescription, JobInfo @@ -648,6 +649,32 @@ class RemoteDBConnection(DBConnection): namespace_path=namespace_path, ) + @override + def create_materialized_view( + self, + name: str, + source: str, + *, + select: SelectArg = None, + where: Optional[str] = None, + limit: Optional[int] = None, + ) -> MaterializedView: + raise NotImplementedError( + "materialized views are supported only on local databases" + ) + + @override + def open_materialized_view(self, name: str) -> MaterializedView: + raise NotImplementedError( + "materialized views are supported only on local databases" + ) + + @override + def list_materialized_views(self) -> List[str]: + raise NotImplementedError( + "materialized views are supported only on local databases" + ) + @override def drop_table(self, name: str, namespace_path: Optional[List[str]] = None): """Drop a table from the database. diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py new file mode 100644 index 000000000..5fa3aa4fb --- /dev/null +++ b/python/python/tests/test_materialized_views.py @@ -0,0 +1,268 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import lancedb +import pytest +from lancedb.materialized_view import MaterializedViewDefinition + + +STABLE_ROW_IDS = {"new_table_enable_stable_row_ids": "true"} + + +def make_db(tmp_path): + db = lancedb.connect(tmp_path, storage_options=STABLE_ROW_IDS) + db.create_table( + "people", + [ + {"name": "ada", "age": 36}, + {"name": "kid", "age": 7}, + {"name": "grace", "age": 85}, + ], + ) + return db + + +def test_create_refresh_and_query(tmp_path): + db = make_db(tmp_path) + view = db.create_materialized_view( + "adults", + "people", + select=["name", ("shout", "upper(name)")], + where="age >= 18", + ) + assert view.name == "adults" + assert view.table.count_rows() == 0 + + result = view.refresh() + assert result.mode == "rebuild" + assert result.rows_written == 2 + + rows = view.table.search().to_list() + assert sorted(row["shout"] for row in rows) == ["ADA", "GRACE"] + + +def test_definition_round_trips(tmp_path): + db = make_db(tmp_path) + db.create_materialized_view("adults", "people", where="age >= 18") + + view = db.open_materialized_view("adults") + assert view.definition == MaterializedViewDefinition( + source_table="people", + projections=[("name", "`name`"), ("age", "`age`")], + filter="age >= 18", + inputs=["age", "name"], + ) + + +def test_incremental_refresh_after_append(tmp_path): + db = make_db(tmp_path) + view = db.create_materialized_view("copy", "people") + view.refresh() + + db.open_table("people").add([{"name": "alan", "age": 41}]) + result = view.refresh() + assert result.mode == "incremental" + assert result.rows_written == 1 + assert view.table.count_rows() == 4 + + assert view.refresh().mode == "no_op" + + +def test_incremental_refresh_after_update(tmp_path): + db = make_db(tmp_path) + view = db.create_materialized_view("copy", "people") + view.refresh() + + db.open_table("people").update(where="name = 'kid'", values={"age": 8}) + result = view.refresh() + assert result.mode == "incremental" + assert result.rows_written == 1 + rows = view.table.search().to_list() + assert sorted(row["age"] for row in rows) == [8, 36, 85] + + +def test_legacy_storage_source_update_rebuilds(tmp_path): + db = lancedb.connect( + tmp_path, + storage_options={**STABLE_ROW_IDS, "new_table_data_storage_version": "legacy"}, + ) + db.create_table("people", [{"name": "ada", "age": 36}, {"name": "kid", "age": 7}]) + view = db.create_materialized_view("copy", "people") + view.refresh() + + db.open_table("people").update(where="name = 'kid'", values={"age": 8}) + result = view.refresh() + assert result.mode == "rebuild" + rows = view.table.search().to_list() + assert sorted(row["age"] for row in rows) == [8, 36] + + +def test_list_and_not_a_view(tmp_path): + db = make_db(tmp_path) + db.create_materialized_view("adults", "people", where="age >= 18") + + assert db.list_materialized_views() == ["adults"] + with pytest.raises(ValueError, match="not a materialized view"): + db.open_materialized_view("people") + + +def test_invalid_expression_fails_at_create(tmp_path): + db = make_db(tmp_path) + with pytest.raises(Exception, match="missing"): + db.create_materialized_view("bad", "people", select=[("x", "missing + 1")]) + assert "bad" not in db.list_tables().tables + + +@pytest.mark.asyncio +async def test_async_create_refresh_and_open(tmp_path): + db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) + await db.create_table("people", [{"name": "ada", "age": 36}]) + + view = await db.create_materialized_view( + "shouts", "people", select=[("shout", "upper(name)")] + ) + result = await view.refresh() + assert result.mode == "rebuild" + assert result.rows_written == 1 + + reopened = await db.open_materialized_view("shouts") + definition = await reopened.definition() + assert definition.projections == [("shout", "upper(name)")] + assert await db.list_materialized_views() == ["shouts"] + + +@pytest.mark.asyncio +async def test_async_incremental(tmp_path): + db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) + await db.create_table("people", [{"name": "ada", "age": 36}]) + view = await db.create_materialized_view("copy", "people") + await view.refresh() + + table = await db.open_table("people") + await table.add([{"name": "alan", "age": 41}]) + result = await view.refresh() + assert result.mode == "incremental" + assert result.rows_written == 1 + + +def test_source_requires_stable_row_ids(tmp_path): + db = lancedb.connect(tmp_path) + db.create_table("plain", [{"x": 1}]) + with pytest.raises(Exception, match="stable row ids"): + db.create_materialized_view("v", "plain") + + +def test_bare_select_names_are_quoted(tmp_path): + db = lancedb.connect(tmp_path, storage_options=STABLE_ROW_IDS) + db.create_table("odd_names", [{"order item": "widget", "select": 2}]) + + view = db.create_materialized_view( + "quoted", "odd_names", select=["order item", "select"] + ) + result = view.refresh() + assert result.rows_written == 1 + rows = view.table.search().to_list() + assert rows[0]["order item"] == "widget" + assert rows[0]["select"] == 2 + + +@pytest.mark.asyncio +async def test_async_remote_is_refused_without_network(): + db = await lancedb.connect_async( + "db://nowhere", api_key="sk_test", region="us-east-1" + ) + with pytest.raises(NotImplementedError, match="local"): + await db.create_materialized_view("v", "src") + with pytest.raises(NotImplementedError, match="local"): + await db.open_materialized_view("v") + with pytest.raises(NotImplementedError, match="local"): + await db.list_materialized_views() + + +def test_scalar_select_is_one_column(tmp_path): + db = make_db(tmp_path) + view = db.create_materialized_view("just_name", "people", select="name") + view.refresh() + rows = view.table.search().to_list() + assert set(rows[0]) - {"__source_row_id"} == {"name"} + assert sorted(row["name"] for row in rows) == ["ada", "grace", "kid"] + + +@pytest.mark.asyncio +async def test_async_scalar_select_is_one_column(tmp_path): + db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) + await db.create_table("people", [{"name": "ada", "age": 36}]) + view = await db.create_materialized_view("just_name", "people", select="name") + await view.refresh() + rows = await view.table.query().to_list() + assert set(rows[0]) - {"__source_row_id"} == {"name"} + + +def test_limit_above_i64_max_is_refused(tmp_path): + db = make_db(tmp_path) + with pytest.raises(ValueError, match="exceeds the maximum"): + db.create_materialized_view("too_big", "people", limit=2**63) + # The boundary is fine, and zero still means an empty view. + db.create_materialized_view("at_max", "people", limit=2**63 - 1) + empty = db.create_materialized_view("none", "people", limit=0) + empty.refresh() + assert empty.table.count_rows() == 0 + + +def _namespace_db(tmp_path): + return lancedb.connect_namespace( + "dir", + {"root": str(tmp_path)}, + storage_options=STABLE_ROW_IDS, + ) + + +def test_namespace_connection_materialized_views(tmp_path): + db = _namespace_db(tmp_path) + db.create_table( + "people", + [{"name": "ada", "age": 36}, {"name": "kid", "age": 7}], + storage_options=STABLE_ROW_IDS, + ) + + view = db.create_materialized_view("adults", "people", where="age >= 18") + view.refresh() + assert view.table.count_rows() == 1 + assert db.list_materialized_views() == ["adults"] + + reopened = db.open_materialized_view("adults") + assert reopened.definition.source_table == "people" + with pytest.raises(ValueError, match="not a materialized view"): + db.open_materialized_view("people") + + +@pytest.mark.asyncio +async def test_async_namespace_connection_materialized_views(tmp_path): + db = lancedb.connect_namespace_async( + "dir", + {"root": str(tmp_path)}, + storage_options=STABLE_ROW_IDS, + ) + await db.create_table( + "people", + [{"name": "ada", "age": 36}, {"name": "kid", "age": 7}], + storage_options=STABLE_ROW_IDS, + ) + + view = await db.create_materialized_view("adults", "people", where="age >= 18") + await view.refresh() + assert await view.table.count_rows() == 1 + assert await db.list_materialized_views() == ["adults"] + + reopened = await db.open_materialized_view("adults") + assert (await reopened.definition()).source_table == "people" + + # The view's table came through the namespace, not straight from the + # inner connection: a bare inner table carries no namespace context, so + # its pushdown routing differs from a table the namespace opened. + through_namespace = await db.open_table("adults") + for handle in (view.table, reopened.table): + assert ( + handle._route_pushdown_to_rust == through_namespace._route_pushdown_to_rust + ) + assert handle._namespace_path == through_namespace._namespace_path diff --git a/python/src/connection.rs b/python/src/connection.rs index 87870b800..4143ac9c9 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -333,6 +333,40 @@ impl Connection { }) } + #[pyo3(signature = (name, source, projections=None, filter=None, limit=None))] + pub fn create_materialized_view( + self_: PyRef<'_, Self>, + name: String, + source: String, + projections: Option>, + filter: Option, + limit: Option, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + let mut builder = inner.create_materialized_view(name, source); + if let Some(projections) = projections { + builder = builder.select(projections); + } + if let Some(filter) = filter { + builder = builder.only_if(filter); + } + if let Some(limit) = limit { + builder = builder.limit(limit); + } + let view = builder.execute().await.infer_error()?; + Ok(Table::new(view.table().clone())) + }) + } + + pub fn list_materialized_views(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + let views = inner.list_materialized_views().await.infer_error()?; + Ok(views.into_iter().map(|view| view.name).collect::>()) + }) + } + #[pyo3(signature = (name, namespace_path=None))] pub fn drop_table( self_: PyRef<'_, Self>, diff --git a/python/src/lib.rs b/python/src/lib.rs index 756b3557f..c1dfbc02b 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -16,8 +16,8 @@ use query::{FTSQuery, HybridQuery, Query, VectorQuery}; use session::Session; use table::{ AddColumnsResult, AddResult, AlterColumnsResult, DeleteResult, DropColumnsResult, FtsToken, - LsmWriteSpec, MergeResult, PyBlobFile, RefreshColumnResult, Table, UpdateFieldMetadataResult, - UpdateResult, + LsmWriteSpec, MergeResult, PyBlobFile, RefreshColumnResult, RefreshMaterializedViewResult, + Table, UpdateFieldMetadataResult, UpdateResult, }; pub mod arrow; @@ -60,6 +60,7 @@ 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::()?; diff --git a/python/src/table.rs b/python/src/table.rs index cb4752cce..a3a7c9d68 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -441,6 +441,41 @@ impl From for RefreshColumnResult { } } +#[pyclass(get_all, from_py_object)] +#[derive(Clone, Debug)] +pub struct RefreshMaterializedViewResult { + pub mode: String, + pub rows_written: u64, + pub source_version: u64, + pub version: u64, +} + +#[pymethods] +impl RefreshMaterializedViewResult { + pub fn __repr__(&self) -> String { + format!( + "RefreshMaterializedViewResult(mode={}, rows_written={}, source_version={}, version={})", + self.mode, self.rows_written, self.source_version, self.version + ) + } +} + +impl From for RefreshMaterializedViewResult { + fn from(result: lancedb::RefreshMaterializedViewResult) -> Self { + let mode = match result.mode { + lancedb::RefreshMode::Rebuild => "rebuild", + lancedb::RefreshMode::Incremental => "incremental", + lancedb::RefreshMode::NoOp => "no_op", + }; + Self { + mode: mode.to_string(), + rows_written: result.rows_written, + source_version: result.source_version, + version: result.version, + } + } +} + #[pymethods] impl AddColumnsResult { pub fn __repr__(&self) -> String { @@ -1588,6 +1623,26 @@ impl Table { }) } + #[pyo3(signature = (full=false, source_version=None))] + pub fn refresh_materialized_view( + self_: PyRef<'_, Self>, + full: bool, + source_version: Option, + ) -> PyResult> { + let inner = self_.inner_ref()?.clone(); + future_into_py(self_.py(), async move { + let view = lancedb::MaterializedView::from_table(inner) + .await + .infer_error()?; + let mut builder = view.refresh().full(full); + if let Some(version) = source_version { + builder = builder.source_version(version); + } + let result = builder.execute().await.infer_error()?; + Ok(RefreshMaterializedViewResult::from(result)) + }) + } + pub fn add_columns_with_schema( self_: PyRef<'_, Self>, schema: PyArrowType, From e98d8ac6857fa058fa07e005e0796c2a9a940d12 Mon Sep 17 00:00:00 2001 From: Drew Gallardo Date: Fri, 21 Aug 2026 23:37:12 -0700 Subject: [PATCH 091/206] feat!: rename branch merge to cherry_pick (#3986) This PR is a **breaking** rename of #3686. merge reads like git merge w/ three-way, replay history, combine two lines of work. That is not this API. This call takes one additive change on a branch and lands it on main. New column, including a blob column. Main's existing columns are not rewritten. If it cannot land, you get `status="failed"` and `diff.errors`, not a merge conflict to resolve. Cherry-pick is terminology that aligns more with that. ```python table = db.open_table("images") table.branches.create("exp") exp = table.branches.checkout("exp") exp.add_columns({"tag": "cast('draft' as string)"}) diff = table.branches.diff("exp") preview = table.branches.cherry_pick("exp", dry_run=True) result = table.branches.cherry_pick("exp") if result["status"] == "cherryPicked": print("landed at", result["mainVersionAfter"]) elif result["status"] == "failed": print(result["diff"]["errors"]) ``` ### Behavior - Remote / Enterprise only. Local still NotSupported. - HTTP 409 is not an exception. It is Ok with status="failed" and diff.errors (CherryPickError). - Unknown error / status codes still parse as Unknown. - Requests are not retried. 409 is final and carries the body. - Endpoint is POST /v1/table/{id}/branches/cherry_pick/. - merge_insert and Table.merge are unchanged. ### Testing - `cargo test -p lancedb --features remote diff_branch` - `cargo test -p lancedb --features remote cherry_pick` - `pytest python/python/tests/test_remote_db.py -k cherry_pick` - node `remote.test.ts` diffs / cherry-picks path --- docs/src/js/classes/Branches.md | 50 ++++++------ docs/src/js/globals.md | 6 +- docs/src/js/interfaces/BranchDiff.md | 24 ++---- .../{MergeBlocker.md => CherryPickError.md} | 6 +- docs/src/js/interfaces/CherryPickPreview.md | 17 +++++ ...rgeBranchResult.md => CherryPickResult.md} | 12 +-- docs/src/js/interfaces/MergePreview.md | 17 ----- nodejs/__test__/remote.test.ts | 26 +++---- nodejs/lancedb/index.ts | 6 +- nodejs/lancedb/table.ts | 37 +++++---- nodejs/src/table.rs | 6 +- python/python/lancedb/_lancedb.pyi | 2 +- python/python/lancedb/table.py | 22 +++--- python/python/tests/test_remote_db.py | 17 ++--- python/src/table.rs | 4 +- rust/lancedb/src/remote/table.rs | 76 ++++++++++--------- rust/lancedb/src/table.rs | 30 ++++---- .../table/{branch_merge.rs => cherry_pick.rs} | 27 ++++--- 18 files changed, 188 insertions(+), 197 deletions(-) rename docs/src/js/interfaces/{MergeBlocker.md => CherryPickError.md} (54%) create mode 100644 docs/src/js/interfaces/CherryPickPreview.md rename docs/src/js/interfaces/{MergeBranchResult.md => CherryPickResult.md} (60%) delete mode 100644 docs/src/js/interfaces/MergePreview.md rename rust/lancedb/src/table/{branch_merge.rs => cherry_pick.rs} (86%) diff --git a/docs/src/js/classes/Branches.md b/docs/src/js/classes/Branches.md index 5296d0d08..6680fbfee 100644 --- a/docs/src/js/classes/Branches.md +++ b/docs/src/js/classes/Branches.md @@ -37,6 +37,31 @@ latest and stays writable. *** +### cherryPick() + +```ts +cherryPick(fromBranch, dryRun): Promise +``` + +Cherry-pick a branch onto main. + +Set `dryRun` to `true` to preview. A failed cherry-pick resolves +with `status: "failed"` instead of throwing. + +#### Parameters + +* **fromBranch**: `string` + Branch to cherry-pick from. + +* **dryRun**: `boolean` = `false` + When true, only preview. Defaults to false. + +#### Returns + +`Promise`<[`CherryPickResult`](../interfaces/CherryPickResult.md)> + +*** + ### create() ```ts @@ -112,28 +137,3 @@ List all branches, mapping name to branch metadata. #### Returns `Promise`<`Record`<`string`, [`BranchContents`](BranchContents.md)>> - -*** - -### merge() - -```ts -merge(fromBranch, dryRun): Promise -``` - -Merge a branch into main. - -Set `dryRun` to `true` to preview the merge. A rejected merge resolves -with `status: "rejected"` instead of throwing. - -#### Parameters - -* **fromBranch**: `string` - Branch to merge from. - -* **dryRun**: `boolean` = `false` - When true, only preview the merge. Defaults to false. - -#### Returns - -`Promise`<[`MergeBranchResult`](../interfaces/MergeBranchResult.md)> diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 462907cfd..4deeed1bc 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -59,6 +59,9 @@ - [BranchIndexSummary](interfaces/BranchIndexSummary.md) - [BranchRowCountSummary](interfaces/BranchRowCountSummary.md) - [BucketStats](interfaces/BucketStats.md) +- [CherryPickError](interfaces/CherryPickError.md) +- [CherryPickPreview](interfaces/CherryPickPreview.md) +- [CherryPickResult](interfaces/CherryPickResult.md) - [ClientConfig](interfaces/ClientConfig.md) - [ColumnAlteration](interfaces/ColumnAlteration.md) - [ColumnOrdering](interfaces/ColumnOrdering.md) @@ -99,9 +102,6 @@ - [LsmStats](interfaces/LsmStats.md) - [LsmWriteSpec](interfaces/LsmWriteSpec.md) - [MemtableStats](interfaces/MemtableStats.md) -- [MergeBlocker](interfaces/MergeBlocker.md) -- [MergeBranchResult](interfaces/MergeBranchResult.md) -- [MergePreview](interfaces/MergePreview.md) - [MergeResult](interfaces/MergeResult.md) - [NativeOAuthConfig](interfaces/NativeOAuthConfig.md) - [OAuthConfig](interfaces/OAuthConfig.md) diff --git a/docs/src/js/interfaces/BranchDiff.md b/docs/src/js/interfaces/BranchDiff.md index 224be1991..b408ebe11 100644 --- a/docs/src/js/interfaces/BranchDiff.md +++ b/docs/src/js/interfaces/BranchDiff.md @@ -50,6 +50,14 @@ changedColumns: BranchColumnChange[]; *** +### errors + +```ts +errors: CherryPickError[]; +``` + +*** + ### fromBranch ```ts @@ -66,22 +74,6 @@ mainVersion: number; *** -### mergeBlockers - -```ts -mergeBlockers: MergeBlocker[]; -``` - -*** - -### mergeable - -```ts -mergeable: boolean; -``` - -*** - ### parentVersion ```ts diff --git a/docs/src/js/interfaces/MergeBlocker.md b/docs/src/js/interfaces/CherryPickError.md similarity index 54% rename from docs/src/js/interfaces/MergeBlocker.md rename to docs/src/js/interfaces/CherryPickError.md index 6c8f84b37..84f8fe012 100644 --- a/docs/src/js/interfaces/MergeBlocker.md +++ b/docs/src/js/interfaces/CherryPickError.md @@ -2,11 +2,11 @@ *** -[@lancedb/lancedb](../globals.md) / MergeBlocker +[@lancedb/lancedb](../globals.md) / CherryPickError -# Interface: MergeBlocker +# Interface: CherryPickError -A reason why a branch cannot currently be merged. +A reason why a cherry-pick cannot currently land. ## Properties diff --git a/docs/src/js/interfaces/CherryPickPreview.md b/docs/src/js/interfaces/CherryPickPreview.md new file mode 100644 index 000000000..9620068a2 --- /dev/null +++ b/docs/src/js/interfaces/CherryPickPreview.md @@ -0,0 +1,17 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / CherryPickPreview + +# Interface: CherryPickPreview + +Changes that would be, or were, promoted by a cherry-pick. + +## Properties + +### promotedColumns + +```ts +promotedColumns: string[]; +``` diff --git a/docs/src/js/interfaces/MergeBranchResult.md b/docs/src/js/interfaces/CherryPickResult.md similarity index 60% rename from docs/src/js/interfaces/MergeBranchResult.md rename to docs/src/js/interfaces/CherryPickResult.md index 61c2d0d33..c837ab143 100644 --- a/docs/src/js/interfaces/MergeBranchResult.md +++ b/docs/src/js/interfaces/CherryPickResult.md @@ -2,11 +2,11 @@ *** -[@lancedb/lancedb](../globals.md) / MergeBranchResult +[@lancedb/lancedb](../globals.md) / CherryPickResult -# Interface: MergeBranchResult +# Interface: CherryPickResult -Result of previewing or attempting a branch merge. +Result of previewing or attempting a cherry-pick. ## Properties @@ -29,7 +29,7 @@ optional mainVersionAfter: number; ### preview ```ts -preview: MergePreview; +preview: CherryPickPreview; ``` *** @@ -38,9 +38,9 @@ preview: MergePreview; ```ts status: + | "failed" | "unknown" - | "rejected" | "ready" | "notImplemented" - | "merged"; + | "cherryPicked"; ``` diff --git a/docs/src/js/interfaces/MergePreview.md b/docs/src/js/interfaces/MergePreview.md deleted file mode 100644 index 0d9717289..000000000 --- a/docs/src/js/interfaces/MergePreview.md +++ /dev/null @@ -1,17 +0,0 @@ -[**@lancedb/lancedb**](../README.md) • **Docs** - -*** - -[@lancedb/lancedb](../globals.md) / MergePreview - -# Interface: MergePreview - -Changes that would be, or were, promoted by a branch merge. - -## Properties - -### promotedColumns - -```ts -promotedColumns: string[]; -``` diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index e766b3d2a..01320d2b0 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -311,7 +311,7 @@ describe("remote connection", () => { expect(createIndexBody?.["custom_stop_words"]).toEqual(["the"]); }); - it("diffs and merges remote branches", async () => { + it("diffs and cherry-picks remote branches", async () => { const sampleDiff = { fromBranch: "exp", parentVersion: 1, @@ -333,10 +333,9 @@ describe("remote connection", () => { changedColumns: [], addedIndexes: [], removedIndexes: [], - mergeable: true, - mergeBlockers: [], + errors: [], }; - const mergeBodies: Record[] = []; + const cherryPickBodies: Record[] = []; await withMockDatabase( (req, res) => { @@ -366,17 +365,16 @@ describe("remote connection", () => { .end(JSON.stringify(sampleDiff)); return; } - if (path.endsWith("/branches/merge/")) { - mergeBodies.push(body); + if (path.endsWith("/branches/cherry_pick/")) { + cherryPickBodies.push(body); const dryRun = body["dry_run"] === true; const response = { - status: dryRun ? "ready" : "rejected", + status: dryRun ? "ready" : "failed", diff: dryRun ? sampleDiff : { ...sampleDiff, - mergeable: false, - mergeBlockers: [ + errors: [ { code: "baseMoved", message: "main has advanced" }, ], }, @@ -398,19 +396,19 @@ describe("remote connection", () => { await expect(branches.diff("exp")).resolves.toEqual(sampleDiff); - const rejected = await branches.merge("exp"); - expect(rejected.status).toBe("rejected"); - expect(rejected.diff.mergeBlockers).toEqual([ + const failed = await branches.cherryPick("exp"); + expect(failed.status).toBe("failed"); + expect(failed.diff.errors).toEqual([ { code: "baseMoved", message: "main has advanced" }, ]); - const preview = await branches.merge("exp", true); + const preview = await branches.cherryPick("exp", true); expect(preview.status).toBe("ready"); expect(preview.preview.promotedColumns).toEqual(["tag"]); }, ); - expect(mergeBodies).toEqual([ + expect(cherryPickBodies).toEqual([ // biome-ignore lint/style/useNamingConvention: snake_case mandated by the server wire format { from_branch: "exp", dry_run: false }, // biome-ignore lint/style/useNamingConvention: snake_case mandated by the server wire format diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 6a5bfe3b4..aa9c7ef13 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -135,10 +135,10 @@ export { BranchColumnChange, BranchIndexSummary, BranchRowCountSummary, - MergeBlocker, + CherryPickError, BranchDiff, - MergePreview, - MergeBranchResult, + CherryPickPreview, + CherryPickResult, AddDataOptions, UpdateOptions, OptimizeOptions, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 964c2cea3..4e323ec64 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -1557,8 +1557,8 @@ export interface BranchRowCountSummary { deltaAvailable: boolean; } -/** A reason why a branch cannot currently be merged. */ -export interface MergeBlocker { +/** A reason why a cherry-pick cannot currently land. */ +export interface CherryPickError { code: string; message: string; } @@ -1578,20 +1578,19 @@ export interface BranchDiff { changedColumns: BranchColumnChange[]; addedIndexes: BranchIndexSummary[]; removedIndexes: BranchIndexSummary[]; - mergeable: boolean; - mergeBlockers: MergeBlocker[]; + errors: CherryPickError[]; } -/** Changes that would be, or were, promoted by a branch merge. */ -export interface MergePreview { +/** Changes that would be, or were, promoted by a cherry-pick. */ +export interface CherryPickPreview { promotedColumns: string[]; } -/** Result of previewing or attempting a branch merge. */ -export interface MergeBranchResult { - status: "ready" | "rejected" | "notImplemented" | "merged" | "unknown"; +/** Result of previewing or attempting a cherry-pick. */ +export interface CherryPickResult { + status: "ready" | "failed" | "notImplemented" | "cherryPicked" | "unknown"; diff: BranchDiff; - preview: MergePreview; + preview: CherryPickPreview; mainVersionAfter?: number; } @@ -1654,21 +1653,21 @@ export class Branches { } /** - * Merge a branch into main. + * Cherry-pick a branch onto main. * - * Set `dryRun` to `true` to preview the merge. A rejected merge resolves - * with `status: "rejected"` instead of throwing. + * Set `dryRun` to `true` to preview. A failed cherry-pick resolves + * with `status: "failed"` instead of throwing. * - * @param fromBranch Branch to merge from. - * @param dryRun When true, only preview the merge. Defaults to false. + * @param fromBranch Branch to cherry-pick from. + * @param dryRun When true, only preview. Defaults to false. */ - async merge( + async cherryPick( fromBranch: string, dryRun: boolean = false, - ): Promise { - return (await this.#inner.merge( + ): Promise { + return (await this.#inner.cherryPick( fromBranch, dryRun, - )) as unknown as MergeBranchResult; + )) as unknown as CherryPickResult; } } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index b15491202..694b6a704 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -1605,18 +1605,18 @@ impl Branches { } #[napi(ts_return_type = "Promise>")] - pub async fn merge( + pub async fn cherry_pick( &self, from_branch: String, dry_run: Option, ) -> napi::Result { let result = self .inner - .merge_branch(&from_branch, dry_run.unwrap_or(false)) + .cherry_pick(&from_branch, dry_run.unwrap_or(false)) .await .default_error()?; serde_json::to_value(result).map_err(|err| { - napi::Error::from_reason(format!("failed to serialize branch merge result: {err}")) + napi::Error::from_reason(format!("failed to serialize cherry-pick result: {err}")) }) } } diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index b23d79c85..648469579 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -432,7 +432,7 @@ class Branches: async def checkout(self, name: str, version: Optional[int] = None) -> Table: ... async def delete(self, name: str) -> None: ... async def diff(self, from_branch: str) -> Dict[str, Any]: ... - async def merge( + async def cherry_pick( self, from_branch: str, dry_run: bool = False ) -> Dict[str, Any]: ... diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 913ab5289..0c84b4036 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -6801,21 +6801,21 @@ class Branches: """Diff a branch against main.""" return LOOP.run(self._table.branches.diff(from_branch)) - def merge(self, from_branch: str, dry_run: bool = False) -> Dict[str, Any]: - """Merge a branch into main, or dry-run. + def cherry_pick(self, from_branch: str, dry_run: bool = False) -> Dict[str, Any]: + """Cherry-pick a branch onto main, or dry-run. Parameters ---------- from_branch: str - Branch to merge from. + Branch to cherry-pick from. dry_run: bool, default False - When True, only preview. When False, attempt the merge. + When True, only preview. When False, attempt the cherry-pick. Notes ----- - A rejected merge returns ``status="rejected"`` instead of raising. + A failed cherry-pick returns ``status="failed"`` instead of raising. """ - return LOOP.run(self._table.branches.merge(from_branch, dry_run)) + return LOOP.run(self._table.branches.cherry_pick(from_branch, dry_run)) def _wrap( self, async_table: "AsyncTable", version: Optional[int] = None @@ -6951,9 +6951,11 @@ class AsyncBranches: """Diff a branch against main.""" return await self._table.branches.diff(from_branch) - async def merge(self, from_branch: str, dry_run: bool = False) -> Dict[str, Any]: - """Merge a branch into main, or dry-run. + async def cherry_pick( + self, from_branch: str, dry_run: bool = False + ) -> Dict[str, Any]: + """Cherry-pick a branch onto main, or dry-run. - A rejected merge returns ``status="rejected"`` instead of raising. + A failed cherry-pick returns ``status="failed"`` instead of raising. """ - return await self._table.branches.merge(from_branch, dry_run) + return await self._table.branches.cherry_pick(from_branch, dry_run) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 13ffc4415..08f5550eb 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -242,8 +242,8 @@ def test_remote_table_branches_sync(): table.branches.delete("exp") -def test_remote_table_branch_merge_defaults_to_execute(): - merge_bodies = [] +def test_remote_table_cherry_pick_defaults_to_execute(): + cherry_pick_bodies = [] diff = { "fromBranch": "exp", "parentVersion": 1, @@ -265,8 +265,7 @@ def test_remote_table_branch_merge_defaults_to_execute(): "changedColumns": [], "addedIndexes": [], "removedIndexes": [], - "mergeable": True, - "mergeBlockers": [], + "errors": [], } def handler(request): @@ -276,11 +275,11 @@ def test_remote_table_branch_merge_defaults_to_execute(): else: content_len = int(request.headers.get("Content-Length")) request_body = json.loads(request.rfile.read(content_len)) - merge_bodies.append(request_body) + cherry_pick_bodies.append(request_body) dry_run = request_body["dry_run"] status = 200 if dry_run else 409 body = { - "status": "ready" if dry_run else "rejected", + "status": "ready" if dry_run else "failed", "diff": diff, "preview": {"promotedColumns": []}, } @@ -292,10 +291,10 @@ def test_remote_table_branch_merge_defaults_to_execute(): with mock_lancedb_connection(handler) as db: branches = db.open_table("test").branches - assert branches.merge("exp")["status"] == "rejected" - assert branches.merge("exp", dry_run=True)["status"] == "ready" + assert branches.cherry_pick("exp")["status"] == "failed" + assert branches.cherry_pick("exp", dry_run=True)["status"] == "ready" - assert merge_bodies == [ + assert cherry_pick_bodies == [ {"from_branch": "exp", "dry_run": False}, {"from_branch": "exp", "dry_run": True}, ] diff --git a/python/src/table.rs b/python/src/table.rs index a3a7c9d68..5cdcc3653 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1940,7 +1940,7 @@ impl Branches { } #[pyo3(signature = (from_branch, dry_run=false))] - pub fn merge( + pub fn cherry_pick( self_: PyRef<'_, Self>, from_branch: String, dry_run: bool, @@ -1948,7 +1948,7 @@ impl Branches { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { let result = inner - .merge_branch(&from_branch, dry_run) + .cherry_pick(&from_branch, dry_run) .await .infer_error()?; Python::attach(|py| struct_to_wire_py(py, &result)) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 6c446907d..fb7278db9 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -21,11 +21,11 @@ use crate::remote::job::RemoteJob; use crate::table::AddColumnsResult; use crate::table::AddResult; use crate::table::BranchDiff; +use crate::table::CherryPickResult; use crate::table::DeleteResult; use crate::table::DropColumnsResult; use crate::table::LsmStats; use crate::table::LsmWriteSpec; -use crate::table::MergeBranchResult; use crate::table::MergeResult; use crate::table::Tags; use crate::table::UpdateResult; @@ -2031,7 +2031,7 @@ impl BaseTable for RemoteTable { async fn diff_branch(&self, from_branch: &str) -> Result { if from_branch.trim().is_empty() { return Err(Error::InvalidInput { - message: "from_branch must be a non-empty string".into(), + message: "Branch name cannot be empty.".into(), }); } let request = self @@ -2058,20 +2058,23 @@ impl BaseTable for RemoteTable { }) } - async fn merge_branch(&self, from_branch: &str, dry_run: bool) -> Result { + async fn cherry_pick(&self, from_branch: &str, dry_run: bool) -> Result { if from_branch.trim().is_empty() { return Err(Error::InvalidInput { - message: "from_branch must be a non-empty string".into(), + message: "Branch name cannot be empty.".into(), }); } let request = self .client - .post(&format!("/v1/table/{}/branches/merge/", self.identifier)) + .post(&format!( + "/v1/table/{}/branches/cherry_pick/", + self.identifier + )) .json(&serde_json::json!({ "from_branch": from_branch, "dry_run": dry_run, })); - // No retry. 409 rejected merge is final and carries a body. + // No retry. HTTP 409 is CherryPickStatus::Failed with a body, not a transport error. let (request_id, response) = self.send(request, false).await?; let status = response.status(); if status == StatusCode::NOT_FOUND { @@ -2080,11 +2083,11 @@ impl BaseTable for RemoteTable { source: format!("branch '{}' does not exist", from_branch).into(), }); } - // 200 and 409 both carry MergeBranchResult. + // 200 and 409 both carry CherryPickResult. if status != StatusCode::OK && status != StatusCode::CONFLICT { let body = response.text().await.unwrap_or_default(); return Err(Error::Http { - source: format!("unexpected status {status} from merge_branch: {body}").into(), + source: format!("unexpected status {status} from cherry_pick: {body}").into(), request_id, status_code: Some(status), }); @@ -2092,7 +2095,7 @@ impl BaseTable for RemoteTable { let body = response.text().await.err_to_http(request_id.clone())?; serde_json::from_str(&body).map_err(|err| Error::Http { source: format!( - "Failed to parse merge_branch response: {}, body: {}", + "Failed to parse cherry_pick response: {}, body: {}", err, body ) .into(), @@ -10513,8 +10516,7 @@ mod tests { "changedColumns":[], "addedIndexes":[], "removedIndexes":[], - "mergeable":true, - "mergeBlockers":[] + "errors":[] }"# } @@ -10532,15 +10534,18 @@ mod tests { }); let diff = table.diff_branch("exp").await.unwrap(); assert_eq!(diff.from_branch, "exp"); - assert!(diff.mergeable); + assert!(diff.errors.is_empty()); assert_eq!(diff.added_columns.len(), 1); assert_eq!(diff.added_columns[0].name, "tag"); } #[tokio::test] - async fn test_merge_branch_dry_run() { + async fn test_cherry_pick_dry_run() { let table = Table::new_with_handler("my_table", |request| { - assert_eq!(request.url().path(), "/v1/table/my_table/branches/merge/"); + assert_eq!( + request.url().path(), + "/v1/table/my_table/branches/cherry_pick/" + ); let body = request_body_json(&request); assert_eq!(body["from_branch"], "exp"); assert_eq!(body["dry_run"], true); @@ -10550,27 +10555,29 @@ mod tests { ); http::Response::builder().status(200).body(resp).unwrap() }); - let result = table.merge_branch("exp", true).await.unwrap(); - assert_eq!(result.status, crate::table::MergeBranchStatus::Ready); + let result = table.cherry_pick("exp", true).await.unwrap(); + assert_eq!(result.status, crate::table::CherryPickStatus::Ready); assert_eq!(result.preview.promoted_columns, vec!["tag".to_string()]); assert!(result.main_version_after.is_none()); } #[tokio::test] - async fn test_merge_branch_rejected_returns_ok_with_body() { + async fn test_cherry_pick_failed_returns_ok_with_body() { let table = Table::new_with_handler("my_table", |request| { - assert_eq!(request.url().path(), "/v1/table/my_table/branches/merge/"); + assert_eq!( + request.url().path(), + "/v1/table/my_table/branches/cherry_pick/" + ); let body = request_body_json(&request); assert_eq!(body["dry_run"], false); let mut diff: serde_json::Value = serde_json::from_str(sample_branch_diff_json()).unwrap(); - diff["mergeable"] = serde_json::json!(false); - diff["mergeBlockers"] = serde_json::json!([{ + diff["errors"] = serde_json::json!([{ "code": "baseMoved", "message": "main has advanced" }]); let resp = serde_json::json!({ - "status": "rejected", + "status": "failed", "diff": diff, "preview": { "promotedColumns": [] } }); @@ -10579,24 +10586,23 @@ mod tests { .body(resp.to_string()) .unwrap() }); - let result = table.merge_branch("exp", false).await.unwrap(); - assert_eq!(result.status, crate::table::MergeBranchStatus::Rejected); - assert!(!result.diff.mergeable); - assert_eq!(result.diff.merge_blockers.len(), 1); + let result = table.cherry_pick("exp", false).await.unwrap(); + assert_eq!(result.status, crate::table::CherryPickStatus::Failed); + assert!(!result.diff.errors.is_empty()); + assert_eq!(result.diff.errors.len(), 1); } #[tokio::test] - async fn test_merge_branch_unknown_blocker_code_parses() { + async fn test_cherry_pick_unknown_error_code_parses() { let table = Table::new_with_handler("my_table", |_| { let mut diff: serde_json::Value = serde_json::from_str(sample_branch_diff_json()).unwrap(); - diff["mergeable"] = serde_json::json!(false); - diff["mergeBlockers"] = serde_json::json!([{ + diff["errors"] = serde_json::json!([{ "code": "multipleCommits", "message": "branch has more than one data commit" }]); let resp = serde_json::json!({ - "status": "rejected", + "status": "failed", "diff": diff, "preview": { "operation": "append", "rowsAdded": 2 } }); @@ -10605,24 +10611,24 @@ mod tests { .body(resp.to_string()) .unwrap() }); - let result = table.merge_branch("exp", false).await.unwrap(); - assert_eq!(result.status, crate::table::MergeBranchStatus::Rejected); + let result = table.cherry_pick("exp", false).await.unwrap(); + assert_eq!(result.status, crate::table::CherryPickStatus::Failed); assert_eq!( - result.diff.merge_blockers[0].code, - crate::table::MergeBlockerCode::Unknown + result.diff.errors[0].code, + crate::table::CherryPickErrorCode::Unknown ); assert!(result.preview.promoted_columns.is_empty()); } #[tokio::test] - async fn test_merge_branch_unexpected_2xx_is_error() { + async fn test_cherry_pick_unexpected_2xx_is_error() { let table = Table::new_with_handler("my_table", |_| { http::Response::builder() .status(204) .body(String::new()) .unwrap() }); - let err = table.merge_branch("exp", false).await.unwrap_err(); + let err = table.cherry_pick("exp", false).await.unwrap_err(); match err { Error::Http { status_code: Some(code), diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index ca9ed8f26..c2c12fff5 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -66,8 +66,8 @@ use self::merge::MergeInsertBuilder; pub mod add_columns; mod add_data; -pub mod branch_merge; pub mod checkpoint; +pub mod cherry_pick; pub mod computed_columns; mod create_index; pub mod datafusion; @@ -87,9 +87,9 @@ pub use add_columns::AddColumnsBuilder; #[cfg(feature = "remote")] pub(crate) use add_data::PreprocessingOutput; pub use add_data::{AddDataBuilder, AddDataMode, AddResult, NaNVectorBehavior}; -pub use branch_merge::{ - BranchDiff, ColumnChange, ColumnSummary, IndexSummary, MergeBlocker, MergeBlockerCode, - MergeBranchResult, MergeBranchStatus, MergePreview, RowCountSummary, +pub use cherry_pick::{ + BranchDiff, CherryPickError, CherryPickErrorCode, CherryPickPreview, CherryPickResult, + CherryPickStatus, ColumnChange, ColumnSummary, IndexSummary, RowCountSummary, }; pub use chrono::Duration; pub use computed_columns::{ @@ -832,14 +832,14 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// Diff a branch against main. Remote only. async fn diff_branch(&self, _from_branch: &str) -> Result { Err(Error::NotSupported { - message: "diff_branch is only supported on remote tables".into(), + message: "Branch diffs are only supported on Enterprise tables.".into(), }) } - /// Merge a branch into main, or dry-run. Remote only. - /// HTTP 409 still returns [`Ok`] with [`MergeBranchStatus::Rejected`]. - async fn merge_branch(&self, _from_branch: &str, _dry_run: bool) -> Result { + /// Cherry-pick a branch onto main, or dry-run. Remote only. + /// HTTP 409 still returns [`Ok`] with [`CherryPickStatus::Failed`]. + async fn cherry_pick(&self, _from_branch: &str, _dry_run: bool) -> Result { Err(Error::NotSupported { - message: "merge_branch is only supported on remote tables".into(), + message: "Cherry-picking branches is only supported on Enterprise tables.".into(), }) } /// The branch this handle is scoped to, or `None` for `main`. @@ -2263,14 +2263,10 @@ impl Table { self.inner.diff_branch(from_branch).await } - /// Merge a branch into main, or dry-run. Remote only. - /// HTTP 409 still returns [`Ok`] with [`MergeBranchStatus::Rejected`]. - pub async fn merge_branch( - &self, - from_branch: &str, - dry_run: bool, - ) -> Result { - self.inner.merge_branch(from_branch, dry_run).await + /// Cherry-pick a branch onto main, or dry-run. Remote only. + /// HTTP 409 still returns [`Ok`] with [`CherryPickStatus::Failed`]. + pub async fn cherry_pick(&self, from_branch: &str, dry_run: bool) -> Result { + self.inner.cherry_pick(from_branch, dry_run).await } /// The branch this handle is scoped to, or `None` for `main`. diff --git a/rust/lancedb/src/table/branch_merge.rs b/rust/lancedb/src/table/cherry_pick.rs similarity index 86% rename from rust/lancedb/src/table/branch_merge.rs rename to rust/lancedb/src/table/cherry_pick.rs index ad81ab64c..93bc76637 100644 --- a/rust/lancedb/src/table/branch_merge.rs +++ b/rust/lancedb/src/table/cherry_pick.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! Types for remote branch diff / merge against main. +//! Types for remote branch diff / cherry-pick onto main. use serde::{Deserialize, Serialize}; @@ -44,13 +44,13 @@ pub struct RowCountSummary { #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "camelCase")] -pub enum MergeBlockerCode { +pub enum CherryPickErrorCode { BaseMoved, RowCountMismatch, RowsChanged, ColumnRemoved, ColumnChanged, - NoMergeableChanges, + NothingToApply, NoColumnChanges, InputColumnDependency, ParentNotMain, @@ -60,8 +60,8 @@ pub enum MergeBlockerCode { #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "camelCase")] -pub struct MergeBlocker { - pub code: MergeBlockerCode, +pub struct CherryPickError { + pub code: CherryPickErrorCode, pub message: String, } @@ -81,34 +81,33 @@ pub struct BranchDiff { pub changed_columns: Vec, pub added_indexes: Vec, pub removed_indexes: Vec, - pub mergeable: bool, - pub merge_blockers: Vec, + pub errors: Vec, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "camelCase")] -pub struct MergePreview { +pub struct CherryPickPreview { #[serde(default)] pub promoted_columns: Vec, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "camelCase")] -pub enum MergeBranchStatus { +pub enum CherryPickStatus { Ready, - Rejected, + Failed, NotImplemented, - Merged, + CherryPicked, #[serde(other)] Unknown, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "camelCase")] -pub struct MergeBranchResult { - pub status: MergeBranchStatus, +pub struct CherryPickResult { + pub status: CherryPickStatus, pub diff: BranchDiff, - pub preview: MergePreview, + pub preview: CherryPickPreview, #[serde(default, skip_serializing_if = "Option::is_none")] pub main_version_after: Option, } From 68749ecfa38f966bec6e650bc41c3f6b8e498818 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Fri, 21 Aug 2026 23:48:43 -0700 Subject: [PATCH 092/206] feat(nodejs): materialized view bindings (#3935) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Exposes materialized views to TypeScript: createMaterializedView, openMaterializedView and listMaterializedViews on Connection, and a MaterializedView handle carrying the parsed definition and refresh({full, sourceVersion}), which returns the typed refresh result. select accepts column names, [alias, expression] pairs, or a record of the same; the definition reads back off the stored schema, so a reopened handle needs no side channel. Remote connections surface the core's not-supported error up front. The napi crate needed the same recursion-limit raise as the core crate: the refresh future's type graph overflows the default trait-recursion depth. Stack created with GitHub Stacks CLIGive Feedback 💬 --- docs/src/js/classes/Connection.md | 80 ++++++++- docs/src/js/classes/MaterializedView.md | 101 +++++++++++ docs/src/js/globals.md | 4 + .../interfaces/MaterializedViewDefinition.md | 59 +++++++ .../RefreshMaterializedViewResult.md | 41 +++++ .../js/type-aliases/MaterializedViewSelect.md | 14 ++ nodejs/__test__/embedding.test.ts | 48 ++++++ nodejs/__test__/materialized_view.test.ts | 147 ++++++++++++++++ nodejs/__test__/remote.test.ts | 19 +++ nodejs/__test__/table.test.ts | 2 +- nodejs/lancedb/connection.ts | 70 ++++++++ nodejs/lancedb/index.ts | 6 + nodejs/lancedb/materialized_view.ts | 161 ++++++++++++++++++ nodejs/lancedb/table.ts | 20 +++ nodejs/src/connection.rs | 52 ++++++ nodejs/src/lib.rs | 4 + nodejs/src/table.rs | 45 +++++ 17 files changed, 867 insertions(+), 6 deletions(-) create mode 100644 docs/src/js/classes/MaterializedView.md create mode 100644 docs/src/js/interfaces/MaterializedViewDefinition.md create mode 100644 docs/src/js/interfaces/RefreshMaterializedViewResult.md create mode 100644 docs/src/js/type-aliases/MaterializedViewSelect.md create mode 100644 nodejs/__test__/materialized_view.test.ts create mode 100644 nodejs/lancedb/materialized_view.ts diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index e4cbc1e96..92cfd2568 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -169,6 +169,45 @@ Creates a new empty Table *** +### createMaterializedView() + +```ts +abstract createMaterializedView( + name, + source, + options?): Promise +``` + +Define a materialized view named `name` over the table `source`. + +The view is created empty, with the query recorded in its schema +metadata; `view.refresh()` computes the rows. The view is a normal +table: it can be queried, indexed and searched, and it appears in +`tableNames`. The source table must have stable row ids (create it with +the `newTableEnableStableRowIds` storage option); they keep the view's +provenance valid across source compactions and cannot be enabled after +a table exists. Local databases only. + +#### Parameters + +* **name**: `string` + +* **source**: `string` + +* **options?** + +* **options.limit?**: `number` + +* **options.select?**: [`MaterializedViewSelect`](../type-aliases/MaterializedViewSelect.md) + +* **options.where?**: `string` + +#### Returns + +`Promise`<[`MaterializedView`](MaterializedView.md)> + +*** + ### createNamespace() ```ts @@ -499,6 +538,22 @@ List server-side jobs across the database's tables. *** +### listMaterializedViews() + +```ts +abstract listMaterializedViews(): Promise +``` + +The names of the materialized views in this database. + +Found by reading every table's schema, so this costs an open per table. + +#### Returns + +`Promise`<`string`[]> + +*** + ### listNamespaces() ```ts @@ -529,6 +584,26 @@ Child namespace names and *** +### openMaterializedView() + +```ts +abstract openMaterializedView(name): Promise +``` + +Open the materialized view named `name`. + +Rejects a table that exists but is not a materialized view. + +#### Parameters + +* **name**: `string` + +#### Returns + +`Promise`<[`MaterializedView`](MaterializedView.md)> + +*** + ### openTable() ```ts @@ -538,18 +613,13 @@ abstract openTable( options?): Promise
``` -Open a table in the database. - #### Parameters * **name**: `string` - The name of the table * **namespacePath?**: `string`[] - The namespace path of the table (defaults to root namespace) * **options?**: `Partial`<[`OpenTableOptions`](../interfaces/OpenTableOptions.md)> - Additional options #### Returns diff --git a/docs/src/js/classes/MaterializedView.md b/docs/src/js/classes/MaterializedView.md new file mode 100644 index 000000000..e6ff66142 --- /dev/null +++ b/docs/src/js/classes/MaterializedView.md @@ -0,0 +1,101 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / MaterializedView + +# Class: MaterializedView + +A handle on a materialized view: its table plus its definition. + +Obtained from [Connection#createMaterializedView](Connection.md#creatematerializedview) or +[Connection#openMaterializedView](Connection.md#openmaterializedview). The view is a normal table -- +queries, indexes and search all apply through [MaterializedView#table](MaterializedView.md#table) +-- whose contents are maintained by [MaterializedView#refresh](MaterializedView.md#refresh). + +## Constructors + +### new MaterializedView() + +```ts +new MaterializedView(table): MaterializedView +``` + +#### Parameters + +* **table**: [`Table`](Table.md) + +#### Returns + +[`MaterializedView`](MaterializedView.md) + +## Accessors + +### name + +```ts +get name(): string +``` + +#### Returns + +`string` + +## Methods + +### definition() + +```ts +definition(): Promise +``` + +The query that defines the view, read from its stored schema. + +#### Returns + +`Promise`<[`MaterializedViewDefinition`](../interfaces/MaterializedViewDefinition.md)> + +*** + +### refresh() + +```ts +refresh(options?): Promise +``` + +Recompute the view from its source. + +The refresh is incremental when the source's changes can be reconciled +into the view -- rows added, changed or removed since the last one -- +and otherwise rebuilds. `full` forces a rebuild; `sourceVersion` +refreshes to that source version instead of the latest. + +Concurrent refreshes of one view do not duplicate its rows. Two that +plan the same source rows conflict on commit, and the loser throws +rather than writing them a second time. + +#### Parameters + +* **options?** + +* **options.full?**: `boolean` + +* **options.sourceVersion?**: `number` + +#### Returns + +`Promise`<[`RefreshMaterializedViewResult`](../interfaces/RefreshMaterializedViewResult.md)> + +*** + +### table() + +```ts +table(): Table +``` + +The view, as the table it is. + +#### Returns + +[`Table`](Table.md) diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 4deeed1bc..6a8f644eb 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -28,6 +28,7 @@ - [Job](classes/Job.md) - [MakeArrowTableOptions](classes/MakeArrowTableOptions.md) - [MatchQuery](classes/MatchQuery.md) +- [MaterializedView](classes/MaterializedView.md) - [MergeInsertBuilder](classes/MergeInsertBuilder.md) - [MultiMatchQuery](classes/MultiMatchQuery.md) - [NativeJsHeaderProvider](classes/NativeJsHeaderProvider.md) @@ -101,6 +102,7 @@ - [ListNamespacesResponse](interfaces/ListNamespacesResponse.md) - [LsmStats](interfaces/LsmStats.md) - [LsmWriteSpec](interfaces/LsmWriteSpec.md) +- [MaterializedViewDefinition](interfaces/MaterializedViewDefinition.md) - [MemtableStats](interfaces/MemtableStats.md) - [MergeResult](interfaces/MergeResult.md) - [NativeOAuthConfig](interfaces/NativeOAuthConfig.md) @@ -110,6 +112,7 @@ - [OptimizeStats](interfaces/OptimizeStats.md) - [QueryExecutionOptions](interfaces/QueryExecutionOptions.md) - [RefreshColumnResult](interfaces/RefreshColumnResult.md) +- [RefreshMaterializedViewResult](interfaces/RefreshMaterializedViewResult.md) - [RemovalStats](interfaces/RemovalStats.md) - [RenameTableOptions](interfaces/RenameTableOptions.md) - [RestNamespaceConfig](interfaces/RestNamespaceConfig.md) @@ -142,6 +145,7 @@ - [FieldLike](type-aliases/FieldLike.md) - [IntoSql](type-aliases/IntoSql.md) - [IntoVector](type-aliases/IntoVector.md) +- [MaterializedViewSelect](type-aliases/MaterializedViewSelect.md) - [MultiVector](type-aliases/MultiVector.md) - [RecordBatchLike](type-aliases/RecordBatchLike.md) - [SchemaLike](type-aliases/SchemaLike.md) diff --git a/docs/src/js/interfaces/MaterializedViewDefinition.md b/docs/src/js/interfaces/MaterializedViewDefinition.md new file mode 100644 index 000000000..741bbba31 --- /dev/null +++ b/docs/src/js/interfaces/MaterializedViewDefinition.md @@ -0,0 +1,59 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / MaterializedViewDefinition + +# Interface: MaterializedViewDefinition + +The query that defines a materialized view. + +## Properties + +### filter? + +```ts +optional filter: string; +``` + +SQL predicate selecting the source rows the view holds. + +*** + +### inputs + +```ts +inputs: string[]; +``` + +Source columns the projections and filter read. + +*** + +### limit? + +```ts +optional limit: number; +``` + +Cap on the number of rows the view holds. + +*** + +### projections + +```ts +projections: [string, string][]; +``` + +`[output column, SQL expression]` pairs, in view schema order. + +*** + +### sourceTable + +```ts +sourceTable: string; +``` + +Name of the source table, in the same database as the view. diff --git a/docs/src/js/interfaces/RefreshMaterializedViewResult.md b/docs/src/js/interfaces/RefreshMaterializedViewResult.md new file mode 100644 index 000000000..cb7100cd8 --- /dev/null +++ b/docs/src/js/interfaces/RefreshMaterializedViewResult.md @@ -0,0 +1,41 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / RefreshMaterializedViewResult + +# Interface: RefreshMaterializedViewResult + +## Properties + +### mode + +```ts +mode: string; +``` + +How the view was brought up to date: "rebuild", "incremental" or "no_op". + +*** + +### rowsWritten + +```ts +rowsWritten: number; +``` + +*** + +### sourceVersion + +```ts +sourceVersion: number; +``` + +*** + +### version + +```ts +version: number; +``` diff --git a/docs/src/js/type-aliases/MaterializedViewSelect.md b/docs/src/js/type-aliases/MaterializedViewSelect.md new file mode 100644 index 000000000..7b246e945 --- /dev/null +++ b/docs/src/js/type-aliases/MaterializedViewSelect.md @@ -0,0 +1,14 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / MaterializedViewSelect + +# Type Alias: MaterializedViewSelect + +```ts +type MaterializedViewSelect: (string | [string, string])[] | Record; +``` + +The view's columns: column names, `[alias, SQL expression]` pairs, or a +record of the same. A bare name projects itself. diff --git a/nodejs/__test__/embedding.test.ts b/nodejs/__test__/embedding.test.ts index 06184751e..2a8494e0f 100644 --- a/nodejs/__test__/embedding.test.ts +++ b/nodejs/__test__/embedding.test.ts @@ -487,4 +487,52 @@ describe("embedding functions", () => { expect(stringSchema3).toEqual(stringExpectedSchema); }, ); + test("parses one function writing several vector columns", async () => { + class MockEmbeddingFunction extends EmbeddingFunction { + ndims() { + return 3; + } + embeddingDataType(): Float { + return new Float32(); + } + async computeQueryEmbeddings(_data: string) { + return [1, 2, 3]; + } + async computeSourceEmbeddings(data: string[]) { + return Array.from({ length: data.length }).fill([ + 1, 2, 3, + ]) as number[][]; + } + } + const registry = getRegistry(); + registry.register("multi_output_mock")(MockEmbeddingFunction); + + // A materialized view can project one source vector column under two + // names, so a table's configuration names the same function twice. + const parsed = await registry.parseFunctions( + new Map([ + [ + "embedding_functions", + JSON.stringify([ + { + name: "multi_output_mock", + sourceColumn: "text", + vectorColumn: "vector_a", + model: {}, + }, + { + name: "multi_output_mock", + sourceColumn: "text", + vectorColumn: "vector_b", + model: {}, + }, + ]), + ], + ]), + ); + + expect( + [...parsed.values()].map(({ vectorColumn }) => vectorColumn).sort(), + ).toEqual(["vector_a", "vector_b"]); + }); }); diff --git a/nodejs/__test__/materialized_view.test.ts b/nodejs/__test__/materialized_view.test.ts new file mode 100644 index 000000000..2e7b2ec4d --- /dev/null +++ b/nodejs/__test__/materialized_view.test.ts @@ -0,0 +1,147 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import * as tmp from "tmp"; + +import { Connection, connect } from "../lancedb"; +import { + DEFINITION_META_KEY, + definitionFromMetadata, +} from "../lancedb/materialized_view"; + +describe("materialized views", () => { + let tmpDir: tmp.DirResult; + let db: Connection; + + beforeEach(async () => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + db = await connect(tmpDir.name); + await db.createTable( + "people", + [ + { name: "ada", age: 36 }, + { name: "kid", age: 7 }, + { name: "grace", age: 85 }, + ], + { storageOptions: { newTableEnableStableRowIds: "true" } }, + ); + }); + afterEach(() => tmpDir.removeCallback()); + + it("rejects a stored limit a number cannot carry", () => { + const big = new Map([ + [ + DEFINITION_META_KEY, + '{"kind":"select","source_table":"people","limit":9007199254740993}', + ], + ]); + expect(() => definitionFromMetadata(big, "v")).toThrow( + /too large to represent exactly/, + ); + + const safe = new Map([ + [ + DEFINITION_META_KEY, + '{"kind":"select","source_table":"people","limit":42}', + ], + ]); + expect(definitionFromMetadata(safe, "v").limit).toBe(42); + }); + + it("creates, refreshes and queries a view", async () => { + const view = await db.createMaterializedView("adults", "people", { + select: ["name", ["shout", "upper(name)"]], + where: "age >= 18", + }); + expect(view.name).toBe("adults"); + expect(await view.table().countRows()).toBe(0); + + const result = await view.refresh(); + expect(result.mode).toBe("rebuild"); + expect(Number(result.rowsWritten)).toBe(2); + + const rows = await view.table().query().toArray(); + expect(rows.map((r) => r.shout).sort()).toEqual(["ADA", "GRACE"]); + }); + + it("round-trips the definition", async () => { + await db.createMaterializedView("adults", "people", { + where: "age >= 18", + }); + const view = await db.openMaterializedView("adults"); + const definition = await view.definition(); + expect(definition.sourceTable).toBe("people"); + expect(definition.filter).toBe("age >= 18"); + expect(definition.projections).toEqual([ + ["name", "`name`"], + ["age", "`age`"], + ]); + expect(definition.inputs).toEqual(["age", "name"]); + }); + + it("refreshes incrementally after an append", async () => { + const view = await db.createMaterializedView("copy", "people"); + await view.refresh(); + + const people = await db.openTable("people"); + await people.add([{ name: "alan", age: 41 }]); + const result = await view.refresh(); + expect(result.mode).toBe("incremental"); + expect(Number(result.rowsWritten)).toBe(1); + expect(await view.table().countRows()).toBe(4); + + expect((await view.refresh()).mode).toBe("no_op"); + }); + + it("lists views and rejects non-views", async () => { + await db.createMaterializedView("adults", "people", { + where: "age >= 18", + }); + expect(await db.listMaterializedViews()).toEqual(["adults"]); + await expect(db.openMaterializedView("people")).rejects.toThrow( + "not a materialized view", + ); + }); + + it("rejects an invalid expression at create time", async () => { + await expect( + db.createMaterializedView("bad", "people", { + select: [["x", "missing + 1"]], + }), + ).rejects.toThrow("missing"); + }); + + it("rejects invalid numeric options before creating anything", async () => { + for (const limit of [-5, 1.5, Infinity, NaN]) { + await expect( + db.createMaterializedView("bad", "people", { limit }), + ).rejects.toThrow("non-negative integer"); + } + expect(await db.listMaterializedViews()).toEqual([]); + + const view = await db.createMaterializedView("copy", "people"); + for (const sourceVersion of [-1, 1.5, Infinity, NaN]) { + await expect(view.refresh({ sourceVersion })).rejects.toThrow( + "non-negative integer", + ); + } + }); + + it("quotes bare select names", async () => { + await db.createTable("odd_names", [{ "order item": "widget" }], { + storageOptions: { newTableEnableStableRowIds: "true" }, + }); + const view = await db.createMaterializedView("quoted", "odd_names", { + select: ["order item"], + }); + const result = await view.refresh(); + expect(Number(result.rowsWritten)).toBe(1); + }); + + it("requires stable row ids on the source", async () => { + await db.createTable("plain", [{ x: 1 }]); + await expect(db.createMaterializedView("v", "plain")).rejects.toThrow( + "stable row ids", + ); + }); +}); diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 01320d2b0..c51cbbbb7 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -75,6 +75,25 @@ async function withMockDatabase( } describe("remote connection", () => { + it("refuses materialized views before issuing any request", async () => { + const paths: string[] = []; + await withMockDatabase( + (req, res) => { + paths.push(req.url ?? ""); + res.writeHead(404).end(); + }, + async (db) => { + await expect(db.openMaterializedView("secret_table")).rejects.toThrow( + /only on local databases/, + ); + await expect(db.listMaterializedViews()).rejects.toThrow( + /only on local databases/, + ); + expect(paths).toEqual([]); + }, + ); + }); + 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 80c50f1ac..0f6ed3615 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -2953,7 +2953,7 @@ describe("column name options", () => { .limit(10) .toArray(); expect(results2.length).toBe(10); - }); + }, 30_000); }); describe("when creating an empty table", () => { diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index a81dc0442..e5528f8c6 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -16,6 +16,12 @@ import { makeEmptyTable, } from "./arrow"; import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry"; +import { + MaterializedView, + MaterializedViewSelect, + normalizeSelect, + validateNonNegativeInteger, +} from "./materialized_view"; import { Connection as LanceDbConnection } from "./native"; import type { CreateNamespaceResponse, @@ -247,6 +253,41 @@ export abstract class Connection { * @param {string[]} namespacePath - The namespace path of the table (defaults to root namespace) * @param {Partial} options - Additional options */ + /** + * Define a materialized view named `name` over the table `source`. + * + * The view is created empty, with the query recorded in its schema + * metadata; `view.refresh()` computes the rows. The view is a normal + * table: it can be queried, indexed and searched, and it appears in + * `tableNames`. The source table must have stable row ids (create it with + * the `newTableEnableStableRowIds` storage option); they keep the view's + * provenance valid across source compactions and cannot be enabled after + * a table exists. Local databases only. + */ + abstract createMaterializedView( + name: string, + source: string, + options?: { + select?: MaterializedViewSelect; + where?: string; + limit?: number; + }, + ): Promise; + + /** + * Open the materialized view named `name`. + * + * Rejects a table that exists but is not a materialized view. + */ + abstract openMaterializedView(name: string): Promise; + + /** + * The names of the materialized views in this database. + * + * Found by reading every table's schema, so this costs an open per table. + */ + abstract listMaterializedViews(): Promise; + abstract openTable( name: string, namespacePath?: string[], @@ -531,6 +572,35 @@ export class LocalConnection extends Connection { ); } + async createMaterializedView( + name: string, + source: string, + options?: { + select?: MaterializedViewSelect; + where?: string; + limit?: number; + }, + ): Promise { + validateNonNegativeInteger(options?.limit, "limit"); + const innerTable = await this.inner.createMaterializedView( + name, + source, + normalizeSelect(options?.select), + options?.where, + options?.limit, + ); + return new MaterializedView(new LocalTable(innerTable)); + } + + async openMaterializedView(name: string): Promise { + const innerTable = await this.inner.openMaterializedView(name); + return new MaterializedView(new LocalTable(innerTable)); + } + + async listMaterializedViews(): Promise { + return await this.inner.listMaterializedViews(); + } + async openTable( name: string, namespacePath?: string[], diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index aa9c7ef13..da13b434f 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -21,6 +21,11 @@ import type { BaseTokenizer } from "./indices"; import type { FtsToken } from "./table"; // Re-export native header provider for use with connectWithHeaderProvider +export { + MaterializedView, + MaterializedViewDefinition, + MaterializedViewSelect, +} from "./materialized_view"; export { JsHeaderProvider as NativeJsHeaderProvider } from "./native.js"; // OpenTelemetry metrics bridge. Only the high-level entry point is public; the @@ -51,6 +56,7 @@ export { AddResult, AddColumnsResult, RefreshColumnResult, + RefreshMaterializedViewResult, AlterColumnsResult, UpdateFieldMetadataResult, DeleteResult, diff --git a/nodejs/lancedb/materialized_view.ts b/nodejs/lancedb/materialized_view.ts new file mode 100644 index 000000000..b26dee59e --- /dev/null +++ b/nodejs/lancedb/materialized_view.ts @@ -0,0 +1,161 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { RefreshMaterializedViewResult } from "./native"; +import { Table } from "./table"; + +/** Schema metadata key holding a materialized view's definition. */ +export const DEFINITION_META_KEY = "mv.definition"; + +/** The query that defines a materialized view. */ +export interface MaterializedViewDefinition { + /** Name of the source table, in the same database as the view. */ + sourceTable: string; + /** `[output column, SQL expression]` pairs, in view schema order. */ + projections: [string, string][]; + /** SQL predicate selecting the source rows the view holds. */ + filter?: string; + /** Cap on the number of rows the view holds. */ + limit?: number; + /** Source columns the projections and filter read. */ + inputs: string[]; +} + +/** + * The view's columns: column names, `[alias, SQL expression]` pairs, or a + * record of the same. A bare name projects itself. + */ +export type MaterializedViewSelect = + | (string | [string, string])[] + | Record; + +/** + * @internal Reject a numeric option N-API would otherwise silently coerce: + * `Infinity` reaches Rust as 0, `1.5` as 1. + */ +export function validateNonNegativeInteger( + value: number | undefined, + name: string, +): void { + if (value !== undefined && !(Number.isSafeInteger(value) && value >= 0)) { + throw new Error(`${name} must be a non-negative integer`); + } +} + +/** @internal Quote a column name as a Lance SQL identifier (backticks). */ +function quoteIdentifier(name: string): string { + return "`" + name.replace(/`/g, "``") + "`"; +} + +/** + * @internal Normalize a select argument into `[alias, expression]` pairs. + * A bare name projects itself and is quoted, so any valid column name works; + * pair and record entries are kept verbatim because their right side is an + * expression. + */ +export function normalizeSelect( + select?: MaterializedViewSelect, +): [string, string][] | undefined { + if (select === undefined) { + return undefined; + } + if (Array.isArray(select)) { + return select.map((item) => + typeof item === "string" ? [item, quoteIdentifier(item)] : item, + ); + } + return Object.entries(select); +} + +/** @internal Parse a definition off a table's stored schema metadata. */ +export function definitionFromMetadata( + metadata: Map, + name: string, +): MaterializedViewDefinition { + const raw = metadata.get(DEFINITION_META_KEY); + if (raw === undefined) { + throw new Error(`Table '${name}' is not a materialized view`); + } + // biome-ignore lint/suspicious/noExplicitAny: raw JSON + const value: any = JSON.parse(raw); + if (value.kind !== "select") { + throw new Error( + `materialized view '${name}' is defined by '${value.kind}', which this ` + + "version of lancedb cannot refresh", + ); + } + const limit = value.limit ?? undefined; + // JSON.parse rounds integers past 2^53; every exact u64 parses to a safe + // integer and every rounded one does not, so this rejects precisely the + // values a number cannot carry. + if (limit !== undefined && !Number.isSafeInteger(limit)) { + throw new Error( + `materialized view '${name}' has a stored limit too large to represent exactly`, + ); + } + return { + sourceTable: value.source_table, + // biome-ignore lint/suspicious/noExplicitAny: raw JSON + projections: (value.projections ?? []).map((p: any) => [ + p.output, + p.expression, + ]), + filter: value.filter ?? undefined, + limit, + inputs: value.inputs ?? [], + }; +} + +/** + * A handle on a materialized view: its table plus its definition. + * + * Obtained from {@link Connection#createMaterializedView} or + * {@link Connection#openMaterializedView}. The view is a normal table -- + * queries, indexes and search all apply through {@link MaterializedView#table} + * -- whose contents are maintained by {@link MaterializedView#refresh}. + */ +export class MaterializedView { + private readonly inner: Table; + + constructor(table: Table) { + this.inner = table; + } + + get name(): string { + return this.inner.name; + } + + /** The view, as the table it is. */ + table(): Table { + return this.inner; + } + + /** The query that defines the view, read from its stored schema. */ + async definition(): Promise { + const schema = await this.inner.schema(); + return definitionFromMetadata(schema.metadata, this.name); + } + + /** + * Recompute the view from its source. + * + * The refresh is incremental when the source's changes can be reconciled + * into the view -- rows added, changed or removed since the last one -- + * and otherwise rebuilds. `full` forces a rebuild; `sourceVersion` + * refreshes to that source version instead of the latest. + * + * Concurrent refreshes of one view do not duplicate its rows. Two that + * plan the same source rows conflict on commit, and the loser throws + * rather than writing them a second time. + */ + async refresh(options?: { + full?: boolean; + sourceVersion?: number; + }): Promise { + validateNonNegativeInteger(options?.sourceVersion, "sourceVersion"); + return await this.inner.refreshMaterializedView( + options?.full, + options?.sourceVersion, + ); + } +} diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 4e323ec64..28603cca9 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -35,6 +35,7 @@ import { Branches as NativeBranches, OptimizeStats, RefreshColumnResult, + RefreshMaterializedViewResult, TableStatistics, Tags, UpdateFieldMetadataResult, @@ -602,6 +603,18 @@ export abstract class Table { */ abstract refreshColumnAsync(column: string): Promise; + /** + * Recompute this table's contents from its materialized-view definition. + * + * Plumbing for {@link MaterializedView.refresh}, which is the way to call + * it: rejects tables that carry no view definition. Local tables only. + * @ignore + */ + abstract refreshMaterializedView( + full?: boolean, + sourceVersion?: number, + ): Promise; + /** * Alter the name or nullability of columns. * @param {ColumnAlteration[]} columnAlterations One or more alterations to @@ -1264,6 +1277,13 @@ export class LocalTable extends Table { return await this.inner.refreshColumnAsync(column); } + async refreshMaterializedView( + full?: boolean, + sourceVersion?: number, + ): Promise { + return await this.inner.refreshMaterializedView(full, sourceVersion); + } + async alterColumns( columnAlterations: ColumnAlteration[], ): Promise { diff --git a/nodejs/src/connection.rs b/nodejs/src/connection.rs index c9f5e10ea..44eb68f32 100644 --- a/nodejs/src/connection.rs +++ b/nodejs/src/connection.rs @@ -266,6 +266,58 @@ impl Connection { Ok(Table::new(tbl)) } + #[napi(catch_unwind)] + pub async fn create_materialized_view( + &self, + name: String, + source: String, + projections: Option>>, + filter: Option, + limit: Option, + ) -> napi::Result
{ + let mut builder = self.get_inner()?.create_materialized_view(name, source); + if let Some(projections) = projections { + let mut pairs = Vec::with_capacity(projections.len()); + for pair in projections { + let [output, expression]: [String; 2] = pair.try_into().map_err(|_| { + napi::Error::from_reason("each projection must be an [output, expression] pair") + })?; + pairs.push((output, expression)); + } + builder = builder.select(pairs); + } + if let Some(filter) = filter { + builder = builder.only_if(filter); + } + if let Some(limit) = limit { + let limit = u64::try_from(limit) + .map_err(|_| napi::Error::from_reason("limit must be a non-negative integer"))?; + builder = builder.limit(limit); + } + let view = builder.execute().await.default_error()?; + Ok(Table::new(view.table().clone())) + } + + #[napi(catch_unwind)] + pub async fn open_materialized_view(&self, name: String) -> napi::Result
{ + let view = self + .get_inner()? + .open_materialized_view(&name) + .await + .default_error()?; + Ok(Table::new(view.table().clone())) + } + + #[napi(catch_unwind)] + pub async fn list_materialized_views(&self) -> napi::Result> { + let views = self + .get_inner()? + .list_materialized_views() + .await + .default_error()?; + Ok(views.into_iter().map(|v| v.name).collect()) + } + #[napi(catch_unwind)] pub async fn open_table( &self, diff --git a/nodejs/src/lib.rs b/nodejs/src/lib.rs index 312b675bd..1110f6203 100644 --- a/nodejs/src/lib.rs +++ b/nodejs/src/lib.rs @@ -1,6 +1,10 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +// The materialized-view refresh future deepens the type graph past the +// default trait-recursion depth; same raise as the core crate applies. +#![recursion_limit = "256"] + use std::collections::HashMap; use env_logger::Env; diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 694b6a704..9d60b2056 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -381,6 +381,26 @@ impl Table { Ok(crate::job::Job::new(job)) } + #[napi(catch_unwind)] + pub async fn refresh_materialized_view( + &self, + full: Option, + source_version: Option, + ) -> napi::Result { + let view = lancedb::MaterializedView::from_table(self.inner_ref()?.clone()) + .await + .default_error()?; + let mut builder = view.refresh().full(full.unwrap_or(false)); + if let Some(version) = source_version { + let version = u64::try_from(version).map_err(|_| { + napi::Error::from_reason("sourceVersion must be a non-negative integer") + })?; + builder = builder.source_version(version); + } + let result = builder.execute().await.default_error()?; + Ok(result.into()) + } + #[napi(catch_unwind)] pub async fn add_columns_with_schema( &self, @@ -1387,6 +1407,31 @@ pub struct RefreshColumnResult { pub version: i64, } +#[napi(object)] +pub struct RefreshMaterializedViewResult { + /// How the view was brought up to date: "rebuild", "incremental" or "no_op". + pub mode: String, + pub rows_written: i64, + pub source_version: i64, + pub version: i64, +} + +impl From for RefreshMaterializedViewResult { + fn from(value: lancedb::RefreshMaterializedViewResult) -> Self { + let mode = match value.mode { + lancedb::RefreshMode::Rebuild => "rebuild", + lancedb::RefreshMode::Incremental => "incremental", + lancedb::RefreshMode::NoOp => "no_op", + }; + Self { + mode: mode.to_string(), + rows_written: value.rows_written as i64, + source_version: value.source_version as i64, + version: value.version as i64, + } + } +} + impl From for RefreshColumnResult { fn from(value: lancedb::table::RefreshColumnResult) -> Self { Self { From 45cd05347846bc2280103680e497e8fc0cdf480e Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sat, 22 Aug 2026 16:38:08 +0000 Subject: [PATCH 093/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.3=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package-lock.json | 4 ++-- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index b1d2bf1dc..bba238f96 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.3" +current_version = "0.38.0-beta.4" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 5947187cc..87fec3378 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5398,7 +5398,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.3" +version = "0.38.0-beta.4" dependencies = [ "ahash", "anyhow", @@ -5486,7 +5486,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.3" +version = "0.38.0-beta.4" dependencies = [ "arrow-array", "arrow-buffer", @@ -5511,7 +5511,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.3" +version = "0.38.0-beta.4" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index a8869d319..cff4cf2f5 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.38.0-beta.3 + 0.38.0-beta.4 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 9de14d1f9..98c10ca38 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.3 + 0.38.0-beta.4 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 36ec01d9e..56366bb15 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.3 + 0.38.0-beta.4 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index cba7012d1..99aed2e71 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.3" +version = "0.38.0-beta.4" 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 3c76481fc..c84b83c45 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.38.0-beta.3", + "version": "0.38.0-beta.4", "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 7a1a3af03..52f2b7901 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.38.0-beta.3", + "version": "0.38.0-beta.4", "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 7175233af..afa7fac32 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.38.0-beta.3", + "version": "0.38.0-beta.4", "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 add5a1da2..36cfa0343 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.38.0-beta.3", + "version": "0.38.0-beta.4", "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 72a82bf6d..23ea473ef 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.38.0-beta.3", + "version": "0.38.0-beta.4", "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 c69beeb8a..880b65540 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.38.0-beta.3", + "version": "0.38.0-beta.4", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index d21fc1eb3..8cc40de7b 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.38.0-beta.3", + "version": "0.38.0-beta.4", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index 1c368dab5..dba3ede7c 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.3", + "version": "0.38.0-beta.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.3", + "version": "0.38.0-beta.4", "cpu": [ "x64", "arm64" diff --git a/nodejs/package.json b/nodejs/package.json index 7f72eb8b0..c2f5be2c8 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.3", + "version": "0.38.0-beta.4", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index ddc13b69f..dace5aa7c 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.3" +version = "0.38.0-beta.4" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index f785e6743..2920498b1 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.3" +version = "0.38.0-beta.4" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 1f1d03f306c322c42df93a42eb064225b0206f20 Mon Sep 17 00:00:00 2001 From: Weston Pace Date: Sun, 23 Aug 2026 00:28:07 -0700 Subject: [PATCH 094/206] feat(python): add backpressure to StreamingDataset post-transform queue (#3897) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rename prefetch_batches → io_queue_depth and introduce transform_queue_depth as a symmetric pair: both express "number of batches to buffer per split at this pipeline stage." The old names are still accepted as keyword arguments but log a deprecation warning redirecting callers to the new names. transform_queue_depth caps how many transform-result batches can accumulate per split in the post-transform queue. Without this limit a slow consumer (e.g. a GPU training step) causes cooked rows to pile up unboundedly. The backpressure check in _try_submit_tx counts both already-cooked rows and rows expected from in-flight transforms; it skips proactive transform submission when the combined total reaches the limit. The reactive _ensure_cooked path bypasses the check so the consumer never stalls. --------- Co-authored-by: Claude Sonnet 4.6 --- python/python/lancedb/streaming.py | 65 +++++- .../python/tests/test_elastic_dataloader.py | 186 +++++++++++++++++- 2 files changed, 239 insertions(+), 12 deletions(-) diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py index b27e606a4..6951fa0bc 100644 --- a/python/python/lancedb/streaming.py +++ b/python/python/lancedb/streaming.py @@ -61,7 +61,7 @@ class StreamingDataset(IterableDataset): Internally ``__iter__`` runs a two-stage pipeline: - - **Stage 1 (I/O)**: one thread pool with ``num_splits * prefetch_batches`` + - **Stage 1 (I/O)**: one thread pool with ``num_splits * io_queue_depth`` workers fetches raw ``RecordBatch`` objects from LanceDB in parallel across all splits and places them in a per-split raw-batch queue. - **Stage 2 (transform)**: a second thread pool with @@ -104,11 +104,11 @@ class StreamingDataset(IterableDataset): call. Larger values amortise per-request overhead (critical on object storage) at the cost of higher memory usage per split buffer. Defaults to ``DEFAULT_READ_BATCH_SIZE`` (64). - prefetch_batches: + io_queue_depth: Number of I/O batches to keep in flight per split. Higher values overlap storage latency with transform and training compute at the cost - of more memory and threads. Defaults to ``DEFAULT_PREFETCH_BATCHES`` - (4). + of more memory and threads. Must be greater than zero. Defaults to + ``DEFAULT_PREFETCH_BATCHES`` (4). columns: Optional list of column names to read. When set, only those columns are fetched from storage; all others are omitted. ``None`` (the @@ -175,6 +175,16 @@ class StreamingDataset(IterableDataset): Prefer the ``filter`` parameter when bad rows can be expressed as a SQL predicate (e.g. ``"col IS NOT NULL"``) — filtering happens before splits are built, so every guarantee is fully preserved. + transform_queue_depth: + Number of transform-result batches to buffer per split in the + post-transform queue before backpressure is applied to the transform + stage. When the combined count of in-flight transform futures and + already-buffered rows for a split reaches + ``transform_queue_depth * read_batch_size``, no new transforms are + submitted for that split until the consumer catches up. Useful for + capping peak memory when the consumer (e.g. a GPU training step) is + slower than the transform stage. Must be greater than zero. + ``None`` (the default) imposes no limit. worker_info_override: If set, used in place of ``torch.utils.data.get_worker_info()`` to determine the DataLoader worker assignment. Intended for unit tests @@ -194,17 +204,26 @@ class StreamingDataset(IterableDataset): rank: int = 0, world_size: int = 1, read_batch_size: int = DEFAULT_READ_BATCH_SIZE, - prefetch_batches: int = DEFAULT_PREFETCH_BATCHES, + io_queue_depth: int = DEFAULT_PREFETCH_BATCHES, columns: Optional[list[str]] = None, shuffle_clump_size: Optional[int] = None, filter: Optional[str] = None, transform: Optional[Callable] = None, transform_parallelism: Optional[int] = None, on_transform_error: Union[str, Callable[[Exception], bool]] = "raise", + transform_queue_depth: Optional[int] = None, connection_factory: Optional[Callable[[str], Any]] = None, worker_info_override=None, + # Deprecated; use io_queue_depth instead. + prefetch_batches: Optional[int] = None, ): super().__init__() + if prefetch_batches is not None: + logger.warning( + "prefetch_batches is deprecated and will be removed in a future " + "version; use io_queue_depth instead" + ) + io_queue_depth = prefetch_batches if num_splits is None: num_splits = world_size if shuffle_seed is None: @@ -214,6 +233,8 @@ class StreamingDataset(IterableDataset): f"num_splits ({num_splits}) must be divisible by " f"world_size ({world_size})" ) + if io_queue_depth <= 0: + raise ValueError("io_queue_depth must be greater than 0") if transform_parallelism is not None and transform_parallelism <= 0: raise ValueError("transform_parallelism must be greater than 0") if on_transform_error not in ("raise", "skip", "warn") and not callable( @@ -223,6 +244,8 @@ class StreamingDataset(IterableDataset): "on_transform_error must be 'raise', 'skip', 'warn', or a " f"callable, got {on_transform_error!r}" ) + if transform_queue_depth is not None and transform_queue_depth <= 0: + raise ValueError("transform_queue_depth must be greater than 0") self._table = table self._num_splits = num_splits @@ -232,13 +255,14 @@ class StreamingDataset(IterableDataset): self._rank = rank self._world_size = world_size self._read_batch_size = read_batch_size - self._prefetch_batches = prefetch_batches + self._io_queue_depth = io_queue_depth self._columns = columns self._shuffle_clump_size = shuffle_clump_size self._filter = filter self._transform = transform self._transform_parallelism = transform_parallelism self._on_transform_error = on_transform_error + self._transform_queue_depth = transform_queue_depth self._connection_factory = connection_factory self._worker_info_override = worker_info_override @@ -365,7 +389,7 @@ class StreamingDataset(IterableDataset): pos_consumed = list(initial_positions) batch_size = self._read_batch_size - max_prefetch = self._prefetch_batches + io_queue_depth = self._io_queue_depth transform_workers = ( self._transform_parallelism if self._transform_parallelism is not None @@ -374,6 +398,13 @@ class StreamingDataset(IterableDataset): final_transform = ( self._transform if self._transform is not None else Transforms.arrow2python ) + # None means no limit; otherwise cap rows per split to + # transform_queue_depth batches worth (including in-flight transforms). + max_cooked_rows = ( + self._transform_queue_depth * batch_size + if self._transform_queue_depth is not None + else None + ) # Per-split pipeline state. Batches are paired with the absolute # permutation position of their first row so that skipped rows can be @@ -409,7 +440,9 @@ class StreamingDataset(IterableDataset): io_pending[i].append((abs_start, io_pool.submit(_io_call, perm_i, indices))) def _fill_io(i: int) -> None: - while len(io_pending[i]) < max_prefetch and fetch_head[i] < split_sizes[i]: + while ( + len(io_pending[i]) < io_queue_depth and fetch_head[i] < split_sizes[i] + ): _submit_io(i) def _drain_io(i: int) -> None: @@ -487,7 +520,19 @@ class StreamingDataset(IterableDataset): def _try_submit_tx(i: int) -> None: """Submit transforms for raw_batches[i] up to available capacity.""" - while raw_batches[i] and tx_semaphore.acquire(blocking=False): + while raw_batches[i]: + # Backpressure: only submit a new transform when there is room + # for a full batch in the post-transform queue. Checking for + # a full batch prevents submitting a transform that would + # overflow the limit mid-batch (e.g. 990 rows queued with a + # capacity of 1000 and a batch_size of 128 must wait until + # 128 rows have been consumed, not just 1). + if max_cooked_rows is not None: + in_pipeline = len(cooked[i]) + len(tx_pending[i]) * batch_size + if in_pipeline + batch_size > max_cooked_rows: + break + if not tx_semaphore.acquire(blocking=False): + break abs_start, batch = raw_batches[i].popleft() tx_pending[i].append(tx_pool.submit(_tx_call_guarded, abs_start, batch)) @@ -531,7 +576,7 @@ class StreamingDataset(IterableDataset): # ── Main loop ───────────────────────────────────────────────────────── - with ThreadPoolExecutor(max_workers=n * max_prefetch) as io_pool: + with ThreadPoolExecutor(max_workers=n * io_queue_depth) as io_pool: with ThreadPoolExecutor(max_workers=transform_workers) as tx_pool: self._raw_batches_ref = raw_batches self._cooked_ref = cooked diff --git a/python/python/tests/test_elastic_dataloader.py b/python/python/tests/test_elastic_dataloader.py index 0c1a70765..4d860a5de 100644 --- a/python/python/tests/test_elastic_dataloader.py +++ b/python/python/tests/test_elastic_dataloader.py @@ -1374,6 +1374,188 @@ def test_transform_parallelism_must_be_positive(lance_table, transform_paralleli ) +# --------------------------------------------------------------------------- +# Backpressure / transform_queue_depth tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("transform_queue_depth", [0, -1]) +def test_transform_queue_depth_must_be_positive(lance_table, transform_queue_depth): + """transform_queue_depth=0 or negative must raise ValueError.""" + with pytest.raises( + ValueError, match="transform_queue_depth must be greater than 0" + ): + StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + transform_queue_depth=transform_queue_depth, + ) + + +@pytest.mark.parametrize("transform_queue_depth", [1, 2, 4]) +def test_transform_queue_depth_correctness(lance_table, transform_queue_depth): + """With backpressure enabled, every row is still yielded exactly once.""" + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + transform_queue_depth=transform_queue_depth, + read_batch_size=8, + ) + items = list(ds) + assert sorted(item["id"] for item in items) == list(range(NUM_ROWS)) + + +def test_transform_queue_depth_matches_no_backpressure(lance_table): + """With backpressure enabled the same samples are produced as without it.""" + ds_unlimited = StreamingDataset( + lance_table, num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED + ) + ds_limited = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + transform_queue_depth=1, + ) + assert [item["id"] for item in ds_unlimited] == [ + item["id"] for item in ds_limited + ], "transform_queue_depth must not affect the sample ordering or set" + + +def test_transform_queue_depth_bounds_cooked_rows(lance_table): + """prefetch_queue_depth stays within transform_queue_depth * read_batch_size + per split when observed from the main thread during iteration.""" + n_splits = 4 + batch_size = 8 + cooked_depth = 2 + # max cooked rows across all 4 splits: 4 * 2 * 8 = 64 + max_allowed = n_splits * cooked_depth * batch_size + + ds = StreamingDataset( + lance_table, + num_splits=n_splits, + shuffle_seed=SHUFFLE_SEED, + transform_queue_depth=cooked_depth, + read_batch_size=batch_size, + transform_parallelism=1, + world_size=1, + ) + + peak = 0 + for _ in ds: + depth = ds.prefetch_queue_depth + if depth > peak: + peak = depth + + # The main thread observes depth *after* popping a row, so the peak is at + # most max_allowed (one row already popped from the split just served). + assert peak <= max_allowed, ( + f"prefetch_queue_depth peaked at {peak}, expected <= {max_allowed}" + ) + + +def test_transform_queue_depth_does_not_admit_at_capacity_minus_one(tmp_path): + """Admission requires a full read_batch_size of free space, not just one slot. + + The test intercepts ThreadPoolExecutor.submit to make I/O calls execute + synchronously on the main thread. This ensures all raw batches land in + raw_batches (via _drain_io) before _try_submit_tx evaluates the admission + predicate for the first time. Without this, the I/O future for batch N+1 + might still be in io_pending at the capacity-minus-one transition, leaving + raw_batches empty and causing _try_submit_tx to skip the admission check + entirely — so both the correct and the broken predicate produce depth=0 + observations and the test cannot distinguish them. + + With all raw batches pre-loaded in raw_batches the 4→3 cooked transition + (consuming one row from a full cooked queue) always triggers _try_submit_tx + against a non-empty raw_batches. + + With transform_queue_depth=1 and batch_size=4, max_cooked_rows=4. + A transform may only be submitted when in_pipeline + batch_size <= 4, i.e. + when in_pipeline == 0 (cooked is completely empty). Under the old broken + predicate (in_pipeline >= max_cooked_rows) the second transform would be + admitted with cooked containing batch_size-1 rows still unconsumed. + """ + import concurrent.futures as cf + from concurrent.futures import ThreadPoolExecutor + from unittest.mock import patch + + db = lancedb.connect(tmp_path) + batch_size = 4 + # Four full batches → four transform submissions to observe. + table = db.create_table("t", pa.table({"id": list(range(batch_size * 4))})) + + cooked_at_submit: list[int] = [] + + original_submit = ThreadPoolExecutor.submit + + def tracking_submit(self, fn, *args, **kwargs): + name = getattr(fn, "__name__", "") + if name == "_io_call": + # Run I/O synchronously on the calling (main) thread and return an + # already-completed Future. _drain_io checks fut.done(), so a + # completed Future is moved to raw_batches immediately on the next + # _advance call — making raw-batch readiness deterministic at the + # capacity-minus-one transition instead of depending on I/O thread + # scheduling. + fut = cf.Future() + try: + fut.set_result(fn(*args, **kwargs)) + except Exception as exc: + fut.set_exception(exc) + return fut + if name == "_tx_call_guarded": + # Capture cooked depth synchronously on the main thread before the + # transform worker can drain the queue. + ref = ds._cooked_ref + cooked_at_submit.append(len(ref[0]) if ref is not None else -1) + return original_submit(self, fn, *args, **kwargs) + + with patch.object(ThreadPoolExecutor, "submit", tracking_submit): + ds = StreamingDataset( + table, + num_splits=1, + shuffle_seed=42, + read_batch_size=batch_size, + transform_queue_depth=1, + transform_parallelism=1, + ) + list(ds) + + assert len(cooked_at_submit) == 4, ( + f"Expected 4 transform submissions (one per batch), got {len(cooked_at_submit)}" + ) + # With full-batch backpressure each transform is only admitted when the + # cooked queue is completely empty (depth == 0). The old broken predicate + # would admit at depth == batch_size - 1 == 3. + assert all(depth == 0 for depth in cooked_at_submit), ( + "Transform admitted with non-empty cooked queue; full-batch backpressure " + "requires in_pipeline + batch_size <= max_cooked_rows before admission. " + f"Cooked depths at each submission: {cooked_at_submit}" + ) + + +# --------------------------------------------------------------------------- +# Deprecated parameter name tests +# --------------------------------------------------------------------------- + + +def test_prefetch_batches_deprecated_warns(lance_table, caplog): + """prefetch_batches logs a deprecation warning and behaves like io_queue_depth.""" + with caplog.at_level(logging.WARNING, logger="lancedb.streaming"): + ds = StreamingDataset( + lance_table, + num_splits=NUM_SPLITS, + shuffle_seed=SHUFFLE_SEED, + prefetch_batches=2, + ) + messages = [r.message for r in caplog.records if r.levelno >= logging.WARNING] + assert any("deprecated" in m.lower() and "io_queue_depth" in m for m in messages), ( + f"Expected deprecation warning mentioning io_queue_depth; got: {messages}" + ) + assert sorted(item["id"] for item in ds) == list(range(NUM_ROWS)) + + def test_filter_limits_rows(tmp_path): """A filter expression is applied to the permutation so only matching rows are yielded. IDs 0..59 pass ``id < 60``; the other 60 are excluded.""" @@ -1954,7 +2136,7 @@ def test_doc_example_basic(tmp_path): def test_doc_example_prefetch_params(tmp_path): - """doc: Prefetching — read_batch_size and prefetch_batches still cover all rows.""" + """doc: Prefetching — read_batch_size and io_queue_depth still cover all rows.""" db = lancedb.connect(tmp_path) table = db.create_table("t", pa.table({"id": list(range(NUM_ROWS))})) @@ -1963,7 +2145,7 @@ def test_doc_example_prefetch_params(tmp_path): num_splits=NUM_SPLITS, shuffle_seed=SHUFFLE_SEED, read_batch_size=8, - prefetch_batches=2, + io_queue_depth=2, ) assert sorted(s["id"] for s in ds) == list(range(NUM_ROWS)) From 6cc77b573c0013e4d36205d1fee42f03972ae29a Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Sun, 23 Aug 2026 00:53:14 -0700 Subject: [PATCH 095/206] chore: update lance dependency to v11.0.0-beta.21 (#4029) Updates the Rust workspace and Java `lance-core` dependency to Lance v11.0.0-beta.21. No compatibility fixes were required; workspace Clippy passes with warnings denied. Triggering tag: https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.21 --- Cargo.lock | 84 ++++++++++++++++++++++++++-------------------------- Cargo.toml | 28 +++++++++--------- java/pom.xml | 2 +- 3 files changed, 57 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 87fec3378..804b5c8d6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow", "arrow-array", @@ -5013,8 +5013,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow", "arrow-array", @@ -5031,8 +5031,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "proc-macro2", "quote", @@ -5041,8 +5041,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow-arith", "arrow-array", @@ -5075,8 +5075,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow-arith", "arrow-array", @@ -5107,8 +5107,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arc-swap", "arrow", @@ -5172,8 +5172,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow-array", "arrow-schema", @@ -5195,8 +5195,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow", "arrow-array", @@ -5232,8 +5232,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow-array", "arrow-schema", @@ -5247,8 +5247,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow", "async-trait", @@ -5260,8 +5260,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow", "arrow-ipc", @@ -5314,8 +5314,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow-array", "arrow-buffer", @@ -5329,8 +5329,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow", "arrow-array", @@ -5370,8 +5370,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "arrow-array", "arrow-schema", @@ -5384,8 +5384,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.19" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.19#3128c0024427cb5bf8c04d492893ae45e78b0511" +version = "11.0.0-beta.21" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index c147b06db..d45fe9a68 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.19", default-features = false, "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.19", default-features = false, "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.19", default-features = false, "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.19", "tag" = "v11.0.0-beta.19", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.21", default-features = false, "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.21", default-features = false, "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.21", default-features = false, "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index 56366bb15..e53ad869f 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.19 + 11.0.0-beta.21 false 2.30.0 1.7 From 1b950188c3dc73383707fbab1ce85d4679787e07 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 23 Aug 2026 08:07:09 +0000 Subject: [PATCH 096/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.4=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package-lock.json | 4 ++-- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index bba238f96..daaec8171 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.4" +current_version = "0.38.0-beta.5" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 804b5c8d6..f83e81dc3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5398,7 +5398,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.4" +version = "0.38.0-beta.5" dependencies = [ "ahash", "anyhow", @@ -5486,7 +5486,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.4" +version = "0.38.0-beta.5" dependencies = [ "arrow-array", "arrow-buffer", @@ -5511,7 +5511,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.4" +version = "0.38.0-beta.5" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index cff4cf2f5..b39c2dafb 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.38.0-beta.4 + 0.38.0-beta.5 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 98c10ca38..7ebcb5743 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.4 + 0.38.0-beta.5 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index e53ad869f..10dc4c78c 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.4 + 0.38.0-beta.5 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 99aed2e71..527715d8c 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.4" +version = "0.38.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 c84b83c45..42e5bd09c 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.38.0-beta.4", + "version": "0.38.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 52f2b7901..d01e72d4e 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.38.0-beta.4", + "version": "0.38.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 afa7fac32..6c57484cf 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.38.0-beta.4", + "version": "0.38.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 36cfa0343..50a02b0de 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.38.0-beta.4", + "version": "0.38.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 23ea473ef..c8257452f 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.38.0-beta.4", + "version": "0.38.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 880b65540..cd98d84d4 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.38.0-beta.4", + "version": "0.38.0-beta.5", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 8cc40de7b..1fda855df 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.38.0-beta.4", + "version": "0.38.0-beta.5", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index dba3ede7c..429845ba8 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.4", + "version": "0.38.0-beta.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.4", + "version": "0.38.0-beta.5", "cpu": [ "x64", "arm64" diff --git a/nodejs/package.json b/nodejs/package.json index c2f5be2c8..a82757bff 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.4", + "version": "0.38.0-beta.5", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index dace5aa7c..d88a25257 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.4" +version = "0.38.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 2920498b1..439c9613b 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.4" +version = "0.38.0-beta.5" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 000e3b506b58ba71e4f0d43d1f5812006c696257 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Sun, 23 Aug 2026 10:31:32 -0700 Subject: [PATCH 097/206] chore: update lance dependency to v11.0.0-beta.22 (#4036) Updates the Rust workspace Lance dependencies and Java lance-core dependency to v11.0.0-beta.22, including the refreshed Cargo lockfile. No compatibility fixes were required; see the [Lance tag](https://github.com/lance-format/lance/releases/tag/v11.0.0-beta.22). --- Cargo.lock | 88 +++++++++++++++++++++++++++------------------------- Cargo.toml | 28 ++++++++--------- java/pom.xml | 2 +- 3 files changed, 61 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f83e81dc3..89e4a1e30 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow", "arrow-array", @@ -5013,8 +5013,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow", "arrow-array", @@ -5031,8 +5031,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "proc-macro2", "quote", @@ -5041,8 +5041,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow-arith", "arrow-array", @@ -5075,8 +5075,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow-arith", "arrow-array", @@ -5107,8 +5107,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arc-swap", "arrow", @@ -5172,8 +5172,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow-array", "arrow-schema", @@ -5195,8 +5195,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow", "arrow-array", @@ -5222,7 +5222,11 @@ dependencies = [ "pin-project", "prost", "rand 0.9.5", + "reqsign-core", + "reqsign-file-read-tokio", + "reqsign-google", "serde", + "serde_json", "tempfile", "tokio", "tracing", @@ -5232,8 +5236,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow-array", "arrow-schema", @@ -5247,8 +5251,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow", "async-trait", @@ -5260,8 +5264,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow", "arrow-ipc", @@ -5314,8 +5318,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow-array", "arrow-buffer", @@ -5329,8 +5333,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow", "arrow-array", @@ -5370,8 +5374,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "arrow-array", "arrow-schema", @@ -5384,8 +5388,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.21" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.21#dd08336cf61b117701a7f5bbf76a7f7080f7e210" +version = "11.0.0-beta.22" +source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index d45fe9a68..716b14d7a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.21", default-features = false, "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.21", default-features = false, "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.21", default-features = false, "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.21", "tag" = "v11.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0-beta.22", default-features = false, "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=11.0.0-beta.22", default-features = false, "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=11.0.0-beta.22", default-features = false, "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index 10dc4c78c..a6b1ced24 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.21 + 11.0.0-beta.22 false 2.30.0 1.7 From 40d4d012e760ba0cc0bb9033ac9bf67fd1b83c43 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 23 Aug 2026 17:32:40 +0000 Subject: [PATCH 098/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.5=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package-lock.json | 4 ++-- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index daaec8171..f5f981b2c 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.5" +current_version = "0.38.0-beta.6" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 89e4a1e30..6c6dd4aea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.5" +version = "0.38.0-beta.6" dependencies = [ "ahash", "anyhow", @@ -5490,7 +5490,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.5" +version = "0.38.0-beta.6" dependencies = [ "arrow-array", "arrow-buffer", @@ -5515,7 +5515,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.5" +version = "0.38.0-beta.6" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index b39c2dafb..d6c285fc3 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.38.0-beta.5 + 0.38.0-beta.6 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 7ebcb5743..23d58124d 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.5 + 0.38.0-beta.6 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index a6b1ced24..a07414ec0 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.5 + 0.38.0-beta.6 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 527715d8c..ead873855 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.5" +version = "0.38.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 42e5bd09c..d89eb5ad1 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.38.0-beta.5", + "version": "0.38.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 d01e72d4e..1721c970e 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.38.0-beta.5", + "version": "0.38.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 6c57484cf..177804dce 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.38.0-beta.5", + "version": "0.38.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 50a02b0de..9af443583 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.38.0-beta.5", + "version": "0.38.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 c8257452f..c98aa3812 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.38.0-beta.5", + "version": "0.38.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 cd98d84d4..05b1086f5 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.38.0-beta.5", + "version": "0.38.0-beta.6", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 1fda855df..50432bdea 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.38.0-beta.5", + "version": "0.38.0-beta.6", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index 429845ba8..219025534 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.5", + "version": "0.38.0-beta.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.5", + "version": "0.38.0-beta.6", "cpu": [ "x64", "arm64" diff --git a/nodejs/package.json b/nodejs/package.json index a82757bff..63c51a799 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.5", + "version": "0.38.0-beta.6", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index d88a25257..2e4f8996f 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.5" +version = "0.38.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 439c9613b..d32d88ecd 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.5" +version = "0.38.0-beta.6" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 242ade8017e6935485f37f18a1bd5050434fec06 Mon Sep 17 00:00:00 2001 From: Ayush Chaurasia Date: Mon, 24 Aug 2026 13:26:36 +0530 Subject: [PATCH 099/206] feat(python): support sequence packing in streaming dataset (#3920) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## How packing works Consider four tokenized documents: [1] [2] [10, 11, 12, 13, 14, 15, 16, 17] [20] With: ``` StreamingDataset( table, shuffle=False, columns=["tokens"], num_splits=2, pack_sequences=5, eos_id=9, pad_id=0, blocks_per_epoch=6, ) ``` the documents are assigned to two fixed logical splits. Each split maintains an independent token buffer, appends eos_id after every document, and emits blocks of five tokens. Because blocks_per_epoch=6, each split emits exactly three blocks: Cycl/e 1: Split 0: [1, 9, 2, 9, 0] # 9 is eos, 0 is padding Split 1: [10, 11, 12, 13, 14] Cycle 2: Split 0: [0, 0, 0, 0, 0] Split 1: [15, 16, 17, 9, 20] Cycle 3: Split 0: [0, 0, 0, 0, 0] Split 1: [9, 0, 0, 0, 0] If a split runs out of tokens early, it emits padded blocks through the fixed budget. This prevents one rank from finishing before another. Logical splits are independent of rank and worker ownership. A checkpoint records each split’s consumed-document count, emitted-block count, remaining tokens, and document boundaries. Merging those per-split states allows the same packed stream to resume after the topology changes. doc_ids identifies document segments, including continuations across block boundaries. It is not a padding mask: padding retains the preceding document ID, so callers must mask padding using a reserved pad_id. blocks_per_epoch="auto" is also available. It estimates the budget from a deterministic bounded sample and warns that the result is approximate. WIP pre-training tests: ``` ┌────────────────────────────────────┬────────────────────────┬─────────────────────────────────────┐ │ │ GPT-2 124M │ GPT-2 medium 354M │ ├────────────────────────────────────┼────────────────────────┼─────────────────────────────────────┤ │ Corpus │ 2.4M docs / 12GB table │ 9.67M docs / 45GB table │ │ Tokens (Chinchilla) │ 2.43B │ 7.0B │ ├────────────────────────────────────┼────────────────────────┼─────────────────────────────────────┤ │ Data prep (ingest→curate→tokenize) │ ~12 min │ ~51 min │ ├────────────────────────────────────┼────────────────────────┼─────────────────────────────────────┤ │ Training wall time │ ~50 min │ 3h 06m │ ├────────────────────────────────────┼────────────────────────┼─────────────────────────────────────┤ │ Throughput / MFU │ 1.60M tok/s / 35% │ 684k tok/s / 42.0%, │ ├────────────────────────────────────┼────────────────────────┼─────────────────────────────────────┤ │ Final val loss │ 3.230 │ 2.840 │ └────────────────────────────────────┴────────────────────────┴─────────────────────────────────────┘ ``` --------- Co-authored-by: OpenAI Codex --- python/python/lancedb/streaming.py | 491 +++++++++++++++--- .../python/tests/test_elastic_dataloader.py | 208 ++++++++ 2 files changed, 638 insertions(+), 61 deletions(-) diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py index 6951fa0bc..c54940ab7 100644 --- a/python/python/lancedb/streaming.py +++ b/python/python/lancedb/streaming.py @@ -24,11 +24,16 @@ import os import random import threading import time +import warnings from collections import deque from concurrent.futures import ThreadPoolExecutor +from copy import deepcopy from multiprocessing import RawArray -from typing import Any, Callable, Iterator, Optional, Union +from typing import Any, Callable, cast, Iterator, Literal, Optional, Union +import pyarrow as pa +import pyarrow.compute as pc +import torch from torch.utils.data import IterableDataset, get_worker_info from .permutation import ( @@ -132,6 +137,39 @@ class StreamingDataset(IterableDataset): Maximum number of transforms to run concurrently. Must be greater than zero. When ``None`` (the default), uses ``os.cpu_count()`` or 1 when the CPU count is unavailable. + pack_sequences: + Sequence-packing mode: token lists from consecutive documents are + joined with ``eos_id`` and sliced into blocks of this many tokens. + Each item is then a dict of two ``(pack_sequences,)`` LongTensors — + ``input_ids`` and ``doc_ids`` (per-position document index within + the block, for block-diagonal masks or position-id resets). + * Packing happens independently per owned split and preserves per-split + resume state. + * When a split cannot fill a real block for a cycle but an owned sibling + still can, or when only a short tail remains at epoch end, the short buffer + is padded to ``pack_sequences`` with ``pad_id`` so every local cycle emits + one block per owned split. + * ``eos_id``, ``pad_id``, and ``columns`` naming a single integer-list + column are required; incompatible with ``transform``. + eos_id: + Separator token id between packed documents. Required with + ``pack_sequences``, ignored otherwise. + pad_id: + Padding token id used to complete blocks when a split runs out of + real tokens mid-cycle or at epoch end. Required with + ``pack_sequences``, ignored otherwise. It must be reserved for padding: + padding positions retain the preceding document's ``doc_id`` (or zero + in an all-padding block), so callers must mask them separately using + ``input_ids == pad_id``. + blocks_per_epoch: + Total number of packed blocks emitted globally per epoch. Required with + ``pack_sequences``. An integer must be divisible by ``num_splits``. + Every logical split emits exactly ``blocks_per_epoch / num_splits`` + blocks: exhausted splits emit padding, while tokens beyond the budget + are left out of the epoch. This fixed per-split budget keeps packed + iteration and checkpoints independent of rank topology. + Pass ``"auto"`` to estimate a corpus-level budget from a bounded sample + of token lists. The estimate may be inaccurate. on_transform_error: What to do when the transform raises an exception: @@ -210,6 +248,10 @@ class StreamingDataset(IterableDataset): filter: Optional[str] = None, transform: Optional[Callable] = None, transform_parallelism: Optional[int] = None, + pack_sequences: Optional[int] = None, + eos_id: Optional[int] = None, + pad_id: Optional[int] = None, + blocks_per_epoch: Optional[Union[int, Literal["auto"]]] = None, on_transform_error: Union[str, Callable[[Exception], bool]] = "raise", transform_queue_depth: Optional[int] = None, connection_factory: Optional[Callable[[str], Any]] = None, @@ -237,6 +279,55 @@ class StreamingDataset(IterableDataset): raise ValueError("io_queue_depth must be greater than 0") if transform_parallelism is not None and transform_parallelism <= 0: raise ValueError("transform_parallelism must be greater than 0") + if pack_sequences is not None: + if pack_sequences <= 0: + raise ValueError("pack_sequences must be greater than 0") + if eos_id is None: + raise ValueError("eos_id is required when pack_sequences is set") + if pad_id is None: + raise ValueError("pad_id is required when pack_sequences is set") + if blocks_per_epoch is None: + raise ValueError( + "blocks_per_epoch is required when pack_sequences is set" + ) + if blocks_per_epoch != "auto": + if not isinstance(blocks_per_epoch, int) or isinstance( + blocks_per_epoch, bool + ): + raise ValueError( + "blocks_per_epoch must be a positive integer or 'auto'" + ) + if blocks_per_epoch <= 0: + raise ValueError("blocks_per_epoch must be greater than 0") + if blocks_per_epoch % num_splits != 0: + raise ValueError( + f"blocks_per_epoch ({blocks_per_epoch}) must be divisible by " + f"num_splits ({num_splits})" + ) + if transform is not None: + raise ValueError("transform cannot be combined with pack_sequences") + if columns is None or len(columns) != 1: + raise ValueError( + "pack_sequences requires columns to name exactly one " + "list-typed column of token ids" + ) + field = table.schema.field(columns[0]) + if not ( + pa.types.is_list(field.type) + or pa.types.is_large_list(field.type) + or pa.types.is_fixed_size_list(field.type) + ): + raise ValueError( + f"pack_sequences requires a list-typed token column; " + f"{columns[0]} has type {field.type}" + ) + if not pa.types.is_integer(field.type.value_type): + raise ValueError( + "pack_sequences requires a token column with integer values; " + f"{columns[0]} has value type {field.type.value_type}" + ) + elif blocks_per_epoch is not None: + raise ValueError("blocks_per_epoch requires pack_sequences") if on_transform_error not in ("raise", "skip", "warn") and not callable( on_transform_error ): @@ -261,11 +352,20 @@ class StreamingDataset(IterableDataset): self._filter = filter self._transform = transform self._transform_parallelism = transform_parallelism + self._pack_sequences = pack_sequences + self._eos_id = eos_id + self._pad_id = pad_id + self._blocks_per_epoch = blocks_per_epoch self._on_transform_error = on_transform_error self._transform_queue_depth = transform_queue_depth self._connection_factory = connection_factory self._worker_info_override = worker_info_override + # Packing resume state: permutation positions and partial-block buffers. + self._pack_consumed: list[int] = [0] * num_splits + self._pack_buffers: dict[int, dict[str, list[int]]] = {} + self._pack_blocks_emitted: list[int] = [0] * num_splits + # Live references to pipeline state, set only while __iter__ is running # in the same process. Used by the observability properties when the # DataLoader runs with num_workers=0. @@ -315,6 +415,9 @@ class StreamingDataset(IterableDataset): else: self._perm_table = builder.split_sequential(fixed=num_splits).execute() + if self._blocks_per_epoch == "auto": + self._blocks_per_epoch = self._estimate_blocks_per_epoch() + # Contiguous block of global split indices assigned to this rank. splits_per_rank = num_splits // world_size rank_start = rank * splits_per_rank @@ -322,6 +425,71 @@ class StreamingDataset(IterableDataset): range(rank_start, rank_start + splits_per_rank) ) + def _estimate_blocks_per_epoch(self) -> int: + """Estimate a fixed packed-block budget from a bounded token sample.""" + # TODO: Replace this fallback with Lance's dedicated exact token-count + # estimation API once it is available. + if self._pack_sequences is None or not self._columns: + raise RuntimeError( + "packing must be configured before estimating its budget" + ) + + pack_len = self._pack_sequences + token_column = self._columns[0] + sample_cap_per_split = max(1, 100_000 // self._num_splits) + sampled_tokens = 0 + total_sampled = 0 + total_rows = 0 + rng = random.Random(self._shuffle_seed) + + warnings.warn( + "blocks_per_epoch='auto' uses an approximate token-count sample; " + "pass an explicit value for exact epoch sizing", + ) + + for split in range(self._num_splits): + permutation = Permutation.from_tables( + self._table, self._perm_table, split=split + ) + permutation = permutation.select_columns([token_column]) + permutation = permutation.with_transform(Transforms.arrow2arrow) + split_rows = permutation.num_rows + if split_rows == 0: + raise ValueError( + "blocks_per_epoch='auto' cannot estimate an empty dataset" + ) + + # Sample roughly 1% from each logical split, with at least one row + # per split and a global target cap of 100,000 rows. + sample_rows = min( + split_rows, + max(1, min((split_rows + 99) // 100, sample_cap_per_split)), + ) + sample_offsets = sorted(rng.sample(range(split_rows), sample_rows)) + sample_batch_size = max(1, self._read_batch_size) + for start in range(0, sample_rows, sample_batch_size): + batch = permutation.__getitems__( + sample_offsets[start : start + sample_batch_size] + ) + lengths = pc.list_value_length(batch.column(0)) + if lengths.null_count: + raise ValueError("pack_sequences does not support null token lists") + sampled_tokens += int(pc.sum(lengths).as_py()) + + total_sampled += sample_rows + total_rows += split_rows + + # Pool the samples into one global average. Each document contributes + # one EOS token. + estimated_tokens = ( + (sampled_tokens + total_sampled) * total_rows // total_sampled + ) + blocks = estimated_tokens // pack_len + return max( + self._num_splits, + blocks - blocks % self._num_splits, + ) + def _resolve_my_splits(self) -> list[int]: """Return the split indices this instance should read in __iter__.""" torch_worker_info = get_worker_info() @@ -372,8 +540,14 @@ class StreamingDataset(IterableDataset): ) if self._columns is not None: perm = perm.select_columns(self._columns) - perm = perm.with_transform(lambda batch: batch) - start_pos = self._resume_positions.get(split_idx, self._resume_offset) + perm = perm.with_transform(Transforms.arrow2arrow) + # Both modes resume from absolute permutation positions. Packing + # stores them separately because it also checkpoints partial blocks. + start_pos = ( + self._pack_consumed[split_idx] + if self._pack_sequences is not None + else self._resume_positions.get(split_idx, self._resume_offset) + ) if start_pos > 0: perm = perm.with_skip(start_pos) initial_positions.append(start_pos) @@ -395,9 +569,24 @@ class StreamingDataset(IterableDataset): if self._transform_parallelism is not None else (os.cpu_count() or 1) ) - final_transform = ( - self._transform if self._transform is not None else Transforms.arrow2python - ) + final_transform: Callable[[pa.RecordBatch], Any] + if self._pack_sequences is not None: + # Packing consumes raw token lists, one per document. + def arrow_tokens(batch: pa.RecordBatch) -> list[list[int]]: + token_column = batch.column(0) + if token_column.null_count or token_column.flatten().null_count: + raise ValueError( + "pack_sequences does not support null token lists or values" + ) + return cast(list[list[int]], token_column.to_pylist()) + + final_transform = arrow_tokens + else: + final_transform = ( + self._transform + if self._transform is not None + else Transforms.arrow2python + ) # None means no limit; otherwise cap rows per split to # transform_queue_depth batches worth (including in-flight transforms). max_cooked_rows = ( @@ -574,6 +763,82 @@ class StreamingDataset(IterableDataset): else: break # split exhausted + def _update_stats(*, idle: bool = False) -> None: + """Refresh pipeline statistics visible to the parent process.""" + ws = self._worker_stats + ws[0] = sum(split_sizes[j] - fetch_head[j] for j in range(n)) + ws[1] = ( + 0 + if idle + else sum(batch.num_rows for q in raw_batches for _, batch in q) + ) + ws[2] = 0 if idle else sum(len(q) for q in cooked) + ws[3] = sum(local_consumed) + ws[4] = self._bytes_loaded + ws[5] = int(self._fetch_time * 1_000_000) + ws[6] = int(self._transform_time * 1_000_000) + ws[7] = self._rows_skipped + + # Sequence-packing helpers + pack_len = cast(int, self._pack_sequences) + eos_id = cast(int, self._eos_id) + pad_id = cast(int, self._pad_id) + blocks_per_split = ( + cast(int, self._blocks_per_epoch) // self._num_splits + if self._pack_sequences is not None + else 0 + ) + pack_consumed = list(self._pack_consumed) + pack_buffers = deepcopy(self._pack_buffers) + pack_blocks_emitted = list(self._pack_blocks_emitted) + + def _pack_buffer(i: int) -> dict[str, list[int]]: + return pack_buffers.setdefault(my_splits[i], {"tokens": [], "starts": []}) + + def _fill_block(i: int) -> None: + """Fill split i's buffer to one block or exhaust the split.""" + buf = _pack_buffer(i) + while len(buf["tokens"]) < pack_len: + _ensure_cooked(i) + if not cooked[i]: + return + buf["starts"].append(len(buf["tokens"])) + pos, tokens = cooked[i].popleft() + buf["tokens"].extend(tokens) + buf["tokens"].append(eos_id) + pack_consumed[my_splits[i]] = pos + 1 + local_consumed[i] += 1 + _advance(i) + + def _emit_block(i: int) -> dict[str, Any]: + buf = _pack_buffer(i) + tokens, starts = buf["tokens"], buf["starts"] + # doc_ids label document segments within the block; 0 also covers + # the continuation of a document begun in a prior block. + doc_ids = torch.zeros(pack_len, dtype=torch.int64) + doc_starts = [s for s in starts if 0 < s < pack_len] + doc_ids[doc_starts] = 1 + doc_ids.cumsum_(dim=0) # cumulative sum marks document boundaries + block = { + "input_ids": torch.tensor(tokens[:pack_len], dtype=torch.int64), + "doc_ids": doc_ids, + } + del tokens[:pack_len] + # Shift start boundaries for the next call. + buf["starts"] = [s - pack_len for s in starts if s >= pack_len] + return block + + def _commit_pack_state() -> None: + self._pack_consumed = list(pack_consumed) + self._pack_buffers = { + split: { + "tokens": list(buffer["tokens"]), + "starts": list(buffer["starts"]), + } + for split, buffer in pack_buffers.items() + } + self._pack_blocks_emitted = list(pack_blocks_emitted) + # ── Main loop ───────────────────────────────────────────────────────── with ThreadPoolExecutor(max_workers=n * io_queue_depth) as io_pool: @@ -583,10 +848,42 @@ class StreamingDataset(IterableDataset): self._fetch_head_ref = fetch_head self._split_sizes_ref = split_sizes self._local_consumed_ref = local_consumed + try: for i in range(n): _fill_io(i) + if self._pack_sequences is not None: + first_count = pack_blocks_emitted[my_splits[0]] + if any( + pack_blocks_emitted[split] != first_count + for split in my_splits[1:] + ): + raise ValueError( + "Packed checkpoint is not aligned across the splits " + "owned by this iterator; merge every rank " + "state with merge_state_dicts before resuming on a " + "different topology" + ) + + while pack_blocks_emitted[my_splits[0]] < blocks_per_split: + # Each logical split gets one block per cycle. Exhausted + # splits are padded through the fixed global budget. + for i in range(n): + _fill_block(i) + + for i in range(n): + tokens = _pack_buffer(i)["tokens"] + if len(tokens) < pack_len: + tokens.extend([pad_id] * (pack_len - len(tokens))) + block = _emit_block(i) + pack_blocks_emitted[my_splits[i]] += 1 + if i == n - 1: + _commit_pack_state() + _update_stats() + yield block + return + while True: # A cycle only runs if every split can still produce a # row. Without skips all splits exhaust simultaneously @@ -620,21 +917,7 @@ class StreamingDataset(IterableDataset): self._resume_offset = initial_offset + local_consumed[i] for j, split_idx in enumerate(my_splits): self._resume_positions[split_idx] = pos_consumed[j] - ws = self._worker_stats - ws[0] = sum( - split_sizes[j] - fetch_head[j] for j in range(n) - ) - ws[1] = sum( - batch.num_rows - for q in raw_batches - for _, batch in q - ) - ws[2] = sum(len(q) for q in cooked) - ws[3] = sum(local_consumed) - ws[4] = self._bytes_loaded - ws[5] = int(self._fetch_time * 1_000_000) - ws[6] = int(self._transform_time * 1_000_000) - ws[7] = self._rows_skipped + _update_stats() yield row finally: @@ -642,15 +925,7 @@ class StreamingDataset(IterableDataset): # when iteration ends mid-cycle (e.g. a split whose rows # were all skipped before completing a single cycle), so # counters like rows_skipped would otherwise be stale. - ws = self._worker_stats - ws[0] = sum(split_sizes[j] - fetch_head[j] for j in range(n)) - ws[1] = 0 # queue-depth properties document 0 when idle - ws[2] = 0 - ws[3] = sum(local_consumed) - ws[4] = self._bytes_loaded - ws[5] = int(self._fetch_time * 1_000_000) - ws[6] = int(self._transform_time * 1_000_000) - ws[7] = self._rows_skipped + _update_stats(idle=True) self._raw_batches_ref = None self._cooked_ref = None self._fetch_head_ref = None @@ -808,21 +1083,31 @@ class StreamingDataset(IterableDataset): def state_dict(self) -> dict: """Snapshot the dataset's consumption state. - The returned dict is topology-independent: at global step boundaries - every split has been consumed the same number of times (by the - round-robin design), so the per-split count is a single uniform value - that is identical across all ranks and DataLoader workers. - - ``positions_consumed_per_split`` records how far into each split's - permutation iteration has advanced. It only differs from - ``samples_consumed_per_split`` when ``on_transform_error`` skipped - rows, in which case entries are exact for the splits this instance - iterated and a lower bound (the sample count) for splits owned by - other ranks or workers. Combine the state dicts from all ranks with + In row mode, the returned dict is topology-independent at global step + boundaries. ``positions_consumed_per_split`` records how far each + split's permutation has advanced, which can differ from the sample + count when ``on_transform_error`` skips rows. Combine state dicts from + every rank with [merge_state_dicts][lancedb.streaming.StreamingDataset.merge_state_dicts] - to recover the exact value for every split before resuming on a - different topology. + before resuming on a different topology. + + Packed state includes partial token buffers and emitted block counts + for every logical split. When packing is sharded, merge every rank + state with ``merge_state_dicts`` before loading it. """ + if self._pack_sequences is not None: + return { + "shuffle_seed": self._shuffle_seed, + "num_splits": self._num_splits, + "epoch": self._epoch, + "pack_sequences": self._pack_sequences, + "eos_id": self._eos_id, + "pad_id": self._pad_id, + "blocks_per_epoch": self._blocks_per_epoch, + "samples_consumed_per_split": list(self._pack_consumed), + "blocks_emitted_per_split": list(self._pack_blocks_emitted), + "pack_buffers": deepcopy(self._pack_buffers), + } positions = [ self._resume_positions.get(split, self._resume_offset) for split in range(self._num_splits) @@ -840,7 +1125,9 @@ class StreamingDataset(IterableDataset): Raises ``ValueError`` if ``num_splits`` or ``shuffle_seed`` differ from the checkpoint, since a different split structure or shuffle order - makes mid-epoch resumption meaningless. + makes mid-epoch resumption meaningless. Packed checkpoints + pin ``pack_sequences``, ``eos_id``, ``pad_id``, + ``blocks_per_epoch``, and ``epoch``. """ if state["num_splits"] != self._num_splits: raise ValueError( @@ -852,6 +1139,31 @@ class StreamingDataset(IterableDataset): f"shuffle_seed mismatch: checkpoint has {state['shuffle_seed']}, " f"current dataset has {self._shuffle_seed}" ) + + if "pack_buffers" in state or self._pack_sequences is not None: + for key in ( + "pack_sequences", + "eos_id", + "pad_id", + "blocks_per_epoch", + "epoch", + ): + ours = getattr(self, f"_{key}") + if state.get(key) != ours: + raise ValueError( + f"{key} mismatch: checkpoint has {state.get(key)}, " + f"current dataset has {ours}" + ) + self._pack_consumed = [int(c) for c in state["samples_consumed_per_split"]] + self._pack_blocks_emitted = [ + int(c) for c in state["blocks_emitted_per_split"] + ] + self._pack_buffers = { + int(g): {"tokens": list(b["tokens"]), "starts": list(b["starts"])} + for g, b in state["pack_buffers"].items() + } + return + consumed = state["samples_consumed_per_split"] # All entries are equal at step boundaries; use the first. if isinstance(consumed, list): @@ -873,25 +1185,22 @@ class StreamingDataset(IterableDataset): def merge_state_dicts(states: list[dict]) -> dict: """Merge state dicts saved by different ranks into one exact state. - Only needed when ``on_transform_error`` skips rows in multi-rank - training: each rank then knows the exact permutation position only for - its own splits, and records a lower bound for the rest. Because - exactly one rank owns each split, the elementwise maximum across all - ranks' ``positions_consumed_per_split`` recovers the exact position of - every split. Without skipped rows every rank's state is already - identical and merging is a no-op. + For row mode, the elementwise maximum of permutation positions recovers + splits advanced by different ranks after transform failures. For packed + mode, the state that emitted the most blocks for each logical split + supplies that split's permutation position and partial token buffer. Packed + states must cover every rank at the same global step. - Raises ``ValueError`` if the states are empty or were not produced by - the same run (mismatched seed, split count, epoch, or sample counts). + Raises ``ValueError`` if the states are empty, were not produced by + the same run, or do not represent the same global step. The merge is always all-to-all and topology-agnostic: collect the - ``state_dict()`` from every rank of the *previous* run into one list, - merge that whole list, and hand the identical merged result to every - rank of the *next* run — regardless of whether the rank count grew, - shrank, or stayed the same. There is no pairwise or subset merging - step, because each split's exact position is only known to whichever - rank owned that split, and the elementwise maximum needs every rank's - contribution to be correct. + ``state_dict()`` from every rank of the *previous* run into + one list, merge that whole list, and hand the identical merged result + to every rank of the *next* run — regardless of whether the + topology grew, shrank, or stayed the same. There is no pairwise or + subset merging step, because each split's exact state is only known to + whichever iterator owned that split. For example, checkpointing 8 ranks and resuming on 4 (the same pattern applies when growing, e.g. 4 ranks resuming on 8):: @@ -924,13 +1233,73 @@ class StreamingDataset(IterableDataset): if not states: raise ValueError("merge_state_dicts requires at least one state dict") first = states[0] + packed = "pack_buffers" in first + config_keys = ["shuffle_seed", "num_splits", "epoch"] + if packed: + config_keys.extend( + ["pack_sequences", "eos_id", "pad_id", "blocks_per_epoch"] + ) + for state in states[1:]: - for key in ("shuffle_seed", "num_splits", "epoch"): + if ("pack_buffers" in state) != packed: + raise ValueError("cannot merge packed and unpacked state dicts") + for key in config_keys: if state[key] != first[key]: raise ValueError( f"{key} mismatch across state dicts: " f"{state[key]} != {first[key]}" ) + + if packed: + num_splits = first["num_splits"] + for state in states: + for key in ( + "samples_consumed_per_split", + "blocks_emitted_per_split", + ): + if len(state[key]) != num_splits: + raise ValueError( + f"{key} must contain one entry per logical split" + ) + + merged_consumed = [] + merged_emitted = [] + merged_buffers = {} + for split in range(num_splits): + owner = states[0] + owner_progress = ( + owner["blocks_emitted_per_split"][split], + owner["samples_consumed_per_split"][split], + ) + for state in states[1:]: + progress = ( + state["blocks_emitted_per_split"][split], + state["samples_consumed_per_split"][split], + ) + if progress > owner_progress: + owner = state + owner_progress = progress + merged_consumed.append(owner["samples_consumed_per_split"][split]) + merged_emitted.append(owner["blocks_emitted_per_split"][split]) + buffer = owner["pack_buffers"].get( + split, owner["pack_buffers"].get(str(split)) + ) + if buffer is not None: + merged_buffers[split] = deepcopy(buffer) + + if len(set(merged_emitted)) > 1: + raise ValueError( + "packed state dicts were not captured at the same global " + "step or do not cover every rank" + ) + + merged = dict(first) + merged["samples_consumed_per_split"] = merged_consumed + merged["blocks_emitted_per_split"] = merged_emitted + merged["pack_buffers"] = merged_buffers + return merged + + for state in states[1:]: if ( state["samples_consumed_per_split"] != first["samples_consumed_per_split"] diff --git a/python/python/tests/test_elastic_dataloader.py b/python/python/tests/test_elastic_dataloader.py index 4d860a5de..ff65d100c 100644 --- a/python/python/tests/test_elastic_dataloader.py +++ b/python/python/tests/test_elastic_dataloader.py @@ -2113,6 +2113,214 @@ def test_shuffle_seed_none_generates_stable_seed(lance_table): assert first == second, "Same resolved seed must produce the same ordering" +# Sequence packing tests + + +def _create_token_table(tmp_path, documents): + db = lancedb.connect(tmp_path) + tokens = pa.array(documents, type=pa.list_(pa.int64())) + return db.create_table("tokens", pa.table({"tokens": tokens})) + + +def _packed_dataset(table, pack_sequences, *, blocks_per_epoch, pad_id=0, **kwargs): + return StreamingDataset( + table, + shuffle=False, + columns=["tokens"], + pack_sequences=pack_sequences, + eos_id=9, + pad_id=pad_id, + blocks_per_epoch=blocks_per_epoch, + **kwargs, + ) + + +def test_pack_sequences_emits_blocks_and_pads_final_tail(tmp_path): + table = _create_token_table(tmp_path, [[1, 2], [3, 4], [5]]) + dataset = _packed_dataset(table, 6, blocks_per_epoch=2) + + blocks = list(dataset) + + assert len(blocks) == 2 + assert blocks[0]["input_ids"].tolist() == [1, 2, 9, 3, 4, 9] + assert blocks[0]["doc_ids"].tolist() == [0, 0, 0, 1, 1, 1] + assert blocks[1]["input_ids"].tolist() == [5, 9, 0, 0, 0, 0] + assert blocks[1]["doc_ids"].tolist() == [0, 0, 0, 0, 0, 0] + assert blocks[0]["input_ids"].dtype == torch.int64 + assert blocks[0]["doc_ids"].dtype == torch.int64 + + +def test_pack_sequences_pads_lagging_splits(tmp_path): + table = _create_token_table( + tmp_path, + [[1], [2], [10, 11, 12, 13, 14, 15, 16, 17], [20]], + ) + dataset = _packed_dataset(table, 5, blocks_per_epoch=6, num_splits=2) + input_ids = [block["input_ids"].tolist() for block in dataset] + # Split 0 has four real tokens including EOS markers, while split 1 has + # eleven. Packing must emit three complete two-split cycles. + assert input_ids == [ + [1, 9, 2, 9, 0], + [10, 11, 12, 13, 14], + [0, 0, 0, 0, 0], + [15, 16, 17, 9, 20], + [0, 0, 0, 0, 0], + [9, 0, 0, 0, 0], + ] + + per_rank = [] + for rank in range(2): + rank_dataset = _packed_dataset( + table, + 5, + blocks_per_epoch=6, + num_splits=2, + world_size=2, + rank=rank, + ) + per_rank.append([block["input_ids"].tolist() for block in rank_dataset]) + + assert [len(blocks) for blocks in per_rank] == [3, 3] + sharded = [block for cycle in zip(*per_rank) for block in cycle] + assert sharded == input_ids + + +def test_pack_sequences_auto_estimates_filtered_token_column(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table( + "tokens", + pa.table( + { + "tokens": pa.array([[1] * 4, [2] * 9], type=pa.list_(pa.int64())), + "keep": [True, False], + } + ), + ) + table.add( + pa.table( + { + "tokens": pa.array([[3] * 4, [4] * 9], type=pa.list_(pa.int64())), + "keep": [True, False], + } + ) + ) + + with pytest.warns(UserWarning, match="approximate token-count sample"): + dataset = _packed_dataset( + table, + 5, + blocks_per_epoch="auto", + num_splits=2, + filter="keep", + ) + + # Two kept documents contain 8 tokens plus 2 EOS tokens: two blocks. + assert dataset.state_dict()["blocks_per_epoch"] == 2 + + +def test_pack_sequences_checkpoint_resumes_on_new_topology(tmp_path): + table = _create_token_table( + tmp_path, + [[1], [2], [10, 11, 12, 13, 14, 15, 16, 17], [20]], + ) + kwargs = dict(pack_sequences=5, blocks_per_epoch=6, num_splits=2) + reference = list(_packed_dataset(table, **kwargs)) + + datasets = [ + _packed_dataset(table, world_size=2, rank=rank, **kwargs) for rank in range(2) + ] + iterators = [iter(dataset) for dataset in datasets] + first_cycle = [next(iterator) for iterator in iterators] + checkpoint = StreamingDataset.merge_state_dicts( + [dataset.state_dict() for dataset in datasets] + ) + for iterator in iterators: + iterator.close() + + resumed = _packed_dataset(table, **kwargs) + resumed.load_state_dict(checkpoint) + actual_remaining = list(resumed) + + assert [block["input_ids"].tolist() for block in first_cycle] == [ + [1, 9, 2, 9, 0], + [10, 11, 12, 13, 14], + ] + assert checkpoint["blocks_emitted_per_split"] == [1, 1] + assert [block["input_ids"].tolist() for block in actual_remaining] == [ + block["input_ids"].tolist() for block in reference[2:] + ] + assert [block["doc_ids"].tolist() for block in actual_remaining] == [ + block["doc_ids"].tolist() for block in reference[2:] + ] + + +def test_pack_sequences_validates_configuration_and_tokens(tmp_path): + table = _create_token_table(tmp_path, [[1, 2]]) + + with pytest.raises(ValueError, match="pad_id is required"): + StreamingDataset( + table, + shuffle=False, + columns=["tokens"], + pack_sequences=4, + eos_id=9, + ) + + with pytest.raises(ValueError, match="blocks_per_epoch is required"): + StreamingDataset( + table, + shuffle=False, + columns=["tokens"], + pack_sequences=4, + eos_id=9, + pad_id=0, + ) + + with pytest.raises(ValueError, match="must be divisible"): + _packed_dataset(table, 4, blocks_per_epoch=3, num_splits=2) + + with pytest.raises(ValueError, match="positive integer or 'auto'"): + _packed_dataset(table, 4, blocks_per_epoch="estimate") + + checkpoint = _packed_dataset(table, 4, blocks_per_epoch=1).state_dict() + resumed = _packed_dataset(table, 4, blocks_per_epoch=1, pad_id=8) + with pytest.raises(ValueError, match="pad_id mismatch"): + resumed.load_state_dict(checkpoint) + + float_db = lancedb.connect(tmp_path / "float") + float_table = float_db.create_table( + "tokens", + pa.table({"tokens": pa.array([[1.5, 2.5]], type=pa.list_(pa.float64()))}), + ) + with pytest.raises(ValueError, match="token column with integer values"): + _packed_dataset(float_table, 4, blocks_per_epoch=1) + + null_db = lancedb.connect(tmp_path / "null") + null_table = null_db.create_table( + "tokens", + pa.table({"tokens": pa.array([None], type=pa.list_(pa.int64()))}), + ) + with pytest.raises(ValueError, match="does not support null token lists"): + list(_packed_dataset(null_table, 4, blocks_per_epoch=1)) + + null_value_db = lancedb.connect(tmp_path / "null_value") + null_value_table = null_value_db.create_table( + "tokens", + pa.table( + {"tokens": pa.array([[1], [2, None], [3]], type=pa.list_(pa.int64()))} + ), + ) + blocks = list( + _packed_dataset( + null_value_table, + 2, + blocks_per_epoch=2, + on_transform_error="skip", + ) + ) + assert [block["input_ids"].tolist() for block in blocks] == [[1, 9], [3, 9]] + + # --------------------------------------------------------------------------- # Doc examples — each test mirrors the code snippet in index.mdx so that # broken doc examples are caught before they ship. From b0dae5eb0b468a89b2f353a548e49011ce4881d6 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 25 Aug 2026 00:01:32 +0800 Subject: [PATCH 100/206] feat: return typed refresh job results (#4013) ## Problem `refresh_column_async` returned a unit-result job even though durable refresh jobs carry a canonical terminal result. Python callers could not obtain row counts or source and published versions through the public `Job` API, and local and remote refresh jobs exposed different result semantics. ## Behavior `refresh_column_async` now returns `Job[RefreshColumnResult]` for local and remote tables. The general typed-job bridge binds each endpoint to its public result model while preserving unit-result jobs and existing status, wait, cancel, and timeout behavior. A local no-op refresh reports no published version. The Node.js API continues to resolve `wait()` as `void`; its binding erases the Rust result type internally to preserve the existing public contract. ## Ownership and integration boundary LanceDB owns the language-neutral `Job` contract and language-binding decode. Sophon owns production and durable persistence of terminal payloads. Sophon #7348 and #7378 now publish the canonical refresh result for Function-backed and expression-backed refresh jobs, respectively. The remote client fixture matches the merged server schema; live deployment and end-to-end demo acceptance remain separate rollout checks. --- nodejs/src/job.rs | 7 +- python/python/lancedb/__init__.py | 1 + python/python/lancedb/_lancedb.pyi | 11 +- python/python/lancedb/db.py | 4 +- python/python/lancedb/functions.py | 10 +- python/python/lancedb/job.py | 58 ++++--- python/python/lancedb/remote/table.py | 4 +- python/python/lancedb/table.py | 39 ++++- python/python/tests/test_db.py | 4 +- .../tests/test_first_class_function_slice2.py | 2 +- python/python/tests/test_index.py | 2 +- python/python/tests/test_remote_db.py | 76 ++++++++- python/python/tests/test_table.py | 21 ++- python/src/connection.rs | 2 +- python/src/job.rs | 73 +++------ python/src/lib.rs | 1 - python/src/table.rs | 2 +- rust/lancedb/src/function.rs | 14 +- rust/lancedb/src/job.rs | 152 +++++++++++++----- rust/lancedb/src/remote/db.rs | 4 +- rust/lancedb/src/remote/table.rs | 36 ++++- rust/lancedb/src/table.rs | 22 ++- rust/lancedb/src/table/refresh.rs | 71 ++++++-- 23 files changed, 429 insertions(+), 187 deletions(-) diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 6aaeee174..14013fd27 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -14,9 +14,12 @@ pub struct Job { } impl Job { - pub(crate) fn new(inner: lancedb::Job) -> Self { + pub(crate) fn new(inner: lancedb::Job) -> Self + where + T: Clone + Send + Sync + 'static, + { Self { - inner: Arc::new(inner), + inner: Arc::new(inner.map(|_| ())), } } } diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index aa473c5f8..df8950686 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -29,6 +29,7 @@ from .functions import ( FunctionRegistrationRequest as FunctionRegistrationRequest, FunctionVersion as FunctionVersion, PythonRuntimeSpec as PythonRuntimeSpec, + RefreshColumnResult as RefreshColumnResult, UdfDefinition as UdfDefinition, udf as udf, ) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 648469579..1e314ede8 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -147,7 +147,7 @@ class Connection(object): limit: Optional[int], ) -> list[str]: ... # Deprecated: Use list_tables instead def job(self, job_id: str) -> Job: ... - async def create_function_async(self, request_json: str) -> FunctionJob: ... + async def create_function_async(self, request_json: str) -> Job: ... async def get_function(self, name: str, version: str) -> str: ... async def list_jobs(self) -> List[JobInfo]: ... async def get_job(self, job_id: str) -> Optional[JobDescription]: ... @@ -234,14 +234,7 @@ class Job: @property def id(self) -> Optional[str]: ... async def status(self) -> str: ... - async def wait(self) -> None: ... - async def cancel(self) -> None: ... - -class FunctionJob: - @property - def id(self) -> Optional[str]: ... - async def status(self) -> str: ... - async def wait(self) -> str: ... + async def wait(self) -> Optional[str]: ... async def cancel(self) -> None: ... class JobInfo: diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 7ad749920..51b8d9993 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -46,7 +46,7 @@ from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError from . import __version__ from ._lancedb import connect as lancedb_connect # type: ignore from .functions import FunctionVersion, UdfDefinition -from .job import AsyncJob, Job, _function_job +from .job import AsyncJob, Job, _typed_job from .materialized_view import ( AsyncMaterializedView, MaterializedView, @@ -2237,7 +2237,7 @@ class AsyncConnection(object): inner = await self._inner.create_function_async( definition.registration_request.to_canonical_json() ) - return _function_job(inner) + return _typed_job(inner, FunctionVersion.from_json) async def get_function(self, name: str, *, version: str) -> FunctionVersion: """Open one exact immutable Function version from the remote catalog.""" diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 9532ab8b9..c4ff9a9b3 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -1,10 +1,12 @@ # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright The LanceDB Authors -"""Canonical values exchanged with LanceDB Enterprise Function services. +"""Canonical Function values exchanged with LanceDB Enterprise services. These immutable models contain client/wire state only. Catalog persistence, environment bake, secret resolution, and execution are owned by Sophon. +``RefreshColumnResult`` is also the backend-neutral result of a local +expression-backed refresh job. """ from __future__ import annotations @@ -460,7 +462,11 @@ class FunctionBinding(_RemoteValue): class RefreshColumnResult(_RemoteValue): - """Terminal result of a remote Function-column refresh Job.""" + """Terminal result of an expression-backed or Function-backed refresh Job. + + Local jobs produce this value in process. LanceDB Cloud and Enterprise + decode the same value from the durable server-job terminal payload. + """ rows_assigned: _UInt64 rows_failed: _UInt64 diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index 7bd600a74..f688768cb 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -5,12 +5,11 @@ import asyncio from datetime import timedelta -from typing import Any, Generic, Optional, TypeVar, cast +from typing import Any, Callable, Generic, Optional, TypeVar, cast from lancedb.background_loop import LOOP from . import _lancedb -from .functions import FunctionVersion T = TypeVar("T") @@ -18,11 +17,18 @@ T = TypeVar("T") class AsyncJob(Generic[T]): """A handle to an operation that may still be running. - The operation may already be complete when the handle is created. + The operation may already be complete when the handle is created. ``T`` + is the endpoint's terminal result type; unit-result jobs resolve to + ``None``. """ - def __init__(self, inner: Optional[Any]): + def __init__( + self, + inner: Optional[Any], + result_decoder: Optional[Callable[[Any], T]] = None, + ): self._inner = inner + self._result_decoder = result_decoder @property def id(self) -> Optional[str]: @@ -50,17 +56,21 @@ class AsyncJob(Generic[T]): async def wait(self, timeout: Optional[timedelta] = None) -> T: """Wait until the operation reaches a terminal state. + Returns the endpoint's typed result, or ``None`` for a unit-result + job. + Raises `JobFailedError` if the operation failed, `JobCancelledError` if it was cancelled, and `TimeoutError` if `timeout` elapses first. """ if self._inner is None: return cast(T, None) if timeout is None: - return cast(T, await self._inner.wait()) - return cast( - T, - await asyncio.wait_for(self._inner.wait(), timeout.total_seconds()), - ) + result = await self._inner.wait() + else: + result = await asyncio.wait_for(self._inner.wait(), timeout.total_seconds()) + if self._result_decoder is not None: + return self._result_decoder(result) + return cast(T, result) async def cancel(self): """Request cancellation. Cancelling a finished operation is a no-op.""" @@ -70,7 +80,7 @@ class AsyncJob(Generic[T]): class Job(Generic[T]): - """Synchronous counterpart of `AsyncJob`.""" + """Synchronous counterpart of `AsyncJob` with the same result type.""" def __init__(self, inner: Optional[AsyncJob[T]]): self._inner = inner @@ -96,6 +106,9 @@ class Job(Generic[T]): def wait(self, timeout: Optional[timedelta] = None) -> T: """Block until the operation reaches a terminal state. + Returns the endpoint's typed result, or ``None`` for a unit-result + job. + Raises `JobFailedError` if the operation failed, `JobCancelledError` if it was cancelled, and `TimeoutError` if `timeout` elapses first. """ @@ -110,23 +123,8 @@ class Job(Generic[T]): LOOP.run(self._inner.cancel()) -class _FunctionJobAdapter: - def __init__(self, inner: "_lancedb.FunctionJob"): - self._inner = inner - - @property - def id(self) -> Optional[str]: - return self._inner.id - - async def status(self) -> str: - return await self._inner.status() - - async def wait(self) -> FunctionVersion: - return FunctionVersion.from_json(await self._inner.wait()) - - async def cancel(self): - await self._inner.cancel() - - -def _function_job(inner: "_lancedb.FunctionJob") -> AsyncJob[FunctionVersion]: - return AsyncJob(_FunctionJobAdapter(inner)) +def _typed_job( + inner: "_lancedb.Job", result_decoder: Callable[[str], T] +) -> AsyncJob[T]: + """Bind an internal JSON-producing job to its public result model.""" + return AsyncJob(inner, result_decoder) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index b97f8f194..41394ed71 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -49,7 +49,7 @@ from lancedb.index import ( LabelList, ) from lancedb.job import Job -from lancedb.functions import FunctionApplication +from lancedb.functions import FunctionApplication, RefreshColumnResult from lancedb.remote.db import LOOP from lancedb.table import IndexConfigType, KNOWN_METRICS import pyarrow as pa @@ -972,7 +972,7 @@ class RemoteTable(Table): def refresh_column(self, column: str): return LOOP.run(self._table.refresh_column(column)) - def refresh_column_async(self, column: str) -> Job: + def refresh_column_async(self, column: str) -> Job[RefreshColumnResult]: return Job(LOOP.run(self._table.refresh_column_async(column))) def alter_columns( diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 0c84b4036..75b7b1db8 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -40,7 +40,7 @@ from ._blob import ( from .types import BlobMode from lancedb.arrow import peek_reader from lancedb.background_loop import LOOP, embedding_executor -from lancedb.job import AsyncJob, Job +from lancedb.job import AsyncJob, Job, _typed_job from .dependencies import ( _check_for_hugging_face, _check_for_lance, @@ -72,7 +72,10 @@ from .index import ( FTS, ) from .expr import Expr -from .functions import FunctionApplication +from .functions import ( + FunctionApplication, + RefreshColumnResult as RefreshColumnJobResult, +) from .merge import LanceMergeInsertBuilder from .pydantic import LanceModel, model_to_dict from .query import ( @@ -2039,7 +2042,7 @@ class Table(ABC): """ @abstractmethod - def refresh_column_async(self, column: str) -> Job: + def refresh_column_async(self, column: str) -> Job[RefreshColumnJobResult]: """ Like :meth:`refresh_column`, but returns a handle to the refresh job instead of blocking until it completes. @@ -2050,6 +2053,12 @@ class Table(ABC): than failing the job. On local tables the job runs in-process; on LanceDB Cloud and Enterprise it is the server's backfill job. + Returns + ------- + Job[RefreshColumnResult] + A job whose successful ``wait`` returns row counts plus the source + and published table versions. + Examples -------- >>> import lancedb @@ -2058,7 +2067,9 @@ class Table(ABC): >>> table.add_columns(computed={"doubled": "x * 2"}) AddColumnsResult(version=2) >>> job = table.refresh_column_async("doubled") - >>> job.wait() + >>> result = job.wait() + >>> result.rows_assigned + 2 >>> job.status() 'finished' """ @@ -4082,7 +4093,7 @@ class LanceTable(Table): [`AsyncTable.refresh_column`][lancedb.AsyncTable.refresh_column].""" return LOOP.run(self._table.refresh_column(column)) - def refresh_column_async(self, column: str) -> Job: + def refresh_column_async(self, column: str) -> Job[RefreshColumnJobResult]: """Fill a computed column's unfilled rows, returning a handle to the refresh job. See [`Table.refresh_column_async`][lancedb.table.Table.refresh_column_async]. @@ -6122,7 +6133,9 @@ class AsyncTable: """ return await self._inner.refresh_column(column) - async def refresh_column_async(self, column: str) -> AsyncJob: + async def refresh_column_async( + self, column: str + ) -> AsyncJob[RefreshColumnJobResult]: """ Like :meth:`refresh_column`, but returns a handle to the refresh job instead of blocking until it completes. @@ -6134,6 +6147,12 @@ class AsyncTable: in-process; on LanceDB Cloud and Enterprise it is the server's backfill job. + Returns + ------- + AsyncJob[RefreshColumnResult] + A job whose successful ``wait`` returns row counts plus the source + and published table versions. + Examples -------- >>> import asyncio @@ -6143,12 +6162,16 @@ class AsyncTable: ... table = await db.create_table("computed_job_async_demo", [{"x": 1}]) ... await table.add_columns(computed={"doubled": "x * 2"}) ... job = await table.refresh_column_async("doubled") - ... await job.wait() + ... result = await job.wait() + ... assert result.rows_assigned == 1 ... return await job.status() >>> asyncio.run(refresh_in_background()) 'finished' """ - return AsyncJob(await self._inner.refresh_column_async(column)) + return _typed_job( + await self._inner.refresh_column_async(column), + RefreshColumnJobResult.from_json, + ) async def alter_columns( self, *alterations: Iterable[dict[str, Any]] diff --git a/python/python/tests/test_db.py b/python/python/tests/test_db.py index 38bbb53fb..aeb9feeb8 100644 --- a/python/python/tests/test_db.py +++ b/python/python/tests/test_db.py @@ -774,7 +774,7 @@ def test_drop_table_async(tmp_db: lancedb.DBConnection): job = tmp_db.drop_table_async("test") assert job.id is None assert job.status() == "finished" - job.wait() + assert job.wait() is None assert tmp_db.table_names() == [] tmp_db.create_table("test", data=data) @@ -790,7 +790,7 @@ async def test_drop_table_async_connection(tmp_db_async: lancedb.AsyncConnection job = await tmp_db_async.drop_table_async("test") assert job.id is None assert await job.status() == "finished" - await job.wait() + assert await job.wait() is None assert await tmp_db_async.table_names() == [] diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 99c68876c..a20347771 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -187,7 +187,7 @@ def _mock_remote_function_catalog(): "job_state": "DONE", "result": state["version"], } - elif self.path == "/v1/functions/get": + elif self.path == "/v1/functions/describe": assert body == { "name": "normalize_score", "version": "fv_exact", diff --git a/python/python/tests/test_index.py b/python/python/tests/test_index.py index 94268a53e..fe6ebe87a 100644 --- a/python/python/tests/test_index.py +++ b/python/python/tests/test_index.py @@ -88,7 +88,7 @@ async def binary_table(db_async): async def test_create_index_async_returns_done_job(some_table: AsyncTable): job = await some_table.create_index_async("id", config=BTree()) assert job.id is None - await job.wait() + assert await job.wait() is None assert len(await some_table.list_indices()) == 1 await job.cancel() diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 08f5550eb..2952f00a4 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -875,11 +875,85 @@ def test_remote_create_index_async_returns_job(): table = db.create_table("test", [{"id": 1}]) job = table.create_index_async("id", config=BTree()) assert job.id == "job-1" - job.wait(timeout=timedelta(seconds=30)) + assert job.wait(timeout=timedelta(seconds=30)) is None assert len(describe_calls) == 2 job.cancel() +def test_remote_refresh_async_returns_typed_terminal_result(): + terminal_result = { + "rows_assigned": 12, + "rows_failed": 0, + "rows_remaining": 0, + "source_version": 7, + "published_version": 8, + } + + def handler(request): + content_len = int(request.headers.get("Content-Length", 0)) + body = request.rfile.read(content_len) if content_len > 0 else b"" + if request.path == "/v1/table/test/backfill_column": + assert json.loads(body)["column"] == "derived" + request.send_response(202) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b'{"job_id": "refresh-1"}') + elif request.path == "/v1/jobs/describe": + assert json.loads(body)["job_id"] == "refresh-1" + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "job_id": "refresh-1", + "job_type": "function_refresh", + "job_state": "DONE", + "result": terminal_result, + } + ).encode() + ) + elif request.path == "/v1/table/test/create/?mode=create": + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(b"{}") + elif request.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": 1, + "schema": { + "fields": [ + { + "name": "id", + "type": {"type": "int64"}, + "nullable": False, + } + ] + }, + } + ).encode() + ) + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + table = db.create_table("test", [{"id": 1}]) + job = table.refresh_column_async("derived") + assert job.id == "refresh-1" + result = job.wait(timeout=timedelta(seconds=30)) + + assert isinstance(result, lancedb.RefreshColumnResult) + assert result.model_dump() == terminal_result + assert result.rows_filled == 12 + assert result.version == 8 + + def test_remote_job_wait_raises_on_failure(): from lancedb.exceptions import JobFailedError from lancedb.index import BTree diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 0f98219bf..56e0eacfd 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -1467,7 +1467,7 @@ def test_create_index_async_returns_done_job(mem_db: DBConnection): table = mem_db.create_table("job_test", [{"id": i} for i in range(10)]) job = table.create_index_async("id", config=BTree()) assert job.id is None - job.wait() + assert job.wait() is None assert len(table.list_indices()) == 1 job.cancel() @@ -3947,10 +3947,21 @@ def test_refresh_column_async_returns_job(tmp_path): job = table.refresh_column_async("doubled") assert job.id is None # in-process jobs have no server id - assert job.wait() is None + result = job.wait() + assert isinstance(result, lancedb.RefreshColumnResult) + assert result.rows_assigned == 2 + assert result.rows_failed == 0 + assert result.rows_remaining == 0 + assert result.source_version == 2 + assert result.published_version == 3 assert job.status() == "finished" assert sorted(table.to_arrow()["doubled"].to_pylist()) == [2, 4] + no_op = table.refresh_column_async("doubled").wait() + assert no_op.rows_assigned == 0 + assert no_op.source_version == 3 + assert no_op.published_version is None + # Bad input raises at the call, not through the job. with pytest.raises(Exception, match="not a computed column"): table.refresh_column_async("x") @@ -3963,6 +3974,10 @@ async def test_refresh_column_async_job_async_table(tmp_path): await table.add_columns(computed={"tripled": "x * 3"}) job = await table.refresh_column_async("tripled") - assert await job.wait() is None + result = await job.wait() + assert isinstance(result, lancedb.RefreshColumnResult) + assert result.rows_assigned == 1 + assert result.source_version == 2 + assert result.published_version == 3 assert await job.status() == "finished" assert (await table.to_arrow())["tripled"].to_pylist() == [9] diff --git a/python/src/connection.rs b/python/src/connection.rs index 4143ac9c9..902489f4f 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -609,7 +609,7 @@ impl Connection { .create_function_async(request) .await .infer_error() - .map(crate::job::FunctionJob::new) + .map(crate::job::Job::new_typed) }) } diff --git a/python/src/job.rs b/python/src/job.rs index a08b958a6..688cba7f9 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -5,72 +5,33 @@ use std::sync::Arc; use crate::runtime::future_into_py; use pyo3::{Bound, PyAny, PyRef, PyResult, pyclass, pymethods}; +use serde::Serialize; use crate::error::PythonErrorExt; #[pyclass] pub struct Job { - inner: Arc, -} - -/// Python bridge for a typed remote Function registration job. -/// -/// The public Python layer decodes the canonical JSON returned by `wait` -/// into its immutable `FunctionVersion` model. -#[pyclass] -pub struct FunctionJob { - inner: Arc>, -} - -impl FunctionJob { - pub(crate) fn new(inner: lancedb::Job) -> Self { - Self { - inner: Arc::new(inner), - } - } + inner: Arc, String>>>, } impl Job { pub(crate) fn new(inner: lancedb::Job) -> Self { Self { - inner: Arc::new(inner), + inner: Arc::new(inner.map(|()| Ok(None))), } } -} -#[pymethods] -impl FunctionJob { - #[getter] - pub fn id(&self) -> Option { - self.inner.id().map(str::to_string) - } - - pub fn status(self_: PyRef<'_, Self>) -> PyResult> { - let inner = self_.inner.clone(); - future_into_py( - self_.py(), - async move { inner.status().await.infer_error() }, - ) - } - - pub fn wait(self_: PyRef<'_, Self>) -> PyResult> { - let inner = self_.inner.clone(); - future_into_py(self_.py(), async move { - inner - .wait() - .await - .infer_error()? - .to_canonical_json() - .infer_error() - }) - } - - pub fn cancel(self_: PyRef<'_, Self>) -> PyResult> { - let inner = self_.inner.clone(); - future_into_py(self_.py(), async move { - inner.cancel().await.infer_error()?; - Ok(()) - }) + pub(crate) fn new_typed(inner: lancedb::Job) -> Self + where + T: Clone + Serialize + Send + Sync + 'static, + { + Self { + inner: Arc::new(inner.map(|result| { + serde_json::to_string(&result) + .map(Some) + .map_err(|error| format!("failed to serialize typed job result: {error}")) + })), + } } } @@ -92,8 +53,10 @@ impl Job { pub fn wait(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move { - inner.wait().await.infer_error()?; - Ok(None::<()>) + let result = inner.wait().await.infer_error()?; + result + .map_err(|message| lancedb::Error::Runtime { message }) + .infer_error() }) } diff --git a/python/src/lib.rs b/python/src/lib.rs index c1dfbc02b..8d3eab787 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -47,7 +47,6 @@ 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::()?; diff --git a/python/src/table.rs b/python/src/table.rs index 5cdcc3653..b225b191f 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -1619,7 +1619,7 @@ impl Table { let inner = self_.inner_ref()?.clone(); future_into_py(self_.py(), async move { let job = inner.refresh_column_async(column).await.infer_error()?; - Ok(crate::job::Job::new(job)) + Ok(crate::job::Job::new_typed(job)) }) } diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 835fca9a2..f02158871 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -1,7 +1,8 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -//! Canonical values exchanged with the Enterprise Function service. +//! Canonical Function values exchanged with the Enterprise service, plus the +//! backend-neutral terminal result of a computed-column refresh. //! //! This module contains client/wire values only. Catalog persistence, //! environment bake, secret resolution, and execution are owned by Sophon. @@ -580,13 +581,22 @@ impl FunctionBinding { impl_json!(FunctionBinding); -/// Stable terminal result of a remote Function-column refresh Job. +/// Stable terminal result of an expression-backed or Function-backed column +/// refresh [`crate::Job`]. +/// +/// Local refresh jobs produce this value in process. LanceDB Cloud and +/// Enterprise decode the same value from the durable job's terminal payload. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RefreshColumnResult { + /// Rows assigned a value by this refresh. pub rows_assigned: u64, + /// Rows whose computation failed. pub rows_failed: u64, + /// Rows that still need a value when the job completes. pub rows_remaining: u64, + /// Exact table version the refresh read. pub source_version: u64, + /// Table version made visible by the refresh, when one was published. #[serde(default, skip_serializing_if = "Option::is_none")] pub published_version: Option, } diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 1a76c7683..94d1ba2b6 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use async_trait::async_trait; -use serde::de::DeserializeOwned; +use serde::{Serialize, de::DeserializeOwned}; use serde_json::Value; use tokio::sync::watch; use tokio::task::{AbortHandle, JoinHandle}; @@ -26,20 +26,16 @@ pub(crate) trait JobHandle: Send + Sync { } /// A backend-neutral successful terminal result. -/// -/// Local operations do not carry a value. Remote operations may carry JSON -/// that the public [`Job`] decodes according to its result type. +#[derive(Clone)] pub(crate) struct TerminalResult { - #[allow(dead_code)] // Typed remote submit endpoints consume this after Slice 1. value: Option, - #[allow(dead_code)] // Preserved so typed decode errors retain request correlation. request_id: Option, } impl TerminalResult { - pub(crate) fn local() -> Self { + fn local(value: Value) -> Self { Self { - value: None, + value: Some(value), request_id: None, } } @@ -51,23 +47,31 @@ impl TerminalResult { } } - #[allow(dead_code)] // Exercised by the remote typed-result fixtures in Slice 1. fn decode(self) -> Result { - let request_id = self.request_id.unwrap_or_default(); - let value = self.value.ok_or_else(|| Error::Http { - source: "successful typed job response did not contain a result".into(), - request_id: request_id.clone(), - status_code: None, + let value = self.value.ok_or_else(|| match &self.request_id { + Some(request_id) => Error::Http { + source: "successful typed job response did not contain a result".into(), + request_id: request_id.clone(), + status_code: None, + }, + None => Error::Runtime { + message: "successful typed job did not contain a result".to_string(), + }, })?; - serde_json::from_value(value).map_err(|error| Error::Http { - source: format!("failed to parse typed job result: {error}").into(), - request_id, - status_code: None, + serde_json::from_value(value).map_err(|error| match self.request_id { + Some(request_id) => Error::Http { + source: format!("failed to parse typed job result: {error}").into(), + request_id, + status_code: None, + }, + None => Error::Runtime { + message: format!("failed to parse typed job result: {error}"), + }, }) } } -type ResultDecoder = fn(TerminalResult) -> Result; +type ResultDecoder = Arc Result + Send + Sync>; enum JobInner { Handle { @@ -79,7 +83,9 @@ enum JobInner { /// A handle to an operation that may still be running. /// -/// The operation may already be complete when the handle is created. +/// The operation may already be complete when the handle is created. `T` is +/// the endpoint's successful terminal result; unit-result operations use the +/// default `Job<()>`. pub struct Job where T: Clone + Send + Sync + 'static, @@ -111,15 +117,10 @@ impl Job<()> { Self { inner: JobInner::Handle { handle, - decode: |_| Ok(()), + decode: Arc::new(|_| Ok(())), }, } } - - /// A unit-result job running as a task in this process. - pub(crate) fn spawned(task: JoinHandle>) -> Self { - Self::new(Box::new(SpawnedJob::new(task))) - } } impl Job @@ -131,12 +132,22 @@ where Self { inner: JobInner::Handle { handle, - decode: TerminalResult::decode::, + decode: Arc::new(TerminalResult::decode::), }, } } } +impl Job +where + T: Clone + Serialize + DeserializeOwned + Send + Sync + 'static, +{ + /// A typed job running as a task in this process. + pub(crate) fn spawned(task: JoinHandle>) -> Self { + Self::new_typed(Box::new(SpawnedJob::new(task))) + } +} + impl Job where T: Clone + Send + Sync + 'static, @@ -169,11 +180,13 @@ where /// Waits until the operation reaches a terminal state. /// + /// Returns the endpoint's typed result. Unit-result jobs return `()`. + /// /// Returns [`crate::Error::JobFailed`] if the operation failed and /// [`crate::Error::JobCancelled`] if it was cancelled. pub async fn wait(&self) -> Result { match &self.inner { - JobInner::Handle { handle, decode } => decode(handle.wait().await?), + JobInner::Handle { handle, decode } => (decode)(handle.wait().await?), JobInner::Completed(result) => Ok(result.clone()), } } @@ -187,21 +200,53 @@ where JobInner::Completed(_) => Ok(()), } } + + /// Maps a successful terminal result without changing the job lifecycle. + /// The mapping may run once for each call to [`Job::wait`], so it should + /// be deterministic and free of externally visible side effects. + /// + /// ``` + /// use lancedb::{Job, function::RefreshColumnResult}; + /// + /// # async fn rows_assigned( + /// # job: Job, + /// # ) -> lancedb::Result { + /// let job = job.map(|result| result.rows_assigned); + /// job.wait().await + /// # } + /// ``` + pub fn map(self, map: F) -> Job + where + U: Clone + Send + Sync + 'static, + F: Fn(T) -> U + Send + Sync + 'static, + { + match self.inner { + JobInner::Handle { handle, decode } => Job { + inner: JobInner::Handle { + handle, + decode: Arc::new(move |result| Ok(map((decode)(result)?))), + }, + }, + JobInner::Completed(result) => Job { + inner: JobInner::Completed(map(result)), + }, + } + } } /// How an in-process operation ended. Cloneable so every waiter can be given /// the outcome; [`Error`] is not, so failures share one behind an [`Arc`]. #[derive(Clone)] enum Outcome { - Succeeded, + Succeeded(TerminalResult), Failed(Arc), Cancelled, } impl Outcome { - fn into_result(self) -> Result<()> { + fn into_result(self) -> Result { match self { - Self::Succeeded => Ok(()), + Self::Succeeded(result) => Ok(result), Self::Failed(source) => Err(Error::JobFailed { job_id: None, failure: JobFailure::from_source(source), @@ -220,12 +265,20 @@ struct SpawnedJob { } impl SpawnedJob { - fn new(task: JoinHandle>) -> Self { + fn new(task: JoinHandle>) -> Self + where + T: Serialize + Send + 'static, + { let abort = task.abort_handle(); let (tx, outcome) = watch::channel(None); tokio::spawn(async move { let outcome = match task.await { - Ok(Ok(())) => Outcome::Succeeded, + Ok(Ok(result)) => match serde_json::to_value(result) { + Ok(value) => Outcome::Succeeded(TerminalResult::local(value)), + Err(err) => Outcome::Failed(Arc::new(Error::Runtime { + message: format!("failed to serialize job result: {err}"), + })), + }, Ok(Err(err)) => Outcome::Failed(Arc::new(err)), Err(err) if err.is_cancelled() => Outcome::Cancelled, Err(err) => Outcome::Failed(Arc::new(Error::Runtime { @@ -243,7 +296,7 @@ impl JobHandle for SpawnedJob { async fn status(&self) -> Result { let label = match &*self.outcome.borrow() { None => "running", - Some(Outcome::Succeeded) => "finished", + Some(Outcome::Succeeded(_)) => "finished", Some(Outcome::Failed(_)) => "failed", Some(Outcome::Cancelled) => "cancelled", }; @@ -256,12 +309,11 @@ impl JobHandle for SpawnedJob { .wait_for(|outcome| outcome.is_some()) .await .map_err(|_| Error::Runtime { - message: "index job outcome was dropped before it completed".to_string(), + message: "job outcome was dropped before it completed".to_string(), })? .clone() .expect("wait_for returns once an outcome is set"); - settled.into_result()?; - Ok(TerminalResult::local()) + settled.into_result() } async fn cancel(&self) -> Result<()> { @@ -269,3 +321,29 @@ impl JobHandle for SpawnedJob { Ok(()) } } + +#[cfg(test)] +mod tests { + use std::future::pending; + + use super::*; + + #[tokio::test] + async fn mapped_spawned_job_reuses_outcome() { + let job = Job::spawned(tokio::spawn(async { Ok(41_u64) })).map(|value| value + 1); + + assert_eq!(job.wait().await.unwrap(), 42); + assert_eq!(job.wait().await.unwrap(), 42); + assert_eq!(job.status().await.unwrap(), "finished"); + } + + #[tokio::test] + async fn mapped_spawned_job_preserves_cancellation() { + let job = Job::spawned(tokio::spawn(async { pending::>().await })) + .map(|value| value.to_string()); + + job.cancel().await.unwrap(); + assert!(matches!(job.wait().await, Err(Error::JobCancelled { .. }))); + assert_eq!(job.status().await.unwrap(), "cancelled"); + } +} diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 169d0fda5..8265d22c0 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -513,7 +513,7 @@ impl Database for RemoteDatabase { async fn get_function(&self, name: &str, version: &str) -> Result { let req = self .client - .post("/v1/functions/get") + .post("/v1/functions/describe") .json(&serde_json::json!({ "name": name, "version": version, @@ -2520,7 +2520,7 @@ mod tests { ); let conn = Connection::new_with_handler(|request| { assert_eq!(request.method(), &reqwest::Method::POST); - assert_eq!(request.url().path(), "/v1/functions/get"); + assert_eq!(request.url().path(), "/v1/functions/describe"); let body: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); assert_eq!( diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index fb7278db9..c6b078282 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2864,7 +2864,10 @@ impl BaseTable for RemoteTable { }) } - async fn refresh_column_async(&self, column: &str) -> Result { + async fn refresh_column_async( + &self, + column: &str, + ) -> Result> { self.check_mutable().await?; let mut body = serde_json::json!({ "column": column }); self.apply_branch_body(&mut body); @@ -2885,7 +2888,7 @@ impl BaseTable for RemoteTable { status_code: None, })?; - Ok(Job::new(Box::new(FreshnessJob { + Ok(Job::new_typed(Box::new(FreshnessJob { inner: RemoteJob::new(self.client.clone(), response.job_id), freshness: self.freshness.clone(), version: self.version.clone(), @@ -3280,6 +3283,21 @@ mod tests { }, }; + fn refresh_done(job_id: &str) -> String { + json!({ + "job_id": job_id, + "job_state": "DONE", + "result": { + "rows_assigned": 12, + "rows_failed": 0, + "rows_remaining": 0, + "source_version": 7, + "published_version": 8, + } + }) + .to_string() + } + #[tokio::test] async fn test_not_found() { let table = Table::new_with_handler("my_table", |_| { @@ -6892,7 +6910,7 @@ mod tests { .unwrap(), "/v1/jobs/describe" => http::Response::builder() .status(200) - .body(r#"{"job_id": "j-7", "job_state": "DONE"}"#.to_string()) + .body(refresh_done("j-7")) .unwrap(), "/v1/table/my_table/count_rows/" => { saw.store( @@ -6908,7 +6926,9 @@ mod tests { }); let job = table.refresh_column_async("doubled").await.unwrap(); - job.wait().await.unwrap(); + let result = job.wait().await.unwrap(); + assert_eq!(result.rows_assigned, 12); + assert_eq!(result.published_version, Some(8)); table.count_rows(None).await.unwrap(); assert!( saw_min_timestamp.load(std::sync::atomic::Ordering::SeqCst), @@ -6930,7 +6950,7 @@ mod tests { .unwrap(), "/v1/jobs/describe" => http::Response::builder() .status(200) - .body(r#"{"job_id": "j-8", "job_state": "DONE"}"#.to_string()) + .body(refresh_done("j-8")) .unwrap(), "/v1/table/my_table/describe/" => { let schema = Schema::new(vec![Field::new("x", DataType::Int32, true)]); @@ -6976,7 +6996,7 @@ mod tests { .unwrap(), "/v1/jobs/describe" => http::Response::builder() .status(200) - .body(r#"{"job_id": "j-9", "job_state": "DONE"}"#.to_string()) + .body(refresh_done("j-9")) .unwrap(), "/v1/table/my_table/tags/version/" => http::Response::builder() .status(200) @@ -7040,7 +7060,7 @@ mod tests { } "/v1/jobs/describe" => http::Response::builder() .status(200) - .body(r#"{"job_id": "j-10", "job_state": "DONE"}"#.to_string()) + .body(refresh_done("j-10")) .unwrap(), "/v1/table/my_table/describe/" => { let schema = Schema::new(vec![Field::new("x", DataType::Int32, true)]); @@ -7113,7 +7133,7 @@ mod tests { } "/v1/jobs/describe" => http::Response::builder() .status(200) - .body(r#"{"job_id": "j-11", "job_state": "DONE"}"#.to_string()) + .body(refresh_done("j-11")) .unwrap(), "/v1/table/my_table/count_rows/" => { *saw.lock().unwrap() = request diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index c2c12fff5..41551bd37 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -771,7 +771,10 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { } /// Fill a computed column's unfilled rows, returning a [`Job`] tracking /// the operation. - async fn refresh_column_async(&self, _column: &str) -> Result { + async fn refresh_column_async( + &self, + _column: &str, + ) -> Result> { Err(Error::NotSupported { message: "computed columns are supported only on local tables".into(), }) @@ -1708,7 +1711,9 @@ impl Table { /// operation instead of blocking until it completes. /// /// The job may already be complete when returned, and callers must not - /// assume the column is filled until [`Job::wait`] returns. Invalid input + /// assume the column is filled until [`Job::wait`] returns. A successful + /// wait returns the durable [`crate::function::RefreshColumnResult`] for + /// both expression-backed and Function-backed columns. Invalid input /// -- an unknown column, or one that is not computed -- is reported by /// this call rather than by the job. On local tables the job runs as an /// in-process task; on LanceDB Cloud and Enterprise it is the server's @@ -1719,11 +1724,15 @@ impl Table { /// # async fn refresh_in_background(table: &Table) -> Result<(), Box> { /// let job = table.refresh_column_async("doubled").await?; /// println!("refresh running: {:?}", job.status().await?); - /// job.wait().await?; + /// let result = job.wait().await?; + /// println!("assigned {} rows", result.rows_assigned); /// # Ok(()) /// # } /// ``` - pub async fn refresh_column_async(&self, column: impl AsRef) -> Result { + pub async fn refresh_column_async( + &self, + column: impl AsRef, + ) -> Result> { self.inner.refresh_column_async(column.as_ref()).await } @@ -3425,7 +3434,10 @@ impl BaseTable for NativeTable { Ok(result) } - async fn refresh_column_async(&self, column: &str) -> Result { + async fn refresh_column_async( + &self, + column: &str, + ) -> Result> { refresh::execute_refresh_column_async(self, column).await } diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 7d74bbae7..35f883411 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -49,11 +49,25 @@ pub struct RefreshColumnResult { pub version: u64, } +struct RefreshExecution { + result: RefreshColumnResult, + source_version: u64, +} + /// Internal implementation of the refresh logic. pub(crate) async fn execute_refresh_column( table: &NativeTable, column: &str, ) -> Result { + Ok(execute_refresh_column_with_source(table, column) + .await? + .result) +} + +async fn execute_refresh_column_with_source( + table: &NativeTable, + column: &str, +) -> Result { table.dataset.ensure_mutable()?; ensure_no_lsm_write_spec(table).await?; let dataset = table.dataset.get().await?; @@ -87,9 +101,13 @@ pub(crate) async fn execute_refresh_column( } if replacements.is_empty() { - return Ok(RefreshColumnResult { - rows_filled: 0, - version: dataset.version().version, + let source_version = dataset.version().version; + return Ok(RefreshExecution { + result: RefreshColumnResult { + rows_filled: 0, + version: source_version, + }, + source_version, }); } @@ -110,14 +128,20 @@ pub(crate) async fn execute_refresh_column( let version = new_dataset.version().version; table.dataset.update(new_dataset); - Ok(RefreshColumnResult { - rows_filled, - version, + Ok(RefreshExecution { + result: RefreshColumnResult { + rows_filled, + version, + }, + source_version: read_version, }) } /// Run the refresh as a [`Job`] in this process. -pub(crate) async fn execute_refresh_column_async(table: &NativeTable, column: &str) -> Result { +pub(crate) async fn execute_refresh_column_async( + table: &NativeTable, + column: &str, +) -> Result> { // Validate before spawning so bad input is reported by this call rather // than only by the job. table.dataset.ensure_mutable()?; @@ -129,9 +153,16 @@ pub(crate) async fn execute_refresh_column_async(table: &NativeTable, column: &s let table = table.clone(); let column = column.to_string(); Ok(Job::spawned(tokio::spawn(async move { - execute_refresh_column(&table, &column).await?; + let execution = execute_refresh_column_with_source(&table, &column).await?; table.bump_freshness(); - Ok(()) + Ok(crate::function::RefreshColumnResult { + rows_assigned: execution.result.rows_filled, + rows_failed: 0, + rows_remaining: 0, + source_version: execution.source_version, + published_version: (execution.result.rows_filled > 0) + .then_some(execution.result.version), + }) }))) } @@ -396,6 +427,17 @@ mod tests { read(&table, "doubled").await, vec![Some(2), Some(4), Some(6)] ); + + let no_op = table + .refresh_column_async("doubled") + .await + .unwrap() + .wait() + .await + .unwrap(); + assert_eq!(no_op.rows_assigned, 0); + assert_eq!(no_op.source_version, 3); + assert_eq!(no_op.published_version, None); } /// Values written after the last refresh must be reachable by another one. @@ -646,7 +688,12 @@ mod tests { let job = table.refresh_column_async("doubled").await.unwrap(); assert!(job.id().is_none(), "in-process jobs have no server id"); - job.wait().await.unwrap(); + let result = job.wait().await.unwrap(); + assert_eq!(result.rows_assigned, 3); + assert_eq!(result.rows_failed, 0); + assert_eq!(result.rows_remaining, 0); + assert_eq!(result.source_version, 2); + assert_eq!(result.published_version, Some(3)); assert_eq!(job.status().await.unwrap(), "finished"); assert_eq!( read(&table, "doubled").await, @@ -672,9 +719,9 @@ mod tests { declare_doubled(&table).await.unwrap(); let job = table.refresh_column_async("doubled").await.unwrap(); - job.wait().await.unwrap(); + let first = job.wait().await.unwrap(); // A second wait after completion observes the same outcome. - job.wait().await.unwrap(); + assert_eq!(job.wait().await.unwrap(), first); assert_eq!(job.status().await.unwrap(), "finished"); } From 94d484f539048ada0b92deb289251d6e5ed7211e Mon Sep 17 00:00:00 2001 From: Will Jones Date: Mon, 24 Aug 2026 12:00:48 -0700 Subject: [PATCH 101/206] fix(listing): don't drop a table at a page boundary (#4040) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Listing tables a page at a time against a local database silently skipped one table at every page boundary. `ListingDatabase::list_tables` returned the first name of the *next* page as that page's token, but resuming from a token drops every name at or before it — so the table the token named was never handed to the caller. Walking `[a, b, c, d, e]` with a limit of 2 returned `[a, b, d, e]`. This PR returns the last name of the page as the token instead, which is what resuming after the token expects. This is reachable from Python today through `db.list_tables(page_token=...)` on a local connection; it also affects `len(db)` and `name in db`, which walk the pages. Remote and namespace-backed connections page on the server and were never affected. ## Example ```python db = lancedb.connect(tmp_path) for name in ["a", "b", "c", "d", "e"]: db.create_table(name, [{"id": 1}]) names, token = [], None while True: page = db.list_tables(page_token=token, limit=2) names += page.tables token = page.page_token if not token: break # before: ['a', 'b', 'd', 'e'] # after: ['a', 'b', 'c', 'd', 'e'] ``` Co-authored-by: Claude Opus 5 (1M context) --- rust/lancedb/src/connection.rs | 44 ++++++++++++++++++++++++++++ rust/lancedb/src/database/listing.rs | 16 +++++----- 2 files changed, 51 insertions(+), 9 deletions(-) diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 187e2df0e..5f66d9dee 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -1679,6 +1679,50 @@ mod tests { assert_eq!(tables, names[..7]); } + #[tokio::test] + async fn test_list_tables_walks_page_boundaries() { + let tc = new_test_connection().await.unwrap(); + if tc.is_remote { + // What resumes a page is the server's to decide, and asserting it here would be + // asserting the server's contract rather than this one. + return; + } + let db = tc.connection; + let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, false)])); + let mut names = Vec::with_capacity(5); + for _ in 0..5 { + let name = uuid::Uuid::new_v4().to_string(); + names.push(name.clone()); + db.create_empty_table(name, schema.clone()) + .execute() + .await + .unwrap(); + } + names.sort(); + + // Walking in pages has to reach every table exactly once, with nothing lost at a + // page boundary. + let mut seen = Vec::with_capacity(names.len()); + let mut page_token = None; + loop { + let page = db + .list_tables(ListTablesRequest { + id: Some(Vec::new()), + limit: Some(2), + page_token, + ..Default::default() + }) + .await + .unwrap(); + seen.extend(page.tables); + page_token = page.page_token.filter(|token| !token.is_empty()); + if page_token.is_none() { + break; + } + } + assert_eq!(seen, names); + } + #[tokio::test] async fn test_open_table() { let tc = new_test_connection().await.unwrap(); diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index c9e9bcb22..17dc82756 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -974,17 +974,15 @@ impl Database for ListingDatabase { f.drain(0..index); } - // Determine if there's a next page - let next_page_token = if let Some(limit) = request.limit { - if f.len() > limit as usize { - let token = f[limit as usize].clone(); + // Determine if there's a next page. The token is the last name of this page, + // not the first of the next one: the next page resumes strictly after the + // token, so naming the next page's first entry would skip it. + let next_page_token = match request.limit { + Some(limit) if f.len() > limit as usize => { f.truncate(limit as usize); - Some(token) - } else { - None + f.last().cloned() } - } else { - None + _ => None, }; Ok(ListTablesResponse { From 105fd73bc6da822e40f2c7206c8612bd009023bd Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Tue, 25 Aug 2026 04:22:22 +0800 Subject: [PATCH 102/206] fix(python): commit streaming worker checkpoints on consumption (#4023) ## Summary - add `StreamingDataLoader`, which transports worker snapshots with prefetched batches and commits them to the parent dataset only when the trainer receives each batch - preserve exact non-uniform per-split progress and resume lagging splits without replaying already-consumed rows - reject stale parent checkpoints after a standard multi-process `DataLoader` has started, with guidance to use the consumer-aware loader - document the new public loader and merge non-uniform state across ranks ## Root cause PyTorch runs `StreamingDataset.__iter__` in private worker-process copies, while callers invoke `state_dict()` on the parent dataset. Sharing producer counters would still be incorrect because DataLoader prefetch can advance workers beyond batches returned to the trainer. ## Validation - `uv run --extra tests pytest python/tests/test_elastic_dataloader.py -q` (154 passed) - focused non-uniform merge regression (1 passed) - `uv run --project python --extra tests --extra dev ruff format .` - `uv run --project python --extra tests --extra dev ruff check .` - `cd docs && PYTHONPATH=. ../python/.venv/bin/mkdocs build` Fixes #3967 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- docs/src/python/python.md | 2 + python/python/lancedb/streaming.py | 594 +++++++++++++++- .../python/tests/test_elastic_dataloader.py | 658 ++++++++++++++++++ 3 files changed, 1221 insertions(+), 33 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 8a24ea199..3cbeee6f0 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -261,6 +261,8 @@ instead of being materialized with the rest of the row. ::: lancedb.streaming.StreamingDataset +::: lancedb.streaming.StreamingDataLoader + ::: lancedb.permutation.permutation_builder ::: lancedb.permutation.PermutationBuilder diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py index c54940ab7..2c0e2d5c1 100644 --- a/python/python/lancedb/streaming.py +++ b/python/python/lancedb/streaming.py @@ -19,6 +19,7 @@ above. """ import ctypes +import heapq import logging import os import random @@ -29,12 +30,12 @@ from collections import deque from concurrent.futures import ThreadPoolExecutor from copy import deepcopy from multiprocessing import RawArray -from typing import Any, Callable, cast, Iterator, Literal, Optional, Union +from typing import Any, Callable, cast, Iterator, Literal, NamedTuple, Optional, Union import pyarrow as pa import pyarrow.compute as pc import torch -from torch.utils.data import IterableDataset, get_worker_info +from torch.utils.data import DataLoader, IterableDataset, get_worker_info from .permutation import ( Permutation, @@ -55,6 +56,155 @@ DEFAULT_READ_BATCH_SIZE = 64 DEFAULT_PREFETCH_BATCHES = 4 +class _WorkerSample(NamedTuple): + data: Any + dataset: "StreamingDataset" + + +class _WorkerBatch(NamedTuple): + data: Any + state: dict + + +class _ConsumerIteratorLease(NamedTuple): + owner_token: int + owner_thread: int + + +class _CheckpointCollate: + """Attach the worker's post-fetch state to a collated batch.""" + + def __init__(self, collate_fn: Callable): + self._collate_fn = collate_fn + + def __call__(self, samples): + try: + if isinstance(samples, list): + if not samples: + return _WorkerBatch(self._collate_fn(samples), {}) + worker_samples = samples + data = self._collate_fn([sample.data for sample in worker_samples]) + dataset = worker_samples[-1].dataset + else: + data = self._collate_fn(samples.data) + dataset = samples.dataset + except StopIteration as exc: + raise RuntimeError( + "collate_fn raised StopIteration before returning a batch" + ) from exc + return _WorkerBatch(data, dataset._checkpoint_snapshot()) + + +class _StreamingDatasetAdapter(IterableDataset): + """Yield private sample wrappers for :class:`StreamingDataLoader`.""" + + def __init__(self, dataset: "StreamingDataset"): + super().__init__() + self.dataset = dataset + + def __iter__(self): + for sample in self.dataset._iter(consumer_checkpoint_transport=True): + yield _WorkerSample(sample, self.dataset) + + def __getattr__(self, name): + dataset = self.__dict__.get("dataset") + if dataset is None: + raise AttributeError(name) + return getattr(dataset, name) + + +class _ConsumerCommitIterator: + def __init__( + self, + iterator, + dataset: "StreamingDataset", + *, + owner_token: int, + require_uniform: bool, + ): + self._iterator = iterator + self._dataset = dataset + self._owner_token = owner_token + self._require_uniform = require_uniform + self._released = False + self._terminal = False + + def __iter__(self): + return self + + def __next__(self): + if self._terminal: + raise StopIteration + try: + batch = next(self._iterator) + except StopIteration: + self._terminal = True + self._release() + raise + except BaseException as exc: + self._dataset._invalidate_checkpoint( + f"a DataLoader batch failed before it was returned: {exc}" + ) + raise + try: + if not isinstance(batch, _WorkerBatch): + raise RuntimeError( + "StreamingDataLoader did not receive worker checkpoint metadata" + ) + self._dataset._commit_worker_state( + batch.state, require_uniform=self._require_uniform + ) + return batch.data + except BaseException as exc: + self._dataset._invalidate_checkpoint( + f"a DataLoader batch failed before it was returned: {exc}" + ) + raise + + def _release(self) -> None: + if self.__dict__.get("_released", True): + return + self._released = True + dataset = self.__dict__.get("_dataset") + if dataset is not None: + dataset._release_consumer_iterator(self._owner_token) + + def _shutdown_workers(self): + if self.__dict__.get("_released", True): + return None + self._terminal = True + iterator = self.__dict__.get("_iterator") + shutdown = getattr(iterator, "_shutdown_workers", None) + try: + if shutdown is not None: + shutdown() + else: + fetcher = getattr(iterator, "_dataset_fetcher", None) + dataset_iterator = getattr(fetcher, "dataset_iter", None) + close = getattr(dataset_iterator, "close", None) + if close is None: + raise RuntimeError( + "StreamingDataLoader could not close its inner iterator" + ) + close() + except BaseException as exc: + self._dataset._invalidate_checkpoint( + f"a DataLoader iterator could not be shut down safely: {exc}" + ) + raise + else: + self._release() + + def __del__(self): + try: + self._shutdown_workers() + except BaseException: + pass + + def __getattr__(self, name): + return getattr(self._iterator, name) + + class StreamingDataset(IterableDataset): """An elastic, resumable PyTorch IterableDataset backed by a LanceDB table. @@ -384,6 +534,22 @@ class StreamingDataset(IterableDataset): # rows_skipped] self._worker_stats: RawArray = RawArray(ctypes.c_int64, 8) + # A standard multi-process DataLoader cannot report which prefetched + # batches were actually returned to its consumer. Workers set this + # shared flag so state_dict() can reject a stale parent checkpoint + # unless StreamingDataLoader installed the consumer-commit transport. + self._untracked_worker_iteration: RawArray = RawArray(ctypes.c_int64, 1) + + # Parent-side checkpoint lifecycle. A failed DataLoader task creates + # a permanent hole in that iterator's delivery stream, while a + # multi-worker checkpoint is safe to restore only after all splits + # reach the same logical step boundary. + self._checkpoint_invalid_reason: Optional[str] = None + self._consumer_checkpoint_requires_uniform = False + self._consumer_iterator_lock = threading.Lock() + self._consumer_iterator_generation = 0 + self._consumer_iterator_lease: Optional[_ConsumerIteratorLease] = None + # Cumulative bytes of Arrow buffer data fetched across all iterations. self._bytes_loaded: int = 0 # Cumulative seconds spent in LanceDB I/O and in transform functions. @@ -396,6 +562,10 @@ class StreamingDataset(IterableDataset): # step boundaries all splits have consumed this many samples, so a # single scalar captures the topology-independent checkpoint state. self._resume_offset: int = 0 + # Exact yielded-sample counts for splits this process has advanced. + # Missing entries use _resume_offset, which remains the lower-bound + # checkpoint inherited from an earlier uniform/global state. + self._resume_samples: dict[int, int] = {} # Permutation position each split has consumed through, keyed by # global split index. Equal to _resume_offset for every split unless # on_transform_error skipped rows, in which case skipped positions @@ -521,11 +691,45 @@ class StreamingDataset(IterableDataset): return self._rank_splits[start : start + splits_per_worker] def __iter__(self) -> Iterator[dict[str, Any]]: + return self._iter() + + def _iter( + self, *, consumer_checkpoint_transport: bool = False + ) -> Iterator[dict[str, Any]]: + owner_token = None + previous_lease = self._consumer_iterator_lease + if consumer_checkpoint_transport: + if not self._consumer_iterator_active: + raise RuntimeError( + "StreamingDataLoader worker transport requires an active " + "parent iterator reservation" + ) + else: + try: + owner_token = self._acquire_consumer_iterator() + except BaseException: + self._release_consumer_iterator_after_failed_acquire(previous_lease) + raise + try: + yield from self._iter_owned( + consumer_checkpoint_transport=consumer_checkpoint_transport + ) + finally: + if owner_token is not None: + self._release_consumer_iterator(owner_token) + + def _iter_owned( + self, *, consumer_checkpoint_transport: bool + ) -> Iterator[dict[str, Any]]: if self._raw_batches_ref is not None: raise RuntimeError( "StreamingDataset does not support concurrent iteration. " "Only one active iterator per dataset instance is allowed." ) + real_worker = get_worker_info() is not None + if real_worker and not consumer_checkpoint_transport: + self._untracked_worker_iteration[0] = 1 + my_splits = self._resolve_my_splits() if not my_splits: return @@ -533,6 +737,7 @@ class StreamingDataset(IterableDataset): # Set identity transform on each Permutation so __getitems__ returns # the raw RecordBatch. Stage 2 applies the real transform. permutations: list[Permutation] = [] + initial_samples: list[int] = [] initial_positions: list[int] = [] for split_idx in my_splits: perm = Permutation.from_tables( @@ -541,21 +746,22 @@ class StreamingDataset(IterableDataset): if self._columns is not None: perm = perm.select_columns(self._columns) perm = perm.with_transform(Transforms.arrow2arrow) + sample_count = self._resume_samples.get(split_idx, self._resume_offset) # Both modes resume from absolute permutation positions. Packing # stores them separately because it also checkpoints partial blocks. start_pos = ( self._pack_consumed[split_idx] if self._pack_sequences is not None - else self._resume_positions.get(split_idx, self._resume_offset) + else self._resume_positions.get(split_idx, sample_count) ) if start_pos > 0: perm = perm.with_skip(start_pos) + initial_samples.append(sample_count) initial_positions.append(start_pos) permutations.append(perm) n = len(permutations) split_sizes = [perm.num_rows for perm in permutations] - initial_offset = self._resume_offset local_consumed = [0] * n # Permutation position each split has consumed through (absolute, # i.e. counted from the start of the unskipped split). Runs ahead of @@ -853,6 +1059,27 @@ class StreamingDataset(IterableDataset): for i in range(n): _fill_io(i) + def _yield_row(i: int): + pos, row = cooked[i].popleft() + # Surface any completed prefetched failure before the + # current row becomes durable checkpoint progress. + _advance(i) + local_consumed[i] += 1 + pos_consumed[i] = pos + 1 + split_idx = my_splits[i] + self._resume_samples[split_idx] = ( + initial_samples[i] + local_consumed[i] + ) + self._resume_positions[split_idx] = pos_consumed[i] + return row + + def _update_progress_stats() -> None: + if not real_worker: + self._resume_offset = min( + initial_samples[j] + local_consumed[j] for j in range(n) + ) + _update_stats() + if self._pack_sequences is not None: first_count = pack_blocks_emitted[my_splits[0]] if any( @@ -878,12 +1105,38 @@ class StreamingDataset(IterableDataset): tokens.extend([pad_id] * (pack_len - len(tokens))) block = _emit_block(i) pack_blocks_emitted[my_splits[i]] += 1 + # Checkpoint state must advance before yielding so + # StreamingDataLoader can attach the exact state to + # the batch it transports to the parent process. + _commit_pack_state() if i == n - 1: - _commit_pack_state() _update_stats() yield block return + # A checkpoint taken between round-robin split turns has + # non-uniform counts. Resume lagging splits first so the + # exact canonical sequence continues without replaying + # already-consumed rows. + if len(set(initial_samples)) > 1: + catch_up_to = max(initial_samples) + pending = [ + (initial_samples[i], my_splits[i], i) + for i in range(n) + if initial_samples[i] < catch_up_to + ] + heapq.heapify(pending) + while pending: + consumed, _, i = heapq.heappop(pending) + _ensure_cooked(i) + if not cooked[i]: + return + row = _yield_row(i) + if consumed + 1 < catch_up_to: + heapq.heappush(pending, (consumed + 1, my_splits[i], i)) + _update_progress_stats() + yield row + while True: # A cycle only runs if every split can still produce a # row. Without skips all splits exhaust simultaneously @@ -904,20 +1157,14 @@ class StreamingDataset(IterableDataset): break for i in range(n): - pos, row = cooked[i].popleft() - local_consumed[i] += 1 - pos_consumed[i] = pos + 1 - _advance(i) + row = _yield_row(i) # After the last split in each cycle: update the # global offset and refresh the shared-memory stats # so the main process can observe pipeline depth # even when __iter__ runs in a worker process. if i == n - 1: - self._resume_offset = initial_offset + local_consumed[i] - for j, split_idx in enumerate(my_splits): - self._resume_positions[split_idx] = pos_consumed[j] - _update_stats() + _update_progress_stats() yield row finally: @@ -1064,6 +1311,7 @@ class StreamingDataset(IterableDataset): "_local_consumed_ref", ): state[key] = None + state["_consumer_iterator_lock"] = None return state def __setstate__(self, state): @@ -1074,6 +1322,7 @@ class StreamingDataset(IterableDataset): table_state = state.pop("_table") perm_name, perm_data = state.pop("_perm_table") self.__dict__.update(state) + self._consumer_iterator_lock = threading.Lock() if self._connection_factory is not None: self._table = self._connection_factory(table_name) else: @@ -1083,10 +1332,18 @@ class StreamingDataset(IterableDataset): def state_dict(self) -> dict: """Snapshot the dataset's consumption state. + When using DataLoader workers, construct a + [StreamingDataLoader][lancedb.streaming.StreamingDataLoader]. It + commits worker state only when a prefetched batch is returned to the + trainer. A standard multi-process ``DataLoader`` cannot expose that + boundary, so calling this method after one has started raises + ``RuntimeError`` instead of returning stale producer state. + In row mode, the returned dict is topology-independent at global step boundaries. ``positions_consumed_per_split`` records how far each split's permutation has advanced, which can differ from the sample - count when ``on_transform_error`` skips rows. Combine state dicts from + count when ``on_transform_error`` skips rows. ``StreamingDataLoader`` + combines worker state in its parent process. Combine state dicts from every rank with [merge_state_dicts][lancedb.streaming.StreamingDataset.merge_state_dicts] before resuming on a different topology. @@ -1095,6 +1352,43 @@ class StreamingDataset(IterableDataset): for every logical split. When packing is sharded, merge every rank state with ``merge_state_dicts`` before loading it. """ + if self._untracked_worker_iteration[0] and get_worker_info() is None: + raise RuntimeError( + "StreamingDataset cannot checkpoint a standard DataLoader with " + "num_workers > 0 because prefetched worker progress is not " + "consumer-committed. Use StreamingDataLoader instead." + ) + if self._checkpoint_invalid_reason is not None: + raise RuntimeError( + "StreamingDataset checkpointing is invalid because " + f"{self._checkpoint_invalid_reason}. Load the last valid " + "checkpoint into a fresh dataset before continuing." + ) + state = self._checkpoint_snapshot() + if self._pack_sequences is not None: + rank_blocks = [ + state["blocks_emitted_per_split"][split] for split in self._rank_splits + ] + if len(set(rank_blocks)) > 1: + raise RuntimeError( + "Packed StreamingDataset checkpointing is only safe at a " + "complete logical step boundary, when every split assigned " + "to this rank has emitted the same block count. Consume more " + "batches before calling state_dict()." + ) + elif self._consumer_checkpoint_requires_uniform: + samples = state["samples_consumed_per_split"] + rank_samples = [samples[split] for split in self._rank_splits] + if len(set(rank_samples)) > 1: + raise RuntimeError( + "StreamingDataLoader checkpointing with multiple workers is " + "only safe at a complete logical step boundary, when every " + "split assigned to this rank has the same consumed-sample " + "count. Consume more batches before calling state_dict()." + ) + return state + + def _checkpoint_snapshot(self) -> dict: if self._pack_sequences is not None: return { "shuffle_seed": self._shuffle_seed, @@ -1108,18 +1402,141 @@ class StreamingDataset(IterableDataset): "blocks_emitted_per_split": list(self._pack_blocks_emitted), "pack_buffers": deepcopy(self._pack_buffers), } + samples = [ + self._resume_samples.get(split, self._resume_offset) + for split in range(self._num_splits) + ] positions = [ - self._resume_positions.get(split, self._resume_offset) + self._resume_positions.get(split, samples[split]) for split in range(self._num_splits) ] return { "shuffle_seed": self._shuffle_seed, "num_splits": self._num_splits, "epoch": self._epoch, - "samples_consumed_per_split": [self._resume_offset] * self._num_splits, + "samples_consumed_per_split": samples, "positions_consumed_per_split": positions, } + def _invalidate_checkpoint(self, reason: str) -> None: + if self._checkpoint_invalid_reason is None: + self._checkpoint_invalid_reason = reason + + @property + def _consumer_iterator_active(self) -> bool: + return self._consumer_iterator_lease is not None + + @property + def _consumer_iterator_owner(self) -> Optional[int]: + lease = self._consumer_iterator_lease + return lease.owner_token if lease is not None else None + + @property + def _consumer_iterator_owner_thread(self) -> Optional[int]: + lease = self._consumer_iterator_lease + return lease.owner_thread if lease is not None else None + + def _acquire_consumer_iterator(self) -> int: + """Reserve this parent dataset for one checkpoint-aware iterator.""" + with self._consumer_iterator_lock: + if self._consumer_iterator_active or self._raw_batches_ref is not None: + raise RuntimeError( + "StreamingDataset does not support concurrent iteration. " + "Only one active iterator per dataset instance is allowed." + ) + owner_thread = threading.get_ident() + owner_token = self._consumer_iterator_generation + 1 + lease = _ConsumerIteratorLease(owner_token, owner_thread) + self._consumer_iterator_generation = owner_token + self._consumer_iterator_lease = lease + return owner_token + + def _release_consumer_iterator(self, owner_token: int) -> None: + with self._consumer_iterator_lock: + lease = self._consumer_iterator_lease + if lease is not None and lease.owner_token == owner_token: + self._consumer_iterator_lease = None + + def _release_consumer_iterator_after_failed_acquire( + self, previous_lease: Optional[_ConsumerIteratorLease] + ) -> None: + """Clean up when an interrupted acquire set a lease but did not return it.""" + owner_thread = threading.current_thread().ident + with self._consumer_iterator_lock: + lease = self._consumer_iterator_lease + if ( + lease is not None + and lease is not previous_lease + and lease.owner_thread == owner_thread + ): + self._consumer_iterator_lease = None + + def _commit_worker_state(self, state: dict, *, require_uniform: bool) -> None: + """Merge one trainer-consumed worker batch into parent state.""" + for key, expected in ( + ("shuffle_seed", self._shuffle_seed), + ("num_splits", self._num_splits), + ("epoch", self._epoch), + ): + if state.get(key) != expected: + raise ValueError( + f"{key} mismatch in worker checkpoint: " + f"{state.get(key)} != {expected}" + ) + packed = "pack_buffers" in state + if packed != (self._pack_sequences is not None): + raise ValueError("worker checkpoint mode does not match the dataset") + if packed: + for key in ("pack_sequences", "eos_id", "pad_id", "blocks_per_epoch"): + expected = getattr(self, f"_{key}") + if state.get(key) != expected: + raise ValueError( + f"{key} mismatch in worker checkpoint: " + f"{state.get(key)} != {expected}" + ) + samples = state["samples_consumed_per_split"] + emitted = state["blocks_emitted_per_split"] + if len(samples) != self._num_splits or len(emitted) != self._num_splits: + raise ValueError( + "packed worker checkpoint must contain one entry per split" + ) + buffers = state["pack_buffers"] + for split, (count, blocks) in enumerate(zip(samples, emitted)): + incoming = (int(blocks), int(count)) + current = ( + self._pack_blocks_emitted[split], + self._pack_consumed[split], + ) + if incoming > current: + self._pack_blocks_emitted[split] = incoming[0] + self._pack_consumed[split] = incoming[1] + buffer = buffers.get(split, buffers.get(str(split))) + if buffer is None: + self._pack_buffers.pop(split, None) + else: + self._pack_buffers[split] = { + "tokens": list(buffer["tokens"]), + "starts": list(buffer["starts"]), + } + self._consumer_checkpoint_requires_uniform |= require_uniform + return + + samples = state["samples_consumed_per_split"] + positions = state.get("positions_consumed_per_split", samples) + for split, count in enumerate(samples): + current = self._resume_samples.get(split, self._resume_offset) + self._resume_samples[split] = max(current, int(count)) + for split, position in enumerate(positions): + current = self._resume_positions.get( + split, self._resume_samples.get(split, self._resume_offset) + ) + self._resume_positions[split] = max(current, int(position)) + self._resume_offset = min( + self._resume_samples.get(split, self._resume_offset) + for split in range(self._num_splits) + ) + self._consumer_checkpoint_requires_uniform |= require_uniform + def load_state_dict(self, state: dict) -> None: """Resume from a previously snapshotted state. @@ -1139,6 +1556,7 @@ class StreamingDataset(IterableDataset): f"shuffle_seed mismatch: checkpoint has {state['shuffle_seed']}, " f"current dataset has {self._shuffle_seed}" ) + self._consumer_checkpoint_requires_uniform = False if "pack_buffers" in state or self._pack_sequences is not None: for key in ( @@ -1165,14 +1583,17 @@ class StreamingDataset(IterableDataset): return consumed = state["samples_consumed_per_split"] - # All entries are equal at step boundaries; use the first. if isinstance(consumed, list): - self._resume_offset = consumed[0] if consumed else 0 + self._resume_offset = min(consumed) if consumed else 0 + self._resume_samples = { + split: int(count) for split, count in enumerate(consumed) + } else: self._resume_offset = int(consumed) + self._resume_samples = {} # Older checkpoints predate positions_consumed_per_split; without # skipped rows positions equal sample counts, so falling back to - # _resume_offset (the .get default in __iter__) is exact. + # the per-split sample count (the .get default in __iter__) is exact. positions = state.get("positions_consumed_per_split") if positions is None: self._resume_positions = {} @@ -1185,10 +1606,11 @@ class StreamingDataset(IterableDataset): def merge_state_dicts(states: list[dict]) -> dict: """Merge state dicts saved by different ranks into one exact state. - For row mode, the elementwise maximum of permutation positions recovers - splits advanced by different ranks after transform failures. For packed - mode, the state that emitted the most blocks for each logical split - supplies that split's permutation position and partial token buffer. Packed + In row mode, each rank records exact consumer-committed progress for + its own splits and lower bounds for the rest, so elementwise maxima + recover both sample counts and permutation positions. In packed mode, + the state that emitted the most blocks for each logical split supplies + that split's permutation position and partial token buffer. Packed states must cover every rank at the same global step. Raises ``ValueError`` if the states are empty, were not produced by @@ -1299,17 +1721,13 @@ class StreamingDataset(IterableDataset): merged["pack_buffers"] = merged_buffers return merged - for state in states[1:]: - if ( - state["samples_consumed_per_split"] - != first["samples_consumed_per_split"] - ): - raise ValueError( - "samples_consumed_per_split mismatch across state dicts; " - "state_dict() must be called at the same global step " - "boundary on every rank" - ) merged = dict(first) + merged["samples_consumed_per_split"] = [ + max(per_split) + for per_split in zip( + *(state["samples_consumed_per_split"] for state in states) + ) + ] all_positions = [ state.get( "positions_consumed_per_split", state["samples_consumed_per_split"] @@ -1320,3 +1738,113 @@ class StreamingDataset(IterableDataset): max(per_split) for per_split in zip(*all_positions) ] return merged + + +class StreamingDataLoader(DataLoader): + """A PyTorch DataLoader with consumer-committed dataset checkpoints. + + PyTorch workers prefetch batches ahead of the trainer, so worker-local + producer progress is not a safe checkpoint. This loader carries a state + snapshot alongside every internal batch and applies it to the parent + [StreamingDataset][lancedb.streaming.StreamingDataset] only when that batch + is returned by ``next()``. + The trainer receives the same collated batch it would receive from a + standard ``torch.utils.data.DataLoader``. + + With more than one worker, row-mode ``state_dict()`` is available only at + complete logical step boundaries, when every split assigned to the rank has + the same consumed-sample count. Packed checkpoints require equal emitted-block + counts across the rank's splits for any worker count. ``persistent_workers=True`` + is not supported because prefetched worker copies cannot be restored from + parent-committed state. If batch collation raises, checkpointing remains + invalid for that dataset instance; restore the last valid checkpoint into a + fresh dataset before continuing. + Only one active iterator may own a dataset at a time, including when worker + processes are used. Exhausting or explicitly shutting down the iterator + releases that ownership. ``drop_last=True`` is not supported because worker + replicas discard incomplete tails independently, which cannot produce a + topology-independent checkpoint. + + Parameters are the same as ``torch.utils.data.DataLoader`` except that + ``dataset`` must be a + [StreamingDataset][lancedb.streaming.StreamingDataset]. + Subclasses that override ``StreamingDataset.__iter__`` are not supported + because the custom iterator cannot provide the exact per-yield checkpoint + snapshots required by this loader. + + Examples + -------- + >>> # dataset = StreamingDataset(table, num_splits=2) + >>> # loader = StreamingDataLoader(dataset, batch_size=8, num_workers=2) + >>> # batch = next(iter(loader)) + >>> # checkpoint = dataset.state_dict() + """ + + def __init__(self, dataset: StreamingDataset, *args, **kwargs): + if not isinstance(dataset, StreamingDataset): + raise TypeError("StreamingDataLoader requires a StreamingDataset") + if type(dataset).__iter__ is not StreamingDataset.__iter__: + raise TypeError( + "StreamingDataLoader does not support StreamingDataset subclasses " + "that override __iter__ because they cannot provide exact " + "per-yield checkpoint state" + ) + if kwargs.get("in_order", True) is False: + raise ValueError( + "StreamingDataLoader requires in_order=True for deterministic " + "consumer checkpoints" + ) + if kwargs.get("persistent_workers", False): + raise ValueError( + "StreamingDataLoader does not support persistent_workers=True " + "because worker prefetch state cannot be reset from a checkpoint" + ) + self._streaming_dataset = dataset + super().__init__(_StreamingDatasetAdapter(dataset), *args, **kwargs) + if self.drop_last: + raise ValueError( + "StreamingDataLoader does not support drop_last=True because " + "discarded worker tails cannot be checkpointed " + "topology-independently" + ) + self.collate_fn = _CheckpointCollate(self.collate_fn) + + def __iter__(self): + dataset = self._streaming_dataset + previous_lease = dataset._consumer_iterator_lease + owner_token = None + try: + owner_token = dataset._acquire_consumer_iterator() + state = dataset._checkpoint_snapshot() + packed = dataset._pack_sequences is not None + if packed: + blocks = state["blocks_emitted_per_split"] + rank_blocks = [blocks[split] for split in dataset._rank_splits] + if len(set(rank_blocks)) > 1: + raise RuntimeError( + "StreamingDataLoader cannot start from a partial packed " + "logical step; resume from a checkpoint whose splits " + "assigned to this rank have equal emitted-block counts" + ) + elif self.num_workers > 1: + samples = state["samples_consumed_per_split"] + rank_samples = [samples[split] for split in dataset._rank_splits] + if len(set(rank_samples)) > 1: + raise RuntimeError( + "StreamingDataLoader cannot start multiple workers from a " + "partial logical step; resume from a checkpoint whose " + "splits assigned to this rank have equal consumed-sample " + "counts" + ) + return _ConsumerCommitIterator( + super().__iter__(), + dataset, + owner_token=owner_token, + require_uniform=self.num_workers > 1 or packed, + ) + except BaseException: + if owner_token is not None: + dataset._release_consumer_iterator(owner_token) + else: + dataset._release_consumer_iterator_after_failed_acquire(previous_lease) + raise diff --git a/python/python/tests/test_elastic_dataloader.py b/python/python/tests/test_elastic_dataloader.py index ff65d100c..da27e5bfc 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 threading from unittest.mock import patch import lancedb @@ -46,6 +47,7 @@ from utils import ( torch = pytest.importorskip("torch") streaming = pytest.importorskip("lancedb.streaming") StreamingDataset = streaming.StreamingDataset +StreamingDataLoader = streaming.StreamingDataLoader # --------------------------------------------------------------------------- # Dataset parameters @@ -92,6 +94,27 @@ class FakeWorkerInfo: num_workers: int +def _collate_with_first_batch_error(samples): + ids = [sample["id"] for sample in samples] + if ids == [0, 1]: + raise ValueError("first batch fails") + return ids + + +def _collate_with_first_batch_stop(samples): + ids = [sample["id"] for sample in samples] + if ids == [0, 1]: + raise StopIteration("first batch stopped") + return ids + + +def _collate_with_first_batch_interrupt(samples): + ids = [sample["id"] for sample in samples] + if ids == [0, 1]: + raise KeyboardInterrupt("first batch interrupted") + return ids + + # --------------------------------------------------------------------------- # Fixtures # --------------------------------------------------------------------------- @@ -1008,6 +1031,565 @@ def test_multi_worker_elastic_det_across_worker_counts(lance_table): # ── Resumability with num_workers ───────────────────────────────────────────── +def test_streaming_dataloader_commits_only_consumed_worker_batches(tmp_path): + """Prefetched worker state is committed only as the trainer receives it.""" + db = lancedb.connect(tmp_path) + table = db.create_table( + "worker_commit", pa.table({"id": [1, 2, 3, 4, 10, 20, 30, 40]}) + ) + dataset = StreamingDataset(table, num_splits=2, shuffle=False) + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=2, + multiprocessing_context="spawn", + prefetch_factor=4, + ) + iterator = iter(loader) + try: + first = next(iterator)["id"].tolist() + + assert first == [1, 2] + assert dataset._checkpoint_snapshot()["samples_consumed_per_split"] == [2, 0] + with pytest.raises(RuntimeError, match="complete logical step boundary"): + dataset.state_dict() + + second = next(iterator)["id"].tolist() + assert second == [10, 20] + checkpoint = dataset.state_dict() + assert checkpoint["samples_consumed_per_split"] == [2, 2] + uninterrupted = [batch["id"].tolist() for batch in iterator] + finally: + iterator._shutdown_workers() + + resumed = StreamingDataset(table, num_splits=2, shuffle=False) + resumed.load_state_dict(checkpoint) + resumed_loader = StreamingDataLoader( + resumed, + batch_size=2, + num_workers=2, + multiprocessing_context="spawn", + prefetch_factor=4, + ) + resumed_iterator = iter(resumed_loader) + try: + remaining = [batch["id"].tolist() for batch in resumed_iterator] + finally: + resumed_iterator._shutdown_workers() + assert remaining == uninterrupted == [[3, 4], [30, 40]] + + +def test_distributed_checkpoint_uses_rank_local_worker_boundary(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("rank_boundary", pa.table({"id": list(range(8))})) + dataset = StreamingDataset( + table, + num_splits=4, + shuffle=False, + rank=0, + world_size=2, + ) + loader = StreamingDataLoader( + dataset, + batch_size=1, + num_workers=2, + multiprocessing_context="spawn", + ) + iterator = iter(loader) + try: + assert next(iterator)["id"].tolist() == [0] + assert dataset._checkpoint_snapshot()["samples_consumed_per_split"] == [ + 1, + 0, + 0, + 0, + ] + with pytest.raises(RuntimeError, match="complete logical step boundary"): + dataset.state_dict() + + assert next(iterator)["id"].tolist() == [2] + checkpoint = dataset.state_dict() + remaining = [batch["id"].tolist() for batch in iterator] + finally: + iterator._shutdown_workers() + + assert checkpoint["samples_consumed_per_split"] == [1, 1, 0, 0] + assert remaining == [[1], [3]] + + +def test_standard_dataloader_rejects_stale_parent_checkpoint(tmp_path): + """A standard DataLoader must not expose prefetched producer progress.""" + db = lancedb.connect(tmp_path) + table = db.create_table("untracked_workers", pa.table({"id": [1, 2, 10, 20]})) + dataset = StreamingDataset(table, num_splits=2, shuffle=False) + # Merely constructing the checkpoint-aware loader must not authorize a + # later plain DataLoader's worker progress. + StreamingDataLoader(dataset, batch_size=2, num_workers=0) + loader = torch.utils.data.DataLoader( + dataset, + batch_size=2, + num_workers=2, + multiprocessing_context="spawn", + ) + iterator = iter(loader) + try: + assert next(iterator)["id"].tolist() == [1, 2] + with pytest.raises(RuntimeError, match="Use StreamingDataLoader"): + dataset.state_dict() + list(iterator) + finally: + iterator._shutdown_workers() + + +def test_streaming_dataloader_rejects_persistent_workers(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("persistent_workers", pa.table({"id": [1, 2]})) + dataset = StreamingDataset(table, num_splits=2, shuffle=False) + + with pytest.raises(ValueError, match="persistent_workers=True"): + StreamingDataLoader( + dataset, + batch_size=1, + num_workers=2, + persistent_workers=True, + ) + + +def test_collate_failure_invalidates_consumer_checkpoint(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table( + "collate_failure", pa.table({"id": [0, 1, 2, 3, 100, 101, 102, 103]}) + ) + dataset = StreamingDataset(table, num_splits=2, shuffle=False) + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=2, + multiprocessing_context="spawn", + collate_fn=_collate_with_first_batch_error, + prefetch_factor=2, + ) + iterator = iter(loader) + try: + with pytest.raises(ValueError, match="first batch fails"): + next(iterator) + assert next(iterator) == [100, 101] + assert next(iterator) == [2, 3] + with pytest.raises(RuntimeError, match="failed before it was returned"): + dataset.state_dict() + list(iterator) + finally: + iterator._shutdown_workers() + + +def test_collate_stop_iteration_invalidates_consumer_checkpoint(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("collate_stop", pa.table({"id": list(range(6))})) + dataset = StreamingDataset(table, num_splits=1, shuffle=False) + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=0, + collate_fn=_collate_with_first_batch_stop, + ) + iterator = iter(loader) + + with pytest.raises(RuntimeError, match="collate_fn raised StopIteration"): + next(iterator) + assert dataset._checkpoint_snapshot()["samples_consumed_per_split"] == [2] + with pytest.raises(RuntimeError, match="failed before it was returned"): + dataset.state_dict() + assert list(iterator) == [[2, 3], [4, 5]] + + +def test_batch_base_exception_invalidates_consumer_checkpoint(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("collate_interrupt", pa.table({"id": list(range(6))})) + dataset = StreamingDataset(table, num_splits=1, shuffle=False) + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=0, + collate_fn=_collate_with_first_batch_interrupt, + ) + iterator = iter(loader) + + with pytest.raises(KeyboardInterrupt, match="first batch interrupted"): + next(iterator) + assert dataset._checkpoint_snapshot()["samples_consumed_per_split"] == [2] + with pytest.raises(RuntimeError, match="failed before it was returned"): + dataset.state_dict() + assert list(iterator) == [[2, 3], [4, 5]] + + +def test_parent_commit_base_exception_invalidates_consumer_checkpoint(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("commit_interrupt", pa.table({"id": list(range(4))})) + dataset = StreamingDataset(table, num_splits=1, shuffle=False) + loader = StreamingDataLoader(dataset, batch_size=2, num_workers=0) + iterator = iter(loader) + real_commit = dataset._commit_worker_state + + def interrupt_after_commit(state, *, require_uniform): + real_commit(state, require_uniform=require_uniform) + raise KeyboardInterrupt("after parent commit") + + with patch.object( + dataset, "_commit_worker_state", side_effect=interrupt_after_commit + ): + with pytest.raises(KeyboardInterrupt, match="after parent commit"): + next(iterator) + + assert dataset._checkpoint_snapshot()["samples_consumed_per_split"] == [2] + with pytest.raises(RuntimeError, match="failed before it was returned"): + dataset.state_dict() + + +def test_direct_iteration_surfaces_prefetch_failure_before_committing_row( + tmp_path, monkeypatch +): + db = lancedb.connect(tmp_path) + table = db.create_table("prefetch_failure", pa.table({"id": list(range(4))})) + release = threading.Event() + failed = threading.Event() + real_getitems = streaming.Permutation.__getitems__ + + def controlled_getitems(permutation, indices): + if indices and indices[0] >= 2: + assert release.wait(timeout=5) + failed.set() + raise RuntimeError("later prefetched I/O failed") + return real_getitems(permutation, indices) + + class SignalDict(dict): + def __setitem__(self, key, value): + super().__setitem__(key, value) + release.set() + assert failed.wait(timeout=5) + + monkeypatch.setattr(streaming.Permutation, "__getitems__", controlled_getitems) + dataset = StreamingDataset( + table, + num_splits=1, + shuffle=False, + read_batch_size=2, + io_queue_depth=2, + ) + dataset._resume_positions = SignalDict() + iterator = iter(dataset) + + assert next(iterator)["id"] == 0 + with pytest.raises(RuntimeError, match="later prefetched I/O failed"): + next(iterator) + + checkpoint = dataset.state_dict() + assert checkpoint["samples_consumed_per_split"] == [1] + assert checkpoint["positions_consumed_per_split"] == [1] + + +@pytest.mark.parametrize("workers", [0, 1, 2]) +def test_streaming_dataloader_rejects_drop_last(tmp_path, workers): + db = lancedb.connect(tmp_path) + table = db.create_table("drop_last", pa.table({"id": [0, 1, 2]})) + dataset = StreamingDataset(table, num_splits=1, shuffle=False) + worker_options = {"multiprocessing_context": "spawn"} if workers else {} + + with pytest.raises(ValueError, match="drop_last=True"): + StreamingDataLoader( + dataset, + batch_size=2, + num_workers=workers, + drop_last=True, + **worker_options, + ) + + +def test_streaming_dataloader_owns_one_iterator_until_teardown(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("iterator_owner", pa.table({"id": list(range(4))})) + dataset = StreamingDataset(table, num_splits=1, shuffle=False) + loader = StreamingDataLoader( + dataset, + batch_size=2, + num_workers=1, + multiprocessing_context="spawn", + ) + + first = iter(loader) + try: + assert next(first)["id"].tolist() == [0, 1] + with pytest.raises(RuntimeError, match="concurrent iteration"): + iter(loader) + finally: + first._shutdown_workers() + + second = iter(loader) + try: + assert [batch["id"].tolist() for batch in second] == [[2, 3]] + except BaseException: + second._shutdown_workers() + raise + + # Natural exhaustion releases ownership too. + third = iter(loader) + try: + assert list(third) == [] + finally: + third._shutdown_workers() + + +def test_zero_worker_shutdown_closes_inner_iterator_before_release(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("zero_worker_shutdown", pa.table({"id": list(range(6))})) + dataset = StreamingDataset(table, num_splits=1, shuffle=False) + loader = StreamingDataLoader(dataset, batch_size=2, num_workers=0) + + first = iter(loader) + assert next(first)["id"].tolist() == [0, 1] + first._shutdown_workers() + + assert dataset._consumer_iterator_active is False + assert dataset._raw_batches_ref is None + second = iter(loader) + try: + with pytest.raises(StopIteration): + next(first) + assert next(second)["id"].tolist() == [2, 3] + finally: + second._shutdown_workers() + + +def test_direct_and_loader_admission_share_one_atomic_lease(tmp_path, monkeypatch): + db = lancedb.connect(tmp_path) + table = db.create_table("direct_loader_lease", pa.table({"id": list(range(4))})) + dataset = StreamingDataset(table, num_splits=1, shuffle=False) + loader = StreamingDataLoader(dataset, batch_size=2, num_workers=0) + entered = threading.Event() + release = threading.Event() + direct_result = [] + direct_error = [] + contender = [] + real_resolve = dataset._resolve_my_splits + + def controlled_resolve(): + if threading.current_thread().name == "direct-start": + entered.set() + assert release.wait(timeout=5) + return real_resolve() + + def advance_direct(iterator): + try: + direct_result.append(next(iterator)["id"]) + except BaseException as exc: + direct_error.append(exc) + + monkeypatch.setattr(dataset, "_resolve_my_splits", controlled_resolve) + direct = iter(dataset) + thread = threading.Thread( + target=advance_direct, args=(direct,), name="direct-start" + ) + thread.start() + assert entered.wait(timeout=5) + try: + with pytest.raises(RuntimeError, match="concurrent iteration"): + contender.append(iter(loader)) + finally: + release.set() + thread.join(timeout=5) + if contender: + contender[0]._shutdown_workers() + direct.close() + + assert not thread.is_alive() + assert direct_error == [] + assert direct_result == [0] + + +def test_loader_acquires_before_snapshot_and_cleans_interrupted_acquire( + tmp_path, monkeypatch +): + db = lancedb.connect(tmp_path) + table = db.create_table("lease_snapshot", pa.table({"id": list(range(4))})) + dataset = StreamingDataset(table, num_splits=1, shuffle=False) + loader = StreamingDataLoader(dataset, batch_size=2, num_workers=0) + first = iter(loader) + assert next(first)["id"].tolist() == [0, 1] + + entered = threading.Event() + release = threading.Event() + pending = [] + pending_errors = [] + observed_snapshots = [] + real_acquire = dataset._acquire_consumer_iterator + real_snapshot = dataset._checkpoint_snapshot + + def controlled_acquire(): + if threading.current_thread().name == "stale-start": + entered.set() + assert release.wait(timeout=5) + return real_acquire() + + def recording_snapshot(): + state = real_snapshot() + if threading.current_thread().name == "stale-start": + observed_snapshots.append(state["samples_consumed_per_split"]) + return state + + def create_pending_iterator(): + try: + pending.append(iter(loader)) + except BaseException as exc: + pending_errors.append(exc) + + monkeypatch.setattr(dataset, "_acquire_consumer_iterator", controlled_acquire) + monkeypatch.setattr(dataset, "_checkpoint_snapshot", recording_snapshot) + thread = threading.Thread(target=create_pending_iterator, name="stale-start") + thread.start() + assert entered.wait(timeout=5) + assert next(first)["id"].tolist() == [2, 3] + with pytest.raises(StopIteration): + next(first) + release.set() + thread.join(timeout=5) + + assert not thread.is_alive() + assert pending_errors == [] + assert observed_snapshots == [[4]] + assert len(pending) == 1 + assert list(pending[0]) == [] + assert dataset.state_dict()["samples_consumed_per_split"] == [4] + + def interrupted_acquire(): + real_acquire() + raise KeyboardInterrupt("after acquire") + + monkeypatch.setattr(dataset, "_acquire_consumer_iterator", interrupted_acquire) + with pytest.raises(KeyboardInterrupt, match="after acquire"): + iter(loader) + assert dataset._consumer_iterator_active is False + + +def test_consumer_iterator_lease_publication_is_atomic(tmp_path, monkeypatch): + db = lancedb.connect(tmp_path) + table = db.create_table("atomic_lease", pa.table({"id": [0, 1]})) + dataset = StreamingDataset(table, num_splits=1, shuffle=False) + loader = StreamingDataLoader(dataset, batch_size=1, num_workers=0) + real_get_ident = streaming.threading.get_ident + calls = 0 + + def interrupt_during_publication(): + nonlocal calls + calls += 1 + if calls == 1: + raise KeyboardInterrupt("during lease mutation") + return real_get_ident() + + monkeypatch.setattr(streaming.threading, "get_ident", interrupt_during_publication) + with pytest.raises(KeyboardInterrupt, match="during lease mutation"): + iter(loader) + monkeypatch.setattr(streaming.threading, "get_ident", real_get_ident) + + assert dataset._consumer_iterator_active is False + iterator = iter(loader) + try: + assert next(iterator)["id"].tolist() == [0] + finally: + iterator._shutdown_workers() + + +def test_streaming_dataloader_rejects_dataset_iter_override(tmp_path): + class CustomizedDataset(StreamingDataset): + def __iter__(self): + return iter([1000, 1001]) + + db = lancedb.connect(tmp_path) + table = db.create_table("custom_iteration", pa.table({"id": [0, 1, 2]})) + dataset = CustomizedDataset(table, num_splits=1, shuffle=False) + + assert list(dataset) == [1000, 1001] + with pytest.raises(TypeError, match="override __iter__"): + StreamingDataLoader( + dataset, + batch_size=2, + num_workers=0, + collate_fn=list, + ) + + +def test_interleaved_adapters_do_not_authorize_plain_iteration(tmp_path): + db = lancedb.connect(tmp_path) + table_a = db.create_table("adapter_a", pa.table({"id": [0, 1]})) + table_b = db.create_table("adapter_b", pa.table({"id": [10, 11]})) + dataset_a = StreamingDataset(table_a, num_splits=1, shuffle=False) + dataset_b = StreamingDataset(table_b, num_splits=1, shuffle=False) + initial_state = dataset_a.state_dict() + + owner_a = dataset_a._acquire_consumer_iterator() + owner_b = dataset_b._acquire_consumer_iterator() + try: + iterator_a = iter(streaming._StreamingDatasetAdapter(dataset_a)) + iterator_b = iter(streaming._StreamingDatasetAdapter(dataset_b)) + assert next(iterator_a).data["id"] == 0 + assert next(iterator_b).data["id"] == 10 + assert [sample.data["id"] for sample in iterator_a] == [1] + assert [sample.data["id"] for sample in iterator_b] == [11] + finally: + dataset_a._release_consumer_iterator(owner_a) + dataset_b._release_consumer_iterator(owner_b) + + dataset_a.load_state_dict(initial_state) + with patch( + "lancedb.streaming.get_worker_info", + return_value=FakeWorkerInfo(id=0, num_workers=1), + ): + plain_iterator = iter(dataset_a) + assert next(plain_iterator)["id"] == 0 + plain_iterator.close() + + assert dataset_a._untracked_worker_iteration[0] == 1 + with pytest.raises(RuntimeError, match="Use StreamingDataLoader"): + dataset_a.state_dict() + + +def test_resume_from_partial_split_cycle_preserves_remaining_order(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("partial_cycle", pa.table({"id": [1, 2, 10, 20]})) + dataset = StreamingDataset(table, num_splits=2, shuffle=False) + iterator = iter(dataset) + + assert next(iterator)["id"] == 1 + checkpoint = dataset.state_dict() + iterator.close() + assert checkpoint["samples_consumed_per_split"] == [1, 0] + + resumed = StreamingDataset(table, num_splits=2, shuffle=False) + resumed.load_state_dict(checkpoint) + assert [row["id"] for row in resumed] == [10, 2, 20] + + +def test_partial_cycle_resume_preserves_skip_truncation(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table( + "partial_skip", pa.table({"id": [0, 1, 2, 3, 100, 101, 102, 103]}) + ) + kwargs = dict( + num_splits=2, + shuffle=False, + transform=_failing_transform({1, 2, 3}), + on_transform_error="skip", + ) + dataset = StreamingDataset(table, **kwargs) + iterator = iter(dataset) + + assert next(iterator)["id"] == 0 + checkpoint = dataset.state_dict() + uninterrupted = [row["id"] for row in iterator] + + resumed = StreamingDataset(table, **kwargs) + resumed.load_state_dict(checkpoint) + assert [row["id"] for row in resumed] == uninterrupted == [100] + + def test_multi_worker_resumability_same_topology(lance_table): """Checkpoint with num_workers=2, resume with num_workers=2: exact continuation.""" world_size = 1 @@ -2018,6 +2600,23 @@ def test_merge_state_dicts_validates_consistency(lance_table): StreamingDataset.merge_state_dicts([]) +def test_merge_state_dicts_combines_nonuniform_consumer_progress(lance_table): + dataset = StreamingDataset( + lance_table, num_splits=2, shuffle=False, shuffle_seed=SHUFFLE_SEED + ) + rank0 = dataset.state_dict() + rank0["samples_consumed_per_split"] = [2, 0] + rank0["positions_consumed_per_split"] = [2, 0] + rank1 = dataset.state_dict() + rank1["samples_consumed_per_split"] = [0, 2] + rank1["positions_consumed_per_split"] = [0, 2] + + merged = StreamingDataset.merge_state_dicts([rank0, rank1]) + + assert merged["samples_consumed_per_split"] == [2, 2] + assert merged["positions_consumed_per_split"] == [2, 2] + + def test_load_state_dict_without_positions_key(lance_table): """Checkpoints from before positions_consumed_per_split existed still resume exactly (positions equal sample counts when nothing is skipped).""" @@ -2254,6 +2853,65 @@ def test_pack_sequences_checkpoint_resumes_on_new_topology(tmp_path): ] +def test_packed_checkpoint_requires_complete_split_cycle(tmp_path): + table = _create_token_table(tmp_path, [[1], [2], [10], [20]]) + dataset = _packed_dataset(table, pack_sequences=3, blocks_per_epoch=4, num_splits=2) + iterator = iter(dataset) + + next(iterator) + with pytest.raises(RuntimeError, match="complete logical step boundary"): + dataset.state_dict() + + next(iterator) + assert dataset.state_dict()["blocks_emitted_per_split"] == [1, 1] + iterator.close() + + +def test_streaming_dataloader_commits_consumed_packed_batches(tmp_path): + table = _create_token_table( + tmp_path, + [[1], [2], [3], [4], [10], [20], [30], [40]], + ) + kwargs = dict(pack_sequences=4, blocks_per_epoch=4, num_splits=2) + dataset = _packed_dataset(table, **kwargs) + loader = StreamingDataLoader( + dataset, + batch_size=1, + num_workers=2, + multiprocessing_context="spawn", + prefetch_factor=2, + ) + iterator = iter(loader) + try: + next(iterator) + with pytest.raises(RuntimeError, match="complete logical step boundary"): + dataset.state_dict() + + next(iterator) + checkpoint = dataset.state_dict() + uninterrupted = [batch["input_ids"].tolist() for batch in iterator] + finally: + iterator._shutdown_workers() + + resumed = _packed_dataset(table, **kwargs) + resumed.load_state_dict(checkpoint) + resumed_loader = StreamingDataLoader( + resumed, + batch_size=1, + num_workers=2, + multiprocessing_context="spawn", + prefetch_factor=2, + ) + resumed_iterator = iter(resumed_loader) + try: + remaining = [batch["input_ids"].tolist() for batch in resumed_iterator] + finally: + resumed_iterator._shutdown_workers() + + assert checkpoint["blocks_emitted_per_split"] == [1, 1] + assert remaining == uninterrupted + + def test_pack_sequences_validates_configuration_and_tokens(tmp_path): table = _create_token_table(tmp_path, [[1, 2]]) From 93f47b8aab4f888ab6cd4da75403e2d41be80da4 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Mon, 24 Aug 2026 13:35:31 -0700 Subject: [PATCH 103/206] fix(remote): stop table_names inventing a page token for a namespace (#4039) `table_names` paginates using a `start_after` table name. This works for the `/v1/table` endpoint, which guarantees table-order. But the `/v1/namespace/{id}/table/list` does not. We change that caller to instead collect all table names, sort, and apply the pagination locally. We are deprecating this API, so this is just an interim fix. For good performance, users should move to the `list_tables` API instead, which uses opaque tokens that don't rely on lexical sorting. --------- Co-authored-by: Claude Opus 5 (1M context) --- rust/lancedb/src/remote/db.rs | 191 ++++++++++++++++++++++++++++++---- 1 file changed, 171 insertions(+), 20 deletions(-) diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 8265d22c0..3f4216bc8 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -344,6 +344,62 @@ impl RemoteDatabase { self.table_cache.remove(&cache_key).await; Ok((request_id, resp)) } + + /// Collect the tables of a namespace in name order, for `table_names`. + /// + /// `table_names` promises name order and resumes after a table name, but the namespace + /// route's `page_token` is opaque -- it belongs to the store the listing walks, and a + /// token this client invented would resume from the wrong place. So the whole namespace is + /// walked by handing each response's token straight back, and the name semantics are + /// applied here. Constructing no token is what makes this work against a server on either + /// side of the change: it only ever repeats what the server said. + /// + /// This is the cost `table_names` already paid -- the server used to enumerate and sort the + /// namespace on every request -- and it is why `list_tables` replaces it. + async fn table_names_in_namespace( + &self, + request: &TableNamesRequest, + ) -> Result<(Vec, ServerVersion)> { + let namespace_id = + build_namespace_identifier(&request.namespace_path, &self.client.id_delimiter); + let path = format!("/v1/namespace/{}/table/list", namespace_id); + + let mut names = Vec::new(); + // Every page reports the same server, so keep the first page's version. + let mut version: Option = None; + let mut page_token: Option = None; + loop { + let mut req = self.client.get(&path); + if let Some(ref token) = page_token { + req = req.query(&[("page_token", token)]); + } + let (request_id, rsp) = self.client.send_with_retry(req, None, true).await?; + let rsp = self.client.check_response(&request_id, rsp).await?; + if version.is_none() { + version = Some(parse_server_version(&request_id, &rsp)?); + } + let response: ListTablesResponse = rsp.json().await.err_to_http(request_id)?; + names.extend(response.tables); + // An empty token is the end of the listing, not a token to send back: a server + // that reads an empty token as "start from the beginning" would hand back the + // first page again. + match response.page_token.filter(|token| !token.is_empty()) { + // A server that repeated a token would never finish; treat that as the end + // rather than looping on it. + Some(token) if Some(&token) != page_token.as_ref() => page_token = Some(token), + _ => break, + } + } + + names.sort(); + if let Some(ref start_after) = request.start_after { + names.retain(|name| name > start_after); + } + if let Some(limit) = request.limit { + names.truncate(limit as usize); + } + Ok((names, version.unwrap_or_default())) + } } #[cfg(all(test, feature = "remote"))] @@ -621,29 +677,29 @@ impl Database for RemoteDatabase { } async fn table_names(&self, request: TableNamesRequest) -> Result> { - let mut req = if !request.namespace_path.is_empty() { - let namespace_id = - build_namespace_identifier(&request.namespace_path, &self.client.id_delimiter); - self.client - .get(&format!("/v1/namespace/{}/table/list", namespace_id)) + let (tables, version) = if request.namespace_path.is_empty() { + // The flat route resumes after a table name and orders by name, which is exactly + // what `start_after` means, so the server does the paging. + let mut req = self.client.get("/v1/table/"); + if let Some(limit) = request.limit { + req = req.query(&[("limit", limit)]); + } + if let Some(ref start_after) = request.start_after { + req = req.query(&[("page_token", start_after)]); + } + let (request_id, rsp) = self.client.send_with_retry(req, None, true).await?; + let rsp = self.client.check_response(&request_id, rsp).await?; + let version = parse_server_version(&request_id, &rsp)?; + let tables = rsp + .json::() + .await + .err_to_http(request_id)? + .tables; + (tables, version) } else { - self.client.get("/v1/table/") + self.table_names_in_namespace(&request).await? }; - if let Some(limit) = request.limit { - req = req.query(&[("limit", limit)]); - } - if let Some(start_after) = request.start_after { - req = req.query(&[("page_token", start_after)]); - } - let (request_id, rsp) = self.client.send_with_retry(req, None, true).await?; - let rsp = self.client.check_response(&request_id, rsp).await?; - let version = parse_server_version(&request_id, &rsp)?; - let tables = rsp - .json::() - .await - .err_to_http(request_id)? - .tables; for table in &tables { let table_identifier = build_table_identifier(table, &request.namespace_path, &self.client.id_delimiter); @@ -1227,6 +1283,101 @@ mod tests { assert_eq!(names, vec!["table1", "table2"]); } + #[tokio::test] + async fn test_table_names_in_a_namespace_never_invents_a_page_token() { + // The namespace route's token belongs to the store, so `table_names` cannot build one + // from `start_after`. It walks the namespace on the server's own tokens and applies the + // name semantics itself, which is what keeps it working either side of the change. + let page = Arc::new(AtomicUsize::new(0)); + let conn = Connection::new_with_handler(move |request| { + assert_eq!(request.url().path(), "/v1/namespace/ns/table/list"); + let query = request.url().query().unwrap_or(""); + assert!( + !query.contains("page_token=users"), + "a table name must never be sent as a page token: {query}" + ); + match page.fetch_add(1, Ordering::SeqCst) { + 0 => { + assert!( + !query.contains("page_token"), + "the walk starts with no token" + ); + http::Response::builder() + .status(200) + .body(r#"{"tables": ["users", "orders"], "page_token": "opaque-1"}"#) + .unwrap() + } + _ => { + assert!(query.contains("page_token=opaque-1")); + http::Response::builder() + .status(200) + .body(r#"{"tables": ["widgets"]}"#) + .unwrap() + } + } + }); + + let names = conn + .table_names() + .namespace(vec!["ns".to_string()]) + .start_after("users") + .execute() + .await + .unwrap(); + // Name order, resumed after "users": "orders" sorts before it and is dropped. + assert_eq!(names, vec!["widgets"]); + } + + #[tokio::test] + async fn test_table_names_in_a_namespace_stops_on_a_repeated_token() { + // A server that handed back the token it was given would never finish the walk. + let conn = Connection::new_with_handler(|_request| { + http::Response::builder() + .status(200) + .body(r#"{"tables": ["a"], "page_token": "same"}"#) + .unwrap() + }); + + let names = conn + .table_names() + .namespace(vec!["ns".to_string()]) + .execute() + .await + .unwrap(); + // The guard bounds the walk instead of letting it run forever. The repeat is the + // server breaking the token contract and is not papered over here. + assert_eq!(names, vec!["a", "a"]); + } + + #[tokio::test] + async fn test_table_names_in_a_namespace_stops_on_an_empty_token() { + // An empty token ends the listing. Sending it back would ask a server that reads it + // as "start from the beginning" for the first page a second time, and every name on + // that page would be collected twice. + let requests = Arc::new(AtomicUsize::new(0)); + let seen = requests.clone(); + let conn = Connection::new_with_handler(move |request| { + seen.fetch_add(1, Ordering::SeqCst); + assert!( + !request.url().query().unwrap_or("").contains("page_token"), + "an empty token must never be sent back" + ); + http::Response::builder() + .status(200) + .body(r#"{"tables": ["a"], "page_token": ""}"#) + .unwrap() + }); + + let names = conn + .table_names() + .namespace(vec!["ns".to_string()]) + .execute() + .await + .unwrap(); + assert_eq!(names, vec!["a"]); + assert_eq!(requests.load(Ordering::SeqCst), 1); + } + #[tokio::test] async fn test_table_names_pagination() { let conn = Connection::new_with_handler(|request| { From c72f5b2960d08a1d6caee703191c360ecfe6f3ff Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Mon, 24 Aug 2026 14:06:40 -0700 Subject: [PATCH 104/206] feat: bind a materialized view refresh to the view incarnation (#4043) A caller that queues a refresh and executes it later can only tell the view it captured from a drop-and-recreate by comparing the definition and version. A recreated view with the same definition and an equal or higher version passes that check, and the check runs before the refresh reloads the view, so it never sees the state it commits against. This mints an `mv.incarnation` token in the schema metadata at each physical creation of a view table. `RefreshMaterializedViewBuilder::expect_incarnation` carries the captured token into the refresh, which compares it against the latest stored manifest before planning and again immediately before each commit (publish, fragment swap, watermark stamp), refusing to land in a different incarnation. A view with no token -- declared before tokens existed, or its metadata replaced wholesale -- is refused under a bound refresh with its own wording and is minted one by its next unbound refresh. The token is exposed through `MaterializedView::incarnation`; refreshes without an expectation are unchanged. This is best effort: the token is not part of lance's commit condition, so a recreation landing between the final pre-commit read and the commit itself is not caught. Closing that window needs a base-manifest precondition in lance's commit path. --- rust/lancedb/src/materialized_view.rs | 58 +++- rust/lancedb/src/materialized_view/refresh.rs | 265 +++++++++++++++++- 2 files changed, 307 insertions(+), 16 deletions(-) diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 1d7cbb5e7..b28d52931 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -37,6 +37,13 @@ pub use refresh::{RefreshMaterializedViewResult, RefreshMode}; /// Schema metadata key holding the view definition, as kind-tagged JSON. pub const DEFINITION_META_KEY: &str = "mv.definition"; +/// Schema metadata key holding the view's incarnation: a token minted at each +/// physical creation of a view table, so a view dropped and recreated under +/// the same name and definition is still told apart from the one a caller +/// captured. A view whose metadata was replaced wholesale, or one declared +/// before tokens existed, carries none until its next refresh mints one. +pub const INCARNATION_META_KEY: &str = "mv.incarnation"; + /// Schema metadata key holding the source table version the view was last /// refreshed to. Absent until the first refresh. pub const SOURCE_VERSION_META_KEY: &str = "mv.source_version"; @@ -612,8 +619,17 @@ impl PreparedDeclaration { pub async fn create(self, name: &str) -> Result { let empty: Vec> = vec![]; + // Minted here, not at preparation: a declaration can be cloned and + // create more than one physical table, and each needs its own token. + let incarnation = uuid::Uuid::new_v4().to_string(); + let mut metadata = self.schema.metadata().clone(); + metadata.insert(INCARNATION_META_KEY.to_string(), incarnation.clone()); + let schema = Arc::new(ArrowSchema::new_with_metadata( + self.schema.fields().clone(), + metadata, + )); let reader: Box = - Box::new(arrow_array::RecordBatchIterator::new(empty, self.schema)); + Box::new(arrow_array::RecordBatchIterator::new(empty, schema)); let mut request = CreateTableRequest::new(name.to_string(), Box::new(reader)); let write_params = request .write_options @@ -648,6 +664,7 @@ impl PreparedDeclaration { Ok(MaterializedView { table, definition: self.definition, + incarnation: Some(incarnation), }) } } @@ -878,6 +895,7 @@ impl CreateMaterializedViewBuilder { pub struct MaterializedView { table: Table, definition: MaterializedViewDefinition, + incarnation: Option, } impl MaterializedView { @@ -893,8 +911,13 @@ impl MaterializedView { }); } let schema = table.schema().await?; + let incarnation = schema.metadata().get(INCARNATION_META_KEY).cloned(); match materialized_view_kind(schema.metadata())? { - Some(MaterializedViewKind::Select(definition)) => Ok(Self { table, definition }), + Some(MaterializedViewKind::Select(definition)) => Ok(Self { + table, + definition, + incarnation, + }), Some(MaterializedViewKind::Unrecognized { kind }) => Err(Error::NotSupported { message: format!( "materialized view '{}' is defined by '{kind}', which this version of \ @@ -923,6 +946,13 @@ impl MaterializedView { &self.definition } + /// The view's incarnation token as of when this handle was opened; see + /// [`RefreshMaterializedViewBuilder::expect_incarnation`]. `None` for a + /// view that has none yet (see [`INCARNATION_META_KEY`]). + pub fn incarnation(&self) -> Option<&str> { + self.incarnation.as_deref() + } + /// Recompute the view from its source. /// /// By default the refresh is incremental when the source's changes can be @@ -943,6 +973,7 @@ impl MaterializedView { view: self.clone(), full: false, source_version: None, + expected_incarnation: None, } } } @@ -952,6 +983,7 @@ pub struct RefreshMaterializedViewBuilder { view: MaterializedView, full: bool, source_version: Option, + expected_incarnation: Option, } impl RefreshMaterializedViewBuilder { @@ -967,8 +999,28 @@ impl RefreshMaterializedViewBuilder { self } + /// Refresh only if the view is still the incarnation that minted `token` + /// (see [`MaterializedView::incarnation`]): a refresh requested against + /// one declaration must not land in a view dropped and recreated since, + /// even under the same name and definition. + /// + /// Best effort. The token is read from the latest stored manifest before + /// planning and again immediately before every commit, but it is not part + /// of the commit's own condition, so a recreation that lands between that + /// final read and the commit is not caught. + pub fn expect_incarnation(mut self, token: impl Into) -> Self { + self.expected_incarnation = Some(token.into()); + self + } + pub async fn execute(self) -> Result { - refresh::execute_refresh(&self.view.table, self.full, self.source_version).await + refresh::execute_refresh( + &self.view.table, + self.full, + self.source_version, + self.expected_incarnation.as_deref(), + ) + .await } } diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index 24d828e01..735751c27 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -46,8 +46,8 @@ use lance_table::format::Fragment; use serde::{Deserialize, Serialize}; use super::{ - MaterializedViewDefinition, REFRESHED_AT_MS_META_KEY, SOURCE_ROW_ID_COLUMN, - SOURCE_VERSION_META_KEY, + INCARNATION_META_KEY, MaterializedViewDefinition, REFRESHED_AT_MS_META_KEY, + SOURCE_ROW_ID_COLUMN, SOURCE_VERSION_META_KEY, }; use crate::database::OpenTableRequest; use crate::table::{NativeTable, NativeTableExt, Table}; @@ -108,6 +108,7 @@ pub(crate) async fn execute_refresh( view: &Table, full: bool, pinned: Option, + expected_incarnation: Option<&str>, ) -> Result { let view_native = view.as_native().ok_or_else(|| Error::NotSupported { message: "materialized views are supported only on local tables".into(), @@ -122,6 +123,8 @@ pub(crate) async fn execute_refresh( view_native.dataset.reload().await?; let view_ds = view_native.dataset.get().await?.as_ref().clone(); + ensure_incarnation(&view_ds, expected_incarnation, view.name()).await?; + // The definition a handle cached at open may since have been replaced; // what refresh executes and what it stamps must be one generation. let definition = match super::materialized_view_kind(&view_ds.schema().metadata)? { @@ -240,6 +243,7 @@ pub(crate) async fn execute_refresh( increment, definition, watermark, + expected_incarnation, ) .await?; match reconciled { @@ -253,6 +257,7 @@ pub(crate) async fn execute_refresh( source_version, source_ts, definition, + expected_incarnation, ) .await } @@ -266,6 +271,7 @@ pub(crate) async fn execute_refresh( source_version, source_ts, definition, + expected_incarnation, ) .await } @@ -595,6 +601,7 @@ async fn incremental( increment: Increment, definition: &MaterializedViewDefinition, watermark: Option, + expected_incarnation: Option<&str>, ) -> Result> { let new_fragments = increment.appended; let watermark_version = watermark.unwrap_or(0); @@ -671,15 +678,35 @@ async fn incremental( }; let nothing_to_add = (new_fragments.is_empty() && !updated_rows) || remaining == Some(0); if nothing_to_add && eviction.is_none() { - result.version = - stamp_watermark(view_native, view_ds.clone(), source_version, source_ts).await?; + result.version = stamp_watermark( + view_native, + view_ds.clone(), + source_version, + source_ts, + expected_incarnation, + ) + .await?; return Ok(Some(result)); } // Rows left but none arrive: the removals still have to be published. if nothing_to_add { let filter = refresh_filter(&empty_keys(view_ds)?)?; - let published = publish(view_ds, eviction, Vec::new(), Some(filter)).await?; - result.version = stamp_watermark(view_native, published, source_version, source_ts).await?; + let published = publish( + view_ds, + eviction, + Vec::new(), + Some(filter), + expected_incarnation, + ) + .await?; + result.version = stamp_watermark( + view_native, + published, + source_version, + source_ts, + expected_incarnation, + ) + .await?; return Ok(Some(result)); } @@ -737,12 +764,20 @@ async fn incremental( eviction, Vec::new(), Some(refresh_filter(&empty_keys(view_ds)?)?), + expected_incarnation, ) .await? } else { view_ds.clone() }; - result.version = stamp_watermark(view_native, published, source_version, source_ts).await?; + result.version = stamp_watermark( + view_native, + published, + source_version, + source_ts, + expected_incarnation, + ) + .await?; return Ok(Some(result)); }; let stream: SendableRecordBatchStream = Box::pin(RecordBatchStreamAdapter::new( @@ -775,9 +810,23 @@ async fn incremental( }); }; let filter = refresh_filter(&keys)?; - let appended = publish(view_ds, eviction, new_fragments, Some(filter)).await?; + let appended = publish( + view_ds, + eviction, + new_fragments, + Some(filter), + expected_incarnation, + ) + .await?; result.rows_written = rows_written.load(Ordering::Relaxed); - result.version = stamp_watermark(view_native, appended, source_version, source_ts).await?; + result.version = stamp_watermark( + view_native, + appended, + source_version, + source_ts, + expected_incarnation, + ) + .await?; Ok(Some(result)) } @@ -788,6 +837,7 @@ async fn rebuild( source_version: u64, source_ts: u128, definition: &MaterializedViewDefinition, + expected_incarnation: Option<&str>, ) -> Result { let rows_written = Arc::new(AtomicU64::new(0)); let schema = Arc::new(ArrowSchema::from(view_ds.schema())); @@ -810,8 +860,16 @@ async fn rebuild( // carries no schema metadata, so it cannot erase a definition update // that raced in the way an overwrite (which adopts its stream's schema) // durably would -- and it must land on the planned generation or abort. - let replaced = replace_retaining_indices(view_ds.clone(), stream, keys).await?; - let version = stamp_watermark(view_native, replaced, source_version, source_ts).await?; + let replaced = + replace_retaining_indices(view_ds.clone(), stream, keys, expected_incarnation).await?; + let version = stamp_watermark( + view_native, + replaced, + source_version, + source_ts, + expected_incarnation, + ) + .await?; Ok(RefreshMaterializedViewResult { mode: RefreshMode::Rebuild, rows_written: rows_written.load(Ordering::Relaxed), @@ -828,11 +886,13 @@ async fn replace_retaining_indices( view_ds: Dataset, stream: SendableRecordBatchStream, keys: Arc>, + expected_incarnation: Option<&str>, ) -> Result { let ds = Arc::new(view_ds); let read_version = ds.version().version; #[cfg(test)] tests::hold_before_publish(ds.uri()).await; + ensure_incarnation(&ds, expected_incarnation, ds.uri()).await?; let removed_fragment_ids: Vec = ds.get_fragments().iter().map(|f| f.id() as u64).collect(); let write_txn = InsertBuilder::new(WriteDestination::Dataset(ds.clone())) @@ -886,6 +946,32 @@ async fn replace_retaining_indices( } /// Record that the view now reflects `source_version`, including the view +/// Refuse to act on a view that is not `expected`'s incarnation, judged from +/// the latest stored manifest. Not a commit condition; see +/// `RefreshMaterializedViewBuilder::expect_incarnation`. +async fn ensure_incarnation(view_ds: &Dataset, expected: Option<&str>, what: &str) -> Result<()> { + let Some(expected) = expected else { + return Ok(()); + }; + let mut latest = view_ds.clone(); + latest.checkout_latest().await?; + match latest.schema().metadata.get(INCARNATION_META_KEY) { + Some(actual) if actual == expected => Ok(()), + Some(_) => Err(Error::Runtime { + message: format!( + "materialized view '{what}' is not the incarnation this refresh was \ + requested for: it was dropped and recreated" + ), + }), + None => Err(Error::Runtime { + message: format!( + "materialized view '{what}' carries no incarnation token: its schema \ + metadata was replaced since the token was captured" + ), + }), + } +} + /// version this very commit produces. The version is predicted and then /// verified; on a mismatch another commit raced in between, and the stamp /// ABORTS rather than certify that commit as the refresh's own generation. @@ -895,10 +981,21 @@ async fn stamp_watermark( mut dataset: Dataset, source_version: u64, source_ts: u128, + expected_incarnation: Option<&str>, ) -> Result { + ensure_incarnation(&dataset, expected_incarnation, dataset.uri()).await?; let predicted = dataset.version().version + 1; + // A view with no token (declared before tokens existed, or its metadata + // replaced wholesale) starts a new incarnation here. + let incarnation = dataset + .schema() + .metadata + .get(INCARNATION_META_KEY) + .cloned() + .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); dataset .update_schema_metadata([ + (INCARNATION_META_KEY.to_string(), Some(incarnation)), ( SOURCE_VERSION_META_KEY.to_string(), Some(source_version.to_string()), @@ -1052,12 +1149,14 @@ async fn publish( eviction: Option<(Vec, Vec)>, new_fragments: Vec, keys: Option, + expected_incarnation: Option<&str>, ) -> Result { let planned = view_ds.version().version; #[cfg(test)] tests::hold_before_publish(view_ds.uri()).await; #[cfg(test)] tests::hold_until_peers_planned(); + ensure_incarnation(view_ds, expected_incarnation, view_ds.uri()).await?; let (updated_fragments, removed_fragment_ids) = eviction.unwrap_or_default(); let committed = CommitBuilder::new(WriteDestination::Dataset(Arc::new(view_ds.clone()))) .execute(Transaction::new( @@ -1830,7 +1929,9 @@ mod tests { ); let staged = eviction.finish().await.unwrap(); assert!(staged.is_some(), "four ids over a chunk of two stage twice"); - publish(&view_ds, staged, Vec::new(), None).await.unwrap(); + publish(&view_ds, staged, Vec::new(), None, None) + .await + .unwrap(); native.dataset.reload().await.unwrap(); assert_eq!(read(view.table(), "x").await, vec![5, 6]); @@ -2486,6 +2587,144 @@ mod tests { assert_eq!(read(view.table(), "twice").await, vec![14]); } + /// A refresh bound to an incarnation refuses a view dropped and recreated + /// since, even under the same name and definition; the recreated view's + /// own token is accepted, and the token survives a refresh's stamp. + #[tokio::test] + async fn test_refresh_refuses_a_recreated_view_incarnation() { + let (conn, _, view) = refreshed_doubled(vec![1]).await; + let token = view.incarnation().unwrap().to_string(); + view.refresh() + .expect_incarnation(&token) + .execute() + .await + .unwrap(); + let reopened = conn.open_materialized_view("doubled").await.unwrap(); + assert_eq!(reopened.incarnation(), Some(token.as_str())); + + conn.drop_table("doubled", &[]).await.unwrap(); + let recreated = doubled_view(&conn).await; + assert_ne!(recreated.incarnation(), Some(token.as_str())); + + let err = recreated + .refresh() + .expect_incarnation(&token) + .execute() + .await + .unwrap_err(); + assert!(err.to_string().contains("dropped and recreated"), "{err}"); + assert_eq!(read(recreated.table(), "twice").await, Vec::::new()); + + recreated + .refresh() + .expect_incarnation(recreated.incarnation().unwrap()) + .execute() + .await + .unwrap(); + assert_eq!(read(recreated.table(), "twice").await, vec![2]); + } + + /// A cloned declaration creates two physical tables; each gets its own + /// token. + #[tokio::test] + async fn test_cloned_declaration_mints_a_fresh_incarnation_per_create() { + let (conn, source) = db_with_source(vec![1]).await; + let prepared = crate::materialized_view::prepare_declaration( + &source, + &[("x".into(), "x".into()), ("twice".into(), "x * 2".into())], + None, + None, + ) + .await + .unwrap(); + let replacement = prepared.clone(); + let first = prepared.create("cloned").await.unwrap(); + let first_token = first.incarnation().unwrap().to_string(); + + conn.drop_table("cloned", &[]).await.unwrap(); + let second = replacement.create("cloned").await.unwrap(); + assert_ne!(second.incarnation(), Some(first_token.as_str())); + } + + /// A recreation that lands after planning but before publication is + /// caught by the pre-commit read: the stale refresh fails and the + /// replacement stays empty under its own token. + #[tokio::test(flavor = "multi_thread")] + async fn test_bound_refresh_cannot_publish_into_a_raced_recreation() { + let _serial = DRIFT_LOCK.lock().await; + let (conn, _) = db_with_source(vec![1]).await; + let view = doubled_view(&conn).await; + let token = view.incarnation().unwrap().to_string(); + let uri = view + .table() + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .uri() + .to_string(); + + *DRIFT_TARGET.lock().unwrap() = Some(uri); + let refreshing = + tokio::spawn(async move { view.refresh().expect_incarnation(token).execute().await }); + tokio::time::timeout(std::time::Duration::from_secs(30), DRIFT_PLANNED.notified()) + .await + .expect("refresh never reached publication"); + + conn.drop_table("doubled", &[]).await.unwrap(); + let replacement = doubled_view(&conn).await; + let replacement_token = replacement.incarnation().unwrap().to_string(); + DRIFT_RELEASED.notify_one(); + + let result = refreshing.await.unwrap(); + assert!(result.is_err(), "the stale refresh unexpectedly succeeded"); + let reopened = conn.open_materialized_view("doubled").await.unwrap(); + assert_eq!(reopened.incarnation(), Some(replacement_token.as_str())); + assert_eq!(read(reopened.table(), "twice").await, Vec::::new()); + } + + /// Replacing the schema metadata wholesale drops the token. A refresh + /// bound to the old token is refused for that reason, not as a + /// recreation; an unbound refresh mints the view a fresh one. + #[tokio::test] + async fn test_a_view_whose_metadata_was_replaced_starts_a_new_incarnation() { + let (conn, _, view) = refreshed_doubled(vec![1]).await; + let token = view.incarnation().unwrap().to_string(); + let mut metadata = HashMap::new(); + metadata.insert( + crate::materialized_view::DEFINITION_META_KEY.to_string(), + crate::materialized_view::definition_to_metadata(view.definition()).unwrap(), + ); + view.table() + .as_native() + .unwrap() + .replace_schema_metadata(metadata) + .await + .unwrap(); + assert_eq!( + conn.open_materialized_view("doubled") + .await + .unwrap() + .incarnation(), + None + ); + + let err = view + .refresh() + .expect_incarnation(&token) + .execute() + .await + .unwrap_err(); + assert!(err.to_string().contains("no incarnation token"), "{err}"); + + view.refresh().execute().await.unwrap(); + let reopened = conn.open_materialized_view("doubled").await.unwrap(); + assert!(reopened.incarnation().is_some()); + assert_ne!(reopened.incarnation(), Some(token.as_str())); + } + /// In-process refreshes of one view serialize: the loser of the race /// observes the winner's watermark instead of appending the same rows. #[tokio::test(flavor = "multi_thread")] @@ -2528,7 +2767,7 @@ mod tests { let stale = view_native.dataset.get().await.unwrap().as_ref().clone(); view.table().delete("x = 1").await.unwrap(); - let err = stamp_watermark(view_native, stale, 99, 99).await; + let err = stamp_watermark(view_native, stale, 99, 99, None).await; assert!(err.is_err()); let result = view.refresh().execute().await.unwrap(); From 71f85a8d9fab89c238648c9963e7c89e1452e74d Mon Sep 17 00:00:00 2001 From: Lance Release Date: Mon, 24 Aug 2026 21:08:39 +0000 Subject: [PATCH 105/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.6=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package-lock.json | 4 ++-- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index f5f981b2c..bcf714002 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.6" +current_version = "0.38.0-beta.7" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 6c6dd4aea..a60a5ddf1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.6" +version = "0.38.0-beta.7" dependencies = [ "ahash", "anyhow", @@ -5490,7 +5490,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.6" +version = "0.38.0-beta.7" dependencies = [ "arrow-array", "arrow-buffer", @@ -5515,7 +5515,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.6" +version = "0.38.0-beta.7" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index d6c285fc3..59ee8a7d6 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.38.0-beta.6 + 0.38.0-beta.7 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 23d58124d..b24ad61ab 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.6 + 0.38.0-beta.7 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index a07414ec0..0ee59bcb7 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.6 + 0.38.0-beta.7 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index ead873855..8732d1965 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.6" +version = "0.38.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 d89eb5ad1..56480c0cb 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.38.0-beta.6", + "version": "0.38.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 1721c970e..a1102ee29 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.38.0-beta.6", + "version": "0.38.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 177804dce..695862baf 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.38.0-beta.6", + "version": "0.38.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 9af443583..9099ee4de 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.38.0-beta.6", + "version": "0.38.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 c98aa3812..f04c2a884 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.38.0-beta.6", + "version": "0.38.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 05b1086f5..f9b35af32 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.38.0-beta.6", + "version": "0.38.0-beta.7", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 50432bdea..cc5340105 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.38.0-beta.6", + "version": "0.38.0-beta.7", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index 219025534..6604da6cd 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.6", + "version": "0.38.0-beta.7", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.6", + "version": "0.38.0-beta.7", "cpu": [ "x64", "arm64" diff --git a/nodejs/package.json b/nodejs/package.json index 63c51a799..66777d60c 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.6", + "version": "0.38.0-beta.7", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 2e4f8996f..d2ccf3064 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.6" +version = "0.38.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 d32d88ecd..071c876d9 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.6" +version = "0.38.0-beta.7" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 5013c176dd9a664813888c8bd8cf99161c047ec7 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Tue, 25 Aug 2026 07:14:33 +0800 Subject: [PATCH 106/206] fix: pin remote snapshots during permutation construction (#4022) Fixes #4015 ## Root cause PermutationBuilder issued count_rows and the projected row-ID scan through an unpinned RemoteTable handle. Each request could independently resolve latest, so a concurrent table update could make the count and scanned rows come from different snapshots. ## Fix - add a backend hook for obtaining an independent handle pinned to the currently selected version - resolve latest once for remote tables while preserving an explicit checkout and leaving the caller handle unchanged - build the count, filtered projection, and scan from that pinned handle while retaining native-table behavior - add a remote mock regression that advances latest between count and scan and covers explicit checkout preservation ## Validation - cargo test --quiet --features remote -p lancedb --lib test_remote_permutation_builder_pins_snapshot - cargo test --quiet --features remote -p lancedb --lib dataloader::permutation::builder::tests - cargo check --quiet --features remote --tests --examples - cargo clippy --quiet --features remote --tests --examples - cargo fmt --all -- --check Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- .../src/dataloader/permutation/builder.rs | 128 +++++++++++++++++- rust/lancedb/src/remote/table.rs | 12 ++ rust/lancedb/src/table.rs | 8 ++ 3 files changed, 146 insertions(+), 2 deletions(-) diff --git a/rust/lancedb/src/dataloader/permutation/builder.rs b/rust/lancedb/src/dataloader/permutation/builder.rs index a3700d0ef..641c191d5 100644 --- a/rust/lancedb/src/dataloader/permutation/builder.rs +++ b/rust/lancedb/src/dataloader/permutation/builder.rs @@ -239,7 +239,20 @@ impl PermutationBuilder { } /// Builds the permutation table and stores it in the given database. - pub async fn build(self) -> Result
{ + 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. + if let Some(snapshot) = self + .base_table + .base_table() + .snapshot_at_current_version() + .await? + { + self.base_table = Table::from(snapshot); + } + // Unflushed rows have no row id, so a permutation cannot address them. match self.base_table.base_table().get_lsm_write_spec().await { Ok(Some(_)) => { @@ -258,7 +271,6 @@ impl PermutationBuilder { // First pass, apply filter and load row ids. `Shuffler` permutes positions, so // every rank must scan the rows in the same order to build the same permutation. - // TODO: pin the version resolved here; remote does not implement Lazy. let mut rows = self.base_table.query().select(Select::columns(&[ROW_ID])); if let Some(filter) = &self.config.filter { @@ -409,6 +421,118 @@ mod tests { assert!(table.base_table().scan_order_is_deterministic()); } + #[cfg(feature = "remote")] + #[tokio::test] + async fn test_remote_permutation_builder_pins_snapshot() { + use std::sync::{ + Mutex, + atomic::{AtomicU64, Ordering}, + }; + + use arrow_array::{RecordBatch, UInt64Array}; + use arrow_schema::{DataType, Field, Schema}; + + let row_ids = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new( + ROW_ID, + DataType::UInt64, + false, + )])), + vec![Arc::new(UInt64Array::from(vec![100]))], + ) + .unwrap(); + let mut query_body = Vec::new(); + { + let mut writer = + arrow_ipc::writer::FileWriter::try_new(&mut query_body, &row_ids.schema()).unwrap(); + writer.write(&row_ids).unwrap(); + writer.finish().unwrap(); + } + + let latest = Arc::new(AtomicU64::new(7)); + let expected_snapshot = Arc::new(AtomicU64::new(7)); + let planning_versions = Arc::new(Mutex::new(Vec::new())); + let latest_ref = latest.clone(); + let expected_snapshot_ref = expected_snapshot.clone(); + let planning_versions_ref = planning_versions.clone(); + let table = Table::new_with_handler("remote_base", move |request| { + let path = request.url().path(); + let body = request + .body() + .and_then(|body| body.as_bytes()) + .map(|body| serde_json::from_slice::(body).unwrap()); + + match path { + "/v1/table/remote_base/describe/" => { + let requested = body.as_ref().and_then(|body| body["version"].as_u64()); + let version = requested.unwrap_or_else(|| latest_ref.load(Ordering::SeqCst)); + http::Response::builder() + .status(200) + .body( + format!(r#"{{"version":{version},"schema":{{"fields":[]}}}}"#) + .into_bytes(), + ) + .unwrap() + } + "/v1/table/remote_base/get_lsm_write_spec/" => http::Response::builder() + .status(200) + .body(br#"{"lsm_write_spec":null}"#.to_vec()) + .unwrap(), + "/v1/table/remote_base/count_rows/" => { + let body = body.unwrap(); + let version = body["version"].as_u64().unwrap(); + assert_eq!(version, expected_snapshot_ref.load(Ordering::SeqCst)); + assert_eq!(body["predicate"], "value > 0"); + planning_versions_ref.lock().unwrap().push(version); + + // Simulate a concurrent append after count_rows. An unpinned + // scan would now resolve version 8 and include different rows. + latest_ref.store(8, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body(b"1".to_vec()) + .unwrap() + } + "/v1/table/remote_base/query/" => { + let body = body.unwrap(); + let version = body["version"].as_u64().unwrap(); + assert_eq!(version, expected_snapshot_ref.load(Ordering::SeqCst)); + assert_eq!(body["filter"], "value > 0"); + assert_eq!(body["columns"], serde_json::json!([ROW_ID])); + planning_versions_ref.lock().unwrap().push(version); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.file") + .body(query_body.clone()) + .unwrap() + } + _ => panic!("unexpected request: {path}"), + } + }); + + let permutation = PermutationBuilder::new(table.clone()) + .with_filter("value > 0".to_string()) + .build() + .await + .unwrap(); + assert_eq!(permutation.count_rows(None).await.unwrap(), 1); + + // Building uses a separate handle and must not pin the caller's table. + assert_eq!(table.version().await.unwrap(), 8); + + // An explicit checkout is copied as-is and remains checked out afterward. + expected_snapshot.store(6, Ordering::SeqCst); + table.checkout(6).await.unwrap(); + let permutation = PermutationBuilder::new(table.clone()) + .with_filter("value > 0".to_string()) + .build() + .await + .unwrap(); + assert_eq!(permutation.count_rows(None).await.unwrap(), 1); + assert_eq!(table.version().await.unwrap(), 6); + assert_eq!(*planning_versions.lock().unwrap(), vec![7, 7, 6, 6]); + } + #[tokio::test] async fn test_permutation_builder() { let temp_dir = tempfile::tempdir().unwrap(); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index c6b078282..633d0ffce 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -1775,6 +1775,18 @@ impl BaseTable for RemoteTable { 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. + let version = match self.current_version().await { + Some(version) => version, + None => self.describe().await?.version, + }; + + let snapshot = self.with_branch(self.branch.clone()); + *snapshot.version.write().await = Some(version); + Ok(Some(Arc::new(snapshot))) + } async fn restore(&self) -> Result<()> { let mut request = self .client diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 41551bd37..356c87bbe 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -792,6 +792,14 @@ 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<()>; + /// Return an independent handle pinned to the version currently selected. + /// + /// Backends that can advance between requests should override this for + /// multi-request operations that need snapshot consistency. Backends whose + /// existing handles already provide the desired behavior return `None`. + async fn snapshot_at_current_version(&self) -> Result>> { + Ok(None) + } /// Whether repeated identical scans return rows in the same order. /// /// Callers that assign meaning to a row's position must order the results From fce45ba9fc5254d3e7fff8fc90c89b99706f120c Mon Sep 17 00:00:00 2001 From: Will Jones Date: Mon, 24 Aug 2026 16:25:14 -0700 Subject: [PATCH 107/206] feat(nodejs): add listTables, deprecate tableNames (#4041) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `table_names` is being replaced by `list_tables` across the SDKs, but TypeScript only had `tableNames`. This PR adds `listTables`, which returns a page of table names together with the token that resumes after it, and marks `tableNames` and `TableNamesOptions` deprecated in favor of it. It binds the `Connection::list_tables` that already exists, so nothing in the Rust API changes and nothing existing breaks. `pageToken` is documented as opaque rather than as a table name, since what resumes a listing is the database's to decide — that keeps callers off a detail that is going to change. Stacked on #4040, which fixes a table being dropped at every page boundary. The page-walking test here needs that fix to pass. Review the last commit only until #4040 lands. ## Example ```ts const names = []; let pageToken = undefined; do { const page = await conn.listTables({ pageToken, limit: 100 }); names.push(...page.tables); pageToken = page.pageToken; } while (pageToken); ``` A namespace can be listed by passing its path first, mirroring `tableNames`: ```ts const page = await conn.listTables(["analytics"], { limit: 100 }); ``` Co-authored-by: Claude Opus 5 (1M context) --- docs/src/js/classes/Connection.md | 74 ++++++++++++++++- docs/src/js/globals.md | 2 + docs/src/js/interfaces/ListTablesOptions.md | 34 ++++++++ docs/src/js/interfaces/ListTablesResponse.md | 23 ++++++ docs/src/js/interfaces/TableNamesOptions.md | 11 ++- nodejs/__test__/connection.test.ts | 69 +++++++++++++++- nodejs/lancedb/connection.ts | 85 ++++++++++++++++++++ nodejs/lancedb/index.ts | 2 + nodejs/src/connection.rs | 34 ++++++++ 9 files changed, 329 insertions(+), 5 deletions(-) create mode 100644 docs/src/js/interfaces/ListTablesOptions.md create mode 100644 docs/src/js/interfaces/ListTablesResponse.md diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index 92cfd2568..1c5abd89f 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -584,6 +584,70 @@ Child namespace names and *** +### listTables() + +#### listTables(options) + +```ts +abstract listTables(options?): Promise +``` + +List a page of the tables in this database. + +To retrieve the tables after the page, pass the `pageToken` the response +carries back in. A page can be shorter than `limit` without being the last +one, so walk until a response carries no page token: + +```ts +const names = []; +let pageToken = undefined; +do { + const page = await conn.listTables({ pageToken, limit: 100 }); + names.push(...page.tables); + pageToken = page.pageToken; +} while (pageToken); +``` + +##### Parameters + +* **options?**: `Partial`<[`ListTablesOptions`](../interfaces/ListTablesOptions.md)> + Pagination options + (`pageToken`, `limit`). + +##### Returns + +`Promise`<[`ListTablesResponse`](../interfaces/ListTablesResponse.md)> + +A page of table names and an + optional token for the tables after it. + +#### listTables(namespacePath, options) + +```ts +abstract listTables(namespacePath?, options?): Promise +``` + +List a page of the tables in this database. + +##### Parameters + +* **namespacePath?**: `string`[] + The namespace path to list tables from + (defaults to root namespace) + +* **options?**: `Partial`<[`ListTablesOptions`](../interfaces/ListTablesOptions.md)> + Pagination options + (`pageToken`, `limit`). + +##### Returns + +`Promise`<[`ListTablesResponse`](../interfaces/ListTablesResponse.md)> + +A page of table names and an + optional token for the tables after it. + +*** + ### openMaterializedView() ```ts @@ -660,7 +724,7 @@ a "not supported" error. *** -### tableNames() +### ~~tableNames()~~ #### tableNames(options) @@ -682,6 +746,10 @@ Tables will be returned in lexicographical order. `Promise`<`string`[]> +##### Deprecated + +Use [Connection.listTables](Connection.md#listtables) instead. + #### tableNames(namespacePath, options) ```ts @@ -704,3 +772,7 @@ Tables will be returned in lexicographical order. ##### Returns `Promise`<`string`[]> + +##### Deprecated + +Use [Connection.listTables](Connection.md#listtables) instead. diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 6a8f644eb..e0635ab65 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -100,6 +100,8 @@ - [JobInfo](interfaces/JobInfo.md) - [ListNamespacesOptions](interfaces/ListNamespacesOptions.md) - [ListNamespacesResponse](interfaces/ListNamespacesResponse.md) +- [ListTablesOptions](interfaces/ListTablesOptions.md) +- [ListTablesResponse](interfaces/ListTablesResponse.md) - [LsmStats](interfaces/LsmStats.md) - [LsmWriteSpec](interfaces/LsmWriteSpec.md) - [MaterializedViewDefinition](interfaces/MaterializedViewDefinition.md) diff --git a/docs/src/js/interfaces/ListTablesOptions.md b/docs/src/js/interfaces/ListTablesOptions.md new file mode 100644 index 000000000..52ace47e5 --- /dev/null +++ b/docs/src/js/interfaces/ListTablesOptions.md @@ -0,0 +1,34 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / ListTablesOptions + +# Interface: ListTablesOptions + +## Properties + +### limit? + +```ts +optional limit: number; +``` + +An upper bound on how many tables to return. + +A page may hold fewer than this and still not be the last one, so keep +going while the response carries a page token rather than while pages are +full. + +*** + +### pageToken? + +```ts +optional pageToken: string; +``` + +Token from a previous response, to resume listing where it left off. + +The token is opaque: it carries whatever the database needs to resume, and +callers should not construct or interpret one. diff --git a/docs/src/js/interfaces/ListTablesResponse.md b/docs/src/js/interfaces/ListTablesResponse.md new file mode 100644 index 000000000..76cac2b23 --- /dev/null +++ b/docs/src/js/interfaces/ListTablesResponse.md @@ -0,0 +1,23 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / ListTablesResponse + +# Interface: ListTablesResponse + +## Properties + +### pageToken? + +```ts +optional pageToken: string; +``` + +*** + +### tables + +```ts +tables: string[]; +``` diff --git a/docs/src/js/interfaces/TableNamesOptions.md b/docs/src/js/interfaces/TableNamesOptions.md index 45fa3d1b0..9254e9fa7 100644 --- a/docs/src/js/interfaces/TableNamesOptions.md +++ b/docs/src/js/interfaces/TableNamesOptions.md @@ -4,11 +4,16 @@ [@lancedb/lancedb](../globals.md) / TableNamesOptions -# Interface: TableNamesOptions +# Interface: ~~TableNamesOptions~~ + +## Deprecated + +Use [ListTablesOptions](ListTablesOptions.md) with [Connection.listTables](../classes/Connection.md#listtables) +instead. ## Properties -### limit? +### ~~limit?~~ ```ts optional limit: number; @@ -18,7 +23,7 @@ An optional limit to the number of results to return. *** -### startAfter? +### ~~startAfter?~~ ```ts optional startAfter: string; diff --git a/nodejs/__test__/connection.test.ts b/nodejs/__test__/connection.test.ts index af471b478..816f8c3de 100644 --- a/nodejs/__test__/connection.test.ts +++ b/nodejs/__test__/connection.test.ts @@ -4,7 +4,13 @@ import { readdirSync } from "fs"; import { Field, Float64, Schema } from "apache-arrow"; import * as tmp from "tmp"; -import { Connection, Table, connect, connectNamespace } from "../lancedb"; +import { + Connection, + ListTablesResponse, + Table, + connect, + connectNamespace, +} from "../lancedb"; import { LocalTable } from "../lancedb/table"; describe("when connecting", () => { @@ -47,6 +53,7 @@ describe("given a connection", () => { await db.close(); expect(db.isOpen()).toBe(false); await expect(db.tableNames()).rejects.toThrow("Connection is closed"); + await expect(db.listTables()).rejects.toThrow("Connection is closed"); await expect(db.renameTable("a", "b")).rejects.toThrow( "Connection is closed", ); @@ -129,6 +136,66 @@ describe("given a connection", () => { expect(tables).toEqual(["b", "c"]); }); + it("should respect limit and page token when listing tables", async () => { + const db = await connect(tmpDir.name); + + await db.createTable("b", [{ id: 1 }]); + await db.createTable("a", [{ id: 1 }]); + await db.createTable("c", [{ id: 1 }]); + + const all = await db.listTables(); + expect(all.tables).toEqual(["a", "b", "c"]); + expect(all.pageToken).toBeUndefined(); + + const first = await db.listTables({ limit: 1 }); + expect(first.tables).toEqual(["a"]); + expect(first.pageToken).toBeDefined(); + + const second = await db.listTables({ + limit: 1, + pageToken: first.pageToken, + }); + expect(second.tables).toEqual(["b"]); + }); + + it("should visit every table exactly once when walking pages", async () => { + const db = await connect(tmpDir.name); + + const created = ["a", "b", "c", "d", "e"]; + for (const name of created) { + await db.createTable(name, [{ id: 1 }]); + } + + const seen: string[] = []; + let pageToken: string | undefined = undefined; + do { + const page: ListTablesResponse = await db.listTables({ + limit: 2, + pageToken, + }); + seen.push(...page.tables); + pageToken = page.pageToken; + } while (pageToken); + + expect(seen).toEqual(created); + }); + + it("should list tables in a namespace", async () => { + const db = await connect(tmpDir.name, { + // biome-ignore lint/style/useNamingConvention: opaque backend property key, must match Rust + namespaceClientProperties: { manifest_enabled: "true" }, + }); + await db.createNamespace(["child"]); + await db.createTable("nested", [{ id: 1 }], ["child"]); + + await expect(db.listTables(["child"])).resolves.toEqual( + expect.objectContaining({ tables: ["nested"] }), + ); + await expect(db.listTables()).resolves.toEqual( + expect.objectContaining({ tables: [] }), + ); + }); + it("should create tables in v2 mode", async () => { const db = await connect(tmpDir.name); const data = [...Array(10000).keys()].map((i) => ({ id: i })); diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index e5528f8c6..263a338ab 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -31,12 +31,14 @@ import type { JobDescription, JobInfo, ListNamespacesResponse, + ListTablesResponse, } from "./native"; export type { CreateNamespaceResponse, DescribeNamespaceResponse, DropNamespaceResponse, ListNamespacesResponse, + ListTablesResponse, }; import { sanitizeTable } from "./sanitize"; import { LocalTable, Table } from "./table"; @@ -134,6 +136,10 @@ export interface OpenTableOptions { indexCacheSize?: number; } +/** + * @deprecated Use {@link ListTablesOptions} with {@link Connection.listTables} + * instead. + */ export interface TableNamesOptions { /** * If present, only return names that come lexicographically after the @@ -147,6 +153,24 @@ export interface TableNamesOptions { limit?: number; } +export interface ListTablesOptions { + /** + * Token from a previous response, to resume listing where it left off. + * + * The token is opaque: it carries whatever the database needs to resume, and + * callers should not construct or interpret one. + */ + pageToken?: string; + /** + * An upper bound on how many tables to return. + * + * A page may hold fewer than this and still not be the last one, so keep + * going while the response carries a page token rather than while pages are + * full. + */ + limit?: number; +} + export interface ListNamespacesOptions { /** Token from a previous response for pagination. */ pageToken?: string; @@ -231,6 +255,7 @@ export abstract class Connection { * @param {Partial} options - options to control the * paging / start point (backwards compatibility) * + * @deprecated Use {@link Connection.listTables} instead. */ abstract tableNames(options?: Partial): Promise; /** @@ -241,12 +266,53 @@ export abstract class Connection { * @param {Partial} options - options to control the * paging / start point * + * @deprecated Use {@link Connection.listTables} instead. */ abstract tableNames( namespacePath?: string[], options?: Partial, ): Promise; + /** + * List a page of the tables in this database. + * + * To retrieve the tables after the page, pass the `pageToken` the response + * carries back in. A page can be shorter than `limit` without being the last + * one, so walk until a response carries no page token: + * + * ```ts + * const names = []; + * let pageToken = undefined; + * do { + * const page = await conn.listTables({ pageToken, limit: 100 }); + * names.push(...page.tables); + * pageToken = page.pageToken; + * } while (pageToken); + * ``` + * + * @param {Partial} options - Pagination options + * (`pageToken`, `limit`). + * @returns {Promise} A page of table names and an + * optional token for the tables after it. + */ + abstract listTables( + options?: Partial, + ): Promise; + /** + * List a page of the tables in this database. + * + * @param {string[]} namespacePath - The namespace path to list tables from + * (defaults to root namespace) + * @param {Partial} options - Pagination options + * (`pageToken`, `limit`). + * @returns {Promise} A page of table names and an + * optional token for the tables after it. + */ + abstract listTables( + namespacePath?: string[], + options?: Partial, + ): Promise; + /** * Open a table in the database. * @param {string} name - The name of the table @@ -601,6 +667,25 @@ export class LocalConnection extends Connection { return await this.inner.listMaterializedViews(); } + async listTables( + namespacePathOrOptions?: string[] | Partial, + options?: Partial, + ): Promise { + // Detect if first argument is namespacePath array or options object + const namespacePath = Array.isArray(namespacePathOrOptions) + ? namespacePathOrOptions + : undefined; + const listTablesOptions = Array.isArray(namespacePathOrOptions) + ? options + : namespacePathOrOptions; + + return this.inner.listTables( + namespacePath ?? [], + listTablesOptions?.pageToken, + listTablesOptions?.limit, + ); + } + async openTable( name: string, namespacePath?: string[], diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index da13b434f..ebc8cda8d 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -81,11 +81,13 @@ export { Connection, CreateTableOptions, TableNamesOptions, + ListTablesOptions, OpenTableOptions, ListNamespacesOptions, CreateNamespaceOptions, DropNamespaceOptions, ListNamespacesResponse, + ListTablesResponse, CreateNamespaceResponse, DropNamespaceResponse, DescribeNamespaceResponse, diff --git a/nodejs/src/connection.rs b/nodejs/src/connection.rs index 44eb68f32..5cf676256 100644 --- a/nodejs/src/connection.rs +++ b/nodejs/src/connection.rs @@ -17,6 +17,7 @@ use lancedb::connection::{ConnectBuilder, Connection as LanceDBConnection, conne use lance_namespace::models::{ CreateNamespaceRequest, DescribeNamespaceRequest, DropNamespaceRequest, ListNamespacesRequest, + ListTablesRequest, }; use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema}; @@ -36,6 +37,12 @@ pub struct ListNamespacesResponse { pub page_token: Option, } +#[napi(object)] +pub struct ListTablesResponse { + pub tables: Vec, + pub page_token: Option, +} + #[napi(object)] pub struct CreateNamespaceResponse { pub properties: Option>, @@ -206,6 +213,33 @@ impl Connection { op.execute().await.default_error() } + /// List a page of tables in the database. + #[napi(catch_unwind)] + pub async fn list_tables( + &self, + namespace_path: Option>, + page_token: Option, + limit: Option, + ) -> napi::Result { + let request = ListTablesRequest { + // The root namespace is an empty path, not an absent one: a namespace-backed + // database rejects a request that names no namespace. + id: Some(namespace_path.unwrap_or_default()), + page_token, + limit: limit.map(|limit| i32::try_from(limit).unwrap_or(i32::MAX)), + ..Default::default() + }; + let response = self + .get_inner()? + .list_tables(request) + .await + .default_error()?; + Ok(ListTablesResponse { + tables: response.tables, + page_token: response.page_token, + }) + } + /// Create table from a Apache Arrow IPC (file) buffer. /// /// Parameters: From c1a8c3f089fbab95883bd58d9a568d4c30d41074 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Mon, 24 Aug 2026 16:41:05 -0700 Subject: [PATCH 108/206] fix(node): validate inferred types across records (#3786) ## Summary - compare inferred Arrow types by their semantic representation across records - throw the schema inference error when a later record has an incompatible type - cover compatible and incompatible multi-record inference across supported Arrow versions ## Root cause Schema inference compared newly allocated Arrow DataType objects by identity, so equivalent inferred types did not compare equal. The mismatch path also constructed an Error without throwing it, which silently accepted incompatible values. ## Validation - pnpm test __test__/arrow.test.ts --runInBand (176 tests passed) - pnpm lint - pnpm build - pnpm run docs Fixes #3781 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- nodejs/__test__/arrow.test.ts | 131 ++++++++ nodejs/lancedb/arrow.ts | 340 ++------------------ nodejs/lancedb/arrow_type.ts | 40 +++ nodejs/lancedb/schema.ts | 566 ++++++++++++++++++++++++++++++++++ 4 files changed, 770 insertions(+), 307 deletions(-) create mode 100644 nodejs/lancedb/arrow_type.ts create mode 100644 nodejs/lancedb/schema.ts diff --git a/nodejs/__test__/arrow.test.ts b/nodejs/__test__/arrow.test.ts index 160f4d5ef..c5bbbf169 100644 --- a/nodejs/__test__/arrow.test.ts +++ b/nodejs/__test__/arrow.test.ts @@ -515,6 +515,137 @@ describe.each([arrow15, arrow16, arrow17, arrow18])( ); }); + it("will allow matching inferred types across records", function () { + expect(() => + makeArrowTable([{ value: 1 }, { value: 2 }]), + ).not.toThrow(); + }); + + it("will reject mismatched inferred types across records", function () { + expect(() => makeArrowTable([{ value: 1 }, { value: "two" }])).toThrow( + "Failed to infer schema for data. Previously inferred type Float64 but found Utf8 for field value at row 1. Consider providing an explicit schema.", + ); + }); + + it("will ignore generated dictionary IDs when comparing inferred types", function () { + const table = makeArrowTable([{ str: "a" }, { str: "b" }], { + dictionaryEncodeStrings: true, + }); + + expect(table.getChild("str")?.toJSON()).toEqual(["a", "b"]); + }); + + it("will preserve null values without treating them as type mismatches", function () { + for (const records of [ + [{ vector: [1, 2, 3] }, { vector: null }], + [{ vector: null }, { vector: [1, 2, 3] }], + ]) { + const table = makeArrowTable(records); + + expect(table.numRows).toBe(2); + expect(table.getChild("vector")?.nullCount).toBe(1); + } + }); + + it("will preserve empty variable-size lists", function () { + for (const records of [ + [{ items: [1] }, { items: [] }], + [{ items: [] }, { items: [1] }], + ]) { + const table = makeArrowTable(records); + expect( + table + .getChild("items") + ?.toJSON() + .map((value) => value.toJSON()), + ).toEqual(records.map((record) => record.items)); + } + }); + + it("will propagate deferred evidence through nested lists", function () { + for (const records of [ + [{ items: [1] }, { items: [null] }], + [{ items: [null] }, { items: [1] }], + [{ items: [null, 1] }, { items: [2, null] }], + ]) { + const table = makeArrowTable(records); + expect( + table + .getChild("items") + ?.toJSON() + .map((value) => value.toJSON()), + ).toEqual(records.map((record) => record.items)); + } + + const nestedRecords = [{ items: [[1]] }, { items: [[null]] }]; + const nestedTable = makeArrowTable(nestedRecords); + expect( + nestedTable + .getChild("items") + ?.toJSON() + .map((value) => + value + .toJSON() + .map((nestedValue: { toJSON: () => unknown[] }) => + nestedValue.toJSON(), + ), + ), + ).toEqual(nestedRecords.map((record) => record.items)); + }); + + it("will reject incompatible deferred evidence within a list", function () { + for (const items of [ + [[], 1], + [1, []], + [[null], 1], + [1, [null]], + ]) { + expect(() => makeArrowTable([{ items }])).toThrow( + "Failed to infer data type for field items at row 0.", + ); + } + }); + + it("will reject empty fixed-size lists", function () { + expect(() => + makeArrowTable([{ vector: [1, 2, 3] }, { vector: [] }]), + ).toThrow( + "Failed to infer schema for data. Previously inferred type FixedSizeList[3] but found List[0] for field vector at row 1.", + ); + }); + + it("will reject inferred leaf and branch shape changes", function () { + expect(() => + makeArrowTable([{ value: 1 }, { value: { nested: 2 } }]), + ).toThrow( + "Failed to infer schema for data. Previously inferred type Float64 but found Struct for field value at row 1.", + ); + expect(() => + makeArrowTable([{ value: { nested: 1 } }, { value: 2 }]), + ).toThrow( + "Failed to infer schema for data. Previously inferred type Struct but found Float64 for field value at row 1.", + ); + }); + + it("will allow null values around inferred struct values", function () { + for (const { records, nullIndex } of [ + { + records: [{ value: null }, { value: { nested: 2 } }], + nullIndex: 0, + }, + { + records: [{ value: { nested: 1 } }, { value: null }], + nullIndex: 1, + }, + ]) { + const table = makeArrowTable(records); + const values = table.getChild("value"); + + expect(values?.nullCount).toBe(1); + expect(values?.get(nullIndex)).toBeNull(); + } + }); + it("will allow a schema to be provided", async function () { await checkTableCreation( async (records, _, schema) => diff --git a/nodejs/lancedb/arrow.ts b/nodejs/lancedb/arrow.ts index 8b388d593..b52ab50ef 100644 --- a/nodejs/lancedb/arrow.ts +++ b/nodejs/lancedb/arrow.ts @@ -5,7 +5,6 @@ import { Data as ArrowData, Table as ArrowTable, Binary, - Bool, BufferType, DataType, DateUnit, @@ -18,12 +17,7 @@ import { FixedSizeList, Float, Float32, - Float64, Int, - Int8, - Int16, - Int32, - Int64, LargeBinary, List, Null, @@ -36,17 +30,16 @@ import { Struct, Timestamp, Type, - Uint8, - Uint16, - Uint32, Utf8, Vector, makeVector as arrowMakeVector, + util as arrowUtil, vectorFromArray as badVectorFromArray, makeBuilder, makeData, } from "apache-arrow"; import { Buffers } from "apache-arrow/data"; +import { typedArrayToArrowType } from "./arrow_type"; import { type EmbeddingFunction } from "./embedding/embedding_function"; import { EmbeddingFunctionConfig, @@ -59,14 +52,7 @@ import { sanitizeTable, sanitizeType, } from "./sanitize"; - -/** - * Check if a field name indicates a vector column. - */ -function nameSuggestsVectorColumn(fieldName: string): boolean { - const nameLower = fieldName.toLowerCase(); - return nameLower.includes("vector") || nameLower.includes("embedding"); -} +import { inferSchema } from "./schema"; export * from "apache-arrow"; export type SchemaLike = @@ -459,110 +445,6 @@ export function makeArrowTable( return new ArrowTable(inferredSchema, finalColumns); } -function inferSchema( - data: Array>, - schema: Schema | undefined, - opts: MakeArrowTableOptions, -): Schema { - // We will collect all fields we see in the data. - const pathTree = new PathTree(); - - for (const [rowI, row] of data.entries()) { - for (const [path, value] of rowPathsAndValues(row)) { - if (!pathTree.has(path)) { - // First time seeing this field. - if (schema !== undefined) { - const field = getFieldForPath(schema, path); - if (field === undefined) { - throw new Error( - `Found field not in schema: ${path.join(".")} at row ${rowI}`, - ); - } else { - pathTree.set(path, field.type); - } - } else { - const inferredType = inferType(value, path, opts); - if (inferredType === undefined) { - throw new Error(`Failed to infer data type for field ${path.join( - ".", - )} at row ${rowI}. \ - Consider providing an explicit schema.`); - } - pathTree.set(path, inferredType); - } - } else if (schema === undefined) { - const currentType = pathTree.get(path); - const newType = inferType(value, path, opts); - if (currentType !== newType) { - new Error(`Failed to infer schema for data. Previously inferred type \ - ${currentType} but found ${newType} at row ${rowI}. Consider \ - providing an explicit schema.`); - } - } - } - } - - if (schema === undefined) { - function fieldsFromPathTree(pathTree: PathTree): Field[] { - const fields = []; - for (const [name, value] of pathTree.map.entries()) { - if (value instanceof PathTree) { - const children = fieldsFromPathTree(value); - fields.push(new Field(name, new Struct(children), true)); - } else { - fields.push(new Field(name, value, true)); - } - } - return fields; - } - const fields = fieldsFromPathTree(pathTree); - return new Schema(fields); - } else { - function takeMatchingFields( - fields: Field[], - pathTree: PathTree, - ): Field[] { - const outFields = []; - for (const field of fields) { - if (pathTree.map.has(field.name)) { - const value = pathTree.get([field.name]); - if (value instanceof PathTree) { - const struct = field.type as Struct; - const children = takeMatchingFields(struct.children, value); - outFields.push( - new Field(field.name, new Struct(children), field.nullable), - ); - } else { - outFields.push( - new Field(field.name, value as DataType, field.nullable), - ); - } - } - } - return outFields; - } - const fields = takeMatchingFields(schema.fields, pathTree); - return new Schema(fields); - } -} - -function* rowPathsAndValues( - row: Record, - basePath: string[] = [], -): Generator<[string[], unknown]> { - for (const [key, value] of Object.entries(row)) { - if (isObject(value)) { - yield* rowPathsAndValues(value, [...basePath, key]); - } else { - // Skip undefined values - they should be treated the same as missing fields - // for embedding function purposes - if (value !== undefined) { - yield [[...basePath, key], value]; - } - } - } -} - function isObject(value: unknown): value is Record { return ( typeof value === "object" && @@ -577,146 +459,19 @@ function isObject(value: unknown): value is Record { ); } -function getFieldForPath(schema: Schema, path: string[]): Field | undefined { - let current: Field | Schema = schema; +function valueAtPath(datum: Record, path: string[]): unknown { + let current: unknown = datum; for (const key of path) { - if (current instanceof Schema) { - const field: Field | undefined = current.fields.find( - (f) => f.name === key, - ); - if (field === undefined) { - return undefined; - } - current = field; - } else if (current instanceof Field && DataType.isStruct(current.type)) { - const struct: Struct = current.type; - const field = struct.children.find((f) => f.name === key); - if (field === undefined) { - return undefined; - } - current = field; + if (current == null) { + return null; + } + if (isObject(current) && (Object.hasOwn(current, key) || key in current)) { + current = current[key]; } else { return undefined; } } - if (current instanceof Field) { - return current; - } else { - return undefined; - } -} - -/** - * Try to infer which Arrow type to use for a given value. - * - * May return undefined if the type cannot be inferred. - */ -function inferType( - value: unknown, - path: string[], - opts: MakeArrowTableOptions, -): DataType | undefined { - if (typeof value === "bigint") { - return new Int64(); - } else if (typeof value === "number") { - // Even if it's an integer, it's safer to assume Float64. Users can - // always provide an explicit schema or use BigInt if they mean integer. - return new Float64(); - } else if (typeof value === "string") { - if (opts.dictionaryEncodeStrings) { - return new Dictionary(new Utf8(), new Int32()); - } else { - return new Utf8(); - } - } else if (typeof value === "boolean") { - return new Bool(); - } else if (value instanceof Buffer) { - return new Binary(); - } else if (ArrayBuffer.isView(value) && !(value instanceof DataView)) { - const info = typedArrayToArrowType(value); - if (info !== undefined) { - const child = new Field("item", info.elementType, true); - return new FixedSizeList(info.length, child); - } - return undefined; - } else if (Array.isArray(value)) { - if (value.length === 0) { - return undefined; // Without any values we can't infer the type - } - if (path.length === 1 && Object.hasOwn(opts.vectorColumns, path[0])) { - const floatType = sanitizeType(opts.vectorColumns[path[0]].type); - return new FixedSizeList( - value.length, - new Field("item", floatType, true), - ); - } - const valueType = inferType(value[0], path, opts); - if (valueType === undefined) { - return undefined; - } - // Try to automatically detect embedding columns. - if (nameSuggestsVectorColumn(path[path.length - 1])) { - // Check if value is a Uint8Array for integer vector type determination - if (value instanceof Uint8Array) { - // For integer vectors, we default to Uint8 (matching Python implementation) - const child = new Field("item", new Uint8(), true); - return new FixedSizeList(value.length, child); - } else { - // For float vectors, we default to Float32 - const child = new Field("item", new Float32(), true); - return new FixedSizeList(value.length, child); - } - } else { - const child = new Field("item", valueType, true); - return new List(child); - } - } else { - // TODO: timestamp - return undefined; - } -} - -class PathTree { - map: Map>; - - constructor(entries?: [string[], V][]) { - this.map = new Map(); - if (entries !== undefined) { - for (const [path, value] of entries) { - this.set(path, value); - } - } - } - has(path: string[]): boolean { - let ref: PathTree = this; - for (const part of path) { - if (!(ref instanceof PathTree) || !ref.map.has(part)) { - return false; - } - ref = ref.map.get(part) as PathTree; - } - return true; - } - get(path: string[]): V | undefined { - let ref: PathTree = this; - for (const part of path) { - if (!(ref instanceof PathTree) || !ref.map.has(part)) { - return undefined; - } - ref = ref.map.get(part) as PathTree; - } - return ref as V; - } - set(path: string[], value: V): void { - let ref: PathTree = this; - for (const part of path.slice(0, path.length - 1)) { - if (!ref.map.has(part)) { - ref.map.set(part, new PathTree()); - } - ref = ref.map.get(part) as PathTree; - } - ref.map.set(path[path.length - 1], value); - } + return current; } function transposeData( @@ -724,37 +479,26 @@ function transposeData( field: Field, path: string[] = [], ): Vector { + const valuesPath = [...path, field.name]; + const values = data.map((datum) => valueAtPath(datum, valuesPath)); if (field.type instanceof Struct) { const childFields = field.type.children; - const fullPath = [...path, field.name]; const childVectors = childFields.map((child) => { - return transposeData(data, child, fullPath); + return transposeData(data, child, valuesPath); }); + const nullCount = values.filter((value) => value === null).length; const structData = makeData({ type: field.type, + length: values.length, + nullCount, + nullBitmap: + nullCount > 0 + ? arrowUtil.packBools(values.map((value) => value !== null)) + : undefined, children: childVectors as unknown as ArrowData[], }); return arrowMakeVector(structData); } else { - const valuesPath = [...path, field.name]; - const values = data.map((datum) => { - let current: unknown = datum; - for (const key of valuesPath) { - if (current == null) { - return null; - } - - if ( - isObject(current) && - (Object.hasOwn(current, key) || key in current) - ) { - current = current[key]; - } else { - return null; - } - } - return current; - }); return makeVector(values, field.type, undefined, field.nullable); } } @@ -797,32 +541,6 @@ function makeListVector(lists: unknown[][]): Vector { return listBuilder.finish().toVector(); } -/** - * Map a JS TypedArray instance to the corresponding Arrow element DataType - * and its length. Returns undefined if the value is not a recognized TypedArray. - */ -function typedArrayToArrowType( - value: ArrayBufferView, -): { elementType: DataType; length: number } | undefined { - if (value instanceof Float32Array) - return { elementType: new Float32(), length: value.length }; - if (value instanceof Float64Array) - return { elementType: new Float64(), length: value.length }; - if (value instanceof Uint8Array) - return { elementType: new Uint8(), length: value.length }; - if (value instanceof Uint16Array) - return { elementType: new Uint16(), length: value.length }; - if (value instanceof Uint32Array) - return { elementType: new Uint32(), length: value.length }; - if (value instanceof Int8Array) - return { elementType: new Int8(), length: value.length }; - if (value instanceof Int16Array) - return { elementType: new Int16(), length: value.length }; - if (value instanceof Int32Array) - return { elementType: new Int32(), length: value.length }; - return undefined; -} - /** Helper function to convert an Array of JS values to an Arrow Vector */ function makeVector( values: unknown[], @@ -1462,8 +1180,12 @@ export function ensureNestedFieldsExist( completeRow[field.name] = row[field.name]; } } else { - // Field is missing from the data - set to null - completeRow[field.name] = null; + // Keep a missing struct valid while filling each of its children with + // null. This is distinct from an explicitly null struct value. + completeRow[field.name] = + field.type.constructor.name === "Struct" + ? ensureStructFieldsExist({}, field.type as Struct) + : null; } } @@ -1498,8 +1220,12 @@ function ensureStructFieldsExist( completeStruct[childField.name] = data[childField.name]; } } else { - // Field is missing - set to null - completeStruct[childField.name] = null; + // Keep a missing struct valid while filling each of its children with + // null. This is distinct from an explicitly null struct value. + completeStruct[childField.name] = + childField.type.constructor.name === "Struct" + ? ensureStructFieldsExist({}, childField.type as Struct) + : null; } } diff --git a/nodejs/lancedb/arrow_type.ts b/nodejs/lancedb/arrow_type.ts new file mode 100644 index 000000000..35da346ef --- /dev/null +++ b/nodejs/lancedb/arrow_type.ts @@ -0,0 +1,40 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { + type DataType, + Float32, + Float64, + Int8, + Int16, + Int32, + Uint8, + Uint16, + Uint32, +} from "apache-arrow"; + +/** + * Map a JS TypedArray instance to the corresponding Arrow element type and + * length. Returns undefined when the view is not a supported TypedArray. + */ +export function typedArrayToArrowType( + value: ArrayBufferView, +): { elementType: DataType; length: number } | undefined { + if (value instanceof Float32Array) + return { elementType: new Float32(), length: value.length }; + if (value instanceof Float64Array) + return { elementType: new Float64(), length: value.length }; + if (value instanceof Uint8Array) + return { elementType: new Uint8(), length: value.length }; + if (value instanceof Uint16Array) + return { elementType: new Uint16(), length: value.length }; + if (value instanceof Uint32Array) + return { elementType: new Uint32(), length: value.length }; + if (value instanceof Int8Array) + return { elementType: new Int8(), length: value.length }; + if (value instanceof Int16Array) + return { elementType: new Int16(), length: value.length }; + if (value instanceof Int32Array) + return { elementType: new Int32(), length: value.length }; + return undefined; +} diff --git a/nodejs/lancedb/schema.ts b/nodejs/lancedb/schema.ts new file mode 100644 index 000000000..e4749ef37 --- /dev/null +++ b/nodejs/lancedb/schema.ts @@ -0,0 +1,566 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { + Binary, + Bool, + DataType, + Dictionary, + Field, + FixedSizeList, + Float32, + Float64, + Int32, + Int64, + List, + Schema, + Struct, + Utf8, + util as arrowUtil, +} from "apache-arrow"; +import { typedArrayToArrowType } from "./arrow_type"; +import { sanitizeType } from "./sanitize"; + +type InferenceOptions = { + dictionaryEncodeStrings: boolean; + vectorColumns: Record; +}; + +/** + * Infer the Arrow schema represented by a set of records. + * + * This is the intentionally small interface to schema inference. The stateful + * details of combining partial type evidence are encapsulated below so callers + * only need to provide records, an optional schema, and inference options. + */ +export function inferSchema( + data: Array>, + schema: Schema | undefined, + options: InferenceOptions, +): Schema { + return new SchemaInferrer(schema, options).infer(data); +} + +class SchemaInferrer { + private readonly fields = new FieldTree(); + + constructor( + private readonly providedSchema: Schema | undefined, + private readonly options: InferenceOptions, + ) {} + + infer(data: Array>): Schema { + for (const [row, record] of data.entries()) { + for (const [path, value] of recordPathsAndValues(record)) { + this.observe(path, value, row); + } + } + + return this.providedSchema === undefined + ? new Schema(fieldsFromTree(this.fields)) + : new Schema(matchingFields(this.providedSchema.fields, this.fields)); + } + + private observe(path: string[], value: unknown, row: number): void { + const current = this.fields.get(path); + if (current === undefined) { + this.addField(path, value, row); + } else if (this.providedSchema === undefined) { + this.updateInferredField(path, value, row, current); + } + } + + private addField(path: string[], value: unknown, row: number): void { + if (this.providedSchema !== undefined) { + this.addSchemaField(this.providedSchema, path, row); + return; + } + + const evidence = + this.inferType(value, path) ?? DeferredTypeEvidence.from(value, row); + if (evidence === undefined) { + throw typeInferenceError(path, row); + } + + const conflict = this.fields.set( + path, + evidence, + (existing) => + existing instanceof DeferredTypeEvidence && existing.isOnlyNulls(), + ); + if (conflict !== undefined) { + throw branchConflictError(conflict, row, "Struct"); + } + } + + private addSchemaField(schema: Schema, path: string[], row: number): void { + const field = fieldAtPath(schema, path); + if (field === undefined) { + throw new Error( + `Found field not in schema: ${path.join(".")} at row ${row}`, + ); + } + + const conflict = this.fields.set(path, field.type); + if (conflict !== undefined) { + throw branchConflictError(conflict, row, "Struct"); + } + } + + private updateInferredField( + path: string[], + value: unknown, + row: number, + current: FieldNode, + ): void { + const newType = this.inferType(value, path); + const deferred = DeferredTypeEvidence.from(value, row); + + if (current instanceof FieldTree) { + if (deferred?.isOnlyNulls()) { + return; + } + throw schemaInferenceError( + path, + row, + "Struct", + describeEvidence(newType ?? deferred), + ); + } + + if (current instanceof DeferredTypeEvidence) { + this.resolveDeferredField(path, row, current, newType, deferred); + return; + } + + if (newType !== undefined) { + if (!inferredTypesEqual(current, newType)) { + throw schemaInferenceError( + path, + row, + describeEvidence(current), + describeEvidence(newType), + ); + } + return; + } + + if (deferred === undefined || !deferred.matches(current)) { + throw schemaInferenceError( + path, + row, + describeEvidence(current), + describeEvidence(deferred), + ); + } + } + + private resolveDeferredField( + path: string[], + row: number, + current: DeferredTypeEvidence, + newType: DataType | undefined, + deferred: DeferredTypeEvidence | undefined, + ): void { + if (newType !== undefined) { + if (!current.matches(newType)) { + throw schemaInferenceError( + path, + row, + current.describe(), + describeEvidence(newType), + ); + } + this.fields.set(path, newType); + return; + } + + if (deferred !== undefined) { + this.fields.set(path, current.merge(deferred)); + return; + } + + throw schemaInferenceError( + path, + row, + current.describe(), + describeEvidence(newType), + ); + } + + private inferType(value: unknown, path: string[]): DataType | undefined { + if (typeof value === "bigint") { + return new Int64(); + } + if (typeof value === "number") { + return new Float64(); + } + if (typeof value === "string") { + return this.options.dictionaryEncodeStrings + ? new Dictionary(new Utf8(), new Int32()) + : new Utf8(); + } + if (typeof value === "boolean") { + return new Bool(); + } + if (value instanceof Buffer) { + return new Binary(); + } + if (ArrayBuffer.isView(value) && !(value instanceof DataView)) { + const typedArray = typedArrayToArrowType(value); + return typedArray === undefined + ? undefined + : new FixedSizeList( + typedArray.length, + new Field("item", typedArray.elementType, true), + ); + } + if (!Array.isArray(value) || value.length === 0) { + return undefined; + } + + const configuredVector = + path.length === 1 ? this.options.vectorColumns[path[0]] : undefined; + if (configuredVector !== undefined) { + return new FixedSizeList( + value.length, + new Field("item", sanitizeType(configuredVector.type), true), + ); + } + + const itemType = this.inferArrayItemType(value, path); + if (itemType === undefined) { + return undefined; + } + + return nameSuggestsVectorColumn(path[path.length - 1]) + ? new FixedSizeList(value.length, new Field("item", new Float32(), true)) + : new List(new Field("item", itemType, true)); + } + + private inferArrayItemType( + values: unknown[], + path: string[], + ): DataType | undefined { + let itemType: DataType | undefined; + const deferredItems: unknown[] = []; + + for (const value of values) { + const candidate = this.inferType(value, path); + if (candidate === undefined) { + if (!isDeferredValue(value)) { + return undefined; + } + deferredItems.push(value); + } else if (itemType === undefined) { + itemType = candidate; + } else if (!inferredTypesEqual(itemType, candidate)) { + return undefined; + } + } + + if (itemType === undefined) { + return undefined; + } + return deferredItems.every((value) => + deferredValueMatchesType(value, itemType), + ) + ? itemType + : undefined; + } +} + +/** Nulls and empty/all-null lists that do not determine a type by themselves. */ +class DeferredTypeEvidence { + private constructor( + private readonly values: Array<{ value: unknown; row: number }>, + ) {} + + static from(value: unknown, row: number): DeferredTypeEvidence | undefined { + return isDeferredValue(value) + ? new DeferredTypeEvidence([{ value, row }]) + : undefined; + } + + isOnlyNulls(): boolean { + return this.values.every(({ value }) => value == null); + } + + matches(type: DataType): boolean { + return this.values.every(({ value }) => + deferredValueMatchesType(value, type), + ); + } + + merge(other: DeferredTypeEvidence): DeferredTypeEvidence { + return new DeferredTypeEvidence([...this.values, ...other.values]); + } + + describe(): string { + const list = this.values.find(({ value }) => Array.isArray(value)); + return list === undefined + ? "null" + : `List[${(list.value as unknown[]).length}]`; + } + + firstRow(): number { + return this.values[0].row; + } +} + +type FieldNode = DataType | DeferredTypeEvidence | FieldTree; +type LeafNode = Exclude; +type FieldConflict = { path: string[]; value: FieldNode }; + +/** Nested field state, kept separate from Arrow's eventual Struct types. */ +class FieldTree { + private readonly children = new Map(); + + get(path: string[]): FieldNode | undefined { + let current: FieldNode = this; + for (const part of path) { + if (!(current instanceof FieldTree)) { + return undefined; + } + const child = current.children.get(part); + if (child === undefined) { + return undefined; + } + current = child; + } + return current; + } + + set( + path: string[], + value: LeafNode, + canReplaceLeaf: (value: LeafNode) => boolean = () => false, + ): FieldConflict | undefined { + let branch: FieldTree = this; + for (const [index, part] of path.slice(0, -1).entries()) { + const child = branch.children.get(part); + if (child === undefined || (isLeaf(child) && canReplaceLeaf(child))) { + const nextBranch = new FieldTree(); + branch.children.set(part, nextBranch); + branch = nextBranch; + } else if (child instanceof FieldTree) { + branch = child; + } else { + return { path: path.slice(0, index + 1), value: child }; + } + } + + const name = path[path.length - 1]; + const current = branch.children.get(name); + if (current instanceof FieldTree) { + return { path, value: current }; + } + branch.children.set(name, value); + return undefined; + } + + entries(): IterableIterator<[string, FieldNode]> { + return this.children.entries(); + } + + has(name: string): boolean { + return this.children.has(name); + } +} + +function isLeaf(value: FieldNode): value is LeafNode { + return !(value instanceof FieldTree); +} + +function fieldsFromTree(tree: FieldTree, path: string[] = []): Field[] { + const fields: Field[] = []; + for (const [name, value] of tree.entries()) { + if (value instanceof FieldTree) { + fields.push( + new Field( + name, + new Struct(fieldsFromTree(value, [...path, name])), + true, + ), + ); + } else if (value instanceof DeferredTypeEvidence) { + throw typeInferenceError([...path, name], value.firstRow()); + } else { + fields.push(new Field(name, value, true)); + } + } + return fields; +} + +function matchingFields(fields: Field[], tree: FieldTree): Field[] { + const matches: Field[] = []; + for (const field of fields) { + if (!tree.has(field.name)) { + continue; + } + const value = tree.get([field.name]); + if (value instanceof FieldTree) { + const struct = field.type as Struct; + matches.push( + new Field( + field.name, + new Struct(matchingFields(struct.children, value)), + field.nullable, + ), + ); + } else { + matches.push(new Field(field.name, value as DataType, field.nullable)); + } + } + return matches; +} + +function* recordPathsAndValues( + record: Record, + path: string[] = [], +): Generator<[string[], unknown]> { + for (const [name, value] of Object.entries(record)) { + if (isRecord(value)) { + yield* recordPathsAndValues(value, [...path, name]); + } else if (value !== undefined) { + yield [[...path, name], value]; + } + } +} + +function isRecord(value: unknown): value is Record { + return ( + typeof value === "object" && + value !== null && + !Array.isArray(value) && + !(value instanceof RegExp) && + !(value instanceof Date) && + !(value instanceof Set) && + !(value instanceof Map) && + !(value instanceof Buffer) && + !ArrayBuffer.isView(value) + ); +} + +function fieldAtPath(schema: Schema, path: string[]): Field | undefined { + let fields = schema.fields; + let field: Field | undefined; + for (const [index, name] of path.entries()) { + field = fields.find((candidate) => candidate.name === name); + if (field === undefined || index === path.length - 1) { + return field; + } + if (!DataType.isStruct(field.type)) { + return undefined; + } + fields = field.type.children; + } + return field; +} + +function isDeferredValue(value: unknown): boolean { + return ( + value == null || (Array.isArray(value) && value.every(isDeferredValue)) + ); +} + +function deferredValueMatchesType(value: unknown, type: DataType): boolean { + if (value == null) { + return true; + } + if (!Array.isArray(value)) { + return false; + } + if (DataType.isList(type)) { + return value.every((item) => + deferredValueMatchesType(item, type.valueType), + ); + } + if (DataType.isFixedSizeList(type)) { + return ( + value.length === type.listSize && + value.every((item) => deferredValueMatchesType(item, type.valueType)) + ); + } + return false; +} + +function inferredTypesEqual(current: DataType, candidate: DataType): boolean { + if (DataType.isDictionary(current)) { + return ( + DataType.isDictionary(candidate) && + current.isOrdered === candidate.isOrdered && + inferredTypesEqual(current.indices, candidate.indices) && + inferredTypesEqual(current.dictionary, candidate.dictionary) + ); + } + if (DataType.isList(current)) { + return ( + DataType.isList(candidate) && + current.valueField.name === candidate.valueField.name && + current.valueField.nullable === candidate.valueField.nullable && + inferredTypesEqual(current.valueType, candidate.valueType) + ); + } + if (DataType.isFixedSizeList(current)) { + return ( + DataType.isFixedSizeList(candidate) && + current.listSize === candidate.listSize && + current.valueField.name === candidate.valueField.name && + current.valueField.nullable === candidate.valueField.nullable && + inferredTypesEqual(current.valueType, candidate.valueType) + ); + } + return arrowUtil.compareTypes(current, candidate); +} + +function describeEvidence( + evidence: DataType | DeferredTypeEvidence | undefined, +): string { + if (evidence === undefined) { + return "an unsupported value"; + } + return evidence instanceof DeferredTypeEvidence + ? evidence.describe() + : evidence.toString(); +} + +function branchConflictError( + conflict: FieldConflict, + row: number, + candidate: string, +): Error { + return schemaInferenceError( + conflict.path, + row, + conflict.value instanceof FieldTree + ? "Struct" + : describeEvidence(conflict.value), + candidate, + ); +} + +function schemaInferenceError( + path: string[], + row: number, + currentType: string, + newType: string, +): Error { + return new Error( + `Failed to infer schema for data. Previously inferred type ${currentType} ` + + `but found ${newType} for field ${path.join(".")} at row ${row}. ` + + "Consider providing an explicit schema.", + ); +} + +function typeInferenceError(path: string[], row: number): Error { + return new Error( + `Failed to infer data type for field ${path.join(".")} at row ${row}. ` + + "Consider providing an explicit schema.", + ); +} + +function nameSuggestsVectorColumn(name: string): boolean { + const normalized = name.toLowerCase(); + return normalized.includes("vector") || normalized.includes("embedding"); +} From 6ed3074d4cf98b08bec11269cd2c1fba5bf8f7d3 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Mon, 24 Aug 2026 17:16:42 -0700 Subject: [PATCH 109/206] feat: pin the base table version for data loader reads (#3982) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A permutation stores `_rowid`s, which are row addresses unless stable row ids are enabled. Nothing in the data loader pinned a table version, so a compaction between building a permutation and reading it can resolve those ids to different rows. The exposure differs by backend but exists on both: - Remote never pins. `prepare_query_bodies` stamps `"version": current_version()` on every request, but `current_version()` is `None` unless `checkout` was called, so every request means "latest". - Native pins implicitly by holding an `Arc` under `ConsistencyMode::Lazy`, but `StreamingDataset.__setstate__` reopens the table in each DataLoader worker, so each worker pins to whatever is latest at fork time. ## Changes `Table::at_version` returns an independent handle pinned to a version without mutating the receiver. `checkout` cannot serve this: on remote the version cell is an `Arc>>` shared across clones, so pinning through it would silently pin the caller's table too. `PermutationBuilder::build` pins for the whole build and records the version in the permutation table's schema metadata, alongside the existing split names. `PermutationReader` pins the base table to that version before any take. Because the reader pins on construction, the Python worker fork is covered without touching the pickle format — `Permutation.__setstate__` drops the reader and `_ensure_open` rebuilds it, which re-pins. ## Behaviour change A permutation is now bound to the version it was built against, so rows appended to the base table afterwards are not visible through an existing permutation. That is the intended semantics — the permutation only addresses rows that existed when it was built — but it is a change worth flagging. Permutations written before this carry no version key and read exactly as they did before. --- python/python/lancedb/permutation.py | 26 ++- python/python/lancedb/streaming.py | 4 + python/python/tests/test_permutation.py | 25 +++ .../src/dataloader/permutation/builder.rs | 186 ++++++++++++++++-- .../src/dataloader/permutation/reader.rs | 93 ++++++++- rust/lancedb/src/remote/table.rs | 37 ++++ rust/lancedb/src/table/query.rs | 3 + 7 files changed, 350 insertions(+), 24 deletions(-) diff --git a/python/python/lancedb/permutation.py b/python/python/lancedb/permutation.py index 5d7a685ef..8287ef2fe 100644 --- a/python/python/lancedb/permutation.py +++ b/python/python/lancedb/permutation.py @@ -391,6 +391,15 @@ def _table_to_pickle_state(table: Table) -> dict[str, Any]: } +def _drop_base_version(permutation_data: pa.Table) -> pa.Table: + """Strip the recorded base version so the reader leaves the base table unpinned.""" + metadata = dict(permutation_data.schema.metadata or {}) + if metadata.pop(b"base_version", None) is None: + return permutation_data + metadata.pop(b"base_branch", None) + return permutation_data.replace_schema_metadata(metadata) + + def _table_from_pickle_state(state: dict[str, Any]) -> Table: from . import connect @@ -679,11 +688,15 @@ class Permutation: from . import connect connection_factory = state["connection_factory"] + rebuilt_base = False if connection_factory is not None: base_table = connection_factory(state["base_table_name"]) elif "base_table_state" in state: - base_table = _table_from_pickle_state(state["base_table_state"]) + base_state = state["base_table_state"] + rebuilt_base = base_state["kind"] == "memory" + base_table = _table_from_pickle_state(base_state) elif "base_table_data" in state: + rebuilt_base = True # In-memory base table inlined into the pickle; rebuild the same # way we rebuild the in-memory permutation table. mem_db = connect("memory://") @@ -701,11 +714,14 @@ class Permutation: ) permutation_table: Optional[Table] = None - if state["permutation_data"] is not None: + permutation_data = state["permutation_data"] + if permutation_data is not None: + if rebuilt_base: + # The base table was materialized from Arrow, so it is a fresh + # single-version dataset and the recorded pin cannot resolve on it. + permutation_data = _drop_base_version(permutation_data) mem_db = connect("memory://") - permutation_table = mem_db.create_table( - "permutation", state["permutation_data"] - ) + permutation_table = mem_db.create_table("permutation", permutation_data) self.base_table = base_table self.permutation_table = permutation_table diff --git a/python/python/lancedb/streaming.py b/python/python/lancedb/streaming.py index 2c0e2d5c1..76b3702a1 100644 --- a/python/python/lancedb/streaming.py +++ b/python/python/lancedb/streaming.py @@ -41,6 +41,7 @@ from .permutation import ( Permutation, Transforms, permutation_builder, + _drop_base_version, _table_from_pickle_state, _table_to_pickle_state, ) @@ -1327,6 +1328,9 @@ class StreamingDataset(IterableDataset): self._table = self._connection_factory(table_name) else: self._table = _table_from_pickle_state(table_state) + if table_state["kind"] == "memory": + # Rebuilt from Arrow, so the recorded pin cannot resolve on it. + perm_data = _drop_base_version(perm_data) self._perm_table = _connect("memory://").create_table(perm_name, perm_data) def state_dict(self) -> dict: diff --git a/python/python/tests/test_permutation.py b/python/python/tests/test_permutation.py index 135742c84..142fc84f1 100644 --- a/python/python/tests/test_permutation.py +++ b/python/python/tests/test_permutation.py @@ -56,6 +56,31 @@ def test_execute_does_not_reenter_background_loop(tmp_path, monkeypatch): assert permutation_tbl._conn.read_consistency_interval is None +def test_pickled_permutation_reads_pinned_version(tmp_path): + """An unpickled copy must still read the pinned version, which also covers the + version surviving the ``to_arrow()`` round trip in ``__getstate__``.""" + import pickle + + db = connect(tmp_path) + tbl = db.create_table("base", pa.table({"idx": range(20)})) + permutation_tbl = permutation_builder(tbl).execute() + perm = Permutation.from_tables(tbl, permutation_tbl) + + payload = pickle.dumps(perm) + + # Compact so the stored row addresses no longer describe these rows at latest. + tbl.delete("true") + tbl.optimize() + assert tbl.count_rows() == 0 + + # Unpickle after the mutation: __setstate__ reopens at latest, so this only + # passes if the recorded version is applied on reopen. + restored = pickle.loads(payload) + assert len(restored) == 20 + rows = restored.__getitems__(list(range(20))) + assert sorted(row["idx"] for row in rows) == list(range(20)) + + def test_split_random_counts(mem_db): """Test random splitting with absolute counts.""" tbl = mem_db.create_table( diff --git a/rust/lancedb/src/dataloader/permutation/builder.rs b/rust/lancedb/src/dataloader/permutation/builder.rs index 641c191d5..ba0d0e180 100644 --- a/rust/lancedb/src/dataloader/permutation/builder.rs +++ b/rust/lancedb/src/dataloader/permutation/builder.rs @@ -27,6 +27,12 @@ pub const SRC_ROW_ID_COL: &str = "row_id"; pub const SPLIT_NAMES_CONFIG_KEY: &str = "split_names"; +/// Base table version the permutation was built against. +pub const BASE_VERSION_CONFIG_KEY: &str = "base_version"; + +/// Base table branch the permutation was built against. Absent means main. +pub const BASE_BRANCH_CONFIG_KEY: &str = "base_branch"; + pub const DEFAULT_MEMORY_LIMIT: usize = 100 * 1024 * 1024; /// Where to store the permutation table @@ -214,21 +220,11 @@ impl PermutationBuilder { Ok(Box::pin(SimpleRecordBatchStream { schema, stream })) } - fn add_split_names( + fn add_config_metadata( data: SendableRecordBatchStream, - split_names: &[String], + metadata: HashMap, ) -> Result { - let schema = data - .schema() - .as_ref() - .clone() - .with_metadata(HashMap::from([( - SPLIT_NAMES_CONFIG_KEY.to_string(), - serde_json::to_string(split_names).map_err(|e| Error::Other { - message: format!("Failed to serialize split names: {}", e), - source: Some(e.into()), - })?, - )])); + let schema = data.schema().as_ref().clone().with_metadata(metadata); let schema = Arc::new(schema); let schema_clone = schema.clone(); let stream = data.map_ok(move |batch| batch.with_schema(schema.clone()).unwrap()); @@ -269,6 +265,12 @@ impl PermutationBuilder { Err(err) => return Err(err), } + // The handle above is already pinned to one version. Record which one, so a + // reader -- in a DataLoader worker, against a table that has since moved -- + // resolves these row addresses against the same snapshot. + let base_version = self.base_table.version().await?; + let base_branch = self.base_table.current_branch(); + // First pass, apply filter and load row ids. `Shuffler` permutes positions, so // every rank must scan the rows in the same order to build the same permutation. let mut rows = self.base_table.query().select(Select::columns(&[ROW_ID])); @@ -330,11 +332,24 @@ impl PermutationBuilder { // Rename _rowid to row_id let renamed = rename_column(sorted, ROW_ID, SRC_ROW_ID_COL)?; - let streaming_data = if let Some(split_names) = &self.config.split_names { - Self::add_split_names(renamed, split_names)? - } else { - renamed - }; + let mut metadata = HashMap::from([( + BASE_VERSION_CONFIG_KEY.to_string(), + base_version.to_string(), + )]); + // Version numbers are per-branch, so the branch is part of the coordinate. + if let Some(branch) = &base_branch { + metadata.insert(BASE_BRANCH_CONFIG_KEY.to_string(), branch.clone()); + } + if let Some(split_names) = &self.config.split_names { + metadata.insert( + SPLIT_NAMES_CONFIG_KEY.to_string(), + serde_json::to_string(split_names).map_err(|e| Error::Other { + message: format!("Failed to serialize split names: {}", e), + source: Some(e.into()), + })?, + ); + } + let streaming_data = Self::add_config_metadata(renamed, metadata)?; let (name, database) = match &self.config.destination { PermutationDestination::Permanent(database, table_name) => { @@ -533,6 +548,141 @@ mod tests { assert_eq!(*planning_versions.lock().unwrap(), vec![7, 7, 6, 6]); } + #[tokio::test] + async fn test_permutation_records_base_version() { + let temp_dir = tempfile::tempdir().unwrap(); + + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + + let initial_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(100), BatchCount::from(2)); + let data_table = db + .create_table("base_tbl", initial_data) + .execute() + .await + .unwrap(); + + let build_version = data_table.version().await.unwrap(); + let permutation_table = PermutationBuilder::new(data_table.clone()) + .build() + .await + .unwrap(); + + let recorded = permutation_table + .schema() + .await + .unwrap() + .metadata + .get(BASE_VERSION_CONFIG_KEY) + .expect("permutation should record the base version") + .parse::() + .unwrap(); + assert_eq!(recorded, build_version); + + // Advancing the base table must not move the recorded version. + let more_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(50), BatchCount::from(1)); + data_table.add(more_data).execute().await.unwrap(); + assert!(data_table.version().await.unwrap() > recorded); + assert_eq!( + permutation_table + .schema() + .await + .unwrap() + .metadata + .get(BASE_VERSION_CONFIG_KEY) + .unwrap() + .parse::() + .unwrap(), + recorded, + ); + } + + /// Version numbers are per-branch, so a permutation built on a branch must record + /// it -- a worker reopens by name and lands on main at the same number. + #[tokio::test] + async fn test_permutation_records_base_branch() { + let temp_dir = tempfile::tempdir().unwrap(); + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + + let initial_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(10), BatchCount::from(1)); + let data_table = db + .create_table("base_tbl", initial_data) + .execute() + .await + .unwrap(); + + let branch = data_table + .create_branch("exp", lance::dataset::refs::Ref::from(("main", 1))) + .await + .unwrap(); + let permutation_table = PermutationBuilder::new(branch.clone()) + .build() + .await + .unwrap(); + + let metadata = permutation_table.schema().await.unwrap().metadata.clone(); + assert_eq!( + metadata.get(BASE_BRANCH_CONFIG_KEY).map(String::as_str), + Some("exp") + ); + + // Main records nothing, so an absent key keeps meaning main. + let main_permutation = PermutationBuilder::new(data_table.clone()) + .build() + .await + .unwrap(); + assert!( + !main_permutation + .schema() + .await + .unwrap() + .metadata + .contains_key(BASE_BRANCH_CONFIG_KEY) + ); + } + + #[tokio::test] + async fn test_build_does_not_pin_the_callers_table() { + let temp_dir = tempfile::tempdir().unwrap(); + + let db = connect(temp_dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + + let initial_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(100), BatchCount::from(1)); + let data_table = db + .create_table("base_tbl", initial_data) + .execute() + .await + .unwrap(); + + PermutationBuilder::new(data_table.clone()) + .build() + .await + .unwrap(); + + // The builder pins its own handle; the caller's must still track latest. + let more_data = lance_datagen::gen_batch() + .col("col_a", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(50), BatchCount::from(1)); + data_table.add(more_data).execute().await.unwrap(); + assert_eq!(data_table.count_rows(None).await.unwrap(), 150); + } + #[tokio::test] async fn test_permutation_builder() { let temp_dir = tempfile::tempdir().unwrap(); diff --git a/rust/lancedb/src/dataloader/permutation/reader.rs b/rust/lancedb/src/dataloader/permutation/reader.rs index 6da92e986..9757dc552 100644 --- a/rust/lancedb/src/dataloader/permutation/reader.rs +++ b/rust/lancedb/src/dataloader/permutation/reader.rs @@ -8,7 +8,9 @@ //! the rows from a source table that correspond to row IDs stored in a separate table. use crate::arrow::{SendableRecordBatchStream, SimpleRecordBatchStream}; -use crate::dataloader::permutation::builder::SRC_ROW_ID_COL; +use crate::dataloader::permutation::builder::{ + BASE_BRANCH_CONFIG_KEY, BASE_VERSION_CONFIG_KEY, SRC_ROW_ID_COL, +}; use crate::dataloader::permutation::split::SPLIT_ID_COLUMN; use crate::error::Error; use crate::query::{ @@ -23,6 +25,7 @@ use arrow_array::{RecordBatch, UInt64Array}; use arrow_schema::SchemaRef; use datafusion_expr::{Expr, col, lit}; use futures::{StreamExt, TryStreamExt}; +use lance::dataset::refs::MAIN_BRANCH; use lance::dataset::scanner::DatasetRecordBatchStream; use lance::io::RecordBatchStream; use lance_arrow::RecordBatchExt; @@ -69,6 +72,10 @@ impl PermutationReader { permutation_table: Option>, split: u64, ) -> Result { + let base_table = match &permutation_table { + Some(permutation_table) => Self::pin_base_table(base_table, permutation_table).await?, + None => base_table, + }; let mut slf = Self { base_table, permutation_table, @@ -89,6 +96,34 @@ impl PermutationReader { Ok(slf) } + /// Pins the base table to the version the permutation was built against. + /// Permutations written before that was recorded carry no key and stay unpinned. + async fn pin_base_table( + base_table: Arc, + permutation_table: &Arc, + ) -> Result> { + let schema = permutation_table.schema().await?; + let Some(raw) = schema.metadata.get(BASE_VERSION_CONFIG_KEY) else { + return Ok(base_table); + }; + let version = raw.parse::().map_err(|e| Error::InvalidInput { + message: format!( + "Permutation table has an unreadable {} of {:?}: {}", + BASE_VERSION_CONFIG_KEY, raw, e + ), + })?; + // The recorded branch, not the handle's: a worker reopens by name and lands + // on main, and version numbers are per-branch. + let branch = schema + .metadata + .get(BASE_BRANCH_CONFIG_KEY) + .map(String::as_str) + .unwrap_or(MAIN_BRANCH); + base_table + .checkout_branch_version(branch, Some(version)) + .await + } + pub async fn try_from_tables( base_table: Arc, permutation_table: Arc, @@ -511,9 +546,13 @@ mod tests { use lance_datagen::{BatchCount, RowCount}; use rand::seq::SliceRandom; + // Aliased: `test_utils::datagen` exports a trait of the same name. + use crate::arrow::LanceDbDatagenExt as _; use crate::{ Table, arrow::SendableRecordBatchStream, + connect, + dataloader::permutation::builder::PermutationBuilder, query::{ExecutableQuery, QueryBase}, test_utils::datagen::{LanceDbDatagenExt, virtual_table}, }; @@ -545,6 +584,58 @@ mod tests { .await } + /// Compaction moves row addresses, so the reader must read the pinned version. + #[tokio::test] + async fn test_reader_pins_base_version() { + 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("idx", lance_datagen::array::step::()) + .into_ldb_stream(RowCount::from(20), BatchCount::from(1)); + let base_table = db.create_table("base_tbl", data).execute().await.unwrap(); + + let permutation_table = PermutationBuilder::new(base_table.clone()) + .build() + .await + .unwrap(); + + base_table.delete("true").await.unwrap(); + base_table + .optimize(crate::table::OptimizeAction::All) + .await + .unwrap(); + assert_eq!(base_table.count_rows(None).await.unwrap(), 0); + + let reader = PermutationReader::try_from_tables( + base_table.base_table().clone(), + permutation_table.base_table().clone(), + 0, + ) + .await + .unwrap(); + + let values = collect_from_stream::( + reader + .read( + Select::Columns(vec!["idx".to_string()]), + QueryExecutionOptions::default(), + ) + .await + .unwrap(), + "idx", + ) + .await; + assert_eq!( + values.len(), + 20, + "reader should still see the pinned version" + ); + } + #[tokio::test] async fn test_permutation_reader() { let base_table = lance_datagen::gen_batch() diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 633d0ffce..10980d55a 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -4349,6 +4349,43 @@ mod tests { assert!(!table.base_table().scan_order_is_deterministic()); } + #[tokio::test] + async fn test_checkout_branch_pins_without_touching_the_original() { + let seen = Arc::new(std::sync::Mutex::new(Vec::new())); + let recorder = seen.clone(); + let table = Table::new_with_handler_version( + "my_table", + semver::Version::new(0, 5, 0), + move |request| match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(br#"{"version": 42, "schema": {"fields": []}}"#.to_vec()) + .unwrap(), + "/v1/table/my_table/count_rows/" => { + let body = request_body_json(&request); + recorder.lock().unwrap().push(body["version"].clone()); + http::Response::builder() + .status(200) + .body(b"0".to_vec()) + .unwrap() + } + path => panic!("unexpected request path: {path}"), + }, + ); + + let pinned = table.checkout_branch("main", Some(42)).await.unwrap(); + pinned.count_rows(None).await.unwrap(); + table.count_rows(None).await.unwrap(); + + let seen = seen.lock().unwrap(); + assert_eq!(seen[0], 42, "the pinned handle must send its version"); + assert!( + seen[1].is_null(), + "the original handle must still track latest, got {:?}", + seen[1] + ); + } + #[tokio::test] async fn test_fetch_blobs_sends_the_checked_out_version() { let ipc = one_row_blob_ipc_stream("image"); diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 9feb9d5ab..9b81786cd 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -70,6 +70,9 @@ async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> R .contains(&NamespaceClientPushdownOperation::QueryTable) && table.namespace_client.is_some() && table.dataset.current_branch().is_none() + // NsQueryTableRequest has no version field, so a pushed-down query would + // read latest and ignore the pin. + && table.dataset.time_travel_version().is_none() && !requires_local_namespace_execution(query)) { return Ok(false); From 0e65123bd8910548c1ad60b4038f0674c33ed940 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Mon, 24 Aug 2026 23:15:07 -0700 Subject: [PATCH 110/206] fix: package ordinary @udf bodies and emit only the V1 type grammar (#4044) Registering a real (embedding) Function failed on the client for three reasons: - `_package_source` treated `inspect.getclosurevars().unbound` as "unresolved globals"; CPython puts attribute names there, so any body with `np.linalg.norm(...)` or `body.split()` was rejected. Module-scope references now come from Python's own scope analysis (`symtable`) over the function source, recursively, and each is resolved the way the interpreter would: the function's globals first (a module global may shadow a builtin), then builtins. Free variables of nested scopes stay lexical; postponed annotations are not runtime loads. A genuinely missing global still fails. - `_canonical_arrow_type` emitted spellings the server's frozen grammar rejects (`fixed_size_list[n]`, `timestamp[us]`, `struct<...>`, zero-sized lists). It now emits exactly the grammar, with the server's `fixed_size_list` form, and the Rust declaration planner parses that form too. A shared golden (`tests/fixtures/first_class_functions/v1/arrow_types.json`) enumerates every grammar type, nested forms and rejected spellings; the Python emitter and Rust parser are tested against it, and the same file is under test in sophon. Packaging tests execute the shipped artifact in a fresh namespace. Contract changes (hence `breaking-change`): - `@udf` now rejects namespace acquisition structurally (`globals()`/`eval`/... by name, plus `import sys`/`builtins`/`importlib`/`inspect` inside the body), requires the function's captured `__builtins__` to be the standard mapping itself (identity, so neither lookups nor implicit hooks such as `__import__` can differ), rejects module globals that are namespace-bearing modules (`builtins`, `sys`, ...), and treats the function's own name as recursion only when the module binds it to the function or to the exact `UdfDefinition` the decorator produced; it resolves module globals through the function's real namespace (a module global may shadow a builtin) and ships importable classes/functions as imports. - List outputs must declare a non-nullable, metadata-free child named `item` (`pa.list_(pa.field("item", t, nullable=False))`); that is what the grammar means, and pyarrow's default nullable child was being silently collapsed into it. Contract, stated in the `udf` docstring: the artifact is a snapshot of the function source plus exactly the module names it references. Reaching the module namespace by another route is rejected where a static packager can see it and is otherwise unsupported; there is no dynamic-access detection beyond that. --- python/python/lancedb/functions.py | 248 ++++++++--- .../tests/test_first_class_function_slice2.py | 399 +++++++++++++++++- rust/lancedb/src/remote/table.rs | 47 +++ rust/lancedb/src/table/computed_columns.rs | 55 +++ .../first_class_functions/v1/arrow_types.json | 333 +++++++++++++++ ...remote_fixed_size_declaration_request.json | 79 ++++ 6 files changed, 1100 insertions(+), 61 deletions(-) create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json create mode 100644 rust/lancedb/tests/fixtures/first_class_functions/v1/remote_fixed_size_declaration_request.json diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index c4ff9a9b3..33a67b413 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -12,10 +12,13 @@ expression-backed refresh job. from __future__ import annotations import ast +import builtins import base64 import functools import hashlib +import importlib import inspect +import symtable import json import math import re @@ -489,59 +492,58 @@ _FUNCTION_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]*$") _SECRET_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") +_GRAMMAR_PRIMITIVES = ( + (pa.bool_(), "bool"), + (pa.int8(), "int8"), + (pa.int16(), "int16"), + (pa.int32(), "int32"), + (pa.int64(), "int64"), + (pa.uint8(), "uint8"), + (pa.uint16(), "uint16"), + (pa.uint32(), "uint32"), + (pa.uint64(), "uint64"), + (pa.float16(), "float16"), + (pa.float32(), "float32"), + (pa.float64(), "float64"), + (pa.string(), "utf8"), + (pa.binary(), "binary"), + (pa.date32(), "date32"), + (pa.date64(), "date64"), +) + + def _canonical_arrow_type(data_type: pa.DataType) -> str: - primitive_types = ( - (pa.bool_(), "bool"), - (pa.int8(), "int8"), - (pa.int16(), "int16"), - (pa.int32(), "int32"), - (pa.int64(), "int64"), - (pa.uint8(), "uint8"), - (pa.uint16(), "uint16"), - (pa.uint32(), "uint32"), - (pa.uint64(), "uint64"), - (pa.float16(), "float16"), - (pa.float32(), "float32"), - (pa.float64(), "float64"), - (pa.string(), "utf8"), - (pa.large_utf8(), "large_utf8"), - (pa.binary(), "binary"), - (pa.large_binary(), "large_binary"), - (pa.date32(), "date32"), - (pa.date64(), "date64"), - ) - for candidate, name in primitive_types: + """The server's V1 Function type grammar. Anything outside it is rejected + here rather than at registration.""" + for candidate, name in _GRAMMAR_PRIMITIVES: if data_type == candidate: return name - if pa.types.is_fixed_size_binary(data_type): - return f"fixed_size_binary[{data_type.byte_width}]" - if pa.types.is_list(data_type): - return f"list<{_canonical_arrow_type(data_type.value_type)}>" - if pa.types.is_large_list(data_type): - return f"large_list<{_canonical_arrow_type(data_type.value_type)}>" - if pa.types.is_fixed_size_list(data_type): + if pa.types.is_list(data_type) or pa.types.is_large_list(data_type): + prefix = "list" if pa.types.is_list(data_type) else "large_list" + return f"{prefix}<{_canonical_list_item(data_type)}>" + if pa.types.is_fixed_size_list(data_type) and data_type.list_size > 0: return ( - f"fixed_size_list<{_canonical_arrow_type(data_type.value_type)}>" - f"[{data_type.list_size}]" + f"fixed_size_list<{_canonical_list_item(data_type)}, {data_type.list_size}>" ) - if pa.types.is_struct(data_type): - fields = ",".join( - f"{field.name}:{_canonical_arrow_type(field.type)}" for field in data_type - ) - return f"struct<{fields}>" - if pa.types.is_timestamp(data_type): - timezone = f",tz={data_type.tz}" if data_type.tz is not None else "" - return f"timestamp[{data_type.unit}{timezone}]" - if pa.types.is_time32(data_type) or pa.types.is_time64(data_type): - return f"time[{data_type.unit}]" - if pa.types.is_duration(data_type): - return f"duration[{data_type.unit}]" - if pa.types.is_decimal(data_type): - bit_width = data_type.bit_width - return f"decimal{bit_width}({data_type.precision},{data_type.scale})" raise TypeError(f"unsupported Arrow type for Function signature: {data_type}") +def _canonical_list_item(data_type: pa.DataType) -> str: + """The grammar names only the item type; it always means a non-nullable + child called `item`, so any other child metadata cannot be represented.""" + child = data_type.value_field + if child.name != "item" or child.nullable or child.metadata: + raise TypeError( + "unsupported Arrow type for Function signature: list items must be a " + f"non-nullable field named 'item', got {child}" + ) + return _canonical_arrow_type(child.type) + + +def _list_of(item: pa.DataType) -> pa.DataType: + return pa.list_(pa.field("item", item, nullable=False)) + + def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: nullable = False origin = get_origin(annotation) @@ -589,7 +591,7 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]: value_type, value_nullable = _annotation_type(arguments[0]) if value_nullable: raise TypeError("nullable Function list elements are not supported") - return pa.list_(value_type), nullable + return _list_of(value_type), nullable raise TypeError(f"unsupported Function annotation: {annotation!r}") @@ -736,6 +738,104 @@ def _literal_source(value: Any) -> str: ) +_DYNAMIC_NAMESPACE_ACCESS = frozenset( + {"globals", "locals", "vars", "eval", "exec", "compile", "__import__"} +) +# 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. +_NAMESPACE_MODULES = frozenset( + {"sys", "builtins", "importlib", "inspect", "gc", "ctypes", "types"} +) + + +def _namespace_acquisition( + definition: ast.FunctionDef, references: set[str] +) -> list[str]: + found = set(references & _DYNAMIC_NAMESPACE_ACCESS) + 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) + + +def _module_references(module_source: str) -> set[str]: + """Names any scope in `module_source` binds or loads at module scope. + Python's own scope analysis on the exact text that ships: free variables + belong to an enclosing scope inside the function, and postponed + annotations are not runtime loads.""" + + def visit(table: symtable.SymbolTable, found: set[str]) -> None: + for symbol in table.get_symbols(): + if symbol.is_global() and ( + symbol.is_referenced() or symbol.is_declared_global() + ): + found.add(symbol.get_name()) + for child in table.get_children(): + visit(child, found) + + found: set[str] = set() + for table in symtable.symtable(module_source, "", "exec").get_children(): + visit(table, found) + return found + + +def _global_source(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.""" + 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}" + ) + try: + imported = importlib.import_module(value.__name__) + except ImportError: + imported = None + if imported is not value: + raise TypeError( + f"Function source references module {name!r} that does not import " + f"as {value.__name__!r}" + ) + return f"import {value.__name__} as {name}" + module_name = getattr(value, "__module__", None) + qualname = getattr(value, "__qualname__", None) + if ( + isinstance(module_name, str) + and isinstance(qualname, str) + and module_name != "__main__" + and "." not in qualname + and "<" not in qualname + ): + try: + imported = getattr(importlib.import_module(module_name), qualname) + except (ImportError, AttributeError): + imported = None + if imported is value: + return f"from {module_name} import {qualname} as {name}" + return f"{name} = {_literal_source(value)}" + + +def _is_recursive_reference(function: Callable[..., Any], name: str) -> bool: + """`name` inside the body means the function itself unless the module has + since bound it to something else.""" + if name != function.__name__: + return False + bound = function.__globals__.get(name, function) + if bound is function: + return True + # The decorator's own result is the one wrapper known to call `function` + # unchanged; any other binding may behave differently from a self-call. + return type(bound) is UdfDefinition and bound._function is function + + def _package_source(function: Callable[..., Any]) -> bytes: if not inspect.isfunction(function) or inspect.iscoroutinefunction(function): raise TypeError("@udf requires a synchronous Python function") @@ -760,23 +860,46 @@ def _package_source(function: Callable[..., Any]) -> bytes: closure = inspect.getclosurevars(function) if closure.nonlocals: raise ValueError("@udf cannot package functions that capture closure values") - if closure.unbound: - raise ValueError( - f"@udf source contains unresolved global names: {sorted(closure.unbound)!r}" - ) - globals_source = [] - for name, value in sorted(closure.globals.items()): - if isinstance(value, types.ModuleType): - globals_source.append(f"import {value.__name__} as {name}") - else: - globals_source.append(f"{name} = {_literal_source(value)}") - function_source = ast.unparse(definition) - parts = ["from __future__ import annotations"] + module_header = "from __future__ import annotations" + references = _module_references(f"{module_header}\n\n{function_source}\n") + dynamic = _namespace_acquisition(definition, references) + if dynamic: + raise ValueError(f"@udf cannot package dynamic namespace access: {dynamic!r}") + # Resolve every module-scope reference the way the interpreter would: the + # function's own globals first (a module global may shadow a builtin, and + # nested scopes are not visible to getclosurevars), then its builtins. + # The artifact runs under the standard builtins; only the exact mapping is + # provably equivalent (a subclass or copy can change lookups and hooks). + if function.__builtins__ is not vars(builtins): + raise ValueError("@udf cannot package a non-standard builtins environment") + globals_source = [] + unresolved = [] + for name in sorted(references): + if name == function.__name__: + if not _is_recursive_reference(function, 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" + ) + continue + if name in function.__globals__: + globals_source.append(_global_source(name, function.__globals__[name])) + elif hasattr(builtins, name): + pass + else: + unresolved.append(name) + if unresolved: + raise ValueError( + f"@udf source contains unresolved global names: {unresolved!r}" + ) + + parts = [module_header] if globals_source: parts.extend(["", *globals_source]) parts.extend(["", function_source, ""]) - return "\n".join(parts).encode("utf-8") + packaged = "\n".join(parts) + return packaged.encode("utf-8") class UdfDefinition: @@ -923,6 +1046,13 @@ def udf( python_version : str, optional Remote Python major/minor version. Defaults to the client version. + The packaged artifact is a snapshot: the function source plus exactly + the module-level names it references (modules as imports, importable + classes and functions as imports, literals inline). Code that reaches the + module namespace another way -- ``globals()``/``eval``, ``sys.modules``, + ``builtins`` -- is rejected where it can be seen and otherwise + unsupported; closures and a non-standard ``__builtins__`` are rejected. + Returns ------- UdfDefinition diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index a20347771..c67e17520 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -3,7 +3,12 @@ from __future__ import annotations +import base64 import contextlib +import functools +import importlib.util +import types +from datetime import date import http.server import json from pathlib import Path @@ -16,6 +21,9 @@ import pytest import lancedb from lancedb.functions import UdfDefinition, udf +THRESHOLD = 20 +_CACHE = None + FIXTURES = ( Path(__file__).parents[3] @@ -71,9 +79,396 @@ def test_scalar_udf_matches_shared_registration_golden_and_remains_callable(): _assert_no_secret_values(request) +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) + return namespace[definition.registration_request.artifact.entrypoint](*args) + + +def test_udf_packages_attribute_access_and_body_imports(): + @udf + def word_norm(body: str) -> float: + import numpy as np + + try: + words = body.split() + except AttributeError as error: + raise ValueError(str(error)) from error + return float(np.linalg.norm([len(w) for w in words])) + + assert _run_packaged(word_norm, "aa bb") == pytest.approx(8**0.5) + + +def test_udf_packages_module_globals_and_global_caches(): + @udf + def label(value: int) -> str: + return "big" if value >= THRESHOLD else "small" + + assert _run_packaged(label, 21) == "big" + + @udf + def cached(value: int) -> int: + global _CACHE + if _CACHE is None: + _CACHE = 40 + return _CACHE + value + + assert _run_packaged(cached, 2) == 42 + + +def test_udf_annotations_are_not_runtime_names(): + @udf + 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 score(value: int) -> int: + offset = 2 + + def add_offset() -> int: + return value + offset + + return add_offset() + sum(v for v in [0]) + + assert _run_packaged(score, 3) == 5 + + +def test_udf_resolves_module_globals_before_builtins(tmp_path): + module_path = tmp_path / "shadowing_udfs.py" + module_path.write_text( + "max = 7\n" + "len = lambda _: 99\n" + "\n" + "def uses_literal_shadow(value: int) -> int:\n" + " def nested() -> int:\n" + " return max\n" + " return nested() + value\n" + "\n" + "def uses_callable_shadow(value: int) -> int:\n" + " def nested() -> int:\n" + " return len([1])\n" + " return nested() + value\n" + ) + spec = importlib.util.spec_from_file_location("shadowing_udfs", module_path) + module = importlib.util.module_from_spec(spec) + 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 + # 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) + + +def test_canonical_arrow_type_is_exactly_the_grammar(): + from lancedb.functions import _GRAMMAR_PRIMITIVES, _canonical_arrow_type + + golden = json.loads( + ( + Path(__file__).parents[3] + / "rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json" + ).read_text() + ) + primitives = [ + case["arrow_type"] for case in golden["valid"] if "<" not in case["arrow_type"] + ] + assert [name for _, name in _GRAMMAR_PRIMITIVES] == primitives + for outside in [ + pa.timestamp("us"), + pa.decimal128(10, 2), + pa.large_string(), + pa.large_binary(), + pa.binary(4), + pa.duration("s"), + pa.struct([pa.field("a", pa.int32())]), + pa.list_(pa.float32(), 0), + pa.list_(pa.timestamp("us")), + ]: + with pytest.raises(TypeError, match="unsupported Arrow type"): + _canonical_arrow_type(outside) + + +def test_udf_nested_annotations_are_postponed_in_the_artifact(): + @udf + def score(value: int) -> int: + def identity(item: date) -> date: + return item + + identity(date(2026, 8, 25)) + return value + + assert _run_packaged(score, 3) == 3 + + +def test_udf_ships_globals_the_body_deletes(): + @udf + def clear(value: int) -> int: + global _CACHE + del _CACHE + return value + + assert _run_packaged(clear, 3) == 3 + + +def test_udf_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" + "np = types.ModuleType('numpy')\n" + "np.sqrt = lambda x: 0\n" + "\n" + "def score(value: int) -> int:\n" + " return int(np.sqrt(value))\n" + ) + spec = importlib.util.spec_from_file_location("fake_module_udfs", module_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) + + +def test_udf_rejects_a_module_level_namespace_alias(tmp_path): + module_path = tmp_path / "aliasing_udfs.py" + module_path.write_text( + "import builtins as b\n" + "THRESHOLD = 5\n" + "\n" + "def score(value: int) -> int:\n" + " return value + b.vars(b.__import__('aliasing_udfs'))['THRESHOLD']\n" + ) + 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"): + udf(module.score) + + +@pytest.mark.parametrize( + "access", + [ + "globals()['THRESHOLD']", + "eval('THRESHOLD')", + "(lambda g: g()['THRESHOLD'])(globals)", + "__import__('sys').modules[__name__].THRESHOLD", + "sys.modules[__name__].THRESHOLD", + ], +) +def test_udf_rejects_dynamic_namespace_access(access): + namespace: dict = {} + exec( + f"def score(value: int) -> int:\n return value + {access}\n", + {"THRESHOLD": 5}, + namespace, + ) + 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" + ) + + +def _package_from_text(source: str, module_globals: dict | None = None): + """Load `source` as a real module file so the packager can inspect it.""" + import tempfile + + directory = tempfile.mkdtemp() + path = Path(directory) / "generated_udf_module.py" + path.write_text(source) + spec = importlib.util.spec_from_file_location(f"generated_udf_{id(source)}", path) + module = importlib.util.module_from_spec(spec) + if module_globals: + module.__dict__.update(module_globals) + spec.loader.exec_module(module) + functions = [ + value + for value in vars(module).values() + if callable(value) and getattr(value, "__module__", None) == module.__name__ + ] + return udf(functions[0]) + + +def test_udf_rejects_a_non_standard_builtins_environment(): + def score(value: int) -> int: + return len([1]) + value + + score.__globals__ # noqa: B018 -- real function, real globals + import builtins + + patched = types.FunctionType( + score.__code__, + {"__builtins__": {**vars(builtins), "len": lambda _: 99}}, + "score", + ) + patched.__annotations__ = score.__annotations__ + assert patched(3) == 102 + with pytest.raises(ValueError, match="non-standard builtins environment"): + udf(patched) + + class ReportingDict(dict): # reports standard entries, resolves differently + def __missing__(self, key): + return vars(builtins)[key] + + disguised = types.FunctionType( + score.__code__, {"__builtins__": ReportingDict(len=lambda _: 99)}, "score" + ) + disguised.__annotations__ = score.__annotations__ + assert disguised(3) == 102 + with pytest.raises(ValueError, match="non-standard builtins environment"): + udf(disguised) + + hooked = types.FunctionType( + score.__code__, + {"__builtins__": {**vars(builtins), "__import__": lambda *a, **k: None}}, + "score", + ) + hooked.__annotations__ = score.__annotations__ + with pytest.raises(ValueError, match="non-standard builtins environment"): + udf(hooked) + + +def test_udf_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" + " return 1 if value <= 1 else value * fact(value - 1)\n" + "\n" + "def score(value: int) -> int:\n" + " return score + value\n" + ) + 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 + raw = module.score + module.score = 10 + with pytest.raises(ValueError, match="binds that name to another value"): + udf(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) + # The decorator's own result is; a subclass of it is not. + module.fact = udf(module.fact) + assert _run_packaged(module.fact, 4) == 24 + + class Twisted(UdfDefinition): + def __call__(self, *args, **kwargs): + return 41 + + raw_fact = module.fact._function + module.fact = Twisted( + raw_fact, + name=None, + input_schema=None, + output_schema=None, + pip=(), + env={}, + secrets=(), + python_version=None, + ) + with pytest.raises(ValueError, match="binds that name to another value"): + udf(raw_fact) + + +def test_canonical_arrow_type_rejects_unrepresentable_list_children(): + from lancedb.functions import _canonical_arrow_type + + for outside in [ + pa.list_(pa.float32()), # pyarrow default: nullable child + pa.list_(pa.field("custom", pa.float32(), nullable=False)), + pa.list_(pa.field("item", pa.float32(), nullable=False, metadata={"k": "v"})), + pa.list_(pa.field("item", pa.float32(), nullable=False), 0), + ]: + with pytest.raises(TypeError, match="unsupported Arrow type"): + _canonical_arrow_type(outside) + assert ( + _canonical_arrow_type( + pa.list_(pa.field("item", pa.float32(), nullable=False), 3) + ) + == "fixed_size_list" + ) + + +def _calls_missing(value: int) -> int: + return missing(value) # noqa: F821 + + +def _shadows_missing_in_a_comprehension(value: int) -> int: + return missing(value) + sum(missing for missing in ()) # noqa: F821 + + +def _shadows_missing_in_a_lambda(value: int) -> int: + return (lambda missing: missing)(value) + missing # noqa: F821 + + +@pytest.mark.parametrize( + "function", + [_calls_missing, _shadows_missing_in_a_comprehension, _shadows_missing_in_a_lambda], +) +def test_udf_rejects_a_truly_unresolved_global(function): + with pytest.raises(ValueError, match=r"unresolved global names: \['missing'\]"): + udf(function) + + +def _arrow_type_from_golden(spec: dict) -> pa.DataType: + kind = spec["type"] + if kind in ("list", "large_list", "fixed_size_list"): + item = _arrow_type_from_golden(spec["fields"][0]["type"]) + field = pa.field("item", item, nullable=False) + if kind == "list": + return pa.list_(field) + if kind == "large_list": + return pa.large_list(field) + return pa.list_(field, spec["length"]) + return { + "null": pa.null(), + "bool": pa.bool_(), + "utf8": pa.string(), + "binary": pa.binary(), + "float16": pa.float16(), + "float32": pa.float32(), + "float64": pa.float64(), + "date32": pa.date32(), + "date64": pa.date64(), + }.get(kind) or getattr(pa, kind)() + + +def test_arrow_type_grammar_matches_the_shared_golden(): + golden = json.loads( + ( + Path(__file__).parents[3] + / "rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json" + ).read_text() + ) + from lancedb.functions import _canonical_arrow_type + + emitted = { + case["arrow_type"]: _canonical_arrow_type(_arrow_type_from_golden(case["json"])) + for case in golden["valid"] + } + assert emitted == { + case["arrow_type"]: case["arrow_type"] for case in golden["valid"] + } + assert not set(emitted) & set(golden["invalid"]) + for case in golden["server_only"]: + with pytest.raises(TypeError, match="unsupported Arrow type"): + _canonical_arrow_type(_arrow_type_from_golden(case["json"])) + + def test_explicit_arrow_schema_is_deterministic(): input_schema = pa.schema([pa.field("value", pa.float32(), nullable=True)]) - output_schema = pa.field("embedding", pa.list_(pa.float32(), 3), nullable=False) + output_schema = pa.field( + "embedding", + pa.list_(pa.field("item", pa.float32(), nullable=False), 3), + nullable=False, + ) @udf(input_schema=input_schema, output_schema=output_schema) def explicit(value): @@ -82,7 +477,7 @@ def test_explicit_arrow_schema_is_deterministic(): signature = explicit.registration_request.signature assert signature.inputs[0].arrow_type == "float32" assert signature.inputs[0].nullable is True - assert signature.output.arrow_type == "fixed_size_list[3]" + assert signature.output.arrow_type == "fixed_size_list" assert signature.output.nullable is False diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 10980d55a..35ac56970 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -6802,6 +6802,53 @@ mod tests { assert_eq!(result.version, 8); } + #[tokio::test] + async fn test_add_fixed_size_list_function_column_declares_the_vector_type() { + 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(); + let expected: serde_json::Value = serde_json::from_str(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_fixed_size_declaration_request.json" + )) + .unwrap(); + assert_eq!(actual, expected); + 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":"embed","version":"fv_01K3EXACT"}, + "inputs":[{"parameter":"text","kind":"column","value":{"path":"description"}}], + "output":{"kind":"scalar","arrow_type":"fixed_size_list","nullable":false}, + "group_id":"fg_fixed" + }"#, + ) + .unwrap(); + + let result = table + .add_columns() + .function_as("embedding", application) + .execute() + .await + .unwrap(); + assert_eq!(result.version, 8); + } + #[tokio::test] async fn test_add_named_struct_function_expands_one_atomic_sibling_group() { let table = Table::new_with_handler("my_table", |request| match request.url().path() { diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index b1c0b8370..133f37a55 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -586,6 +586,25 @@ fn canonical_input_arrow_type(field: &JsonArrowField) -> Result { } } +/// `fixed_size_list` -> (`item`, `size`); the comma must sit outside +/// any nested `<...>`. +fn split_fixed_size_list(raw: &str) -> Option<(&str, i32)> { + let inner = raw.strip_prefix("fixed_size_list<")?.strip_suffix('>')?; + let mut depth = 0_u32; + let mut separator = None; + for (index, byte) in inner.bytes().enumerate() { + match byte { + b'<' => depth += 1, + b'>' => depth = depth.checked_sub(1)?, + b',' if depth == 0 => separator = Some(index), + _ => {} + } + } + let (item, size) = inner.split_at(separator?); + let size: i32 = size[1..].trim().parse().ok()?; + (size > 0).then_some((item.trim(), size)) +} + fn parse_output_arrow_type(raw: &str) -> Result { fn parse(raw: &str) -> Result { let raw = raw.trim(); @@ -618,6 +637,16 @@ fn parse_output_arrow_type(raw: &str) -> Result { )]); return Ok(data_type); } + if let Some((inner, size)) = split_fixed_size_list(raw) { + let mut data_type = JsonArrowDataType::new("fixed_size_list".to_string()); + data_type.fields = Some(vec![JsonArrowField::new( + "item".to_string(), + false, + parse(inner)?, + )]); + data_type.length = Some(i64::from(size)); + return Ok(data_type); + } let normalized = match raw { "boolean" => "bool", "string" => "utf8", @@ -1322,6 +1351,32 @@ pub(super) async fn add_foreign_kind(table: &crate::Table, name: &str, kind: &st #[cfg(test)] 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 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(); + let parsed = super::parse_output_arrow_type(raw) + .unwrap_or_else(|error| panic!("{raw}: {error}")); + assert_eq!( + serde_json::to_value(&parsed).unwrap(), + case["json"], + "{raw}" + ); + } + for raw in golden["invalid"].as_array().unwrap() { + let raw = raw.as_str().unwrap(); + assert!( + super::parse_output_arrow_type(raw).is_err(), + "{raw:?} should be rejected" + ); + } + } + use arrow_array::record_batch; use arrow_schema::DataType; use futures::TryStreamExt; diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json new file mode 100644 index 000000000..ff26e4c08 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json @@ -0,0 +1,333 @@ +{ + "valid": [ + { + "arrow_type": "bool", + "json": { + "type": "bool" + } + }, + { + "arrow_type": "int8", + "json": { + "type": "int8" + } + }, + { + "arrow_type": "int16", + "json": { + "type": "int16" + } + }, + { + "arrow_type": "int32", + "json": { + "type": "int32" + } + }, + { + "arrow_type": "int64", + "json": { + "type": "int64" + } + }, + { + "arrow_type": "uint8", + "json": { + "type": "uint8" + } + }, + { + "arrow_type": "uint16", + "json": { + "type": "uint16" + } + }, + { + "arrow_type": "uint32", + "json": { + "type": "uint32" + } + }, + { + "arrow_type": "uint64", + "json": { + "type": "uint64" + } + }, + { + "arrow_type": "float16", + "json": { + "type": "float16" + } + }, + { + "arrow_type": "float32", + "json": { + "type": "float32" + } + }, + { + "arrow_type": "float64", + "json": { + "type": "float64" + } + }, + { + "arrow_type": "utf8", + "json": { + "type": "utf8" + } + }, + { + "arrow_type": "binary", + "json": { + "type": "binary" + } + }, + { + "arrow_type": "date32", + "json": { + "type": "date32" + } + }, + { + "arrow_type": "date64", + "json": { + "type": "date64" + } + }, + { + "arrow_type": "list", + "json": { + "type": "list", + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "float32" + } + } + ] + } + }, + { + "arrow_type": "large_list", + "json": { + "type": "large_list", + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "float32" + } + } + ] + } + }, + { + "arrow_type": "list", + "json": { + "type": "list", + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "int64" + } + } + ] + } + }, + { + "arrow_type": "large_list", + "json": { + "type": "large_list", + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "int64" + } + } + ] + } + }, + { + "arrow_type": "list", + "json": { + "type": "list", + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "utf8" + } + } + ] + } + }, + { + "arrow_type": "large_list", + "json": { + "type": "large_list", + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "utf8" + } + } + ] + } + }, + { + "arrow_type": "fixed_size_list", + "json": { + "type": "fixed_size_list", + "length": 384, + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "float32" + } + } + ] + } + }, + { + "arrow_type": "fixed_size_list", + "json": { + "type": "fixed_size_list", + "length": 8, + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "float16" + } + } + ] + } + }, + { + "arrow_type": "fixed_size_list", + "json": { + "type": "fixed_size_list", + "length": 1, + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "uint8" + } + } + ] + } + }, + { + "arrow_type": "list>", + "json": { + "type": "list", + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "list", + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "float32" + } + } + ] + } + } + ] + } + }, + { + "arrow_type": "fixed_size_list, 2>", + "json": { + "type": "fixed_size_list", + "length": 2, + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "list", + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "int32" + } + } + ] + } + } + ] + } + }, + { + "arrow_type": "list>", + "json": { + "type": "list", + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "fixed_size_list", + "length": 3, + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "float32" + } + } + ] + } + } + ] + } + } + ], + "server_only": [ + { + "arrow_type": "null", + "json": { + "type": "null" + } + } + ], + "invalid": [ + "", + "list<>", + "list[3]", + "fixed_size_list", + "fixed_size_list", + "fixed_size_list", + "map", + "decimal128(10, 2)", + "timestamp[us]", + "struct" + ] +} \ No newline at end of file diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_fixed_size_declaration_request.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_fixed_size_declaration_request.json new file mode 100644 index 000000000..7d92f1454 --- /dev/null +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_fixed_size_declaration_request.json @@ -0,0 +1,79 @@ +{ + "new_columns": [ + { + "name": "embedding", + "all_null": true + } + ], + "function": { + "application": { + "function": { + "name": "embed", + "version": "fv_01K3EXACT" + }, + "inputs": [ + { + "parameter": "text", + "kind": "column", + "value": { + "path": "description" + } + } + ], + "output": { + "kind": "scalar", + "arrow_type": "fixed_size_list", + "nullable": false + }, + "group_id": "fg_fixed" + }, + "binding_metadata_version": 1, + "input_bindings": [ + { + "parameter": "text", + "field_path": "description", + "arrow_type": "utf8", + "nullable": true + } + ], + "input_schema": { + "fields": [ + { + "name": "text", + "nullable": true, + "type": { + "type": "utf8" + } + } + ] + }, + "output_schema": { + "fields": [ + { + "name": "embedding", + "nullable": true, + "type": { + "type": "fixed_size_list", + "length": 3, + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "float32" + } + } + ] + } + } + ] + }, + "outputs": [ + { + "result_field": "$value", + "output_name": "embedding", + "output_ordinal": 0 + } + ] + } +} \ No newline at end of file From 2fea7cd48d86ef149ab7eee93f7751efeb410233 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Tue, 25 Aug 2026 06:26:01 +0000 Subject: [PATCH 111/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.7=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package-lock.json | 4 ++-- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index bcf714002..86a5064f7 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.7" +current_version = "0.38.0-beta.8" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index a60a5ddf1..8d0058569 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.7" +version = "0.38.0-beta.8" dependencies = [ "ahash", "anyhow", @@ -5490,7 +5490,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.7" +version = "0.38.0-beta.8" dependencies = [ "arrow-array", "arrow-buffer", @@ -5515,7 +5515,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.7" +version = "0.38.0-beta.8" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 59ee8a7d6..28de11c30 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.38.0-beta.7 + 0.38.0-beta.8 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index b24ad61ab..6f4b0744b 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.7 + 0.38.0-beta.8 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 0ee59bcb7..ac6196a45 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.7 + 0.38.0-beta.8 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 8732d1965..e85da66ec 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.7" +version = "0.38.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 56480c0cb..f920c9e91 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.38.0-beta.7", + "version": "0.38.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 a1102ee29..ad6926039 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.38.0-beta.7", + "version": "0.38.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 695862baf..ccd39f18e 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.38.0-beta.7", + "version": "0.38.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 9099ee4de..50446b597 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.38.0-beta.7", + "version": "0.38.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 f04c2a884..d4da82dc7 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.38.0-beta.7", + "version": "0.38.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 f9b35af32..dddc3a470 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.38.0-beta.7", + "version": "0.38.0-beta.8", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index cc5340105..23ac122f7 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.38.0-beta.7", + "version": "0.38.0-beta.8", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index 6604da6cd..21deb8dd8 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.7", + "version": "0.38.0-beta.8", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.7", + "version": "0.38.0-beta.8", "cpu": [ "x64", "arm64" diff --git a/nodejs/package.json b/nodejs/package.json index 66777d60c..96f4bafd5 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.7", + "version": "0.38.0-beta.8", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index d2ccf3064..bffac2ef1 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.7" +version = "0.38.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 071c876d9..7290694f1 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.7" +version = "0.38.0-beta.8" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From c988e4848dade1ebca7ff73a669190761c3e34ac Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 25 Aug 2026 18:30:09 +0800 Subject: [PATCH 112/206] refactor: simplify Function binding identity (#4046) Function applications and bindings currently encode `group_id` and binding `revision` even though `binding_id` already owns the complete immutable binding lifecycle and `outputs` already defines the atomic multi-output set. Make `binding_id` the sole binding identity, remove the redundant fields from the Rust and Python client contracts, and describe multi-output declarations directly. This intentionally replaces the removed wire fields without a compatibility path. --- python/python/lancedb/functions.py | 11 ++--- python/python/lancedb/table.py | 6 +-- .../tests/test_first_class_function_slice1.py | 16 +++---- rust/lancedb/src/function.rs | 21 ++------- rust/lancedb/src/query.rs | 9 ++-- rust/lancedb/src/remote/table.rs | 11 ++--- rust/lancedb/src/table.rs | 2 +- rust/lancedb/src/table/add_columns.rs | 2 +- rust/lancedb/src/table/computed_columns.rs | 45 +++++++------------ .../tests/first_class_function_slice1.rs | 1 - ...remote_fixed_size_declaration_request.json | 5 +-- ...remote_function_application.canonical.json | 2 +- .../v1/remote_function_application.json | 1 - .../v1/remote_function_application_float.json | 3 +- .../v1/remote_function_binding.canonical.json | 2 +- .../v1/remote_function_binding.json | 4 +- ...ote_multi_output_declaration_request.json} | 1 - .../v1/remote_refresh_job.json | 2 +- .../v1/remote_scalar_declaration_request.json | 3 +- 19 files changed, 49 insertions(+), 98 deletions(-) rename rust/lancedb/tests/fixtures/first_class_functions/v1/{remote_grouped_declaration_request.json => remote_multi_output_declaration_request.json} (97%) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 33a67b413..dd8cecfa9 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -25,7 +25,6 @@ import re import sys import textwrap import types -import uuid from collections.abc import Mapping from datetime import date, datetime from typing import ( @@ -276,7 +275,7 @@ class FunctionVersion(_RemoteValue): Every input must be a direct [lancedb.col][lancedb.expr.col] reference. The returned application is immutable and retains a - named-struct output as one sibling group, so every row's sibling values + named-struct output as one binding, so every row's sibling values come from one logical Function evaluation. Map result fields to table columns with [FunctionApplication.rename][lancedb.functions.FunctionApplication.rename], @@ -326,7 +325,6 @@ class FunctionVersion(_RemoteValue): function=FunctionVersionRef(name=self.name, version=self.version), inputs=tuple(bindings), output=self.signature.output, - group_id=f"fg_{uuid.uuid4().hex}", ) @@ -370,7 +368,7 @@ class ApplicationInput(_OpenRemoteValue): class FunctionApplication(_OpenRemoteValue): """Immutable pre-declaration application of an exact Function version. - A named-struct output remains one grouped application through table + A named-struct output remains one application through table declaration and execution. [FunctionApplication.rename][lancedb.functions.FunctionApplication.rename] records the result-field to table-column mapping without splitting sibling @@ -380,7 +378,6 @@ class FunctionApplication(_OpenRemoteValue): function: FunctionVersionRef inputs: tuple[ApplicationInput, ...] output: FunctionOutput - group_id: str columns: Mapping[str, str] = Field(default_factory=dict) def _known_dict(self) -> dict[str, Any]: @@ -452,12 +449,10 @@ class OutputMapping(_RemoteValue): class FunctionBinding(_RemoteValue): - """Immutable grouped binding persisted by the Enterprise table service.""" + """Immutable Function binding persisted by the Enterprise table service.""" binding_id: str - revision: _UInt64 function: FunctionVersionRef - group_id: str inputs: tuple[InputBinding, ...] outputs: tuple[OutputMapping, ...] input_schema: Optional[Mapping[str, Any]] = None diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 75b7b1db8..fe25d5353 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1972,7 +1972,7 @@ class Table(ABC): A mapping with one ``FunctionApplication`` value keeps its scalar or named-struct result in the named table column. A bare named-struct application expands its ordered result fields as one - atomic sibling group; aliases come from ``rename(columns=...)``. + atomic binding; aliases come from ``rename(columns=...)``. Function columns are supported only on LanceDB Cloud and Enterprise. computed: Dict[str, str], optional @@ -6038,7 +6038,7 @@ class AsyncTable: A mapping with one ``FunctionApplication`` value keeps its scalar or named-struct result in the named table column. A bare named-struct application expands its ordered result fields as one - atomic sibling group; aliases come from ``rename(columns=...)``. + atomic binding; aliases come from ``rename(columns=...)``. Function columns are supported only on LanceDB Cloud and Enterprise. computed: Dict[str, str], optional @@ -6075,7 +6075,7 @@ class AsyncTable: isinstance(value, FunctionApplication) for value in transforms.values() ): raise ValueError( - "one add_columns call declares exactly one Function sibling group" + "one add_columns call declares exactly one Function binding" ) function_output_name, function_application = next(iter(transforms.items())) diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index 1bb8feaf4..ca0b30ede 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -121,7 +121,7 @@ def test_function_version_identity_is_immutable_and_exact(): assert FunctionVersion(**changed) != version -def test_function_version_binds_named_columns_as_one_immutable_group(): +def test_function_version_binds_named_columns_as_one_immutable_application(): version = FunctionVersion.from_json( json.dumps(job_result("remote_function_job.json")) ) @@ -131,13 +131,10 @@ def test_function_version_binds_named_columns_as_one_immutable_group(): assert application.function.name == version.name assert application.function.version == version.version assert application.output is version.signature.output - assert application.group_id.startswith("fg_") assert [ (value.parameter, value.kind, value.value["path"]) for value in application.inputs ] == [("text", "column", "documents.body")] - with pytest.raises((TypeError, ValueError)): - application.group_id = "fg_changed" def test_function_version_binding_validates_names_and_direct_columns(): @@ -156,7 +153,7 @@ def test_function_version_binding_validates_names_and_direct_columns(): def test_function_version_keeps_named_struct_outputs_in_one_application(): value = job_result("remote_function_job.json") value["name"] = "text_features" - value["version"] = "fv_grouped" + value["version"] = "fv_multi_output" value["signature"] = { "inputs": [ {"name": "title", "arrow_type": "utf8", "nullable": True}, @@ -221,7 +218,6 @@ def test_function_application_uses_rename_columns_only(): assert application.columns["normalized_text"] == "search_text" assert renamed.columns["normalized_text"] == "body_normalized" assert renamed.function == application.function - assert renamed.group_id == application.group_id assert not hasattr(application, "rename_outputs") with pytest.raises(TypeError, match="immutable"): renamed.columns["normalized_text"] = "changed" @@ -242,7 +238,6 @@ def test_function_application_uses_rename_columns_only(): def test_binding_and_refresh_result_keep_stable_remote_fields(): binding = FunctionBinding.from_json(fixture("remote_function_binding.json")) - assert binding.revision == 3 assert binding.function.version == "fv_01K3TEXT" assert [output.output_ordinal for output in binding.outputs] == [0, 1] assert binding.input_schema is not None @@ -322,7 +317,7 @@ def known_application() -> FunctionApplication: @pytest.mark.asyncio -async def test_add_columns_routes_struct_as_one_and_grouped_expansion_atomically(): +async def test_add_columns_routes_struct_as_one_and_multi_output_binding_atomically(): inner = _FunctionDeclarationInner() table = AsyncTable(inner) application = known_application() @@ -343,12 +338,12 @@ async def test_add_columns_routes_struct_as_one_and_grouped_expansion_atomically @pytest.mark.asyncio -async def test_add_columns_rejects_mixed_groups_and_unknown_newer_application(): +async def test_add_columns_rejects_multiple_bindings_and_unknown_newer_application(): inner = _FunctionDeclarationInner() table = AsyncTable(inner) application = known_application() - with pytest.raises(ValueError, match="exactly one Function sibling group"): + with pytest.raises(ValueError, match="exactly one Function binding"): await table.add_columns({"a": application, "b": application}) future = json.loads(fixture("remote_function_application.json")) @@ -376,7 +371,6 @@ def test_rename_requires_named_struct_and_keeps_partial_mapping_immutable(): "arrow_type": "list", "nullable": False, }, - "group_id": "fg_scalar", } ) ) diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index f02158871..433a7e04c 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -446,7 +446,6 @@ pub struct FunctionApplication { function: FunctionVersionRef, inputs: Vec, output: FunctionOutput, - group_id: String, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] columns: BTreeMap, #[serde(default, flatten, skip_serializing)] @@ -468,10 +467,6 @@ impl FunctionApplication { &self.output } - pub fn group_id(&self) -> &str { - &self.group_id - } - pub fn columns(&self) -> &BTreeMap { &self.columns } @@ -513,7 +508,7 @@ pub struct InputBinding { pub nullable: bool, } -/// Ordered result-field to table-field mapping for a grouped binding. +/// Ordered result-field to table-field mapping for a Function binding. /// /// Assignment state is not part of the Slice 1 client contract. During the /// NULL transition there is no public Lance cell-flag identifier to persist. @@ -527,20 +522,18 @@ pub struct OutputMapping { pub nullable: bool, } -/// Immutable grouped binding persisted by the Enterprise table service. +/// Immutable Function binding persisted by the Enterprise table service. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionBinding { binding_id: String, - revision: u64, function: FunctionVersionRef, - group_id: String, inputs: Vec, outputs: Vec, /// Exact Arrow schema presented to the Function, encoded with the Lance /// Namespace Arrow JSON representation. #[serde(default, skip_serializing_if = "Option::is_none")] input_schema: Option, - /// Exact physical Arrow schema of the grouped table outputs. + /// Exact physical Arrow schema of the binding's table outputs. #[serde(default, skip_serializing_if = "Option::is_none")] output_schema: Option, } @@ -550,18 +543,10 @@ impl FunctionBinding { &self.binding_id } - pub fn revision(&self) -> u64 { - self.revision - } - pub fn function(&self) -> &FunctionVersionRef { &self.function } - pub fn group_id(&self) -> &str { - &self.group_id - } - pub fn inputs(&self) -> &[InputBinding] { &self.inputs } diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index b2c5fefbe..654777adb 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -1774,11 +1774,14 @@ mod tests { .postfilter(); let result = query.execute().await; let mut stream = result.expect("should have result"); - // should only have one batch + let mut num_rows = 0; while let Some(batch) = stream.next().await { - // post filter should have removed some rows - assert!(batch.expect("should be Ok").num_rows() < 10); + let batch = batch.expect("should be Ok"); + let ids: &Int32Array = batch["id"].as_primitive(); + assert!(ids.iter().all(|id| id.unwrap() % 2 == 0)); + num_rows += batch.num_rows(); } + assert!(num_rows <= 10); let query = table .query() diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 35ac56970..742ab547d 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -6787,8 +6787,7 @@ mod tests { r#"{ "function":{"name":"embed","version":"fv_01K3EXACT"}, "inputs":[{"parameter":"text","kind":"column","value":{"path":"description"}}], - "output":{"kind":"scalar","arrow_type":"list","nullable":false}, - "group_id":"fg_scalar" + "output":{"kind":"scalar","arrow_type":"list","nullable":false} }"#, ) .unwrap(); @@ -6834,8 +6833,7 @@ mod tests { r#"{ "function":{"name":"embed","version":"fv_01K3EXACT"}, "inputs":[{"parameter":"text","kind":"column","value":{"path":"description"}}], - "output":{"kind":"scalar","arrow_type":"fixed_size_list","nullable":false}, - "group_id":"fg_fixed" + "output":{"kind":"scalar","arrow_type":"fixed_size_list","nullable":false} }"#, ) .unwrap(); @@ -6850,7 +6848,7 @@ mod tests { } #[tokio::test] - async fn test_add_named_struct_function_expands_one_atomic_sibling_group() { + async fn test_add_named_struct_function_expands_one_atomic_binding() { let table = Table::new_with_handler("my_table", |request| match request.url().path() { "/v1/table/my_table/describe/" => http::Response::builder() .status(200) @@ -6865,7 +6863,7 @@ mod tests { let actual: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); let expected: serde_json::Value = serde_json::from_str(include_str!( - "../../tests/fixtures/first_class_functions/v1/remote_grouped_declaration_request.json" + "../../tests/fixtures/first_class_functions/v1/remote_multi_output_declaration_request.json" )) .unwrap(); assert_eq!(actual, expected); @@ -6887,7 +6885,6 @@ mod tests { {"name":"normalized_text","arrow_type":"utf8","nullable":false}, {"name":"token_count","arrow_type":"int64","nullable":false} ]}, - "group_id":"fg_01K3TEXT", "columns":{"normalized_text":"search_text"} }"#, ) diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 356c87bbe..ecd95f161 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -751,7 +751,7 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "computed columns are not supported on this table type".into(), }) } - /// Declare one immutable registered-Function output group. + /// Declare one immutable registered-Function binding. async fn add_function_columns( &self, _application: &crate::function::FunctionApplication, diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index 3b91c30e4..1ac0c6b4f 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -88,7 +88,7 @@ impl AddColumnsBuilder { } /// Declare every field of a named-struct Function result as one atomic - /// sibling group. Result-field aliases come from + /// binding. Result-field aliases come from /// [`FunctionApplication::columns`](crate::function::FunctionApplication::columns). /// /// ``` diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 133f37a55..2b95cb34c 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -13,7 +13,7 @@ //! self-describing -- both are derived from the expression, so a caller writes //! neither -- while a kind resolved through a registry cannot be typed without //! consulting it. Registered Functions use an exact remote version plus a -//! schema-level grouped binding; unknown newer kinds remain readable and fail +//! schema-level Function binding; unknown newer kinds remain readable and fail //! closed before mutation. //! //! [`computed_columns`] and [`computed_column_from_field`] read declarations @@ -46,16 +46,16 @@ pub const EXPRESSION_META_KEY: &str = "computed_column.expression"; /// Field metadata key holding the column's inputs, as a JSON array of names. pub const INPUTS_META_KEY: &str = "computed_column.inputs"; -/// Field metadata key holding the grouped Function binding identity. +/// Field metadata key holding the Function binding identity. pub const FUNCTION_BINDING_ID_META_KEY: &str = "computed_column.function.binding_id"; /// Field metadata key holding this sibling's ordered Function output ordinal. pub const FUNCTION_OUTPUT_ORDINAL_META_KEY: &str = "computed_column.function.output_ordinal"; -/// Schema metadata key holding all immutable grouped Function bindings. +/// Schema metadata key holding all immutable Function bindings. pub const FUNCTION_BINDINGS_META_KEY: &str = "lancedb::function_bindings"; -/// Version of the schema-level grouped Function binding envelope. +/// Version of the schema-level Function binding envelope. pub const FUNCTION_BINDINGS_VERSION: u32 = 1; /// Value of [`KIND_META_KEY`] for a column defined by a SQL expression. @@ -81,7 +81,7 @@ pub enum ComputedColumnKind { /// The expression. expression: String, }, - /// One physical output in an immutable grouped registered-Function + /// One physical output in an immutable registered-Function /// binding. The full binding lives in schema metadata. Function { /// Shared immutable binding identity. @@ -159,7 +159,7 @@ struct FunctionBindingEnvelope { bindings: Vec, } -/// Encode immutable grouped bindings for schema-level persistence. +/// Encode immutable Function bindings for schema-level persistence. pub fn function_bindings_metadata(bindings: &[FunctionBinding]) -> Result { let bindings = bindings .iter() @@ -177,7 +177,7 @@ pub fn function_bindings_metadata(bindings: &[FunctionBinding]) -> Result Result> { let Some(envelope) = function_binding_envelope(schema)? else { @@ -238,21 +238,15 @@ pub(crate) fn ensure_supported_function_metadata(schema: &ArrowSchema) -> Result message: format!("duplicate Function binding '{}'", binding.binding_id()), }); } - if binding.revision() == 0 || binding.outputs().is_empty() { + if binding.outputs().is_empty() { return Err(Error::InvalidInput { - message: format!( - "Function binding '{}' has no immutable revision or outputs", - binding.binding_id() - ), + message: format!("Function binding '{}' has no outputs", binding.binding_id()), }); } - if binding.function().name.is_empty() - || binding.function().version.is_empty() - || binding.group_id().is_empty() - { + if binding.function().name.is_empty() || binding.function().version.is_empty() { return Err(Error::InvalidInput { message: format!( - "Function binding '{}' has no exact version or group identity", + "Function binding '{}' has no exact version", binding.binding_id() ), }); @@ -493,9 +487,7 @@ fn ensure_known_binding_shape(value: &Value) -> Result<()> { value, &[ "binding_id", - "revision", "function", - "group_id", "inputs", "outputs", "input_schema", @@ -786,12 +778,9 @@ pub(crate) fn plan_function_application( message: "Function application contains fields from a newer contract".into(), }); } - if application.function().name.is_empty() - || application.function().version.is_empty() - || application.group_id().is_empty() - { + if application.function().name.is_empty() || application.function().version.is_empty() { return Err(invalid_function( - "Function application requires an exact version and group identity", + "Function application requires an exact version", )); } @@ -2261,7 +2250,6 @@ mod tests { {{"name":"normalized_text","arrow_type":"utf8","nullable":false}}, {{"name":"token_count","arrow_type":"int64","nullable":false}} ]}}, - "group_id":"fg_exact", "columns":{columns} }}"# )) @@ -2442,8 +2430,7 @@ mod tests { r#"{ "function":{"name":"f","version":"fv"}, "inputs":[{"parameter":"title","kind":"future_source","value":{"path":"title"}}], - "output":{"kind":"scalar","arrow_type":"int64","nullable":false}, - "group_id":"fg" + "output":{"kind":"scalar","arrow_type":"int64","nullable":false} }"#, ) .unwrap(); @@ -2456,7 +2443,6 @@ mod tests { "function":{"name":"f","version":"fv"}, "inputs":[], "output":{"kind":"scalar","arrow_type":"int64","nullable":false}, - "group_id":"fg", "future_declaration":{"mode":"managed"} }"#, ) @@ -2470,8 +2456,7 @@ mod tests { r#"{ "function":{"name":"f","version":"fv"}, "inputs":[], - "output":{"kind":"scalar","arrow_type":"int64","nullable":false,"assignment":"cell_flag"}, - "group_id":"fg" + "output":{"kind":"scalar","arrow_type":"int64","nullable":false,"assignment":"cell_flag"} }"#, ) .unwrap(); diff --git a/rust/lancedb/tests/first_class_function_slice1.rs b/rust/lancedb/tests/first_class_function_slice1.rs index dc565d309..aec264650 100644 --- a/rust/lancedb/tests/first_class_function_slice1.rs +++ b/rust/lancedb/tests/first_class_function_slice1.rs @@ -84,7 +84,6 @@ fn application_and_binding_match_shared_remote_goldens() { let binding = FunctionBinding::from_json(&fixture("remote_function_binding.json")) .expect("binding fixture"); - assert_eq!(binding.revision(), 3); assert_eq!(binding.function().version, "fv_01K3TEXT"); assert_eq!(binding.outputs()[0].output_ordinal, 0); assert_eq!(binding.outputs()[1].output_ordinal, 1); diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_fixed_size_declaration_request.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_fixed_size_declaration_request.json index 7d92f1454..fd3944412 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_fixed_size_declaration_request.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_fixed_size_declaration_request.json @@ -24,8 +24,7 @@ "kind": "scalar", "arrow_type": "fixed_size_list", "nullable": false - }, - "group_id": "fg_fixed" + } }, "binding_metadata_version": 1, "input_bindings": [ @@ -76,4 +75,4 @@ } ] } -} \ No newline at end of file +} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.canonical.json index 05da9fe39..b91dd1061 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.canonical.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.canonical.json @@ -1 +1 @@ -{"columns":{"normalized_text":"search_text","token_count":"search_token_count"},"function":{"name":"text_features","version":"fv_01K3TEXT"},"group_id":"fg_01K3TEXT","inputs":[{"kind":"column","parameter":"title","value":{"path":"title"}},{"kind":"column","parameter":"body","value":{"path":"body"}}],"output":{"fields":[{"arrow_type":"utf8","name":"normalized_text","nullable":false},{"arrow_type":"int64","name":"token_count","nullable":false}],"kind":"named_struct"}} +{"columns":{"normalized_text":"search_text","token_count":"search_token_count"},"function":{"name":"text_features","version":"fv_01K3TEXT"},"inputs":[{"kind":"column","parameter":"title","value":{"path":"title"}},{"kind":"column","parameter":"body","value":{"path":"body"}}],"output":{"fields":[{"arrow_type":"utf8","name":"normalized_text","nullable":false},{"arrow_type":"int64","name":"token_count","nullable":false}],"kind":"named_struct"}} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.json index 44aeff460..177821aaa 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application.json @@ -11,7 +11,6 @@ {"name": "token_count", "arrow_type": "int64", "nullable": false} ] }, - "group_id": "fg_01K3TEXT", "columns": { "normalized_text": "search_text", "token_count": "search_token_count" diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application_float.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application_float.json index 47724eee0..c23c8f3ca 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application_float.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_application_float.json @@ -3,6 +3,5 @@ "inputs": [ {"parameter": "threshold", "kind": "literal", "value": 1e-7} ], - "output": {"kind": "scalar", "arrow_type": "bool", "nullable": false}, - "group_id": "fg_01K3FLOAT" + "output": {"kind": "scalar", "arrow_type": "bool", "nullable": false} } diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.canonical.json index 7bf93b8a8..143190f78 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.canonical.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.canonical.json @@ -1 +1 @@ -{"binding_id":"fb_01K3TEXT","function":{"name":"text_features","version":"fv_01K3TEXT"},"group_id":"fg_01K3TEXT","input_schema":{"fields":[{"name":"title","nullable":true,"type":{"type":"utf8"}},{"name":"body","nullable":true,"type":{"type":"utf8"}}]},"inputs":[{"arrow_type":"utf8","field_id":11,"field_path":"title","nullable":true,"parameter":"title"},{"arrow_type":"utf8","field_id":12,"field_path":"body","nullable":true,"parameter":"body"}],"output_schema":{"fields":[{"name":"search_text","nullable":true,"type":{"type":"utf8"}},{"name":"search_token_count","nullable":true,"type":{"type":"int64"}}]},"outputs":[{"arrow_type":"utf8","nullable":false,"output_field_id":21,"output_name":"search_text","output_ordinal":0,"result_field":"normalized_text"},{"arrow_type":"int64","nullable":false,"output_field_id":22,"output_name":"search_token_count","output_ordinal":1,"result_field":"token_count"}],"revision":3} +{"binding_id":"fb_01K3TEXT","function":{"name":"text_features","version":"fv_01K3TEXT"},"input_schema":{"fields":[{"name":"title","nullable":true,"type":{"type":"utf8"}},{"name":"body","nullable":true,"type":{"type":"utf8"}}]},"inputs":[{"arrow_type":"utf8","field_id":11,"field_path":"title","nullable":true,"parameter":"title"},{"arrow_type":"utf8","field_id":12,"field_path":"body","nullable":true,"parameter":"body"}],"output_schema":{"fields":[{"name":"search_text","nullable":true,"type":{"type":"utf8"}},{"name":"search_token_count","nullable":true,"type":{"type":"int64"}}]},"outputs":[{"arrow_type":"utf8","nullable":false,"output_field_id":21,"output_name":"search_text","output_ordinal":0,"result_field":"normalized_text"},{"arrow_type":"int64","nullable":false,"output_field_id":22,"output_name":"search_token_count","output_ordinal":1,"result_field":"token_count"}]} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.json index 1a2053e42..dec3fa3f8 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_binding.json @@ -1,8 +1,6 @@ { "binding_id": "fb_01K3TEXT", - "revision": 3, "function": {"name": "text_features", "version": "fv_01K3TEXT"}, - "group_id": "fg_01K3TEXT", "inputs": [ {"parameter": "title", "field_id": 11, "field_path": "title", "arrow_type": "utf8", "nullable": true}, {"parameter": "body", "field_id": 12, "field_path": "body", "arrow_type": "utf8", "nullable": true} @@ -23,5 +21,5 @@ {"name": "search_token_count", "nullable": true, "type": {"type": "int64"}} ] }, - "future_binding": {"metadata_revision": 1} + "future_binding": {"mode": "managed"} } diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_grouped_declaration_request.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_multi_output_declaration_request.json similarity index 97% rename from rust/lancedb/tests/fixtures/first_class_functions/v1/remote_grouped_declaration_request.json rename to rust/lancedb/tests/fixtures/first_class_functions/v1/remote_multi_output_declaration_request.json index d0b42cc99..c4ef5009f 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_grouped_declaration_request.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_multi_output_declaration_request.json @@ -17,7 +17,6 @@ {"name": "token_count", "arrow_type": "int64", "nullable": false} ] }, - "group_id": "fg_01K3TEXT", "columns": {"normalized_text": "search_text"} }, "binding_metadata_version": 1, diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_job.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_job.json index bb2490bc8..c2d49827d 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_job.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_refresh_job.json @@ -3,7 +3,7 @@ "job_type": "refresh_function_columns", "job_state": "DONE", "creation_ms": 1787270400001, - "spec": {"table": "documents", "binding_revision": 3}, + "spec": {"table": "documents", "binding_id": "fb_01K3TEXT"}, "result": { "rows_assigned": 999998800, "rows_failed": 0, diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_scalar_declaration_request.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_scalar_declaration_request.json index 0aaa0cf72..357834de0 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_scalar_declaration_request.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_scalar_declaration_request.json @@ -8,8 +8,7 @@ "inputs": [ {"parameter": "text", "kind": "column", "value": {"path": "description"}} ], - "output": {"kind": "scalar", "arrow_type": "list", "nullable": false}, - "group_id": "fg_scalar" + "output": {"kind": "scalar", "arrow_type": "list", "nullable": false} }, "binding_metadata_version": 1, "input_bindings": [ From 81c3f108ce35f148123b831c399c335c0c79b46a Mon Sep 17 00:00:00 2001 From: Lance Release Date: Tue, 25 Aug 2026 10:31:36 +0000 Subject: [PATCH 113/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.8=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package-lock.json | 4 ++-- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 86a5064f7..fb1323d7e 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.8" +current_version = "0.38.0-beta.9" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 8d0058569..80db934d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.8" +version = "0.38.0-beta.9" dependencies = [ "ahash", "anyhow", @@ -5490,7 +5490,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.8" +version = "0.38.0-beta.9" dependencies = [ "arrow-array", "arrow-buffer", @@ -5515,7 +5515,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.8" +version = "0.38.0-beta.9" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 28de11c30..7aa12d0a0 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.38.0-beta.8 + 0.38.0-beta.9 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 6f4b0744b..58d75d214 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.8 + 0.38.0-beta.9 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index ac6196a45..69c8f5ce1 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.8 + 0.38.0-beta.9 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index e85da66ec..99decbd9d 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.8" +version = "0.38.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 f920c9e91..911d6495f 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.38.0-beta.8", + "version": "0.38.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 ad6926039..078b32dd1 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.38.0-beta.8", + "version": "0.38.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 ccd39f18e..0fc54cdee 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.38.0-beta.8", + "version": "0.38.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 50446b597..ecaf22680 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.38.0-beta.8", + "version": "0.38.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 d4da82dc7..081c4c8ba 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.38.0-beta.8", + "version": "0.38.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 dddc3a470..609f701b7 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.38.0-beta.8", + "version": "0.38.0-beta.9", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 23ac122f7..59eb8e06e 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.38.0-beta.8", + "version": "0.38.0-beta.9", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index 21deb8dd8..d8b38ce0f 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.8", + "version": "0.38.0-beta.9", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.8", + "version": "0.38.0-beta.9", "cpu": [ "x64", "arm64" diff --git a/nodejs/package.json b/nodejs/package.json index 96f4bafd5..2c0ff7d69 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.8", + "version": "0.38.0-beta.9", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index bffac2ef1..8c73b602d 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.8" +version = "0.38.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 7290694f1..6f194556a 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.8" +version = "0.38.0-beta.9" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From d0bcc6c6fe71b057f53be07a75be4bdefd463fb8 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 25 Aug 2026 18:35:27 +0800 Subject: [PATCH 114/206] fix: remove unsupported Function secrets contract (#4047) ## Problem The unreleased First-Class Function authoring API exposed `secrets=[...]` and serialized `required_secrets`, promising runtime resolution and injection that Sophon does not implement. ## Behavior Remove the secrets dimension from the public Python decorator, Python and Rust registration/version models, and shared wire fixtures. Existing successfully registered Functions retain stable identity: the field could only be empty and empty values were already omitted from canonical serialization. A stable LanceDB release has not shipped this Function API, so this contracts the surface before it becomes a published compatibility commitment. ## Validation gap The Rust shared-golden Function suites and Python formatting/lint checks pass locally. Python pytest was not run because the local environment lacks its runtime dependencies and the frozen native editable build did not complete in practical time. --- python/python/lancedb/functions.py | 37 +++--------------- .../tests/test_first_class_function_slice1.py | 25 ------------ .../tests/test_first_class_function_slice2.py | 29 -------------- rust/lancedb/src/function.rs | 20 +--------- .../tests/first_class_function_slice1.rs | 38 ------------------- .../tests/first_class_function_slice2.rs | 26 ------------- .../v1/remote_function_job.json | 1 - ...nction_registration_request.canonical.json | 2 +- .../remote_function_registration_request.json | 5 +-- .../v1/remote_function_version.canonical.json | 2 +- 10 files changed, 10 insertions(+), 175 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index dd8cecfa9..237ed73c2 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -4,7 +4,7 @@ """Canonical Function values exchanged with LanceDB Enterprise services. These immutable models contain client/wire state only. Catalog persistence, -environment bake, secret resolution, and execution are owned by Sophon. +environment bake, and execution are owned by Sophon. ``RefreshColumnResult`` is also the backend-neutral result of a local expression-backed refresh job. """ @@ -228,7 +228,7 @@ class PythonEnvironmentSpec(_RemoteValue): class PythonRuntimeSpec(_RemoteValue): - """Remote runtime definition with non-secret environment values. + """Remote runtime definition with environment values. V1 supports ``kind="python"``. Newer runtime kinds remain readable, while their unknown payload fields are intentionally not retained by the client. @@ -267,7 +267,6 @@ class FunctionVersion(_RemoteValue): runtime: PythonRuntimeSpec runtime_digest: str environment_digest: str - required_secrets: tuple[str, ...] = () created_at: str def __call__(self, **inputs: Any) -> FunctionApplication: @@ -329,17 +328,12 @@ class FunctionVersion(_RemoteValue): class FunctionRegistrationRequest(_RemoteValue): - """Stable remote registration envelope produced by :func:`udf`. - - Only secret names are represented. Secret values are resolved inside the - remote service and have no client request field. - """ + """Stable remote registration envelope produced by :func:`udf`.""" name: str artifact: FunctionArtifactRequest signature: FunctionSignature runtime: PythonRuntimeSpec - required_secrets: tuple[str, ...] = () class FunctionVersionRef(_OpenRemoteValue): @@ -484,7 +478,6 @@ class RefreshColumnResult(_RemoteValue): _FUNCTION_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]*$") -_SECRET_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") _GRAMMAR_PRIMITIVES = ( @@ -915,7 +908,6 @@ class UdfDefinition: output_schema: Optional[pa.DataType | pa.Field | pa.Schema], pip: tuple[str, ...], env: Mapping[str, str], - secrets: tuple[str, ...], python_version: Optional[str], ): function_name = name or function.__name__ @@ -930,18 +922,6 @@ class UdfDefinition: for key, value in environment.items() ): raise TypeError("Function env keys and values must be strings") - required_secrets = tuple(sorted(set(secrets))) - invalid_secrets = [ - secret for secret in required_secrets if not _SECRET_NAME.fullmatch(secret) - ] - if invalid_secrets: - raise ValueError(f"invalid Function secret names: {invalid_secrets!r}") - overlap = set(environment) & set(required_secrets) - if overlap: - raise ValueError( - f"Function env and secret names must be disjoint: {sorted(overlap)!r}" - ) - signature = _infer_signature(function, input_schema, output_schema) source = _package_source(function) digest = f"sha256:{hashlib.sha256(source).hexdigest()}" @@ -970,7 +950,6 @@ class UdfDefinition: ), signature=signature, runtime=runtime, - required_secrets=required_secrets, ) functools.update_wrapper(self, function) @@ -996,7 +975,6 @@ def udf( output_schema: Optional[pa.DataType | pa.Field | pa.Schema] = None, pip: tuple[str, ...] | list[str] = (), env: Optional[Mapping[str, str]] = None, - secrets: tuple[str, ...] | list[str] = (), python_version: Optional[str] = None, ) -> Callable[[Callable[..., Any]], UdfDefinition]: ... @@ -1009,7 +987,6 @@ def udf( output_schema: Optional[pa.DataType | pa.Field | pa.Schema] = None, pip: tuple[str, ...] | list[str] = (), env: Optional[Mapping[str, str]] = None, - secrets: tuple[str, ...] | list[str] = (), python_version: Optional[str] = None, ): """Prepare a scalar Python callable for remote Function registration. @@ -1034,10 +1011,7 @@ def udf( pip : sequence of str, optional Pip requirements for the remote environment. env : mapping of str to str, optional - Non-secret environment variables. Use ``secrets`` for credentials. - secrets : sequence of str, optional - Names of secrets resolved by the remote service. Secret values are not - accepted by this API or included in the registration request. + Environment variables included in the Function definition. python_version : str, optional Remote Python major/minor version. Defaults to the client version. @@ -1059,7 +1033,7 @@ def udf( Examples -------- >>> from lancedb import udf - >>> @udf(pip=["numpy==2.2.0"], secrets=["MODEL_TOKEN"]) + >>> @udf(pip=["numpy==2.2.0"]) ... def score(value: float) -> float: ... return value * 2 >>> score(1.5) @@ -1074,7 +1048,6 @@ def udf( output_schema=output_schema, pip=tuple(pip), env={} if env is None else env, - secrets=tuple(secrets), python_version=python_version, ) diff --git a/python/python/tests/test_first_class_function_slice1.py b/python/python/tests/test_first_class_function_slice1.py index ca0b30ede..89172ba3f 100644 --- a/python/python/tests/test_first_class_function_slice1.py +++ b/python/python/tests/test_first_class_function_slice1.py @@ -37,21 +37,6 @@ def job_result(name: str) -> dict: return json.loads(fixture(name))["result"] -def assert_no_secret_values(value): - if isinstance(value, dict): - for key, child in value.items(): - assert key not in { - "secret_value", - "secret_values", - "resolved_secret", - "resolved_secrets", - } - assert_no_secret_values(child) - elif isinstance(value, list): - for child in value: - assert_no_secret_values(child) - - def test_public_function_values_are_in_api_reference(): docs = Path(__file__).parents[3] / "docs" / "src" / "python" / "python.md" rendered = docs.read_text() @@ -109,7 +94,6 @@ def test_function_version_identity_is_immutable_and_exact(): version = FunctionVersion.from_json(json.dumps(value)) assert version.name == "embed" assert version.version == "fv_01K3EXACT" - assert version.required_secrets == ("HF_TOKEN",) with pytest.raises((TypeError, ValueError)): version.version = "fv_changed" @@ -292,15 +276,6 @@ def test_refresh_result_rejects_non_u64_values(field): RefreshColumnResult.from_json(json.dumps(value)) -def test_canonical_client_values_contain_secret_names_only(): - version = FunctionVersion.from_json( - json.dumps(job_result("remote_function_job.json")) - ) - canonical = json.loads(version.to_canonical_json()) - assert canonical["required_secrets"] == ["HF_TOKEN"] - assert_no_secret_values(canonical) - - class _FunctionDeclarationInner: def __init__(self): self.calls = [] diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index c67e17520..55257d322 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -39,28 +39,12 @@ FIXTURES = ( @udf( pip=["numpy>=2"], env={"MODE": "test"}, - secrets=["API_TOKEN"], python_version="3.12", ) def normalize_score(value: float) -> float: return value / 100.0 -def _assert_no_secret_values(value): - if isinstance(value, dict): - for key, child in value.items(): - assert key not in { - "secret_value", - "secret_values", - "resolved_secret", - "resolved_secrets", - } - _assert_no_secret_values(child) - elif isinstance(value, list): - for child in value: - _assert_no_secret_values(child) - - def test_scalar_udf_matches_shared_registration_golden_and_remains_callable(): assert isinstance(normalize_score, UdfDefinition) assert normalize_score(25.0) == 0.25 @@ -75,8 +59,6 @@ def test_scalar_udf_matches_shared_registration_golden_and_remains_callable(): "kind": "scalar_to_arrow_batch", "version": 1, } - assert request["required_secrets"] == ["API_TOKEN"] - _assert_no_secret_values(request) def _run_packaged(definition, *args): @@ -370,7 +352,6 @@ def test_udf_recursion_versus_a_rebound_module_name(tmp_path): output_schema=None, pip=(), env={}, - secrets=(), python_version=None, ) with pytest.raises(ValueError, match="binds that name to another value"): @@ -525,14 +506,6 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): return value -def test_environment_rejects_secret_value_overlap(): - with pytest.raises(ValueError, match="must be disjoint"): - - @udf(env={"TOKEN": "plaintext"}, secrets=["TOKEN"]) - def overlapping(value: int) -> int: - return value - - 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" @@ -569,7 +542,6 @@ def _mock_remote_function_catalog(): "runtime": body["runtime"], "runtime_digest": "sha256:runtime", "environment_digest": "sha256:environment", - "required_secrets": body.get("required_secrets", []), "created_at": "2026-08-21T00:00:00Z", } response = {"job_id": "job-register"} @@ -628,7 +600,6 @@ def test_remote_registration_job_and_exact_version_reopen_round_trip(): assert create_request == json.loads( normalize_score.registration_request.to_canonical_json() ) - _assert_no_secret_values(create_request) def test_blocking_remote_registration_returns_function_version(): diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 433a7e04c..52c70a4b1 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -5,7 +5,7 @@ //! backend-neutral terminal result of a computed-column refresh. //! //! This module contains client/wire values only. Catalog persistence, -//! environment bake, secret resolution, and execution are owned by Sophon. +//! environment bake, and execution are owned by Sophon. use std::collections::BTreeMap; @@ -195,9 +195,6 @@ pub struct PythonEnvironmentSpec { } /// Reproducible Python runtime definition understood by Sophon. -/// -/// `env` contains non-secret values. Secret values have no client model; -/// [`FunctionVersion::required_secrets`] contains names only. #[derive(Debug, Clone, PartialEq, Eq)] #[non_exhaustive] pub enum PythonRuntimeSpec { @@ -239,7 +236,7 @@ impl PythonRuntimeSpec { } } - /// Non-secret environment variables, or `None` for an unknown kind. + /// Environment variables, or `None` for an unknown kind. pub fn env(&self) -> Option<&BTreeMap> { match self { Self::Python { env, .. } => Some(env), @@ -324,8 +321,6 @@ pub struct FunctionVersion { runtime: PythonRuntimeSpec, runtime_digest: String, environment_digest: String, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - required_secrets: Vec, created_at: String, } @@ -358,11 +353,6 @@ impl FunctionVersion { &self.environment_digest } - /// Required secret names. Resolved values exist only inside Sophon. - pub fn required_secrets(&self) -> &[String] { - &self.required_secrets - } - pub fn created_at(&self) -> &str { &self.created_at } @@ -404,18 +394,12 @@ pub struct FunctionArtifactRequest { } /// Stable request envelope for remote immutable Function registration. -/// -/// Secret values deliberately have no field in this model. The only secret -/// material the client may send is the ordered set of names Sophon resolves -/// inside the remote runtime. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionRegistrationRequest { pub name: String, pub artifact: FunctionArtifactRequest, pub signature: FunctionSignature, pub runtime: PythonRuntimeSpec, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub required_secrets: Vec, } impl_json!(FunctionRegistrationRequest); diff --git a/rust/lancedb/tests/first_class_function_slice1.rs b/rust/lancedb/tests/first_class_function_slice1.rs index aec264650..ce020bd53 100644 --- a/rust/lancedb/tests/first_class_function_slice1.rs +++ b/rust/lancedb/tests/first_class_function_slice1.rs @@ -20,25 +20,6 @@ fn job_result(name: &str) -> Value { serde_json::from_str::(&fixture(name)).expect("remote Job fixture")["result"].clone() } -fn assert_no_secret_values(value: &Value) { - match value { - Value::Object(values) => { - for (key, value) in values { - assert!( - !matches!( - key.as_str(), - "secret_value" | "secret_values" | "resolved_secret" | "resolved_secrets" - ), - "client canonical value must not model resolved secret material" - ); - assert_no_secret_values(value); - } - } - Value::Array(values) => values.iter().for_each(assert_no_secret_values), - _ => {} - } -} - #[test] fn function_version_job_result_matches_shared_canonical_golden() { let result = job_result("remote_function_job.json"); @@ -47,7 +28,6 @@ fn function_version_job_result_matches_shared_canonical_golden() { assert_eq!(version.name(), "embed"); assert_eq!(version.version(), "fv_01K3EXACT"); assert_eq!(version.runtime_digest(), "sha256:runtime"); - assert_eq!(version.required_secrets(), &["HF_TOKEN"]); assert_eq!( version.to_canonical_json().expect("canonical JSON"), fixture("remote_function_version.canonical.json").trim() @@ -162,21 +142,3 @@ fn floating_point_application_literals_are_rejected_consistently() { .contains("floating-point Function literals") ); } - -#[test] -fn canonical_client_values_contain_secret_names_only() { - let result = job_result("remote_function_job.json"); - let version = FunctionVersion::from_json(&result.to_string()).expect("FunctionVersion result"); - let canonical: Value = serde_json::from_str( - &version - .to_canonical_json() - .expect("canonical FunctionVersion"), - ) - .expect("canonical JSON"); - - assert_eq!( - canonical["required_secrets"], - serde_json::json!(["HF_TOKEN"]) - ); - assert_no_secret_values(&canonical); -} diff --git a/rust/lancedb/tests/first_class_function_slice2.rs b/rust/lancedb/tests/first_class_function_slice2.rs index 3bae57122..93252dde4 100644 --- a/rust/lancedb/tests/first_class_function_slice2.rs +++ b/rust/lancedb/tests/first_class_function_slice2.rs @@ -6,7 +6,6 @@ use std::path::PathBuf; use lancedb::Error; use lancedb::function::FunctionRegistrationRequest; -use serde_json::Value; fn fixture(name: &str) -> String { let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) @@ -15,25 +14,6 @@ fn fixture(name: &str) -> String { fs::read_to_string(path).expect("fixture must be readable") } -fn assert_no_secret_values(value: &Value) { - match value { - Value::Object(values) => { - for (key, value) in values { - assert!( - !matches!( - key.as_str(), - "secret_value" | "secret_values" | "resolved_secret" | "resolved_secrets" - ), - "registration requests must not model resolved secret material" - ); - assert_no_secret_values(value); - } - } - Value::Array(values) => values.iter().for_each(assert_no_secret_values), - _ => {} - } -} - #[test] fn registration_request_matches_shared_canonical_golden() { let request = FunctionRegistrationRequest::from_json(&fixture( @@ -42,16 +22,10 @@ fn registration_request_matches_shared_canonical_golden() { .expect("registration request"); assert_eq!(request.name, "normalize_score"); assert_eq!(request.artifact.adapter.kind, "scalar_to_arrow_batch"); - assert_eq!(request.required_secrets, ["API_TOKEN"]); assert_eq!( request.to_canonical_json().expect("canonical request"), fixture("remote_function_registration_request.canonical.json").trim() ); - - let value: Value = - serde_json::from_str(&request.to_canonical_json().expect("canonical request")) - .expect("request JSON"); - assert_no_secret_values(&value); } #[tokio::test] diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_job.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_job.json index 6ba4eb226..39a279692 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_job.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_job.json @@ -24,7 +24,6 @@ }, "runtime_digest": "sha256:runtime", "environment_digest": "sha256:environment", - "required_secrets": ["HF_TOKEN"], "created_at": "2026-08-21T00:00:00Z" }, "future_job": {"trace_id": "trace-1"} diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_registration_request.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_registration_request.canonical.json index 24fa2cf30..a2f2c4c21 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_registration_request.canonical.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_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"},"name":"normalize_score","required_secrets":["API_TOKEN"],"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"},"name":"normalize_score","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_registration_request.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_registration_request.json index bbfec3169..092d76dc2 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_registration_request.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_registration_request.json @@ -39,8 +39,5 @@ "env": { "MODE": "test" } - }, - "required_secrets": [ - "API_TOKEN" - ] + } } diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json index 7ab632a98..2670ad0b2 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json @@ -1 +1 @@ -{"artifact":{"digest":"sha256:code","entrypoint":"embed","kind":"python_callable"},"created_at":"2026-08-21T00:00:00Z","environment_digest":"sha256:environment","name":"embed","required_secrets":["HF_TOKEN"],"runtime":{"env":{"TOKENIZERS_PARALLELISM":"false"},"environment":{"kind":"pip","packages":["sentence-transformers>=3"]},"kind":"python","python_version":"3.12"},"runtime_digest":"sha256:runtime","signature":{"inputs":[{"arrow_type":"utf8","name":"text","nullable":true}],"output":{"arrow_type":"list","kind":"scalar","nullable":false}},"version":"fv_01K3EXACT"} +{"artifact":{"digest":"sha256:code","entrypoint":"embed","kind":"python_callable"},"created_at":"2026-08-21T00:00:00Z","environment_digest":"sha256:environment","name":"embed","runtime":{"env":{"TOKENIZERS_PARALLELISM":"false"},"environment":{"kind":"pip","packages":["sentence-transformers>=3"]},"kind":"python","python_version":"3.12"},"runtime_digest":"sha256:runtime","signature":{"inputs":[{"arrow_type":"utf8","name":"text","nullable":true}],"output":{"arrow_type":"list","kind":"scalar","nullable":false}},"version":"fv_01K3EXACT"} From ec4ad54ba253e11c4cfd894cde6d47e788447886 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Tue, 25 Aug 2026 10:36:33 +0000 Subject: [PATCH 115/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.9=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.10?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package-lock.json | 4 ++-- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index fb1323d7e..1c4aea809 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.9" +current_version = "0.38.0-beta.10" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 80db934d2..33e43f9fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.9" +version = "0.38.0-beta.10" dependencies = [ "ahash", "anyhow", @@ -5490,7 +5490,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.9" +version = "0.38.0-beta.10" dependencies = [ "arrow-array", "arrow-buffer", @@ -5515,7 +5515,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.9" +version = "0.38.0-beta.10" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 7aa12d0a0..06dc267f3 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.38.0-beta.9 + 0.38.0-beta.10 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 58d75d214..25e3b10e3 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.9 + 0.38.0-beta.10 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 69c8f5ce1..4d83153ab 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.9 + 0.38.0-beta.10 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 99decbd9d..fd08e7a5e 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.9" +version = "0.38.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 911d6495f..ff6347c4d 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.38.0-beta.9", + "version": "0.38.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 078b32dd1..ed99fee05 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.38.0-beta.9", + "version": "0.38.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 0fc54cdee..5b215dcc0 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.38.0-beta.9", + "version": "0.38.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 ecaf22680..e0f5a9f26 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.38.0-beta.9", + "version": "0.38.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 081c4c8ba..d42541707 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.38.0-beta.9", + "version": "0.38.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 609f701b7..496a40720 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.38.0-beta.9", + "version": "0.38.0-beta.10", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 59eb8e06e..734013343 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.38.0-beta.9", + "version": "0.38.0-beta.10", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index d8b38ce0f..732a7c01c 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.9", + "version": "0.38.0-beta.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.9", + "version": "0.38.0-beta.10", "cpu": [ "x64", "arm64" diff --git a/nodejs/package.json b/nodejs/package.json index 2c0ff7d69..262d4c4a7 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.9", + "version": "0.38.0-beta.10", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 8c73b602d..3a8a05522 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.9" +version = "0.38.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 6f194556a..8276e5bb3 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.9" +version = "0.38.0-beta.10" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 1d880f11ff12edbf6b5c26505b6914bd1817e9e0 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 25 Aug 2026 19:51:40 +0800 Subject: [PATCH 116/206] fix(python): use dev profile for editable builds (#4049) ## Problem `uv run ... maturin develop` synchronizes the project as an editable package before running the command. Maturin's editable build otherwise uses the release profile, which enables the repository's fat LTO configuration during local bootstrap. ## Behavior Editable Python builds now explicitly use Cargo's dev profile. The minimum maturin version is raised to 1.10, where `editable-profile` support was introduced. --- python/pyproject.toml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/python/pyproject.toml b/python/pyproject.toml index fad3b1001..22a41a8a9 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -101,9 +101,12 @@ azure = ["adlfs>=2024.2.0"] [tool.maturin] python-source = "python" module-name = "lancedb._lancedb" +# uv installs the project as an editable package before `uv run`, so keep that +# bootstrap build consistent with `maturin develop`. +editable-profile = "dev" [build-system] -requires = ["maturin>=1.9.4"] +requires = ["maturin>=1.10"] build-backend = "maturin" [tool.ruff.lint] From a614400755b00c472eba6cf743802e4f0c734132 Mon Sep 17 00:00:00 2001 From: Drew Date: Tue, 25 Aug 2026 07:59:53 -0700 Subject: [PATCH 117/206] feat: accept blob URI writes (#3954) #3528 added blob declarations and binary coercion. String values were still rejected. They now coerce to the blob `uri` child. ```python table.add([{"id": 1, "image": "s3://bucket/media/cat.jpg"}]) payload = table.fetch_blobs("image", table.search().to_arrow()) ``` A URI under a registered base writes with no extra options. An unregistered URI fails. `allow_external_blob_outside_bases` is a local escape hatch that stores an absolute URI. It does not register a base. Remote `add` rejects that flag before making a request. String input still coerces and is sent as a `uri` struct. `add_bases` is a follow-up. `merge_insert` does not coerce string blob input. ### Testing - `cargo test -p lancedb --test blob_integration` - `cargo test -p lancedb blob_coerce` - `cargo test -p lancedb --features remote --lib add_rejects_external_blob_flag add_string_blob_becomes_uri_struct` - `cd python && uv run --extra tests pytest python/tests/test_blob.py -k uri -q` Co-authored-by: Xuanwo --- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/remote/table.py | 4 + python/python/lancedb/table.py | 15 ++ python/python/tests/test_blob.py | 68 ++++++ python/src/table.rs | 8 +- rust/lancedb/src/remote/table.rs | 96 +++++++- rust/lancedb/src/table.rs | 5 +- rust/lancedb/src/table/add_data.rs | 14 ++ .../src/table/datafusion/blob_coerce.rs | 153 +++++++++--- rust/lancedb/tests/blob_integration.rs | 230 +++++++++++++++++- 10 files changed, 552 insertions(+), 42 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 1e314ede8..593bceffa 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -283,6 +283,7 @@ class Table: mode: Literal["append", "overwrite"], progress: Optional[Any] = None, write_parallelism: Optional[int] = None, + allow_external_blob_outside_bases: bool = False, ) -> 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 41394ed71..d0bf9f67a 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -610,6 +610,7 @@ class RemoteTable(Table): fill_value: float = 0.0, progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, + allow_external_blob_outside_bases: bool = False, ) -> AddResult: """Add more data to the [Table][lancedb.table.Table]. @@ -642,6 +643,8 @@ class RemoteTable(Table): data in flight. Defaults to an estimate based on the data size, capped at the number of CPU cores. Lower this if bulk ingestion is using too much memory. + allow_external_blob_outside_bases: bool, default False + Not supported on LanceDB Cloud. Setting this raises. Returns ------- @@ -658,6 +661,7 @@ class RemoteTable(Table): fill_value=fill_value, progress=progress, write_parallelism=write_parallelism, + allow_external_blob_outside_bases=allow_external_blob_outside_bases, ) ) finally: diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index fe25d5353..b3cab006e 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1269,6 +1269,7 @@ class Table(ABC): fill_value: float = 0.0, progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, + allow_external_blob_outside_bases: bool = False, ) -> AddResult: """Add more data to the [Table][lancedb.table.Table]. @@ -1320,6 +1321,10 @@ class Table(ABC): data in flight. Defaults to an estimate based on the data size, capped at the number of CPU cores. Lower this if bulk ingestion is using too much memory. + allow_external_blob_outside_bases: bool, default False + Store blob URIs that sit outside registered blob bases. The row + keeps a reference, so the object has to stay readable. Local + tables only. Returns ------- @@ -3409,6 +3414,7 @@ class LanceTable(Table): fill_value: float = 0.0, progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, + allow_external_blob_outside_bases: bool = False, ) -> AddResult: """Add data to the table. If vector columns are missing and the table @@ -3436,6 +3442,9 @@ class LanceTable(Table): data in flight. Defaults to an estimate based on the data size, capped at the number of CPU cores. Lower this if bulk ingestion is using too much memory. + allow_external_blob_outside_bases: bool, default False + Allow blob URIs outside registered bases. See :meth:`Table.add`. + Local tables only. Returns ------- @@ -3452,6 +3461,7 @@ class LanceTable(Table): fill_value=fill_value, progress=progress, write_parallelism=write_parallelism, + allow_external_blob_outside_bases=allow_external_blob_outside_bases, ) ) finally: @@ -5365,6 +5375,7 @@ class AsyncTable: fill_value: Optional[float] = None, progress: Optional[Union[bool, Callable, Any]] = None, write_parallelism: Optional[int] = None, + allow_external_blob_outside_bases: bool = False, ) -> AddResult: """Add more data to the [AsyncTable][lancedb.table.AsyncTable]. @@ -5395,6 +5406,9 @@ class AsyncTable: data in flight. Defaults to an estimate based on the data size, capped at the number of CPU cores. Lower this if bulk ingestion is using too much memory. + allow_external_blob_outside_bases: bool, default False + Allow blob URIs outside registered bases. See :meth:`Table.add`. + Local tables only. """ schema = await self.schema() @@ -5431,6 +5445,7 @@ class AsyncTable: mode or "append", progress=progress, write_parallelism=write_parallelism, + allow_external_blob_outside_bases=allow_external_blob_outside_bases, ) except RuntimeError as e: if "Cast error" in str(e): diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index b205c20a6..5d7682f24 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -617,3 +617,71 @@ def test_fetch_blobs_nested_path_survives_sort_after_query(): def _identifiable_payload(size: int) -> bytes: block = 256 return b"".join(bytes([i % 256]) * block for i in range(size // block)) + + +def _external_uri_blob_array(uris): + blob_type = lancedb.blob("image").type + storage_type = blob_type.storage_type + child_names = [field.name for field in storage_type] + assert "uri" in child_names, "blob layout no longer has a uri child" + children = [ + pa.array(uris if field.name == "uri" else [None] * len(uris), type=field.type) + for field in storage_type + ] + storage = pa.StructArray.from_arrays(children, fields=list(storage_type)) + return pa.ExtensionArray.from_storage(blob_type, storage) + + +def _external_uri_table_and_rows(name, uris): + db = lancedb.connect("memory:///") + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + table = db.create_table(name, schema=schema) + rows = pa.Table.from_arrays( + [ + pa.array(range(len(uris)), type=pa.int64()), + _external_uri_blob_array(uris), + ], + schema=schema, + ) + return table, rows + + +def test_add_external_uri_struct_round_trips_with_flag(tmp_path): + payload = b"external-uri-bytes" + blob_path = tmp_path / "payload.bin" + blob_path.write_bytes(payload) + + table, rows = _external_uri_table_and_rows("external_struct", [blob_path.as_uri()]) + table.add(rows, allow_external_blob_outside_bases=True) + + hits = table.search().to_arrow() + blobs = table.fetch_blobs("image", hits) + assert blobs[0].as_py() == payload + + +def test_add_external_uri_without_flag_raises(tmp_path): + blob_path = tmp_path / "payload.bin" + blob_path.write_bytes(b"unreachable") + + table, rows = _external_uri_table_and_rows("external_no_flag", [blob_path.as_uri()]) + with pytest.raises(ValueError, match="allow_external_blob_outside_bases"): + table.add(rows) + assert table.count_rows() == 0 + + +def test_add_external_uri_string_round_trips_with_flag(tmp_path): + payload = b"external-uri-bytes" + blob_path = tmp_path / "payload.bin" + blob_path.write_bytes(payload) + + db = lancedb.connect("memory:///") + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + table = db.create_table("external_string", schema=schema) + table.add( + [{"id": 1, "image": blob_path.as_uri()}], + allow_external_blob_outside_bases=True, + ) + + hits = table.search().to_arrow() + blobs = table.fetch_blobs("image", hits) + assert blobs[0].as_py() == payload diff --git a/python/src/table.rs b/python/src/table.rs index b225b191f..784d29136 100644 --- a/python/src/table.rs +++ b/python/src/table.rs @@ -780,15 +780,19 @@ impl Table { }) } - #[pyo3(signature = (data, mode, progress=None, write_parallelism=None))] + #[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false))] pub fn add<'a>( self_: PyRef<'a, Self>, data: PyScannable, mode: String, progress: Option>, write_parallelism: Option, + allow_external_blob_outside_bases: bool, ) -> PyResult> { - let mut op = self_.inner_ref()?.add(data); + let mut op = self_ + .inner_ref()? + .add(data) + .allow_external_blob_outside_bases(allow_external_blob_outside_bases); if mode == "append" { op = op.mode(AddDataMode::Append); } else if mode == "overwrite" { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 742ab547d..44c92310f 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -2161,6 +2161,15 @@ impl BaseTable for RemoteTable { async fn add(&self, mut add: AddDataBuilder) -> Result { self.check_mutable().await?; + if add.allow_external_blob_outside_bases { + return Err(Error::NotSupported { + message: "allow_external_blob_outside_bases is only supported on local tables" + .to_string(), + }); + } + // String blob values still coerce to the uri child in into_plan. + // Remote and local share that input shape. + let table_schema = self.schema().await?; crate::table::computed_columns::ensure_supported_function_metadata(table_schema.as_ref())?; let table_def = TableDefinition::try_from_rich_schema(table_schema.clone())?; @@ -3269,7 +3278,10 @@ mod tests { use arrow::{array::AsArray, compute::concat_batches, datatypes::Int32Type}; use arrow_array::Array; use arrow_array::builder::LargeBinaryBuilder; - use arrow_array::{BinaryArray, Int32Array, RecordBatch, RecordBatchIterator, record_batch}; + use arrow_array::{ + BinaryArray, Int32Array, Int64Array, RecordBatch, RecordBatchIterator, StringArray, + StructArray, record_batch, + }; use arrow_schema::{DataType, Field, Schema}; use chrono::{DateTime, Utc}; use futures::{StreamExt, TryFutureExt, future::BoxFuture}; @@ -3621,6 +3633,88 @@ mod tests { assert_eq!(&body, &expected_body); } + #[tokio::test] + async fn add_rejects_external_blob_flag_before_any_request() { + let table = Table::new_with_handler::("my_table", |request| { + panic!("Unexpected request: {}", request.url().path()) + }); + let data = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])), + vec![Arc::new(Int32Array::from(vec![1]))], + ) + .unwrap(); + + let err = table + .add(data) + .allow_external_blob_outside_bases(true) + .execute() + .await + .unwrap_err(); + + assert!(matches!(err, Error::NotSupported { .. }), "got {err:?}"); + assert!(err.to_string().contains("local tables")); + } + + #[tokio::test] + async fn add_string_blob_becomes_uri_struct_without_the_local_flag() { + let table_schema = Schema::new(vec![ + Field::new("id", DataType::Int64, false), + crate::blob("image", true), + ]); + let describe_body = describe_response(&table_schema); + let input = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("image", DataType::Utf8, true), + ])), + vec![ + Arc::new(Int64Array::from(vec![1])), + Arc::new(StringArray::from(vec![Some("s3://bucket/key")])), + ], + ) + .unwrap(); + + let (sender, receiver) = std::sync::mpsc::channel(); + let table = + Table::new_with_handler("my_table", move |mut request| match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_body.clone()) + .unwrap(), + "/v1/table/my_table/insert/" => { + let mut body_out = reqwest::Body::from(Vec::new()); + std::mem::swap(request.body_mut().as_mut().unwrap(), &mut body_out); + sender.send(body_out).unwrap(); + http::Response::builder() + .status(200) + .body(r#"{"version": 2}"#.to_string()) + .unwrap() + } + path => panic!("Unexpected path: {path}"), + }); + + table.add(input).execute().await.unwrap(); + + let body = collect_body(receiver.recv().unwrap()).await; + let mut reader = + arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(body), None).unwrap(); + let batch = reader.next().unwrap().unwrap(); + let image = batch + .column_by_name("image") + .unwrap() + .as_any() + .downcast_ref::() + .expect("remote add should send the coerced blob struct"); + let uri: &StringArray = image + .column_by_name("uri") + .unwrap() + .as_any() + .downcast_ref() + .unwrap(); + assert_eq!(uri.value(0), "s3://bucket/key"); + assert!(image.column_by_name("data").unwrap().is_null(0)); + } + #[rstest] #[case(true)] #[case(false)] diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index ecd95f161..efc36d260 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -3208,7 +3208,7 @@ impl BaseTable for NativeTable { let output = add.into_plan(&table_schema, &table_def)?; - let lance_params = output + let mut lance_params = output .write_options .lance_write_params .unwrap_or(WriteParams { @@ -3218,6 +3218,9 @@ impl BaseTable for NativeTable { }, ..Default::default() }); + if output.allow_external_blob_outside_bases { + lance_params.allow_external_blob_outside_bases = true; + } // Repartition for write parallelism if beneficial. let plan = if num_partitions > 1 { diff --git a/rust/lancedb/src/table/add_data.rs b/rust/lancedb/src/table/add_data.rs index 11ba43dd6..15ccf9f66 100644 --- a/rust/lancedb/src/table/add_data.rs +++ b/rust/lancedb/src/table/add_data.rs @@ -60,6 +60,7 @@ pub struct AddDataBuilder { pub(crate) embedding_registry: Option>, pub(crate) progress_callback: Option, pub(crate) write_parallelism: Option, + pub(crate) allow_external_blob_outside_bases: bool, } impl std::fmt::Debug for AddDataBuilder { @@ -87,6 +88,7 @@ impl AddDataBuilder { embedding_registry, progress_callback: None, write_parallelism: None, + allow_external_blob_outside_bases: false, } } @@ -141,6 +143,16 @@ impl AddDataBuilder { self } + /// Store blob URIs that sit outside registered blob bases. + /// + /// The row keeps a reference, so the object has to stay readable. + /// [`crate::table::Table::fetch_blobs`] reads from that location. + /// Defaults to `false`. Local tables only. + pub fn allow_external_blob_outside_bases(mut self, allow: bool) -> Self { + self.allow_external_blob_outside_bases = allow; + self + } + pub async fn execute(self) -> Result { if self.write_parallelism.map(|p| p == 0).unwrap_or(false) { return Err(Error::InvalidInput { @@ -199,6 +211,7 @@ impl AddDataBuilder { write_options: self.write_options, mode: self.mode, tracker, + allow_external_blob_outside_bases: self.allow_external_blob_outside_bases, }) } } @@ -212,6 +225,7 @@ pub struct PreprocessingOutput { pub write_options: WriteOptions, pub mode: AddDataMode, pub tracker: Option>, + pub allow_external_blob_outside_bases: bool, } /// Check that the input schema is valid for insert. diff --git a/rust/lancedb/src/table/datafusion/blob_coerce.rs b/rust/lancedb/src/table/datafusion/blob_coerce.rs index b29b2423b..cb984f7f4 100644 --- a/rust/lancedb/src/table/datafusion/blob_coerce.rs +++ b/rust/lancedb/src/table/datafusion/blob_coerce.rs @@ -7,7 +7,7 @@ use std::sync::Arc; -use arrow_schema::{DataType, Field, FieldRef}; +use arrow_schema::{DataType, Field, FieldRef, Fields}; use datafusion::functions::core::{get_field, named_struct}; use datafusion_common::ScalarValue; use datafusion_common::config::ConfigOptions; @@ -35,8 +35,9 @@ pub(super) fn coerce_blob_expr( }); }; - let input_struct_children = match input_field.data_type() { - DataType::Binary | DataType::LargeBinary | DataType::BinaryView => None, + let input_shape = match input_field.data_type() { + DataType::Binary | DataType::LargeBinary | DataType::BinaryView => BlobInputShape::Bytes, + DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => BlobInputShape::String, DataType::Struct(children) => { if !children .iter() @@ -49,13 +50,15 @@ pub(super) fn coerce_blob_expr( ), }); } - Some(children) + BlobInputShape::Struct(children) } other => { return Err(Error::InvalidInput { message: format!( "cannot coerce column '{}' with type {} into a blob v2 struct. \ - expected Binary, LargeBinary, BinaryView, or a Struct with a 'data' or 'uri' child", + expected binary bytes (Binary, LargeBinary, BinaryView), \ + strings (Utf8, LargeUtf8, Utf8View), \ + or a Struct with a 'data' or 'uri' child", table_field.name(), other, ), @@ -69,9 +72,8 @@ pub(super) fn coerce_blob_expr( declared.name().as_str(), )))); - let value: Arc = match input_struct_children { - // Raw binary lands in `data` and everything else is a typed null. - None => { + let value: Arc = match &input_shape { + BlobInputShape::Bytes => { if declared.name() == "data" { Arc::new(CastExpr::new( input_expr.clone(), @@ -82,30 +84,43 @@ pub(super) fn coerce_blob_expr( typed_null(declared.data_type())? } } - Some(children) => match children.iter().find(|c| c.name() == declared.name()) { - Some(child) => { - let field_expr: Arc = Arc::new(ScalarFunctionExpr::new( - &format!("get_field({})", declared.name()), - get_field(), - vec![ - input_expr.clone(), - Arc::new(Literal::new(ScalarValue::from(declared.name().as_str()))), - ], - Arc::new(child.as_ref().clone()), - config.clone(), - )); - if child.data_type() == declared.data_type() { - field_expr - } else { - Arc::new(CastExpr::new( - field_expr, - declared.data_type().clone(), - None, - )) - } + BlobInputShape::String => { + if declared.name() == "uri" { + Arc::new(CastExpr::new( + input_expr.clone(), + declared.data_type().clone(), + None, + )) + } else { + typed_null(declared.data_type())? } - None => typed_null(declared.data_type())?, - }, + } + BlobInputShape::Struct(children) => { + match children.iter().find(|c| c.name() == declared.name()) { + Some(child) => { + let field_expr: Arc = Arc::new(ScalarFunctionExpr::new( + &format!("get_field({})", declared.name()), + get_field(), + vec![ + input_expr.clone(), + Arc::new(Literal::new(ScalarValue::from(declared.name().as_str()))), + ], + Arc::new(child.as_ref().clone()), + config.clone(), + )); + if child.data_type() == declared.data_type() { + field_expr + } else { + Arc::new(CastExpr::new( + field_expr, + declared.data_type().clone(), + None, + )) + } + } + None => typed_null(declared.data_type())?, + } + } }; ns_args.push(value); } @@ -120,6 +135,12 @@ pub(super) fn coerce_blob_expr( Ok((expr, table_field.clone())) } +enum BlobInputShape<'a> { + Bytes, + String, + Struct(&'a Fields), +} + fn typed_null(data_type: &DataType) -> Result> { let scalar = ScalarValue::try_from(data_type).map_err(|e| Error::InvalidInput { message: format!("cannot build null literal for blob child type {data_type}: {e}"), @@ -134,7 +155,7 @@ mod tests { use crate::blob::blob; use arrow_array::{ Array, ArrayRef, BinaryArray, BinaryViewArray, Int32Array, Int64Array, LargeBinaryArray, - RecordBatch, StringArray, StructArray, UInt8Array, UInt64Array, + RecordBatch, StringArray, StringViewArray, StructArray, UInt8Array, UInt64Array, }; use arrow_schema::Schema; use datafusion::prelude::SessionContext; @@ -436,14 +457,78 @@ mod tests { #[tokio::test] async fn unsupported_input_type_is_rejected_with_column_name() { let batch = batch_with_image( - Field::new("image", DataType::Utf8, true), - Arc::new(StringArray::from(vec!["not bytes"])), + Field::new("image", DataType::Int64, true), + Arc::new(Int64Array::from(vec![42])), ); let err = coerce_err(batch, &blob_table_schema()).await; assert!(matches!(err, Error::InvalidInput { .. }), "got {err:?}"); assert!(err.to_string().contains("image")); } + #[tokio::test] + async fn utf8_string_coerces_to_uri_child() { + let batch = batch_with_image( + Field::new("image", DataType::Utf8, true), + Arc::new(StringArray::from(vec![Some("s3://bucket/key"), None])), + ); + let coerced = coerce(batch, &blob_table_schema()).await; + let image = image_struct(&coerced); + let uri: &StringArray = image + .column_by_name("uri") + .unwrap() + .as_any() + .downcast_ref() + .unwrap(); + assert_eq!(uri.value(0), "s3://bucket/key"); + assert!(image.column_by_name("data").unwrap().is_null(0)); + assert!(uri.is_null(1)); + } + + #[tokio::test] + async fn large_utf8_string_coerces_into_four_child_blob_layout() { + use arrow_array::LargeStringArray; + + let table_schema = Schema::new(vec![ + Field::new("id", DataType::Int64, false), + wide_blob_field("image"), + ]); + let batch = batch_with_image( + Field::new("image", DataType::LargeUtf8, true), + Arc::new(LargeStringArray::from(vec!["file:///tmp/blob.bin"])), + ); + let coerced = coerce(batch, &table_schema).await; + let image = image_struct(&coerced); + assert_eq!(image.num_columns(), 4); + let uri: &StringArray = image + .column_by_name("uri") + .unwrap() + .as_any() + .downcast_ref() + .unwrap(); + assert_eq!(uri.value(0), "file:///tmp/blob.bin"); + assert!(image.column_by_name("data").unwrap().is_null(0)); + assert!(image.column_by_name("position").unwrap().is_null(0)); + assert!(image.column_by_name("size").unwrap().is_null(0)); + } + + #[tokio::test] + async fn utf8_view_string_coerces_to_uri_child() { + let batch = batch_with_image( + Field::new("image", DataType::Utf8View, true), + Arc::new(StringViewArray::from(vec![Some("s3://bucket/view-key")])), + ); + let coerced = coerce(batch, &blob_table_schema()).await; + let image = image_struct(&coerced); + let uri: &StringArray = image + .column_by_name("uri") + .unwrap() + .as_any() + .downcast_ref() + .unwrap(); + assert_eq!(uri.value(0), "s3://bucket/view-key"); + assert!(image.column_by_name("data").unwrap().is_null(0)); + } + #[tokio::test] async fn blob_metadata_survives_cast_of_sibling_column() { let batch = RecordBatch::try_new( diff --git a/rust/lancedb/tests/blob_integration.rs b/rust/lancedb/tests/blob_integration.rs index b92f961f4..7b709b645 100644 --- a/rust/lancedb/tests/blob_integration.rs +++ b/rust/lancedb/tests/blob_integration.rs @@ -5,12 +5,14 @@ use std::sync::Arc; use arrow_array::{ Array, ArrayRef, BinaryArray, Int64Array, LargeBinaryArray, RecordBatch, StringArray, - StructArray, UInt64Array, + StructArray, UInt64Array, new_null_array, }; use arrow_schema::{DataType, Field, Fields, Schema}; use futures::TryStreamExt; use lance::Dataset; +use lance::dataset::WriteParams; use lance_file::version::{ConcreteFileVersion, LanceFileVersion}; +use lance_table::format::BasePath; use lancedb::{ Connection, Error, Result, Table, blob::{BlobRangeRequest, blob}, @@ -19,7 +21,7 @@ use lancedb::{ ListingDatabaseOptions, NewTableConfig, OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS, }, query::{ExecutableQuery, QueryBase}, - table::{AddDataMode, CompactionOptions, OptimizeAction, OptimizeStats}, + table::{AddDataMode, CompactionOptions, OptimizeAction, OptimizeStats, WriteOptions}, }; use tempfile::tempdir; @@ -261,11 +263,11 @@ async fn add_rejects_uncoercible_blob_input() -> Result<()> { let batch = RecordBatch::try_new( Arc::new(Schema::new(vec![ Field::new("id", DataType::Int64, false), - Field::new("image", DataType::Utf8, true), + Field::new("image", DataType::Int64, true), ])), vec![ Arc::new(Int64Array::from(vec![1])), - Arc::new(StringArray::from(vec!["not bytes"])), + Arc::new(Int64Array::from(vec![42])), ], ) .unwrap(); @@ -1332,3 +1334,223 @@ async fn optimize_preserves_blob_v2_null_and_empty_distinction() -> Result<()> { ); Ok(()) } + +fn uri_struct_batch(id: i64, uri: &str) -> RecordBatch { + let image_field = blob("image", true); + let DataType::Struct(child_fields) = image_field.data_type().clone() else { + unreachable!("blob field is a struct"); + }; + let children: Vec = child_fields + .iter() + .map(|field| match field.name().as_str() { + "uri" => Arc::new(StringArray::from(vec![Some(uri)])) as ArrayRef, + _ => new_null_array(field.data_type(), 1), + }) + .collect(); + let image = StructArray::new(child_fields, children, None); + RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + image_field, + ])), + vec![Arc::new(Int64Array::from(vec![id])), Arc::new(image)], + ) + .unwrap() +} + +fn uri_string_batch(id: i64, uri: &str) -> RecordBatch { + RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + Field::new("image", DataType::Utf8, true), + ])), + vec![ + Arc::new(Int64Array::from(vec![id])), + Arc::new(StringArray::from(vec![Some(uri)])), + ], + ) + .unwrap() +} + +fn write_payload_file_uri(dir: &std::path::Path, name: &str, payload: &[u8]) -> String { + let path = dir.join(name); + std::fs::write(&path, payload).unwrap(); + url::Url::from_file_path(&path).unwrap().to_string() +} + +#[tokio::test] +async fn external_uri_struct_round_trips_with_flag() -> Result<()> { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().join("db").to_str().unwrap()) + .execute() + .await?; + let payload: &[u8] = b"external-struct-payload"; + let uri = write_payload_file_uri(tmp.path(), "payload.bin", payload); + let table = db + .create_empty_table("t", blob_table_schema()) + .execute() + .await?; + + table + .add(uri_struct_batch(1, &uri)) + .allow_external_blob_outside_bases(true) + .execute() + .await?; + + let ids = collect_row_ids(&table).await?; + let bytes = table.fetch_blobs("image", &ids).await?; + assert_eq!(bytes.value(0), payload); + Ok(()) +} + +#[tokio::test] +async fn external_uri_add_requires_opt_in() -> Result<()> { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().join("db").to_str().unwrap()) + .execute() + .await?; + let uri = write_payload_file_uri(tmp.path(), "payload.bin", b"unreachable"); + let table = db + .create_empty_table("t", blob_table_schema()) + .execute() + .await?; + + let err = table + .add(uri_struct_batch(1, &uri)) + .execute() + .await + .unwrap_err(); + + assert!( + err.to_string() + .contains("allow_external_blob_outside_bases"), + "got: {err}" + ); + assert_eq!(table.count_rows(None).await?, 0); + Ok(()) +} + +#[tokio::test] +async fn string_uri_input_round_trips_as_external_reference() -> Result<()> { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().join("db").to_str().unwrap()) + .execute() + .await?; + let payload: &[u8] = b"external-string-payload"; + let uri = write_payload_file_uri(tmp.path(), "payload.bin", payload); + let table = db + .create_empty_table("t", blob_table_schema()) + .execute() + .await?; + + table + .add(uri_string_batch(1, &uri)) + .allow_external_blob_outside_bases(true) + .execute() + .await?; + + let ids = collect_row_ids(&table).await?; + let bytes = table.fetch_blobs("image", &ids).await?; + assert_eq!(bytes.value(0), payload); + + let files = table.fetch_blob_files("image", &ids).await?; + let file = files[0].as_ref().expect("missing blob file"); + assert_eq!(file.uri(), Some(uri.as_str())); + Ok(()) +} + +#[tokio::test] +async fn string_uri_inside_registered_base_does_not_need_the_flag() -> Result<()> { + let tmp = tempdir().unwrap(); + let db_path = tmp.path().join("db"); + let external_base = tmp.path().join("external_base"); + let object_dir = external_base.join("objects"); + std::fs::create_dir_all(&object_dir).unwrap(); + let payload: &[u8] = b"mapped-in-base"; + let object_path = object_dir.join("mapped.bin"); + std::fs::write(&object_path, payload).unwrap(); + let object_uri = url::Url::from_file_path(&object_path).unwrap().to_string(); + let base_uri = url::Url::from_file_path(&external_base) + .unwrap() + .to_string(); + + let db = connect(db_path.to_str().unwrap()).execute().await?; + let table = db + .create_empty_table("t", blob_table_schema()) + .write_options(WriteOptions { + lance_write_params: Some(WriteParams { + initial_bases: Some(vec![BasePath { + id: 1, + name: Some("external".to_string()), + path: base_uri, + is_dataset_root: false, + }]), + ..Default::default() + }), + }) + .execute() + .await?; + + table + .add(uri_string_batch(1, &object_uri)) + .execute() + .await?; + + let ids = collect_row_ids(&table).await?; + let bytes = table.fetch_blobs("image", &ids).await?; + assert_eq!(bytes.value(0), payload); + Ok(()) +} + +#[tokio::test] +async fn external_uri_rows_mix_with_inline_rows() -> Result<()> { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().join("db").to_str().unwrap()) + .execute() + .await?; + let external_payload: &[u8] = b"external-bytes"; + let uri = write_payload_file_uri(tmp.path(), "payload.bin", external_payload); + let table = + create_inline_blob_table(&db, "t", &[1], &[Some(b"inline-bytes".as_slice())]).await?; + + table + .add(uri_string_batch(2, &uri)) + .allow_external_blob_outside_bases(true) + .execute() + .await?; + + let pairs = collect_id_rowid(&table).await?; + let row_ids: Vec = pairs.iter().map(|(_, r)| *r).collect(); + let bytes = table.fetch_blobs("image", &row_ids).await?; + for (i, (id, _)) in pairs.iter().enumerate() { + match id { + 1 => assert_eq!(bytes.value(i), b"inline-bytes"), + 2 => assert_eq!(bytes.value(i), external_payload), + _ => unreachable!(), + } + } + Ok(()) +} + +#[tokio::test] +async fn malformed_string_uri_is_rejected_at_write() -> Result<()> { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().join("db").to_str().unwrap()) + .execute() + .await?; + let table = db + .create_empty_table("t", blob_table_schema()) + .execute() + .await?; + + let err = table + .add(uri_string_batch(1, "not a uri")) + .allow_external_blob_outside_bases(true) + .execute() + .await + .unwrap_err(); + + assert!(err.to_string().contains("not a uri"), "got: {err}"); + assert_eq!(table.count_rows(None).await?, 0); + Ok(()) +} From a57fb68891a081aac6e6466f772ff50b21445172 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Wed, 26 Aug 2026 00:31:14 +0800 Subject: [PATCH 118/206] docs(python): fix Azure storage options examples (#3899) ## Summary - document that Azure Blob Storage credentials can be passed directly through `storage_options` - provide valid quoted `account_name` and `account_key` examples for both sync and async Python connections - execute the option dictionaries during doctests so the original unquoted-key mistake is caught ## Root cause The historical Python storage guide used `account_name` and `account_key` as bare identifiers in dictionary literals. Following that example either raised `NameError` or, when those names were predefined, produced incorrect option keys. The runtime already accepts direct Azure credentials, but the current Python API reference did not contain a corrected Azure example. ## Validation - `python/.venv/bin/ruff format --check python/python/lancedb/__init__.py` - `python/.venv/bin/ruff check .` - `cd python && uv run --no-sync pytest --doctest-modules python/lancedb/__init__.py -q` - `cd python && uv run --no-sync pytest python/tests/test_import.py -q` Fixes #2236 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- python/python/lancedb/__init__.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index df8950686..8cb85a3ed 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -179,6 +179,18 @@ def connect( ... }, ... ) + For Azure Blob Storage, credentials can be passed directly without setting + environment variables: + + >>> azure_storage_options = { + ... "account_name": "some-account", + ... "account_key": "some-key", + ... } + >>> db = lancedb.connect( # doctest: +SKIP + ... "az://my-container/my-database", + ... storage_options=azure_storage_options, + ... ) + For tests and temporary data, use an in-memory database: >>> db = lancedb.connect("memory://") @@ -465,6 +477,10 @@ async def connect_async( -------- >>> import lancedb + >>> azure_storage_options = { + ... "account_name": "some-account", + ... "account_key": "some-key", + ... } >>> async def doctest_example(): ... # For a local directory, provide a path to the database ... db = await lancedb.connect_async("~/.lancedb") @@ -472,6 +488,11 @@ async def connect_async( ... db = await lancedb.connect_async("s3://my-bucket/lancedb", ... storage_options={ ... "aws_access_key_id": "***"}) + ... # Azure credentials can also be passed directly + ... db = await lancedb.connect_async( + ... "az://my-container/my-database", + ... storage_options=azure_storage_options, + ... ) ... # For tests and temporary data, use an in-memory database ... db = await lancedb.connect_async("memory://") ... # Connect to LanceDB cloud From 35b5d015ac8a38313d8322c26f4b2f86ef6f4e23 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Wed, 26 Aug 2026 04:17:32 +0800 Subject: [PATCH 119/206] fix(node): preserve embedding registration in server bundles (#3806) ## Summary - lazily initialize built-in OpenAI and Hugging Face providers when consumers call the public embedding registry API - choose automatic vector versus FTS search from embedding metadata on a fresh pinned table revision for every execution - expose automatic string searches as an `AutoQuery` with only operations common to both native query families - keep the registry shared and built-in registration safe across duplicated module graphs ## Root cause Nitro treats dependency modules as side-effect-free and removes the bare OpenAI provider import from its generated route. Registration therefore never runs, so `getRegistry().get("openai")` remains undefined even when the registry itself is shared globally. Bundlers may also duplicate the provider and registry module graphs. The public embedding entry point now initializes built-in providers only when `getRegistry()` is explicitly called, keeping initialization on a live path that Nitro retains. Each terminal automatic-search execution pins the exact table revision visible at dispatch, reads embedding metadata and computes an embedding from that snapshot, replays the builder operations, and constructs and executes the selected native query against the same snapshot. Pinned native snapshots execute locally when namespace pushdown cannot carry their revision, while remote snapshots are seeded directly from one version-and-schema response. The public `AutoQuery` builder exposes only the operations shared by FTS and vector search, so runtime class narrowing cannot expose invalid vector-only methods. Repeated built-in registration replaces stale constructors from duplicated module graphs while public `register()` retains its duplicate-alias error. ## Validation - `cargo fmt --all` - `cargo check --quiet --features remote --tests --examples` - `cargo clippy --quiet --features remote --tests --examples` - `pnpm build` - `pnpm lint` - `pnpm run docs` - `pnpm test --runInBand` (783 passed, 5 skipped) - serial examples suite with a local OpenAI mock (11 passed), including `sentence-transformers.test.ts` - packaged Nitro 2.13.4 server route using the reported imports returned `{"registered":true}` - fresh-process FTS fixture initialized both public built-ins and confirmed automatic string search still returned the indexed row - schema-consistency regressions cover read-consistency refresh, checkout, checkoutLatest, restore, runtime class narrowing, concurrent overwrite during embedding computation, and reused automatic-search builders - focused regressions confirm pinned native snapshots bypass unversioned namespace pushdown and remote snapshots use one describe request Fixes #2429 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- docs/src/js/classes/AutoQuery.md | 518 ++++++++++++++++++ docs/src/js/classes/Table.md | 4 +- docs/src/js/globals.md | 1 + .../embedding/functions/getRegistry.md | 14 +- nodejs/__test__/embedding_registry.test.ts | 95 ++++ nodejs/__test__/fixtures/auto_fts_search.cjs | 33 ++ nodejs/__test__/table.test.ts | 191 +++++++ nodejs/lancedb/embedding/index.ts | 44 +- nodejs/lancedb/embedding/openai.ts | 5 +- nodejs/lancedb/embedding/registry.ts | 60 +- nodejs/lancedb/embedding/transformers.ts | 5 +- nodejs/lancedb/index.ts | 1 + nodejs/lancedb/query.ts | 139 +++-- nodejs/lancedb/table.ts | 44 +- nodejs/src/table.rs | 6 + rust/lancedb/src/remote/table.rs | 38 ++ rust/lancedb/src/table.rs | 32 ++ rust/lancedb/src/table/query.rs | 49 +- 18 files changed, 1211 insertions(+), 68 deletions(-) create mode 100644 docs/src/js/classes/AutoQuery.md create mode 100644 nodejs/__test__/embedding_registry.test.ts create mode 100644 nodejs/__test__/fixtures/auto_fts_search.cjs diff --git a/docs/src/js/classes/AutoQuery.md b/docs/src/js/classes/AutoQuery.md new file mode 100644 index 000000000..1d7ea6952 --- /dev/null +++ b/docs/src/js/classes/AutoQuery.md @@ -0,0 +1,518 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / AutoQuery + +# Class: AutoQuery + +A builder for automatic string searches. + +Automatic search determines whether to use full-text or vector search from +the table revision selected for each execution. This builder exposes the +common operations supported by both query families. + +## Extends + +- `StandardQueryBase`<`NativeQuery` \| `NativeVectorQuery`> + +## Properties + +### inner + +```ts +protected inner: Query | VectorQuery | Promise; +``` + +#### Inherited from + +`StandardQueryBase.inner` + +## Methods + +### analyzePlan() + +```ts +analyzePlan(distributedMetrics?): Promise +``` + +Executes the query and returns the physical query plan annotated with runtime metrics. + +This is useful for debugging and performance analysis, as it shows how the query was executed +and includes metrics such as elapsed time, rows processed, and I/O statistics. + +#### Parameters + +* **distributedMetrics?**: [`AnalyzePlanDistributedMetrics`](../type-aliases/AnalyzePlanDistributedMetrics.md) + How distributed worker metrics are displayed for remote query plans. + Defaults to `"aggregate"`. + +#### Returns + +`Promise`<`string`> + +A query execution plan with runtime metrics for each step. + +#### Example + +```ts +import * as lancedb from "@lancedb/lancedb" + +const db = await lancedb.connect("./.lancedb"); +const table = await db.createTable("my_table", [ + { vector: [1.1, 0.9], id: "1" }, +]); + +const plan = await table.query().nearestTo([0.5, 0.2]).analyzePlan(); + +Example output (with runtime metrics inlined): +AnalyzeExec verbose=true, metrics=[] + ProjectionExec: expr=[id@3 as id, vector@0 as vector, _distance@2 as _distance], metrics=[output_rows=1, elapsed_compute=3.292µs] + Take: columns="vector, _rowid, _distance, (id)", metrics=[output_rows=1, elapsed_compute=66.001µs, batches_processed=1, bytes_read=8, iops=1, requests=1] + CoalesceBatchesExec: target_batch_size=1024, metrics=[output_rows=1, elapsed_compute=3.333µs] + GlobalLimitExec: skip=0, fetch=10, metrics=[output_rows=1, elapsed_compute=167ns] + FilterExec: _distance@2 IS NOT NULL, metrics=[output_rows=1, elapsed_compute=8.542µs] + SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST], metrics=[output_rows=1, elapsed_compute=63.25µs, row_replacements=1] + KNNVectorDistance: metric=l2, metrics=[output_rows=1, elapsed_compute=114.333µs, output_batches=1] + LanceScan: uri=/path/to/data, projection=[vector], row_id=true, row_addr=false, ordered=false, metrics=[output_rows=1, elapsed_compute=103.626µs, bytes_read=549, iops=2, requests=2] +``` + +#### Inherited from + +`StandardQueryBase.analyzePlan` + +*** + +### execute() + +```ts +protected execute(options?): AsyncGenerator, void, unknown> +``` + +Execute the query and return the results as an + +#### Parameters + +* **options?**: `Partial`<[`QueryExecutionOptions`](../interfaces/QueryExecutionOptions.md)> + +#### Returns + +`AsyncGenerator`<`RecordBatch`<`any`>, `void`, `unknown`> + +#### See + + - AsyncIterator +of + - RecordBatch. + +By default, LanceDb will use many threads to calculate results and, when +the result set is large, multiple batches will be processed at one time. +This readahead is limited however and backpressure will be applied if this +stream is consumed slowly (this constrains the maximum memory used by a +single query) + +#### Inherited from + +`StandardQueryBase.execute` + +*** + +### explainPlan() + +```ts +explainPlan(verbose): Promise +``` + +Generates an explanation of the query execution plan. + +#### Parameters + +* **verbose**: `boolean` = `false` + If true, provides a more detailed explanation. Defaults to false. + +#### Returns + +`Promise`<`string`> + +A Promise that resolves to a string containing the query execution plan explanation. + +#### Example + +```ts +import * as lancedb from "@lancedb/lancedb" +const db = await lancedb.connect("./.lancedb"); +const table = await db.createTable("my_table", [ + { vector: [1.1, 0.9], id: "1" }, +]); +const plan = await table.query().nearestTo([0.5, 0.2]).explainPlan(); +``` + +#### Inherited from + +`StandardQueryBase.explainPlan` + +*** + +### fastSearch() + +```ts +fastSearch(): this +``` + +Skip searching un-indexed data. This can make search faster, but will miss +any data that is not yet indexed. + +Use [Table#optimize](Table.md#optimize) to index all un-indexed data. + +#### Returns + +`this` + +#### Inherited from + +`StandardQueryBase.fastSearch` + +*** + +### ~~filter()~~ + +```ts +filter(predicate): this +``` + +A filter statement to be applied to this query. + +#### Parameters + +* **predicate**: `string` + +#### Returns + +`this` + +#### See + +where + +#### Deprecated + +Use `where` instead + +#### Inherited from + +`StandardQueryBase.filter` + +*** + +### fullTextSearch() + +```ts +fullTextSearch(query, options?): this +``` + +#### Parameters + +* **query**: `string` \| [`FullTextQuery`](../interfaces/FullTextQuery.md) + +* **options?**: `Partial`<[`FullTextSearchOptions`](../interfaces/FullTextSearchOptions.md)> + +#### Returns + +`this` + +#### Inherited from + +`StandardQueryBase.fullTextSearch` + +*** + +### limit() + +```ts +limit(limit): this +``` + +Set the maximum number of results to return. + +By default, a plain search has no limit. If this method is not +called then every valid row from the table will be returned. + +#### Parameters + +* **limit**: `number` + +#### Returns + +`this` + +#### Inherited from + +`StandardQueryBase.limit` + +*** + +### offset() + +```ts +offset(offset): this +``` + +Set the number of rows to skip before returning results. + +This is useful for pagination. + +#### Parameters + +* **offset**: `number` + +#### Returns + +`this` + +#### Inherited from + +`StandardQueryBase.offset` + +*** + +### orderBy() + +```ts +orderBy(ordering): this +``` + +Sort the results by the specified column(s). + +#### Parameters + +* **ordering**: [`ColumnOrdering`](../interfaces/ColumnOrdering.md) \| [`ColumnOrdering`](../interfaces/ColumnOrdering.md)[] + +#### Returns + +`this` + +This query builder. + +#### Inherited from + +`StandardQueryBase.orderBy` + +*** + +### outputSchema() + +```ts +outputSchema(): Promise> +``` + +Returns the schema of the output that will be returned by this query. + +This can be used to inspect the types and names of the columns that will be +returned by the query before executing it. + +#### Returns + +`Promise`<`Schema`<`any`>> + +An Arrow Schema describing the output columns. + +#### Inherited from + +`StandardQueryBase.outputSchema` + +*** + +### select() + +```ts +select(columns): this +``` + +Return only the specified columns. + +By default a query will return all columns from the table. However, this can have +a very significant impact on latency. LanceDb stores data in a columnar fashion. This +means we can finely tune our I/O to select exactly the columns we need. + +As a best practice you should always limit queries to the columns that you need. If you +pass in an array of column names then only those columns will be returned. + +You can also use this method to create new "dynamic" columns based on your existing columns. +For example, you may not care about "a" or "b" but instead simply want "a + b". This is often +seen in the SELECT clause of an SQL query (e.g. `SELECT a+b FROM my_table`). + +To create dynamic columns you can pass in a Map. A column will be returned +for each entry in the map. The key provides the name of the column. The value is +an SQL string used to specify how the column is calculated. + +For example, an SQL query might state `SELECT a + b AS combined, c`. The equivalent +input to this method would be: + +#### Parameters + +* **columns**: `string` \| `string`[] \| `Record`<`string`, `string`> \| `Map`<`string`, `string`> + +#### Returns + +`this` + +#### Example + +```ts +new Map([["combined", "a + b"], ["c", "c"]]) + +Columns will always be returned in the order given, even if that order is different than +the order used when adding the data. + +Note that you can pass in a `Record` (e.g. an object literal). This method +uses `Object.entries` which should preserve the insertion order of the object. However, +object insertion order is easy to get wrong and `Map` is more foolproof. +``` + +#### Inherited from + +`StandardQueryBase.select` + +*** + +### toArray() + +```ts +toArray(options?): Promise +``` + +Collect the results as an array of objects. + +#### Parameters + +* **options?**: `Partial`<[`QueryExecutionOptions`](../interfaces/QueryExecutionOptions.md)> + +#### Returns + +`Promise`<`any`[]> + +#### Inherited from + +`StandardQueryBase.toArray` + +*** + +### toArrow() + +```ts +toArrow(options?): Promise> +``` + +Collect the results as an Arrow + +#### Parameters + +* **options?**: `Partial`<[`QueryExecutionOptions`](../interfaces/QueryExecutionOptions.md)> + +#### Returns + +`Promise`<`Table`<`any`>> + +#### See + +ArrowTable. + +#### Inherited from + +`StandardQueryBase.toArrow` + +*** + +### useLsm() + +```ts +useLsm(enable): this +``` + +Control MemWAL read routing for this query. + +By default (unset), when the table carries a MemWAL write spec (see +[Table#setLsmWriteSpec](Table.md#setlsmwritespec)), reads are routed through the LSM scanner so +they also return data written via the `mergeInsert` LSM path that has not yet +been compacted into the base table (the active/frozen in-memory memtables and +the flushed generations), deduplicated by primary key; a table without a spec +reads the base table. + +#### Parameters + +* **enable**: `boolean` + `true` forces the LSM scanner and errors if the table has no + MemWAL write spec. `false` bypasses the MemWAL and reads the base table only, + even when a spec is present. + Note: the LSM scanner does not support every query shape (e.g. reranking, + hybrid search, `orderBy`). On a MemWAL table those shapes error unless + `useLsm(false)` is set, because a base-only read would silently exclude + un-compacted MemWAL data. + +#### Returns + +`this` + +#### Inherited from + +`StandardQueryBase.useLsm` + +*** + +### where() + +```ts +where(predicate): this +``` + +A filter statement to be applied to this query. + +The filter should be supplied as an SQL query string. For example: + +#### Parameters + +* **predicate**: `string` + +#### Returns + +`this` + +#### Example + +```ts +x > 10 +y > 0 AND y < 100 +x > 5 OR y = 'test' + +Filtering performance can often be improved by creating a scalar index +on the filter column(s). + +Calling this multiple times combines the filters with a logical AND rather +than replacing the previous filter. +``` + +#### Inherited from + +`StandardQueryBase.where` + +*** + +### withRowId() + +```ts +withRowId(): this +``` + +Whether to return the row id in the results. + +This column can be used to match results between different queries. For +example, to match results from a full text search and a vector search in +order to perform hybrid search. + +#### Returns + +`this` + +#### Inherited from + +`StandardQueryBase.withRowId` diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 06dc8479e..9a85d0d96 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -942,7 +942,7 @@ Get the schema of the table. abstract search( query, queryType?, - ftsColumns?): Query | VectorQuery + ftsColumns?): Query | VectorQuery | AutoQuery ``` Create a search query to find the nearest neighbors @@ -964,7 +964,7 @@ of the given query #### Returns -[`Query`](Query.md) \| [`VectorQuery`](VectorQuery.md) +[`Query`](Query.md) \| [`VectorQuery`](VectorQuery.md) \| [`AutoQuery`](AutoQuery.md) *** diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index e0635ab65..beb9cbeff 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -18,6 +18,7 @@ ## Classes +- [AutoQuery](classes/AutoQuery.md) - [BooleanQuery](classes/BooleanQuery.md) - [BoostQuery](classes/BoostQuery.md) - [BranchContents](classes/BranchContents.md) diff --git a/docs/src/js/namespaces/embedding/functions/getRegistry.md b/docs/src/js/namespaces/embedding/functions/getRegistry.md index 331dbd60b..b149a4a88 100644 --- a/docs/src/js/namespaces/embedding/functions/getRegistry.md +++ b/docs/src/js/namespaces/embedding/functions/getRegistry.md @@ -10,16 +10,12 @@ function getRegistry(): EmbeddingFunctionRegistry ``` -Utility function to get the global instance of the registry +Get the global embedding function registry. + +LanceDB built-in providers are initialized when this public API is first +used, so importing the root package does not change automatic search +selection for tables without embedding metadata. ## Returns [`EmbeddingFunctionRegistry`](../classes/EmbeddingFunctionRegistry.md) - -`EmbeddingFunctionRegistry` The global instance of the registry - -## Example - -```ts -const registry = getRegistry(); -const openai = registry.get("openai").create(); diff --git a/nodejs/__test__/embedding_registry.test.ts b/nodejs/__test__/embedding_registry.test.ts new file mode 100644 index 000000000..83933399a --- /dev/null +++ b/nodejs/__test__/embedding_registry.test.ts @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { execFileSync } from "node:child_process"; +import { resolve } from "node:path"; + +import type { OpenAIEmbeddingFunction } from "../lancedb/embedding/openai"; +import type { EmbeddingFunctionRegistry } from "../lancedb/embedding/registry"; + +type EmbeddingModule = typeof import("../lancedb/embedding"); +type OpenAIModule = typeof import("../lancedb/embedding/openai"); +type RegistryModule = typeof import("../lancedb/embedding/registry"); + +describe("embedding function registry", () => { + const registries: EmbeddingFunctionRegistry[] = []; + + afterEach(() => { + for (const registry of registries) { + registry.reset(); + } + registries.length = 0; + }); + + it("defers built-in providers until the public registry API is used", () => { + jest.isolateModules(() => { + const embedding = require("../lancedb/embedding") as EmbeddingModule; + const { getRegistry: getInternalRegistry } = + require("../lancedb/embedding/registry") as RegistryModule; + const registry = getInternalRegistry(); + registries.push(registry); + + expect(registry.length()).toBe(0); + expect(embedding.getRegistry()).toBe(registry); + expect(registry.get("openai")).toBeDefined(); + expect(registry.get("huggingface")).toBeDefined(); + }); + }); + + it("preserves automatic FTS search in a fresh process", () => { + execFileSync( + process.execPath, + [resolve(__dirname, "fixtures", "auto_fts_search.cjs")], + { stdio: "pipe" }, + ); + }); + + it("shares registrations across duplicated provider module graphs", () => { + let registeringRegistry: EmbeddingFunctionRegistry | undefined; + let latestOpenAIConstructor: typeof OpenAIEmbeddingFunction | undefined; + + jest.isolateModules(() => { + require("../lancedb/embedding/openai"); + const { getRegistry } = + require("../lancedb/embedding/registry") as RegistryModule; + registeringRegistry = getRegistry(); + registries.push(registeringRegistry); + expect(registeringRegistry.get("openai")).toBeDefined(); + }); + + expect(() => { + jest.isolateModules(() => { + const { OpenAIEmbeddingFunction } = + require("../lancedb/embedding/openai") as OpenAIModule; + latestOpenAIConstructor = OpenAIEmbeddingFunction; + const { getRegistry } = + require("../lancedb/embedding/registry") as RegistryModule; + registries.push(getRegistry()); + }); + }).not.toThrow(); + + const previousApiKey = process.env.OPENAI_API_KEY; + process.env.OPENAI_API_KEY = "test"; + try { + const latestOpenAI = registeringRegistry! + .get("openai")! + .create(); + expect(latestOpenAI).toBeInstanceOf(latestOpenAIConstructor!); + } finally { + if (previousApiKey === undefined) { + delete process.env.OPENAI_API_KEY; + } else { + process.env.OPENAI_API_KEY = previousApiKey; + } + } + + jest.isolateModules(() => { + const { getRegistry } = + require("../lancedb/embedding") as EmbeddingModule; + const publicRegistry = getRegistry(); + registries.push(publicRegistry); + expect(publicRegistry).toBe(registeringRegistry); + expect(publicRegistry.get("openai")).toBeDefined(); + }); + }); +}); diff --git a/nodejs/__test__/fixtures/auto_fts_search.cjs b/nodejs/__test__/fixtures/auto_fts_search.cjs new file mode 100644 index 000000000..b5ab060b3 --- /dev/null +++ b/nodejs/__test__/fixtures/auto_fts_search.cjs @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +const assert = require("node:assert/strict"); +const tmp = require("tmp"); +const { connect, embedding, Index } = require("../../dist"); +const { getRegistry } = require("../../dist/embedding/registry"); + +async function main() { + assert.equal(typeof embedding.getRegistry, "function"); + assert.equal(getRegistry().length(), 0); + assert.equal(embedding.getRegistry(), getRegistry()); + assert.equal(getRegistry().length(), 2); + + const dir = tmp.dirSync({ unsafeCleanup: true }); + let db; + try { + db = await connect(dir.name); + const table = await db.createTable("docs", [{ text: "hello world" }]); + await table.createIndex("text", { config: Index.fts() }); + + const rows = await table.search("hello").toArray(); + assert.equal(rows[0].text, "hello world"); + } finally { + db?.close(); + dir.removeCallback(); + } +} + +main().catch((error) => { + console.error(error); + process.exitCode = 1; +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 0f6ed3615..0aee5caf0 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -11,10 +11,13 @@ import * as arrow17 from "apache-arrow-17"; import * as arrow18 from "apache-arrow-18"; import { + AutoQuery, Connection, MatchQuery, PhraseQuery, + Query, Table, + VectorQuery, connect, tokenize, } from "../lancedb"; @@ -1777,6 +1780,194 @@ describe("Read consistency interval", () => { }); }); +describe("automatic search schema consistency", () => { + let tmpDir: tmp.DirResult; + + class SchemaRefreshEmbedding extends EmbeddingFunction { + ndims() { + return 2; + } + + embeddingDataType() { + return new Float32(); + } + + async computeSourceEmbeddings(data: string[]) { + return data.map((value) => [value.length, 1]); + } + + async computeQueryEmbeddings(value: string) { + return [value.length, 1]; + } + } + + function embeddingSchema() { + const func = new SchemaRefreshEmbedding(); + return LanceSchema({ + text: func.sourceField(new Utf8()), + vector: func.vectorField(), + }); + } + + beforeEach(() => { + getRegistry().reset(); + register("schema-refresh")(SchemaRefreshEmbedding); + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + }); + + afterEach(() => { + getRegistry().reset(); + tmpDir.removeCallback(); + }); + + it("uses the schema refreshed from another connection", async () => { + const first = await connect(tmpDir.name, { readConsistencyInterval: 0 }); + const second = await connect(tmpDir.name, { readConsistencyInterval: 0 }); + + try { + const stale = await first.createTable("docs", [{ text: "before" }], { + schema: embeddingSchema(), + }); + const replacement = await second.createTable( + "docs", + [{ text: "after hello" }], + { mode: "overwrite" }, + ); + await replacement.createIndex("text", { config: Index.fts() }); + + const search = stale.search("hello"); + expect(search).toBeInstanceOf(AutoQuery); + expect(search).not.toBeInstanceOf(Query); + expect(search).not.toBeInstanceOf(VectorQuery); + expect("nprobes" in search).toBe(false); + + const rows = await search.toArray(); + expect(rows[0].text).toBe("after hello"); + expect((await stale.schema()).metadata.has("embedding_functions")).toBe( + false, + ); + } finally { + first.close(); + second.close(); + } + }); + + it("tracks embedding metadata across checkout and restore", async () => { + const first = await connect(tmpDir.name, { readConsistencyInterval: 0 }); + const second = await connect(tmpDir.name, { readConsistencyInterval: 0 }); + + try { + await first.createTable("docs", [{ text: "before" }], { + schema: embeddingSchema(), + }); + const table = await second.createTable( + "docs", + [{ text: "after hello" }], + { mode: "overwrite" }, + ); + await table.createIndex("text", { config: Index.fts() }); + + await table.checkout(1); + expect((await table.search("before").toArray())[0].text).toBe("before"); + + await table.checkoutLatest(); + expect((await table.search("hello").toArray())[0].text).toBe( + "after hello", + ); + + await table.checkout(1); + await table.restore(); + expect((await table.search("before").toArray())[0].text).toBe("before"); + } finally { + first.close(); + second.close(); + } + }); + + it("pins automatic search while computing an embedding", async () => { + let markStarted!: () => void; + let releaseEmbedding!: () => void; + const started = new Promise((resolve) => { + markStarted = resolve; + }); + const released = new Promise((resolve) => { + releaseEmbedding = resolve; + }); + + class BlockingEmbedding extends SchemaRefreshEmbedding { + async computeQueryEmbeddings(value: string) { + markStarted(); + await released; + return [value.length, 1]; + } + } + + register("schema-refresh-blocking")(BlockingEmbedding); + const func = new BlockingEmbedding(); + const schema = LanceSchema({ + text: func.sourceField(new Utf8()), + vector: func.vectorField(), + }); + const first = await connect(tmpDir.name, { readConsistencyInterval: 0 }); + const second = await connect(tmpDir.name, { readConsistencyInterval: 0 }); + + try { + const table = await first.createTable( + "docs", + [{ text: "hello before" }], + { schema }, + ); + const pending = table.search("hello").toArray(); + await started; + + const replacement = await second.createTable( + "docs", + [{ text: "hello after" }], + { mode: "overwrite" }, + ); + await replacement.createIndex("text", { config: Index.fts() }); + releaseEmbedding(); + + expect((await pending)[0].text).toBe("hello before"); + } finally { + releaseEmbedding(); + first.close(); + second.close(); + } + }); + + it("refreshes a reused automatic search for every execution", async () => { + const first = await connect(tmpDir.name, { readConsistencyInterval: 0 }); + const second = await connect(tmpDir.name, { readConsistencyInterval: 0 }); + + try { + const table = await first.createTable("docs", [ + { text: "hello before", marker: "before" }, + ]); + await table.createIndex("text", { config: Index.fts() }); + const search = table.search("hello").select(["text"]); + + const before = (await search.toArray())[0]; + expect(before.text).toBe("hello before"); + expect(before.marker).toBeUndefined(); + + const replacement = await second.createTable( + "docs", + [{ text: "hello after", marker: "after" }], + { mode: "overwrite" }, + ); + await replacement.createIndex("text", { config: Index.fts() }); + + const after = (await search.toArray())[0]; + expect(after.text).toBe("hello after"); + expect(after.marker).toBeUndefined(); + } finally { + first.close(); + second.close(); + } + }); +}); + describe("schema evolution", function () { let tmpDir: tmp.DirResult; beforeEach(() => { diff --git a/nodejs/lancedb/embedding/index.ts b/nodejs/lancedb/embedding/index.ts index d0ffaec0d..d748e245a 100644 --- a/nodejs/lancedb/embedding/index.ts +++ b/nodejs/lancedb/embedding/index.ts @@ -4,7 +4,15 @@ import { Field, Schema } from "../arrow"; import { sanitizeType } from "../sanitize"; import { EmbeddingFunction } from "./embedding_function"; -import { EmbeddingFunctionConfig, getRegistry } from "./registry"; +import { + EmbeddingFunctionConfig, + EmbeddingFunctionRegistry, + getRegistry as getGlobalRegistry, + registerBuiltIn, +} from "./registry"; + +type OpenAIModule = typeof import("./openai"); +type TransformersModule = typeof import("./transformers"); export { FieldOptions, @@ -14,7 +22,39 @@ export { EmbeddingFunctionConstructor, } from "./embedding_function"; -export * from "./registry"; +export { + EmbeddingFunctionRegistry, + parseEmbeddingMetadata, + register, +} from "./registry"; +export type { + CreateReturnType, + EmbeddingFunctionConfig, + EmbeddingFunctionCreate, + EmbeddingMetadataEntry, + ResolvedEmbeddingFunctionConfig, +} from "./registry"; + +function initializeBuiltInProviders() { + const { OpenAIEmbeddingFunction } = require("./openai") as OpenAIModule; + const { TransformersEmbeddingFunction } = + require("./transformers") as TransformersModule; + + registerBuiltIn("openai", OpenAIEmbeddingFunction); + registerBuiltIn("huggingface", TransformersEmbeddingFunction); +} + +/** + * Get the global embedding function registry. + * + * LanceDB built-in providers are initialized when this public API is first + * used, so importing the root package does not change automatic search + * selection for tables without embedding metadata. + */ +export function getRegistry(): EmbeddingFunctionRegistry { + initializeBuiltInProviders(); + return getGlobalRegistry(); +} /** * Create a schema with embedding functions. diff --git a/nodejs/lancedb/embedding/openai.ts b/nodejs/lancedb/embedding/openai.ts index 5771cfeb5..2218d44bc 100644 --- a/nodejs/lancedb/embedding/openai.ts +++ b/nodejs/lancedb/embedding/openai.ts @@ -5,14 +5,13 @@ import type OpenAI from "openai"; import type { EmbeddingCreateParams } from "openai/resources/index"; import { Float, Float32 } from "../arrow"; import { EmbeddingFunction } from "./embedding_function"; -import { register } from "./registry"; +import { registerBuiltIn } from "./registry"; export type OpenAIOptions = { apiKey: string; model: EmbeddingCreateParams["model"]; }; -@register("openai") export class OpenAIEmbeddingFunction extends EmbeddingFunction< string, Partial @@ -100,3 +99,5 @@ export class OpenAIEmbeddingFunction extends EmbeddingFunction< return response.data[0].embedding; } } + +registerBuiltIn("openai", OpenAIEmbeddingFunction); diff --git a/nodejs/lancedb/embedding/registry.ts b/nodejs/lancedb/embedding/registry.ts index 5f32f683c..c9ee9135e 100644 --- a/nodejs/lancedb/embedding/registry.ts +++ b/nodejs/lancedb/embedding/registry.ts @@ -7,6 +7,10 @@ import { } from "./embedding_function"; import "reflect-metadata"; +const builtInFunctionsKey = Symbol.for( + "@lancedb/lancedb::embedding-built-in-functions::v1", +); + export type CreateReturnType = T extends { init: () => Promise } ? Promise : T; @@ -59,6 +63,15 @@ export class EmbeddingFunctionRegistry { }; } + /** @ignore */ + setBuiltIn< + T extends EmbeddingFunctionConstructor = EmbeddingFunctionConstructor, + >(name: string, ctor: T): T { + this.#functions.set(name, ctor); + Reflect.defineMetadata("lancedb::embedding::name", name, ctor); + return ctor; + } + get>( name: string, ): EmbeddingFunctionCreate | undefined; @@ -96,6 +109,7 @@ export class EmbeddingFunctionRegistry { */ reset(this: EmbeddingFunctionRegistry) { this.#functions.clear(); + getBuiltInFunctions(this).clear(); } /** @@ -183,12 +197,56 @@ export class EmbeddingFunctionRegistry { } } -const _REGISTRY = new EmbeddingFunctionRegistry(); +function getBuiltInFunctions(registry: EmbeddingFunctionRegistry): Set { + const registryWithBuiltIns = registry as EmbeddingFunctionRegistry & { + [key: symbol]: Set | undefined; + }; + let builtInFunctions = registryWithBuiltIns[builtInFunctionsKey]; + if (builtInFunctions === undefined) { + builtInFunctions = new Set(); + registryWithBuiltIns[builtInFunctionsKey] = builtInFunctions; + } + return builtInFunctions; +} + +// Server bundlers can load the side-effect embedding entry points and the public +// embedding API from separate module graphs. Keep their registry shared. +const registryKey = Symbol.for( + "@lancedb/lancedb::embedding-function-registry::v1", +); +const registryGlobal = globalThis as typeof globalThis & { + [key: symbol]: EmbeddingFunctionRegistry | undefined; +}; + +function getGlobalRegistry(): EmbeddingFunctionRegistry { + const existingRegistry = registryGlobal[registryKey]; + if (existingRegistry !== undefined) { + return existingRegistry; + } + const registry = new EmbeddingFunctionRegistry(); + registryGlobal[registryKey] = registry; + return registry; +} + +const _REGISTRY = getGlobalRegistry(); export function register(name?: string) { return _REGISTRY.register(name); } +/** @ignore */ +export function registerBuiltIn< + T extends EmbeddingFunctionConstructor = EmbeddingFunctionConstructor, +>(name: string, ctor: T): T { + const builtInFunctions = getBuiltInFunctions(_REGISTRY); + if (builtInFunctions.has(name)) { + return _REGISTRY.setBuiltIn(name, ctor); + } + _REGISTRY.register(name)(ctor); + builtInFunctions.add(name); + return ctor; +} + /** * Utility function to get the global instance of the registry * @returns `EmbeddingFunctionRegistry` The global instance of the registry diff --git a/nodejs/lancedb/embedding/transformers.ts b/nodejs/lancedb/embedding/transformers.ts index 161575285..06043ea7c 100644 --- a/nodejs/lancedb/embedding/transformers.ts +++ b/nodejs/lancedb/embedding/transformers.ts @@ -3,7 +3,7 @@ import { Float, Float32 } from "../arrow"; import { EmbeddingFunction } from "./embedding_function"; -import { register } from "./registry"; +import { registerBuiltIn } from "./registry"; export type XenovaTransformerOptions = { /** The wasm compatible model to use */ @@ -31,7 +31,6 @@ export type XenovaTransformerOptions = { }; }; -@register("huggingface") export class TransformersEmbeddingFunction extends EmbeddingFunction< string, Partial @@ -158,6 +157,8 @@ export class TransformersEmbeddingFunction extends EmbeddingFunction< } } +registerBuiltIn("huggingface", TransformersEmbeddingFunction); + const tensorDiv = ( src: import("@huggingface/transformers").Tensor, divBy: number, diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index ebc8cda8d..34d7ce4d9 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -103,6 +103,7 @@ export { } from "./native.js"; export { + AutoQuery, ExecutableQuery, Query, QueryBase, diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index 843a1276f..3b9b286a0 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -111,13 +111,15 @@ export class QueryBase< NativeQueryType extends NativeQuery | NativeVectorQuery | NativeTakeQuery, > implements AsyncIterable { + protected inner!: NativeQueryType | Promise; + /** * @hidden */ - protected constructor( - protected inner: NativeQueryType | Promise, - ) { - // intentionally empty + protected constructor(inner?: NativeQueryType | Promise) { + if (inner !== undefined) { + this.inner = inner; + } } // call a function on the inner (either a promise or the actual object) @@ -135,6 +137,15 @@ export class QueryBase< } } + /** + * Return the native query used by the next terminal operation. + * + * @hidden + */ + protected async getInner(): Promise { + return this.inner; + } + /** * Return only the specified columns. * @@ -207,16 +218,11 @@ export class QueryBase< /** * @hidden */ - protected nativeExecute( + protected async nativeExecute( options?: Partial, ): Promise { - if (this.inner instanceof Promise) { - return this.inner.then((inner) => - inner.execute(options?.maxBatchLength, options?.timeoutMs), - ); - } else { - return this.inner.execute(options?.maxBatchLength, options?.timeoutMs); - } + const inner = await this.getInner(); + return inner.execute(options?.maxBatchLength, options?.timeoutMs); } /** @@ -245,12 +251,7 @@ export class QueryBase< /** Collect the results as an Arrow @see {@link ArrowTable}. */ async toArrow(options?: Partial): Promise { const batches = []; - let inner; - if (this.inner instanceof Promise) { - inner = await this.inner; - } else { - inner = this.inner; - } + const inner = await this.getInner(); for await (const batch of new RecordBatchIterable(inner, options)) { batches.push(batch); } @@ -279,11 +280,8 @@ export class QueryBase< * @returns A Promise that resolves to a string containing the query execution plan explanation. */ async explainPlan(verbose = false): Promise { - if (this.inner instanceof Promise) { - return this.inner.then((inner) => inner.explainPlan(verbose)); - } else { - return this.inner.explainPlan(verbose); - } + const inner = await this.getInner(); + return inner.explainPlan(verbose); } /** @@ -321,13 +319,8 @@ export class QueryBase< distributedMetrics?: AnalyzePlanDistributedMetrics, ): Promise { const distributedMetricsMode = distributedMetrics ?? "aggregate"; - if (this.inner instanceof Promise) { - return this.inner.then((inner) => - inner.analyzePlan(distributedMetricsMode), - ); - } else { - return this.inner.analyzePlan(distributedMetricsMode); - } + const inner = await this.getInner(); + return inner.analyzePlan(distributedMetricsMode); } /** @@ -339,12 +332,8 @@ export class QueryBase< * @returns An Arrow Schema describing the output columns. */ async outputSchema(): Promise { - let schemaBuffer: Buffer; - if (this.inner instanceof Promise) { - schemaBuffer = await this.inner.then((inner) => inner.outputSchema()); - } else { - schemaBuffer = await this.inner.outputSchema(); - } + const inner = await this.getInner(); + const schemaBuffer = await inner.outputSchema(); const schema = tableFromIPC(schemaBuffer).schema; return schema; } @@ -356,7 +345,7 @@ export class StandardQueryBase< extends QueryBase implements ExecutableQuery { - constructor(inner: NativeQueryType | Promise) { + constructor(inner?: NativeQueryType | Promise) { super(inner); } @@ -788,6 +777,51 @@ export class TakeQuery extends QueryBase { } } +/** + * A builder for automatic string searches. + * + * Automatic search determines whether to use full-text or vector search from + * the table revision selected for each execution. This builder exposes the + * common operations supported by both query families. + * + * @hideconstructor + */ +export class AutoQuery extends StandardQueryBase< + NativeQuery | NativeVectorQuery +> { + private readonly calls: Array< + (inner: NativeQuery | NativeVectorQuery) => void + > = []; + + /** @hidden */ + constructor( + private readonly createInner: () => Promise< + NativeQuery | NativeVectorQuery + >, + ) { + super(); + } + + /** @hidden */ + protected override doCall( + fn: (inner: NativeQuery | NativeVectorQuery) => void, + ) { + this.calls.push(fn); + } + + /** @hidden */ + protected override async getInner(): Promise< + NativeQuery | NativeVectorQuery + > { + const calls = [...this.calls]; + const inner = await this.createInner(); + for (const call of calls) { + call(inner); + } + return inner; + } +} + /** A builder for LanceDB queries. * * @see {@link Table#query}, {@link Table#search} @@ -802,6 +836,37 @@ export class Query extends StandardQueryBase { super(tbl.query()); } + /** @hidden */ + static autoSearch( + tbl: () => Promise, + query: string, + vector: (tbl: NativeTable) => Promise | undefined>, + columns?: string[], + ): AutoQuery { + const nativeQuery = async () => { + const snapshot = await Promise.resolve(tbl()); + const resolved = await vector(snapshot); + const inner = snapshot.query(); + if (resolved === undefined) { + inner.fullTextSearch({ + query, + columns: columns ?? null, + }); + return inner; + } + + const raw = Array.isArray(resolved) + ? null + : extractVectorBuffer(resolved); + if (raw) { + return inner.nearestToRaw(raw.data, raw.dtype); + } + return inner.nearestTo(Float32Array.from(resolved as number[])); + }; + + return new AutoQuery(nativeQuery); + } + /** * Find the nearest vectors to the given query vector. * diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 28603cca9..a4fc76ef1 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -43,6 +43,7 @@ import { Table as _NativeTable, } from "./native"; import { + AutoQuery, FullTextQuery, Query, TakeQuery, @@ -523,7 +524,7 @@ export abstract class Table { query: string | IntoVector | MultiVector | FullTextQuery, queryType?: string, ftsColumns?: string | string[], - ): VectorQuery | Query; + ): VectorQuery | Query | AutoQuery; /** * Search the table with a given query vector. * @@ -975,10 +976,11 @@ export class LocalTable extends Table { return this.inner.display(); } - private async getEmbeddingFunctions(): Promise< - Map - > { - const schema = await this.schema(); + private async getEmbeddingFunctions( + inner: _NativeTable = this.inner, + ): Promise> { + const schemaBuf = await inner.schema(); + const schema = tableFromIPC(schemaBuf).schema; const registry = getRegistry(); return registry.parseFunctions(schema.metadata); } @@ -1160,7 +1162,7 @@ export class LocalTable extends Table { query: string | IntoVector | MultiVector | FullTextQuery, queryType: string = "auto", ftsColumns?: string | string[], - ): VectorQuery | Query { + ): VectorQuery | Query | AutoQuery { if (typeof query !== "string" && !instanceOfFullTextQuery(query)) { if (queryType === "fts") { throw new Error("Cannot perform full text search on a vector query"); @@ -1175,17 +1177,35 @@ export class LocalTable extends Table { }); } - // The query type is auto or vector - // fall back to full text search if no embedding functions are defined and the query is a string - if ( - queryType === "auto" && - (getRegistry().length() === 0 || instanceOfFullTextQuery(query)) - ) { + if (queryType === "auto" && typeof query !== "string") { return this.query().fullTextSearch(query, { columns: ftsColumns, }); } + if (queryType === "auto" && typeof query === "string") { + const vector = async (snapshot: _NativeTable) => { + const functions = await this.getEmbeddingFunctions(snapshot); + // TODO: Support multiple embedding functions + const embeddingFunc: EmbeddingFunctionConfig | undefined = functions + .values() + .next().value; + if (embeddingFunc === undefined) { + return undefined; + } + return await embeddingFunc.function.computeQueryEmbeddings(query); + }; + + const columns = + typeof ftsColumns === "string" ? [ftsColumns] : ftsColumns; + return Query.autoSearch( + () => this.inner.checkoutCurrent(), + query, + vector, + columns, + ); + } + const queryPromise = this.getEmbeddingFunctions().then( async (functions) => { // TODO: Support multiple embedding functions diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 9d60b2056..ff16ac042 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -554,6 +554,12 @@ impl Table { .default_error() } + #[napi(catch_unwind)] + pub async fn checkout_current(&self) -> napi::Result { + let table = self.inner_ref()?.checkout_current().await.default_error()?; + Ok(Self::new(table)) + } + #[napi(catch_unwind)] pub async fn checkout(&self, version: i64) -> napi::Result<()> { self.inner_ref()? diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 44c92310f..77d5983eb 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -1725,6 +1725,22 @@ impl BaseTable for RemoteTable { async fn version(&self) -> Result { self.describe().await.map(|desc| desc.version) } + + async fn checkout_current(&self) -> Result> { + let description = self.describe().await?; + let TableDescription { + version, + schema, + location, + } = description; + let schema = Arc::new(arrow_schema::Schema::try_from(schema)?); + let snapshot = self.with_branch(self.branch.clone()); + *snapshot.version.write().await = Some(version); + *snapshot.location.write().await = location; + snapshot.schema_cache.seed(schema); + Ok(Arc::new(snapshot)) + } + async fn checkout(&self, version: u64) -> Result<()> { // Validate the version exists. The describe is sent without freshness // headers so a stale `min_version` from a previous write doesn't ride @@ -8739,6 +8755,28 @@ mod tests { } } + /// A pinned snapshot should reuse the version and schema returned by its + /// initial describe instead of issuing two more describe requests. + #[tokio::test] + async fn test_checkout_current_seeds_schema_from_single_describe() { + let describe_calls = Arc::new(AtomicUsize::new(0)); + let calls = describe_calls.clone(); + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/describe/"); + calls.fetch_add(1, Ordering::SeqCst); + http::Response::builder() + .status(200) + .body( + r#"{"version":42,"schema":{"fields":[{"name":"a","type":{"type":"int32"},"nullable":false}]}}"#, + ) + .unwrap() + }); + + let snapshot = table.checkout_current().await.unwrap(); + assert_eq!(snapshot.schema().await.unwrap().fields().len(), 1); + assert_eq!(describe_calls.load(Ordering::SeqCst), 1); + } + /// Test that schema cache is invalidated after checkout #[tokio::test] async fn test_schema_cache_invalidation_on_checkout() { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index efc36d260..5007a61d9 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -785,6 +785,12 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { async fn drop_columns(&self, columns: &[&str]) -> Result; /// Get the version of the table. async fn version(&self) -> Result; + /// Return a new table handle pinned to the exact revision currently visible. + async fn checkout_current(&self) -> Result> { + Err(Error::NotSupported { + message: "checkout_current is not supported on this table type".into(), + }) + } /// Checkout a specific version of the table. async fn checkout(&self, version: u64) -> Result<()>; /// Checkout a table version referenced by a tag. @@ -1944,6 +1950,20 @@ impl Table { self.inner.version().await } + /// Return a new table handle pinned to the exact revision currently visible. + /// + /// This is used when asynchronous preparation must remain consistent with + /// the revision used for a later read. + #[doc(hidden)] + pub async fn checkout_current(&self) -> Result { + let inner = self.inner.checkout_current().await?; + Ok(Self { + inner, + database: self.database.clone(), + embedding_registry: self.embedding_registry.clone(), + }) + } + /// Checks out a specific version of the Table /// /// Any read operation on the table will now access the data at the checked out version. @@ -3043,6 +3063,18 @@ impl BaseTable for NativeTable { Ok(self.dataset.get().await?.version().version) } + async fn checkout_current(&self) -> Result> { + let current = self.dataset.get().await?; + let dataset = dataset::DatasetConsistencyWrapper::new_time_travel( + current.as_ref().clone(), + self.read_consistency_interval, + ); + Ok(Arc::new(Self { + dataset, + ..self.clone() + })) + } + async fn checkout(&self, version: u64) -> Result<()> { self.dataset.as_time_travel(version).await } diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 9b81786cd..d35286c84 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -697,6 +697,7 @@ mod tests { use super::*; use crate::query::{QueryExecutionOptions, QueryRequest}; + use crate::table::BaseTable; fn fixed_size_list_array(values: Vec, dimension: i32) -> FixedSizeListArray { FixedSizeListArray::try_new_from_values(Float32Array::from(values), dimension).unwrap() @@ -889,10 +890,56 @@ mod tests { async fn query_table(&self, _request: NsQueryTableRequest) -> lance::Result { self.query_table_calls.fetch_add(1, Ordering::SeqCst); - panic!("approx_mode queries must not be pushed down to namespace query_table"); + panic!("query must not be pushed down to namespace query_table"); } } + #[tokio::test] + async fn test_execute_query_pinned_snapshot_with_namespace_pushdown_runs_locally() { + use crate::connect; + 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)])); + let batch = RecordBatch::try_new( + schema, + vec![Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5]))], + ) + .unwrap(); + let table = conn + .create_table("test_pinned_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 snapshot = native_table.checkout_current().await.unwrap(); + let snapshot = snapshot.as_any().downcast_ref::().unwrap(); + assert!(snapshot.dataset.time_travel_version().is_some()); + + let query = AnyQuery::Query(QueryRequest { + filter: Some(QueryFilter::Sql("id > 3".to_string())), + ..Default::default() + }); + let stream = execute_query(snapshot, &query, QueryExecutionOptions::default()) + .await + .unwrap(); + let batches = stream.try_collect::>().await.unwrap(); + + assert_eq!( + batches.iter().map(|batch| batch.num_rows()).sum::(), + 2 + ); + assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); + } + #[tokio::test] async fn test_execute_query_approx_mode_with_namespace_pushdown_runs_locally() { use crate::connect; From 302b21aa94317dc74cbe6601212242f54e592d8a Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Wed, 26 Aug 2026 06:42:29 +0800 Subject: [PATCH 120/206] test(node): cover nested PDF metadata queries (#3827) ## Summary - add an end-to-end Node regression matching LangChain PDFLoader metadata - verify create/query round trips rich nested `loc` and `pdf.info` fields against the currently configured Apache Arrow peer ## Root cause LanceDB v0.14 delegated nested object inference to Apache Arrow. Nested strings were dictionary-encoded with colliding dictionary IDs, so serializing query results as an IPC file failed with a dictionary-replacement error. Current `main` recursively infers nested fields and avoids those invalid dictionaries, but the reported LangChain path had no end-to-end regression coverage. ## Validation - `pnpm build` - `pnpm lint` - `pnpm run docs` - `pnpm test --runInBand` (678 passed, 5 skipped) Fixes #1963 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- nodejs/__test__/table.test.ts | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 0aee5caf0..aaa144f16 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -685,6 +685,56 @@ describe.each([arrow15, arrow16, arrow17, arrow18])( }, ); +// https://github.com/lancedb/lancedb/issues/1963 +it("should query documents with LangChain PDF metadata", async () => { + const tmpDir = tmp.dirSync({ unsafeCleanup: true }); + try { + const db = await connect(tmpDir.name); + const documents = [ + { + text: "first page", + vector: [1, 0], + source: "first.pdf", + loc: { pageNumber: 1, lines: { from: 1, to: 12 } }, + pdf: { + version: "1.10.100", + info: { + format: "PDF 1.7", + producer: "pdf.js", + creator: "Writer", + }, + totalPages: 2, + }, + }, + { + text: "second page", + vector: [0, 1], + source: "second.pdf", + loc: { pageNumber: 2, lines: { from: 13, to: 24 } }, + pdf: { + version: "1.10.100", + info: { + format: "PDF 1.7", + producer: "pdf.js", + creator: "Writer", + }, + totalPages: 2, + }, + }, + ]; + const documentsTable = await db.createTable("documents", documents); + + const results = await documentsTable.query().toArray(); + + expect(results).toHaveLength(2); + expect(results[0].source).toBe("first.pdf"); + expect(results[0].pdf.info.producer).toBe("pdf.js"); + expect(results[1].loc.pageNumber).toBe(2); + } finally { + tmpDir.removeCallback(); + } +}); + describe("merge insert", () => { let tmpDir: tmp.DirResult; let table: Table; From 8083232dd57c556a8b45bd82e8fa0d85e5be26bb Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Tue, 25 Aug 2026 16:49:17 -0700 Subject: [PATCH 121/206] chore: update lance dependency to v12.0.0-beta.1 (#4055) Updates the Lance Rust workspace dependencies and Java lance-core dependency to [v12.0.0-beta.1](https://github.com/lance-format/lance/releases/tag/v12.0.0-beta.1). Includes compatibility updates for the renamed shard-manifest API and paginated object-store wrappers. --- Cargo.lock | 84 +++++++++---------- Cargo.toml | 28 +++---- java/pom.xml | 2 +- rust/lancedb/src/io/object_store.rs | 10 ++- .../src/io/object_store/io_tracking.rs | 10 ++- rust/lancedb/src/table.rs | 16 ++++ rust/lancedb/src/table/query/lsm.rs | 2 +- 7 files changed, 92 insertions(+), 60 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 33e43f9fa..63ee13e78 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow", "arrow-array", @@ -5013,8 +5013,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow", "arrow-array", @@ -5031,8 +5031,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "proc-macro2", "quote", @@ -5041,8 +5041,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow-arith", "arrow-array", @@ -5075,8 +5075,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow-arith", "arrow-array", @@ -5107,8 +5107,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arc-swap", "arrow", @@ -5172,8 +5172,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow-array", "arrow-schema", @@ -5195,8 +5195,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow", "arrow-array", @@ -5236,8 +5236,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow-array", "arrow-schema", @@ -5251,8 +5251,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow", "async-trait", @@ -5264,8 +5264,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow", "arrow-ipc", @@ -5318,8 +5318,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow-array", "arrow-buffer", @@ -5333,8 +5333,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow", "arrow-array", @@ -5374,8 +5374,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "arrow-array", "arrow-schema", @@ -5388,8 +5388,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0-beta.22" -source = "git+https://github.com/lance-format/lance.git?tag=v11.0.0-beta.22#ea3cb4d799c468232735e9bcb43959487aca5c20" +version = "12.0.0-beta.1" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 716b14d7a..3f2248e4b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0-beta.22", default-features = false, "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=11.0.0-beta.22", default-features = false, "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=11.0.0-beta.22", default-features = false, "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=11.0.0-beta.22", "tag" = "v11.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=12.0.0-beta.1", default-features = false, "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=12.0.0-beta.1", default-features = false, "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=12.0.0-beta.1", default-features = false, "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index 4d83153ab..78aa17bb7 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0-beta.22 + 12.0.0-beta.1 false 2.30.0 1.7 diff --git a/rust/lancedb/src/io/object_store.rs b/rust/lancedb/src/io/object_store.rs index d594bd857..c4a9a4f7e 100644 --- a/rust/lancedb/src/io/object_store.rs +++ b/rust/lancedb/src/io/object_store.rs @@ -10,7 +10,7 @@ use lance::io::WrappingObjectStore; use object_store::{ CopyOptions, Error, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, ObjectStoreExt, PutMultipartOptions, PutOptions, PutPayload, PutResult, Result, - UploadPart, path::Path, + UploadPart, list::PaginatedListStore, path::Path, }; use async_trait::async_trait; @@ -187,6 +187,14 @@ impl WrappingObjectStore for MirroringObjectStoreWrapper { secondary: self.secondary.clone(), }) } + + fn wrap_paginated( + &self, + _store_prefix: &str, + original: Arc, + ) -> Option> { + Some(original) + } } // windows pathing can't be simply concatenated diff --git a/rust/lancedb/src/io/object_store/io_tracking.rs b/rust/lancedb/src/io/object_store/io_tracking.rs index bd4f8f54a..7f9750216 100644 --- a/rust/lancedb/src/io/object_store/io_tracking.rs +++ b/rust/lancedb/src/io/object_store/io_tracking.rs @@ -12,7 +12,7 @@ use lance::io::WrappingObjectStore; use object_store::{ CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, PutMultipartOptions, PutOptions, PutPayload, PutResult, RenameOptions, Result as OSResult, - UploadPart, path::Path, + UploadPart, list::PaginatedListStore, path::Path, }; #[derive(Debug, Default)] @@ -57,6 +57,14 @@ impl WrappingObjectStore for IoStatsHolder { stats: self.0.clone(), }) } + + fn wrap_paginated( + &self, + _store_prefix: &str, + original: Arc, + ) -> Option> { + Some(original) + } } impl IoTrackingStore { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 5007a61d9..e544607f4 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -4118,6 +4118,14 @@ mod tests { parent_list_calls: self.parent_list_calls.clone(), }) } + + fn wrap_paginated( + &self, + _store_prefix: &str, + _original: Arc, + ) -> Option> { + None + } } #[tokio::test] @@ -4221,6 +4229,14 @@ mod tests { self.called.store(true, Ordering::Relaxed); original } + + fn wrap_paginated( + &self, + _store_prefix: &str, + original: Arc, + ) -> Option> { + Some(original) + } } #[tokio::test] diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index 255d649b1..5c340cc35 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -298,7 +298,7 @@ async fn build_read_context( for shard_id in shard_ids { let manifest_store = ShardManifestStore::new(store.clone(), &base_path, shard_id, scan_batch_size); - if let Some(manifest) = manifest_store.read_latest().await? { + if let Some(manifest) = manifest_store.latest().await? { snapshots.push(snapshot_from_manifest(shard_id, &manifest, &exclude)); } } From 9b825c5f298f45001afd1837bd360682c7282ecc Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Wed, 26 Aug 2026 10:08:48 +0800 Subject: [PATCH 122/206] fix(node): route auto search using table embeddings (#3832) ## Summary - Resolve automatic string-search routing from the active table schema whenever the query executes. - Defer embedding-provider construction while leaving explicit vector and FTS routes unchanged. - Cover unrelated global registrations and metadata transitions across repeated executions of one query builder. ## Root cause LocalTable.search used the number of globally registered embedding providers to choose between vector and full-text search. A provider registered for any other table therefore sent a plain FTS table down the vector path. A wrapper-lifetime metadata snapshot avoided that contamination but became stale after time travel or read-consistency refreshes. The query now records fluent builder operations and creates the appropriate native vector or FTS query from the active schema on each execution. ## Validation - pnpm build - pnpm tsc - pnpm lint - pnpm run docs - pnpm test --runInBand (681 passed, 5 skipped) Fixes #1557 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- nodejs/__test__/table.test.ts | 343 +++++++++++++++++++++++++++++- nodejs/lancedb/query.ts | 224 ++++++++++--------- nodejs/lancedb/table.ts | 39 ++-- nodejs/src/table.rs | 7 + rust/lancedb/src/remote/table.rs | 14 ++ rust/lancedb/src/table.rs | 28 +++ rust/lancedb/src/table/dataset.rs | 69 +++++- rust/lancedb/src/table/merge.rs | 38 ++++ rust/lancedb/src/table/query.rs | 31 +++ 9 files changed, 672 insertions(+), 121 deletions(-) diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index aaa144f16..dae640850 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -2585,7 +2585,24 @@ describe.each([arrow15, arrow16, arrow17, arrow18])( ); }); - test("full text search if no embedding function provided", async () => { + test("full text search if only an unrelated embedding function is registered", async () => { + register("unused")( + class extends EmbeddingFunction { + ndims() { + return 3; + } + embeddingDataType() { + return new Float32(); + } + async computeQueryEmbeddings(_data: string) { + return [1, 2, 3]; + } + async computeSourceEmbeddings(data: string[]) { + return data.map(() => [1, 2, 3]); + } + }, + ); + const db = await connect(tmpDir.name); const data = [ { text: "hello world", vector: [0.1, 0.2, 0.3] }, @@ -2607,6 +2624,306 @@ describe.each([arrow15, arrow16, arrow17, arrow18])( expect(results2[0].text).toBe(data[1].text); }); + test("auto search stays consistent with the active revision", async () => { + let initCalls = 0; + let queryCalls = 0; + let markStarted!: () => void; + const started = new Promise((resolve) => { + markStarted = resolve; + }); + let releaseEmbedding!: () => void; + const embeddingReleased = new Promise((resolve) => { + releaseEmbedding = resolve; + }); + + @register("refresh-test") + class TestEmbedding extends EmbeddingFunction { + async init() { + initCalls += 1; + } + ndims() { + return 1; + } + embeddingDataType() { + return new arrow.Float32(); + } + async computeQueryEmbeddings(value: string) { + queryCalls += 1; + if (value === "blocked") { + markStarted(); + await embeddingReleased; + } + return value === "greetings" ? [0.1] : [0.2]; + } + async computeSourceEmbeddings(values: string[]) { + return values.map((value) => + value === "hello world" ? [0.1] : [0.2], + ); + } + } + + const writer = await connect(tmpDir.name); + await writer.createTable("test", [{ text: "plain", vector: [0.0] }]); + const reader = await connect(tmpDir.name, { + readConsistencyInterval: 0, + }); + const tracked = await reader.openTable("test"); + type SnapshotCountingNative = { + querySnapshot: () => Promise; + }; + const native = (tracked as unknown as { inner: SnapshotCountingNative }) + .inner; + const querySnapshot = native.querySnapshot.bind(native); + let snapshotCalls = 0; + native.querySnapshot = async () => { + snapshotCalls += 1; + return await querySnapshot(); + }; + const autoQuery = tracked.search("greetings").select(["text"]).limit(1); + + const func = new TestEmbedding(); + const schema = LanceSchema({ + text: func.sourceField(new arrow.Utf8()), + vector: func.vectorField(), + }); + const data = [{ text: "hello world" }, { text: "goodbye world" }]; + await writer.createTable("test", data, { mode: "overwrite", schema }); + const baselineInitCalls = initCalls; + + expect( + (await tracked.schema()).metadata.get("embedding_functions"), + ).toBeDefined(); + const results = await autoQuery.toArray(); + expect(results[0].text).toBe(data[0].text); + expect(initCalls).toBe(baselineInitCalls + 1); + expect(queryCalls).toBe(1); + expect(snapshotCalls).toBe(1); + + const repeatedResults = await autoQuery.toArray(); + expect(repeatedResults[0].text).toBe(data[0].text); + expect(initCalls).toBe(baselineInitCalls + 1); + expect(queryCalls).toBe(1); + expect(snapshotCalls).toBe(2); + + const pending = tracked + .search("blocked") + .select(["text"]) + .limit(1) + .toArray(); + await started; + + const ftsData = [ + { text: "greetings from full text", vector: [0.0] }, + { text: "blocked from full text", vector: [0.0] }, + ]; + const ftsTable = await writer.createTable("test", ftsData, { + mode: "overwrite", + }); + await ftsTable.createIndex("text", { config: Index.fts() }); + releaseEmbedding(); + + const pendingResults = await pending; + expect(pendingResults[0].text).toBe(data[1].text); + + expect( + (await tracked.schema()).metadata.get("embedding_functions"), + ).toBeUndefined(); + const ftsResults = await autoQuery.toArray(); + expect(ftsResults[0].text).toBe(ftsData[0].text); + }); + + test("auto search keeps newer preparation during a revision race", async () => { + let aCalls = 0; + let bCalls = 0; + let markAStarted!: () => void; + const aStarted = new Promise((resolve) => { + markAStarted = resolve; + }); + let releaseA!: () => void; + const aReleased = new Promise((resolve) => { + releaseA = resolve; + }); + let markBStarted!: () => void; + const bStarted = new Promise((resolve) => { + markBStarted = resolve; + }); + let releaseB!: () => void; + const bReleased = new Promise((resolve) => { + releaseB = resolve; + }); + + @register("race-a") + class EmbeddingA extends EmbeddingFunction { + ndims() { + return 1; + } + embeddingDataType() { + return new arrow.Float32(); + } + async computeQueryEmbeddings() { + aCalls += 1; + markAStarted(); + await aReleased; + return [0.1]; + } + async computeSourceEmbeddings(values: string[]) { + return values.map(() => [0.1]); + } + } + + @register("race-b") + class EmbeddingB extends EmbeddingFunction { + ndims() { + return 1; + } + embeddingDataType() { + return new arrow.Float32(); + } + async computeQueryEmbeddings() { + bCalls += 1; + markBStarted(); + await bReleased; + return [0.2]; + } + async computeSourceEmbeddings(values: string[]) { + return values.map(() => [0.2]); + } + } + + const writer = await connect(tmpDir.name); + const embeddingA = new EmbeddingA(); + const schemaA = LanceSchema({ + text: embeddingA.sourceField(new arrow.Utf8()), + vector: embeddingA.vectorField(), + }); + await writer.createTable("race", [{ text: "revision a" }], { + schema: schemaA, + }); + const reader = await connect(tmpDir.name, { + readConsistencyInterval: 0, + }); + const tracked = await reader.openTable("race"); + const query = tracked.search("query"); + + const first = query.toArray(); + await aStarted; + + const embeddingB = new EmbeddingB(); + const schemaB = LanceSchema({ + text: embeddingB.sourceField(new arrow.Utf8()), + vector: embeddingB.vectorField(), + }); + await writer.createTable("race", [{ text: "revision b" }], { + mode: "overwrite", + schema: schemaB, + }); + const second = query.toArray(); + await bStarted; + + releaseA(); + releaseB(); + await Promise.all([first, second]); + expect(aCalls).toBe(1); + expect(bCalls).toBe(1); + }); + + test("stale FTS routing keeps newer vector preparation", async () => { + let vectorCalls = 0; + let markVectorStarted!: () => void; + const vectorStarted = new Promise((resolve) => { + markVectorStarted = resolve; + }); + let releaseVector!: () => void; + const vectorReleased = new Promise((resolve) => { + releaseVector = resolve; + }); + + @register("stale-fts-race") + class RaceEmbedding extends EmbeddingFunction { + ndims() { + return 1; + } + embeddingDataType() { + return new arrow.Float32(); + } + async computeQueryEmbeddings() { + vectorCalls += 1; + markVectorStarted(); + await vectorReleased; + return [0.1]; + } + async computeSourceEmbeddings(values: string[]) { + return values.map(() => [0.1]); + } + } + + const writer = await connect(tmpDir.name); + const ftsTable = await writer.createTable("stale_fts", [ + { text: "hello", vector: [0.0] }, + ]); + await ftsTable.createIndex("text", { config: Index.fts() }); + + const reader = await connect(tmpDir.name, { + readConsistencyInterval: 0, + }); + const tracked = await reader.openTable("stale_fts"); + type Snapshot = { + schema: () => Promise; + }; + type NativeWithSnapshot = { + querySnapshot: () => Promise; + }; + const native = (tracked as unknown as { inner: NativeWithSnapshot }) + .inner; + const querySnapshot = native.querySnapshot.bind(native); + let snapshotCalls = 0; + let markStaleSchemaStarted!: () => void; + const staleSchemaStarted = new Promise((resolve) => { + markStaleSchemaStarted = resolve; + }); + let releaseStaleSchema!: () => void; + const staleSchemaReleased = new Promise((resolve) => { + releaseStaleSchema = resolve; + }); + native.querySnapshot = async () => { + const snapshot = await querySnapshot(); + snapshotCalls += 1; + if (snapshotCalls === 1) { + const schema = snapshot.schema.bind(snapshot); + snapshot.schema = async () => { + markStaleSchemaStarted(); + await staleSchemaReleased; + return await schema(); + }; + } + return snapshot; + }; + + const query = tracked.search("hello"); + const staleFtsExecution = query.toArray(); + await staleSchemaStarted; + + const embedding = new RaceEmbedding(); + const vectorSchema = LanceSchema({ + text: embedding.sourceField(new arrow.Utf8()), + vector: embedding.vectorField(), + }); + await writer.createTable("stale_fts", [{ text: "hello" }], { + mode: "overwrite", + schema: vectorSchema, + }); + + const vectorExecution = query.toArray(); + await vectorStarted; + releaseStaleSchema(); + await staleFtsExecution; + releaseVector(); + await vectorExecution; + + await query.toArray(); + expect(vectorCalls).toBe(1); + }); + test("tokenizes FTS queries by column or index name", async () => { const db = await connect(tmpDir.name); const data = [ @@ -3157,6 +3474,30 @@ describe("column name options", () => { expect(results[1].query_index).toBe(1); }); + test("observes promised additional vectors while the query is pending", async () => { + const initialVector = new Promise(() => undefined); + const query = table.query().nearestTo(initialVector); + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => unhandled.push(reason); + process.on("unhandledRejection", onUnhandled); + + try { + query.addQueryVector(Promise.reject(new Error("extra vector failed"))); + await new Promise((resolve) => setImmediate(resolve)); + expect(unhandled).toEqual([]); + + const rejectedQuery = table + .query() + .nearestTo([0.1, 0.2]) + .addQueryVector(Promise.reject(new Error("consumed vector failed"))); + await expect(rejectedQuery.toArray()).rejects.toThrow( + "consumed vector failed", + ); + } finally { + process.off("unhandledRejection", onUnhandled); + } + }); + test("index and search multivectors", async () => { const db = await connect(tmpDir.name); const data = []; diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index 3b9b286a0..f1d31eae1 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -100,6 +100,29 @@ export interface FullTextSearchOptions { columns?: string | string[]; } +function nearestToNative( + inner: NativeQuery, + vector: Awaited, +): NativeVectorQuery { + const raw = Array.isArray(vector) ? null : extractVectorBuffer(vector); + if (raw) { + return inner.nearestToRaw(raw.data, raw.dtype); + } + return inner.nearestTo(Float32Array.from(vector as number[])); +} + +function addQueryVectorToNative( + inner: NativeVectorQuery, + vector: Awaited, +) { + const raw = Array.isArray(vector) ? null : extractVectorBuffer(vector); + if (raw) { + inner.addQueryVectorRaw(raw.data, raw.dtype); + } else { + inner.addQueryVector(Float32Array.from(vector as number[])); + } +} + /** Common methods supported by all query types * * @see {@link Query} @@ -499,6 +522,13 @@ export class VectorQuery extends StandardQueryBase { super(inner); } + /** + * @hidden + */ + protected doVectorCall(fn: (inner: NativeVectorQuery) => void) { + super.doCall(fn); + } + /** * Set the number of partitions to search (probe) * @@ -526,7 +556,7 @@ export class VectorQuery extends StandardQueryBase { * the minimum and maximum to the same value. */ nprobes(nprobes: number): VectorQuery { - super.doCall((inner) => inner.nprobes(nprobes)); + this.doVectorCall((inner) => inner.nprobes(nprobes)); return this; } @@ -540,7 +570,7 @@ export class VectorQuery extends StandardQueryBase { * but will also increase latency. */ minimumNprobes(minimumNprobes: number): VectorQuery { - super.doCall((inner) => inner.minimumNprobes(minimumNprobes)); + this.doVectorCall((inner) => inner.minimumNprobes(minimumNprobes)); return this; } @@ -554,7 +584,7 @@ export class VectorQuery extends StandardQueryBase { * potential false negatives. */ maximumNprobes(maximumNprobes: number): VectorQuery { - super.doCall((inner) => inner.maximumNprobes(maximumNprobes)); + this.doVectorCall((inner) => inner.maximumNprobes(maximumNprobes)); return this; } @@ -567,7 +597,7 @@ export class VectorQuery extends StandardQueryBase { * `undefined` means no lower or upper bound. */ distanceRange(lowerBound?: number, upperBound?: number): VectorQuery { - super.doCall((inner) => inner.distanceRange(lowerBound, upperBound)); + this.doVectorCall((inner) => inner.distanceRange(lowerBound, upperBound)); return this; } @@ -581,7 +611,7 @@ export class VectorQuery extends StandardQueryBase { * also increase the latency of your query. The default value is 1.5*limit. */ ef(ef: number): VectorQuery { - super.doCall((inner) => inner.ef(ef)); + this.doVectorCall((inner) => inner.ef(ef)); return this; } @@ -595,7 +625,7 @@ export class VectorQuery extends StandardQueryBase { * whose data type is a fixed-size-list of floats. */ column(column: string): VectorQuery { - super.doCall((inner) => inner.column(column)); + this.doVectorCall((inner) => inner.column(column)); return this; } @@ -616,7 +646,7 @@ export class VectorQuery extends StandardQueryBase { distanceType( distanceType: Required["distanceType"], ): VectorQuery { - super.doCall((inner) => inner.distanceType(distanceType)); + this.doVectorCall((inner) => inner.distanceType(distanceType)); return this; } @@ -650,7 +680,7 @@ export class VectorQuery extends StandardQueryBase { * distance between the query vector and the actual uncompressed vector. */ refineFactor(refineFactor: number): VectorQuery { - super.doCall((inner) => inner.refineFactor(refineFactor)); + this.doVectorCall((inner) => inner.refineFactor(refineFactor)); return this; } @@ -675,7 +705,7 @@ export class VectorQuery extends StandardQueryBase { * factor can often help restore some of the results lost by post filtering. */ postfilter(): VectorQuery { - super.doCall((inner) => inner.postfilter()); + this.doVectorCall((inner) => inner.postfilter()); return this; } @@ -689,7 +719,7 @@ export class VectorQuery extends StandardQueryBase { * calculate your recall to select an appropriate value for nprobes. */ bypassVectorIndex(): VectorQuery { - super.doCall((inner) => inner.bypassVectorIndex()); + this.doVectorCall((inner) => inner.bypassVectorIndex()); return this; } @@ -705,35 +735,31 @@ export class VectorQuery extends StandardQueryBase { */ addQueryVector(vector: IntoVector): VectorQuery { if (vector instanceof Promise) { + // Observe the promise as soon as it is accepted. The existing native + // query may still be pending, and delaying observation until it resolves + // can otherwise surface a fast rejection as unhandled. + const settledVector = vector.then( + (value) => ({ status: "fulfilled" as const, value }), + (reason) => ({ status: "rejected" as const, reason }), + ); const res = (async () => { - try { - const v = await vector; - // biome-ignore lint/suspicious/noExplicitAny: we need to get the `inner`, but js has no package scoping - const value: any = this.addQueryVector(v); - const inner = value.inner as - | NativeVectorQuery - | Promise; - return inner; - } catch (e) { - return Promise.reject(e); + const inner = await this.getInner(); + const outcome = await settledVector; + if (outcome.status === "rejected") { + throw outcome.reason; } + addQueryVectorToNative(inner, outcome.value); + return inner; })(); return new VectorQuery(res); } else { - super.doCall((inner) => { - const raw = Array.isArray(vector) ? null : extractVectorBuffer(vector); - if (raw) { - inner.addQueryVectorRaw(raw.data, raw.dtype); - } else { - inner.addQueryVector(Float32Array.from(vector as number[])); - } - }); + this.doVectorCall((inner) => addQueryVectorToNative(inner, vector)); return this; } } rerank(reranker: Reranker): VectorQuery { - super.doCall((inner) => + this.doVectorCall((inner) => inner.rerank(async (args) => { const vecResults = await fromBufferToRecordBatch(args.vecResults); const ftsResults = await fromBufferToRecordBatch(args.ftsResults); @@ -752,6 +778,71 @@ export class VectorQuery extends StandardQueryBase { } } +/** + * Create a string query whose vector/FTS routing is resolved against the active + * table schema when the query executes. + * + * @hidden + */ +export function createAutoQuery( + table: NativeTable, + query: string, + columns: string[] | null, + getVector: (metadata: string) => Promise>, +): AutoQuery { + type RouteSnapshot = { + table: NativeTable; + embeddingMetadata: string | undefined; + }; + type CachedPreparation = { + metadata: string; + vector: Promise>; + }; + + let cachedPreparation: CachedPreparation | undefined; + + const snapshotRoute = async (): Promise => { + const snapshot = await table.querySnapshot(); + const schema = tableFromIPC(await snapshot.schema()).schema; + return { + table: snapshot, + embeddingMetadata: schema.metadata.get("embedding_functions"), + }; + }; + + const createInner = async (): Promise => { + const route = await snapshotRoute(); + if (route.embeddingMetadata === undefined) { + const inner = route.table.query(); + inner.fullTextSearch({ query, columns }); + return inner; + } + + const metadata = route.embeddingMetadata; + if (cachedPreparation?.metadata !== metadata) { + cachedPreparation = { + metadata, + vector: Promise.resolve().then(() => getVector(metadata)), + }; + } + + const preparation = cachedPreparation; + let vector: Awaited; + try { + vector = await preparation.vector; + } catch (error) { + if (cachedPreparation === preparation) { + cachedPreparation = undefined; + } + throw error; + } + + return nearestToNative(route.table.query(), vector); + }; + + return new AutoQuery(createInner); +} + /** * A query that returns a subset of the rows in the table. * @@ -836,37 +927,6 @@ export class Query extends StandardQueryBase { super(tbl.query()); } - /** @hidden */ - static autoSearch( - tbl: () => Promise, - query: string, - vector: (tbl: NativeTable) => Promise | undefined>, - columns?: string[], - ): AutoQuery { - const nativeQuery = async () => { - const snapshot = await Promise.resolve(tbl()); - const resolved = await vector(snapshot); - const inner = snapshot.query(); - if (resolved === undefined) { - inner.fullTextSearch({ - query, - columns: columns ?? null, - }); - return inner; - } - - const raw = Array.isArray(resolved) - ? null - : extractVectorBuffer(resolved); - if (raw) { - return inner.nearestToRaw(raw.data, raw.dtype); - } - return inner.nearestTo(Float32Array.from(resolved as number[])); - }; - - return new AutoQuery(nativeQuery); - } - /** * Find the nearest vectors to the given query vector. * @@ -905,45 +965,19 @@ export class Query extends StandardQueryBase { * a default `limit` of 10 will be used. @see {@link Query#limit} */ nearestTo(vector: IntoVector): VectorQuery { - const callNearestTo = ( - inner: NativeQuery, - resolved: Float32Array | Float64Array | Uint8Array | number[], - ): NativeVectorQuery => { - const raw = Array.isArray(resolved) - ? null - : extractVectorBuffer(resolved); - if (raw) { - return inner.nearestToRaw(raw.data, raw.dtype); - } - return inner.nearestTo(Float32Array.from(resolved as number[])); - }; - - if (this.inner instanceof Promise) { - const nativeQuery = this.inner.then(async (inner) => { - const resolved = vector instanceof Promise ? await vector : vector; - return callNearestTo(inner, resolved); - }); + const inner = this.inner; + if (inner instanceof Promise) { + const nativeQuery = inner.then(async (resolvedInner) => + nearestToNative(resolvedInner, await vector), + ); return new VectorQuery(nativeQuery); } if (vector instanceof Promise) { - const res = (async () => { - try { - const v = await vector; - // biome-ignore lint/suspicious/noExplicitAny: we need to get the `inner`, but js has no package scoping - const value: any = this.nearestTo(v); - const inner = value.inner as - | NativeVectorQuery - | Promise; - return inner; - } catch (e) { - return Promise.reject(e); - } - })(); - return new VectorQuery(res); - } else { - const vectorQuery = callNearestTo(this.inner, vector); - return new VectorQuery(vectorQuery); + return new VectorQuery( + vector.then((resolvedVector) => nearestToNative(inner, resolvedVector)), + ); } + return new VectorQuery(nearestToNative(inner, vector)); } nearestToText(query: string | FullTextQuery, columns?: string[]): Query { diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index a4fc76ef1..82f23e2f2 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -48,6 +48,7 @@ import { Query, TakeQuery, VectorQuery, + createAutoQuery, instanceOfFullTextQuery, } from "./query"; import { sanitizeType } from "./sanitize"; @@ -1177,33 +1178,29 @@ export class LocalTable extends Table { }); } - if (queryType === "auto" && typeof query !== "string") { - return this.query().fullTextSearch(query, { - columns: ftsColumns, - }); - } + if (queryType === "auto") { + if (instanceOfFullTextQuery(query)) { + return this.query().fullTextSearch(query, { + columns: ftsColumns, + }); + } - if (queryType === "auto" && typeof query === "string") { - const vector = async (snapshot: _NativeTable) => { - const functions = await this.getEmbeddingFunctions(snapshot); + const columns = + typeof ftsColumns === "string" ? [ftsColumns] : (ftsColumns ?? null); + return createAutoQuery(this.inner, query, columns, async (metadata) => { + const functions = await getRegistry().parseFunctions( + new Map([["embedding_functions", metadata]]), + ); // TODO: Support multiple embedding functions const embeddingFunc: EmbeddingFunctionConfig | undefined = functions .values() .next().value; - if (embeddingFunc === undefined) { - return undefined; - } + // The route only calls this callback when embedding metadata exists. + // parseFunctions either yields a provider or reports malformed metadata. + if (!embeddingFunc) + throw new Error("Invalid embedding function metadata"); return await embeddingFunc.function.computeQueryEmbeddings(query); - }; - - const columns = - typeof ftsColumns === "string" ? [ftsColumns] : ftsColumns; - return Query.autoSearch( - () => this.inner.checkoutCurrent(), - query, - vector, - columns, - ); + }); } const queryPromise = this.getEmbeddingFunctions().then( diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index ff16ac042..db74d38fa 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -278,6 +278,13 @@ impl Table { Ok(Query::new(self.inner_ref()?.query())) } + /// Return a read-only table handle pinned to the current query revision. + #[napi(catch_unwind)] + pub async fn query_snapshot(&self) -> napi::Result { + let snapshot = self.inner_ref()?.query_snapshot().await.default_error()?; + Ok(Self::new(snapshot)) + } + #[napi(catch_unwind)] pub fn take_offsets(&self, offsets: Vec) -> napi::Result { Ok(TakeQuery::new( diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 77d5983eb..b116083c8 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -1722,6 +1722,20 @@ impl BaseTable for RemoteTable { fn id(&self) -> &str { &self.identifier } + async fn query_snapshot(&self) -> Result> { + let description = self.describe().await?; + let TableDescription { + version, + schema, + location, + } = description; + let schema = Arc::new(arrow_schema::Schema::try_from(schema)?); + let snapshot = self.with_branch(self.branch.clone()); + *snapshot.version.write().await = Some(version); + *snapshot.location.write().await = location; + snapshot.schema_cache.seed(schema); + Ok(Arc::new(snapshot)) + } async fn version(&self) -> Result { self.describe().await.map(|desc| desc.version) } diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index e544607f4..6b5f687c7 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -560,6 +560,13 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { fn id(&self) -> &str; /// Get the arrow [Schema] of the table. async fn schema(&self) -> Result; + /// Create a read-only handle pinned to the table's current active revision. + /// + /// The returned handle is independent from later refreshes or checkouts on + /// this handle. This is used by bindings that must prepare client-side + /// query state from the same revision that the query will execute against. + #[doc(hidden)] + async fn query_snapshot(&self) -> Result>; /// Count the number of rows in this table. async fn count_rows(&self, filter: Option) -> Result; /// Create a physical plan for the query. @@ -1139,6 +1146,16 @@ impl Table { self.inner.schema().await } + /// Create a read-only handle pinned to the current active revision. + #[doc(hidden)] + pub async fn query_snapshot(&self) -> Result { + Ok(Self { + inner: self.inner.query_snapshot().await?, + database: self.database.clone(), + embedding_registry: self.embedding_registry.clone(), + }) + } + /// Count the number of rows in this dataset. /// /// # Arguments @@ -3059,6 +3076,17 @@ impl BaseTable for NativeTable { &self.id } + async fn query_snapshot(&self) -> Result> { + let snapshot = self.dataset.new_query_snapshot().await?; + let mut table = self.with_dataset(snapshot); + // QueryTable requests do not carry a revision. A pinned snapshot must + // execute locally until the namespace API can accept that revision. + table + .pushdown_operations + .remove(&NamespaceClientPushdownOperation::QueryTable); + Ok(Arc::new(table)) + } + async fn version(&self) -> Result { Ok(self.dataset.get().await?.version().version) } diff --git a/rust/lancedb/src/table/dataset.rs b/rust/lancedb/src/table/dataset.rs index e37c3fc9f..5e3733b85 100644 --- a/rust/lancedb/src/table/dataset.rs +++ b/rust/lancedb/src/table/dataset.rs @@ -32,6 +32,10 @@ struct DatasetState { /// `Some(version)` = pinned to a specific version (time travel), /// `None` = tracking latest. pinned_version: Option, + /// Whether the pin is an internal query snapshot rather than user-visible + /// time travel. Query snapshots remain read-only but preserve MemWAL read + /// semantics. + query_snapshot: bool, } #[derive(Debug, Clone)] @@ -70,6 +74,7 @@ impl DatasetConsistencyWrapper { state: Arc::new(Mutex::new(DatasetState { dataset, pinned_version: None, + query_snapshot: false, })), consistency, shard_writer: Arc::new(ShardWriterCache::default()), @@ -93,6 +98,36 @@ impl DatasetConsistencyWrapper { wrapper } + /// Create an independent read-only wrapper pinned to the current dataset + /// while retaining this wrapper's live MemWAL read context. + pub async fn new_query_snapshot(&self) -> Result { + // Apply the configured consistency policy before taking the snapshot. + // The returned dataset is intentionally discarded: a checkout may race + // after this await, so the dataset and its pin provenance must instead + // be cloned together from one authoritative state sample below. + self.get().await?; + + let (dataset, query_snapshot) = { + let state = self.state.lock()?; + // Preserve user time travel so the MemWAL safety guard still sees + // it. Latest and already-internal snapshots remain internal pins. + ( + state.dataset.clone(), + state.query_snapshot || state.pinned_version.is_none(), + ) + }; + let version = dataset.version().version; + Ok(Self { + state: Arc::new(Mutex::new(DatasetState { + dataset, + pinned_version: Some(version), + query_snapshot, + })), + consistency: ConsistencyMode::Lazy, + shard_writer: self.shard_writer.clone(), + }) + } + /// The MemWAL `ShardWriter` cache co-located with this dataset. pub(crate) fn shard_writer(&self) -> &Arc { &self.shard_writer @@ -169,6 +204,7 @@ impl DatasetConsistencyWrapper { let mut state = self.state.lock()?; state.dataset = Arc::new(new_dataset); state.pinned_version = None; + state.query_snapshot = false; drop(state); if let ConsistencyMode::Eventual(bg_cache) = &self.consistency { bg_cache.invalidate(); @@ -202,10 +238,10 @@ impl DatasetConsistencyWrapper { /// Returns the version, if in time travel mode, or None otherwise. pub fn time_travel_version(&self) -> Option { - self.state - .lock() - .unwrap_or_else(|e| e.into_inner()) - .pinned_version + let state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + (!state.query_snapshot) + .then_some(state.pinned_version) + .flatten() } /// Convert into a wrapper in latest version mode. @@ -225,6 +261,7 @@ impl DatasetConsistencyWrapper { if state.pinned_version.is_some() { state.dataset = Arc::new(new_dataset); state.pinned_version = None; + state.query_snapshot = false; } drop(state); if let ConsistencyMode::Eventual(bg_cache) = &self.consistency { @@ -260,6 +297,7 @@ impl DatasetConsistencyWrapper { let mut state = self.state.lock()?; state.dataset = Arc::new(new_dataset); state.pinned_version = Some(version_value); + state.query_snapshot = false; Ok(()) } @@ -461,6 +499,29 @@ mod tests { assert_eq!(wrapper.time_travel_version(), Some(1)); } + #[tokio::test] + async fn test_query_snapshot_samples_dataset_and_pin_together() { + let dir = tempfile::tempdir().unwrap(); + let uri = dir.path().to_str().unwrap(); + let ds = create_test_dataset(uri).await; + + let wrapper = DatasetConsistencyWrapper::new_latest(ds, None); + wrapper.as_time_travel(1u64).await.unwrap(); + let stale_time_travel_dataset = wrapper.get().await.unwrap(); + + append_to_dataset(uri).await; + wrapper.as_latest().await.unwrap(); + + let snapshot = wrapper.new_query_snapshot().await.unwrap(); + let snapshot_dataset = snapshot.get().await.unwrap(); + assert_eq!(snapshot_dataset.version().version, 2); + assert_ne!( + snapshot_dataset.version().version, + stale_time_travel_dataset.version().version + ); + assert_eq!(snapshot.time_travel_version(), None); + } + #[tokio::test] async fn test_as_latest_from_time_travel() { let dir = tempfile::tempdir().unwrap(); diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index b9dd5732b..3227e3edf 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -1056,6 +1056,44 @@ mod lsm_tests { ); } + #[tokio::test] + async fn query_snapshot_preserves_lsm_read_semantics() { + let dir = tempdir().unwrap(); + let table = id_value_table(&dir).await; + table + .set_lsm_write_spec(LsmWriteSpec::unsharded()) + .await + .unwrap(); + lsm_upsert(&table, vec![4, 5]).await; + + let snapshot = table.query_snapshot().await.unwrap(); + let rows = collect_id_value(snapshot.query().execute().await.unwrap()).await; + assert_eq!( + rows.iter().map(|(id, _)| *id).collect::>(), + vec![1, 2, 3, 4, 5] + ); + } + + #[tokio::test] + async fn query_snapshot_preserves_time_travel_lsm_guard() { + let dir = tempdir().unwrap(); + let table = id_value_table(&dir).await; + table + .set_lsm_write_spec(LsmWriteSpec::unsharded()) + .await + .unwrap(); + lsm_upsert(&table, vec![4]).await; + + let version = table.version().await.unwrap(); + table.checkout(version).await.unwrap(); + let direct_error = table.query().execute().await.err().unwrap(); + assert!(matches!(direct_error, Error::NotSupported { .. })); + + let snapshot = table.query_snapshot().await.unwrap(); + let snapshot_error = snapshot.query().execute().await.err().unwrap(); + assert!(matches!(snapshot_error, Error::NotSupported { .. })); + } + #[tokio::test] async fn lsm_read_dedup_newest_wins() { let dir = tempdir().unwrap(); diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index d35286c84..629cb4e6f 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -1056,6 +1056,37 @@ mod tests { assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); } + #[tokio::test] + async fn test_query_snapshot_disables_namespace_pushdown() { + use crate::connect; + use crate::table::BaseTable; + 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)])); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![1, 2, 3]))]).unwrap(); + let table = conn + .create_table("test_snapshot_namespace_fallback", vec![batch]) + .execute() + .await + .unwrap(); + let mut native_table = table.as_native().unwrap().clone(); + native_table.namespace_client = Some(Arc::new(CountingNamespaceClient::default())); + native_table + .pushdown_operations + .insert(NamespaceClientPushdownOperation::QueryTable); + + let snapshot = BaseTable::query_snapshot(&native_table).await.unwrap(); + let snapshot = snapshot.as_any().downcast_ref::().unwrap(); + assert!( + !can_execute_namespace_query(snapshot, &AnyQuery::Query(QueryRequest::default()),) + .await + .unwrap() + ); + } + #[tokio::test] async fn test_create_plan_multivector_structure() { use arrow_array::{Float32Array, RecordBatch}; From 21530432a06ddd3814ec8b0e617abe3eda041fc3 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Tue, 25 Aug 2026 19:56:26 -0700 Subject: [PATCH 123/206] chore: update lance dependency to v12.0.0-beta.2 (#4056) Updates the Rust workspace Lance crates and Java lance-core dependency to [v12.0.0-beta.2](https://github.com/lance-format/lance/releases/tag/v12.0.0-beta.2). No compatibility fixes were required; full-workspace Clippy passes with all features and warnings denied. --- Cargo.lock | 84 ++++++++++++++++++++++++++-------------------------- Cargo.toml | 28 +++++++++--------- java/pom.xml | 2 +- 3 files changed, 57 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 63ee13e78..e27f9f271 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow", "arrow-array", @@ -5013,8 +5013,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow", "arrow-array", @@ -5031,8 +5031,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "proc-macro2", "quote", @@ -5041,8 +5041,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow-arith", "arrow-array", @@ -5075,8 +5075,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow-arith", "arrow-array", @@ -5107,8 +5107,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arc-swap", "arrow", @@ -5172,8 +5172,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow-array", "arrow-schema", @@ -5195,8 +5195,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow", "arrow-array", @@ -5236,8 +5236,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow-array", "arrow-schema", @@ -5251,8 +5251,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow", "async-trait", @@ -5264,8 +5264,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow", "arrow-ipc", @@ -5318,8 +5318,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow-array", "arrow-buffer", @@ -5333,8 +5333,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow", "arrow-array", @@ -5374,8 +5374,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "arrow-array", "arrow-schema", @@ -5388,8 +5388,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "12.0.0-beta.1" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.1#e37cee4397abc6a71df3cdfa0e637c274f820aa6" +version = "12.0.0-beta.2" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 3f2248e4b..a16f0412c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=12.0.0-beta.1", default-features = false, "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=12.0.0-beta.1", default-features = false, "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=12.0.0-beta.1", default-features = false, "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=12.0.0-beta.1", "tag" = "v12.0.0-beta.1", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=12.0.0-beta.2", default-features = false, "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=12.0.0-beta.2", default-features = false, "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=12.0.0-beta.2", default-features = false, "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index 78aa17bb7..a2cec19c0 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 12.0.0-beta.1 + 12.0.0-beta.2 false 2.30.0 1.7 From 391cac903438fdf67c7e3675757b4e4898ddb150 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Tue, 25 Aug 2026 21:54:36 -0700 Subject: [PATCH 124/206] fix(remote): centralize timeline consistency (#4053) Centralizes remote table freshness fencing and response-version tracking in the default transport path. Covers schema and blob bypass paths, keeps explicit time-travel and cross-timeline operations unfenced, and advances freshness after refresh and index job completion. --- rust/lancedb/src/job.rs | 4 + rust/lancedb/src/remote/table.rs | 1354 ++++++++++++++++++----- rust/lancedb/src/remote/table/blobs.rs | 77 +- rust/lancedb/src/remote/table/insert.rs | 83 +- 4 files changed, 1218 insertions(+), 300 deletions(-) diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 94d1ba2b6..22f1a0450 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -47,6 +47,10 @@ impl TerminalResult { } } + pub(crate) fn value(&self) -> Option<&Value> { + self.value.as_ref() + } + fn decode(self) -> Result { let value = self.value.ok_or_else(|| match &self.request_id { Some(request_id) => Error::Http { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index b116083c8..b1a02a260 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -86,22 +86,31 @@ const METRIC_TYPE_KEY: &str = "metric_type"; const INDEX_TYPE_KEY: &str = "index_type"; const SCHEMA_CACHE_TTL: Duration = Duration::from_secs(30); const SCHEMA_CACHE_REFRESH_WINDOW: Duration = Duration::from_secs(5); +const SCHEMA_SELECTOR_CHANGED: &str = "table selector changed while fetching schema"; /// Per-table state driving the freshness headers (`x-lancedb-min-version`, -/// `x-lancedb-min-timestamp`, and `x-lancedb-min-read-version`) sent on read +/// `x-lancedb-min-timestamp`, and `x-lancedb-min-read-version`) sent on table /// requests. #[derive(Debug, Default, Clone, Copy)] struct FreshnessState { + /// Identifies the handle timeline that produced this state. Explicit + /// checkout operations advance the generation so responses from older + /// in-flight requests cannot repopulate the new timeline's constraints. + generation: u64, + /// Exact-version, tag, and snapshot handles must not carry latest-timeline + /// constraints. Their request body already selects the precise version. + pinned: bool, /// Provides read-your-write within a single handle: writes that return a /// version update this, and reads send it as `x-lancedb-min-version`. min_version: Option, - /// Highest dataset version observed in a *read* response on this handle. - /// Reads send it as `x-lancedb-min-read-version` so a load-balanced query + /// Highest committed dataset version advertised by a successful table + /// response on this handle. Later requests send it as + /// `x-lancedb-min-read-version` so a load-balanced query /// node whose cache is behind this version must refresh before serving, /// giving monotonic reads across nodes regardless of which one the load - /// balancer routes to. Sourced only from reads (always committed dataset - /// versions), never from writes (which may return WAL entry ids), so it is - /// unaffected by the WAL/version mismatch that retired `min_version`. + /// balancer routes to. Unlike write result bodies, this is sourced only + /// from the server's committed dataset-version response header or other + /// typed dataset-version fields, so WAL entry ids cannot enter it. min_read_version: Option, /// Wall-clock time captured at the last [`BaseTable::checkout_latest`] /// call. Subsequent reads send @@ -118,14 +127,22 @@ struct FreshnessState { checkout_baseline: Option, } -/// Snapshot of the headers that should be attached to a single read request. +/// Snapshot of the headers that should be attached to a single table request. #[derive(Debug, Default, Clone, Copy)] struct FreshnessHeaders { + generation: u64, min_version: Option, min_timestamp: Option, min_read_version: Option, } +#[derive(Debug, Default, Clone, Copy)] +struct ReadSnapshot { + version: Option, + freshness_state: FreshnessState, + freshness: FreshnessHeaders, +} + impl FreshnessHeaders { fn apply(self, mut request: RequestBuilder) -> RequestBuilder { if let Some(v) = self.min_version { @@ -140,6 +157,61 @@ impl FreshnessHeaders { } request } + + fn observe_version(self, freshness: &Mutex, version: u64) { + track_read_version_for_generation(freshness, self.generation, version); + } + + fn observe_headers( + self, + freshness: &Mutex, + headers: &reqwest::header::HeaderMap, + ) { + if let Some(version) = headers + .get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + { + self.observe_version(freshness, version); + } + } + + fn update_if_current( + self, + freshness: &Mutex, + update: impl FnOnce(&mut FreshnessState), + ) { + let mut state = freshness.lock().unwrap(); + if state.generation == self.generation { + update(&mut state); + } + } + + fn is_current(self, freshness: &Mutex) -> bool { + freshness.lock().unwrap().generation == self.generation + } +} + +fn track_read_version(freshness: &Mutex, version: u64) { + if version == 0 { + return; + } + let mut state = freshness.lock().unwrap(); + state.min_read_version = Some(state.min_read_version.map_or(version, |v| v.max(version))); +} + +fn track_read_version_for_generation( + freshness: &Mutex, + generation: u64, + version: u64, +) { + if version == 0 { + return; + } + let mut state = freshness.lock().unwrap(); + if state.generation == generation { + state.min_read_version = Some(state.min_read_version.map_or(version, |v| v.max(version))); + } } /// A backfill job whose successful wait establishes a read-freshness @@ -150,6 +222,8 @@ struct FreshnessJob { inner: RemoteJob, freshness: Arc>, version: Arc>>, + track_refresh_result: bool, + freshness_request: FreshnessHeaders, } #[async_trait] @@ -166,7 +240,31 @@ impl crate::job::JobHandle for FreshnessJob { let result = crate::job::JobHandle::wait(&self.inner).await?; let version = self.version.read().await; if version.is_none() { - self.freshness.lock().unwrap().checkout_baseline = Some(SystemTime::now()); + let result_version = self + .track_refresh_result + .then(|| result.value()) + .flatten() + .and_then(|value| { + serde_json::from_value::(value.clone()) + .ok() + }) + .map(|result| { + result + .published_version + .map_or(result.source_version, |version| { + version.max(result.source_version) + }) + }) + .filter(|version| *version != 0); + if let Some(version) = result_version { + self.freshness_request + .observe_version(&self.freshness, version); + } else { + self.freshness_request + .update_if_current(&self.freshness, |state| { + state.checkout_baseline = Some(SystemTime::now()); + }); + } } Ok(result) } @@ -193,6 +291,38 @@ fn compute_min_timestamp( } } +fn freshness_headers_snapshot( + freshness: &Mutex, + interval: Option, +) -> FreshnessHeaders { + freshness_state_snapshot(freshness, interval).1 +} + +fn freshness_state_snapshot( + freshness: &Mutex, + interval: Option, +) -> (FreshnessState, FreshnessHeaders) { + let state = *freshness.lock().unwrap(); + if state.pinned { + return ( + state, + FreshnessHeaders { + generation: state.generation, + ..FreshnessHeaders::default() + }, + ); + } + ( + state, + FreshnessHeaders { + generation: state.generation, + min_version: state.min_version, + min_timestamp: compute_min_timestamp(&state, interval, SystemTime::now()), + min_read_version: state.min_read_version, + }, + ) +} + /// Normalize a branch selector: trim whitespace and treat `""` or `"main"` as /// the (absent) main branch, matching the server's convention. fn normalize_branch(branch: Option) -> Option { @@ -210,8 +340,9 @@ impl Tags for RemoteTags<'_, S> { async fn list(&self) -> Result> { let request = self .inner - .post_read(&format!("/v1/table/{}/tags/list/", self.inner.identifier)); - let (request_id, response) = self.inner.send(request, true).await?; + .client + .post(&format!("/v1/table/{}/tags/list/", self.inner.identifier)); + let (request_id, response) = self.inner.send_unfenced(request, true).await?; let response = self .inner .check_table_response(&request_id, response) @@ -241,12 +372,12 @@ impl Tags for RemoteTags<'_, S> { } async fn get_version(&self, tag: &str) -> Result { - let request = self.inner.post_read(&format!( + let request = self.inner.client.post(&format!( "/v1/table/{}/tags/version/", self.inner.identifier )); self.inner - .resolve_tag_version_with_request(tag, request) + .resolve_tag_version_with_request(tag, request, false) .await } @@ -276,7 +407,7 @@ impl Tags for RemoteTags<'_, S> { .post(&format!("/v1/table/{}/tags/delete/", self.inner.identifier)) .json(&serde_json::json!({ "tag": tag })); - let (request_id, response) = self.inner.send(request, true).await?; + let (request_id, response) = self.inner.send_unfenced(request, true).await?; self.inner .check_table_response(&request_id, response) .await?; @@ -468,6 +599,7 @@ impl RemoteTable { let Ok(description) = serde_json::from_str::(describe_body) else { return; }; + self.track_read_version(description.version); if let Ok(schema) = arrow_schema::Schema::try_from(description.schema) { self.schema_cache.seed(Arc::new(schema)); } @@ -510,23 +642,50 @@ impl RemoteTable { } async fn describe(&self) -> Result { - let version = self.current_version().await; - self.describe_version(version).await + self.describe_read_snapshot(self.snapshot_read_state().await) + .await } - async fn describe_version(&self, version: Option) -> Result { - let request = self.post_read(&format!("/v1/table/{}/describe/", self.identifier)); - self.describe_with_request(request, version).await + async fn describe_read_snapshot( + &self, + read_snapshot: ReadSnapshot, + ) -> Result { + let request = self + .client + .post(&format!("/v1/table/{}/describe/", self.identifier)); + self.describe_with_request( + request, + read_snapshot.version, + Some(read_snapshot.freshness), + ) + .await + } + + async fn schema_read_snapshot(&self, read_snapshot: ReadSnapshot) -> Result { + if read_snapshot.freshness.is_current(&self.freshness) + && let Some(schema) = self.schema_cache.try_get() + && read_snapshot.freshness.is_current(&self.freshness) + { + return Ok(schema); + } + + let description = self.describe_read_snapshot(read_snapshot).await?; + Ok(Arc::new(description.schema.try_into()?)) } async fn resolve_tag_version_with_request( &self, tag: &str, request: RequestBuilder, + fenced: bool, ) -> Result { let request = request.json(&serde_json::json!({ "tag": tag })); - let (request_id, response) = self.send(request, true).await?; + let (request_id, response) = if fenced { + self.send(request, true).await? + } else { + self.send_unfenced(request, true).await? + }; let response = self.check_table_response(&request_id, response).await?; match response.text().await { @@ -565,7 +724,7 @@ impl RemoteTable { .client .post(&format!("/v1/table/{}/tags/version/", self.identifier)) .json(&serde_json::json!({ "tag": tag })); - let (request_id, response) = self.send(request, true).await?; + let (request_id, response) = self.send_unfenced(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(|e| Error::Http { @@ -592,21 +751,34 @@ impl RemoteTable { &self, request: RequestBuilder, version: Option, + freshness_request: Option, ) -> Result { let mut body = serde_json::json!({ "version": version }); self.apply_branch_body(&mut body); let request = request.json(&body); - let (request_id, response) = self.send(request, true).await?; + let (request_id, response) = if let Some(freshness_request) = freshness_request { + self.send_with_freshness(request, true, freshness_request) + .await? + } else { + self.send_unfenced(request, true).await? + }; let response = self.check_table_response(&request_id, response).await?; match response.text().await { - Ok(body) => serde_json::from_str(&body).map_err(|e| Error::Http { - source: format!("Failed to parse table description: {}", e).into(), - request_id, - status_code: None, - }), + Ok(body) => { + let description: TableDescription = + serde_json::from_str(&body).map_err(|e| Error::Http { + source: format!("Failed to parse table description: {}", e).into(), + request_id, + status_code: None, + })?; + if let Some(freshness_request) = freshness_request { + freshness_request.observe_version(&self.freshness, description.version); + } + Ok(description) + } Err(err) => { let status_code = err.status(); Err(Error::Http { @@ -619,14 +791,41 @@ impl RemoteTable { } async fn send(&self, req: RequestBuilder, with_retry: bool) -> Result<(String, Response)> { + let freshness_request = self.snapshot_freshness_headers(); + self.send_with_freshness(req, with_retry, freshness_request) + .await + } + + async fn send_with_freshness( + &self, + req: RequestBuilder, + with_retry: bool, + freshness_request: FreshnessHeaders, + ) -> Result<(String, Response)> { + let req = freshness_request.apply(req); let res = if with_retry { self.client.send_with_retry(req, None, true).await? } else { self.client.send(req).await? }; + if res.1.status().is_success() { + freshness_request.observe_headers(&self.freshness, res.1.headers()); + } Ok(res) } + async fn send_unfenced( + &self, + req: RequestBuilder, + with_retry: bool, + ) -> Result<(String, Response)> { + if with_retry { + self.client.send_with_retry(req, None, true).await + } else { + self.client.send(req).await + } + } + pub(super) async fn handle_table_not_found( table_name: &str, response: reqwest::Response, @@ -1003,24 +1202,32 @@ impl RemoteTable { } } - async fn current_version(&self) -> Option { - let read_guard = self.version.read().await; - *read_guard + async fn snapshot_read_state(&self) -> ReadSnapshot { + let version = self.version.read().await; + let (freshness_state, freshness) = + freshness_state_snapshot(&self.freshness, self.client.read_consistency_interval); + ReadSnapshot { + version: *version, + freshness_state, + freshness, + } } - /// Snapshot the freshness headers to attach to a single read request. + /// Snapshot the freshness headers to attach to a single table request. /// Computed at call time so that retries reuse the same snapshot. fn snapshot_freshness_headers(&self) -> FreshnessHeaders { - let state = *self.freshness.lock().unwrap(); - FreshnessHeaders { - min_version: state.min_version, - min_timestamp: compute_min_timestamp( - &state, - self.client.read_consistency_interval, - SystemTime::now(), - ), - min_read_version: state.min_read_version, - } + freshness_headers_snapshot(&self.freshness, self.client.read_consistency_interval) + } + + fn reset_freshness(&self, checkout_baseline: Option, pinned: bool) { + let mut state = self.freshness.lock().unwrap(); + let generation = state.generation.wrapping_add(1); + *state = FreshnessState { + generation, + pinned, + checkout_baseline, + ..FreshnessState::default() + }; } /// Send an LSM operator request with the transport retry layer **off**. @@ -1035,46 +1242,25 @@ impl RemoteTable { Ok((request_id, response)) } - /// Build a POST request and attach the read-freshness headers - /// (`x-lancedb-min-version`, `x-lancedb-min-timestamp`). - fn post_read(&self, uri: &str) -> RequestBuilder { - self.snapshot_freshness_headers() - .apply(self.client.post(uri)) - } - /// Record a version returned by a write so subsequent reads can request at /// least that version via `x-lancedb-min-version`. A returned `0` from a /// backward-compatible old server is ignored. - fn track_write_version(&self, version: u64) { + fn track_write_version(&self, freshness_request: FreshnessHeaders, version: u64) { if version == 0 { return; } - let mut state = self.freshness.lock().unwrap(); - state.min_version = Some(state.min_version.map_or(version, |v| v.max(version))); + freshness_request.update_if_current(&self.freshness, |state| { + state.min_version = Some(state.min_version.map_or(version, |v| v.max(version))); + }); } - /// Record a dataset version observed in a *read* response so subsequent - /// reads request at least this version via `x-lancedb-min-read-version`, + /// Record a committed dataset version observed in a table response so + /// subsequent requests ask for at least this version via + /// `x-lancedb-min-read-version`, /// giving monotonic reads across load-balanced query nodes. A returned `0` /// (or absent header from an old server) is ignored. fn track_read_version(&self, version: u64) { - if version == 0 { - return; - } - let mut state = self.freshness.lock().unwrap(); - state.min_read_version = Some(state.min_read_version.map_or(version, |v| v.max(version))); - } - - /// Parse the `x-lancedb-version` response header (the dataset version a read - /// reflects) and fold it into the read-version watermark. - fn track_read_version_from_headers(&self, headers: &reqwest::header::HeaderMap) { - if let Some(version) = headers - .get(&VERSION_HEADER) - .and_then(|value| value.to_str().ok()) - .and_then(|value| value.parse::().ok()) - { - self.track_read_version(version); - } + track_read_version(&self.freshness, version); } async fn execute_query( @@ -1082,7 +1268,9 @@ impl RemoteTable { query: &AnyQuery, options: &QueryExecutionOptions, ) -> Result>>> { - let mut request = self.post_read(&format!("/v1/table/{}/query/", self.identifier)); + let mut request = self + .client + .post(&format!("/v1/table/{}/query/", self.identifier)); if let Some(timeout) = options.timeout { // Also send to server, so it can abort the query if it takes too long. @@ -1092,15 +1280,17 @@ impl RemoteTable { } } - let query_bodies = self.prepare_query_bodies(query).await?; + let read_snapshot = self.snapshot_read_state().await; + let query_bodies = self.prepare_query_bodies(query, read_snapshot.version)?; let requests: Vec = query_bodies .into_iter() .map(|body| request.try_clone().unwrap().json(&body)) .collect(); let futures = requests.into_iter().map(|req| async move { - let (request_id, response) = self.send(req, true).await?; - self.track_read_version_from_headers(response.headers()); + let (request_id, response) = self + .send_with_freshness(req, true, read_snapshot.freshness) + .await?; self.read_arrow_response(&request_id, response).await }); let streams = futures::future::try_join_all(futures); @@ -1125,8 +1315,11 @@ impl RemoteTable { } } - async fn prepare_query_bodies(&self, query: &AnyQuery) -> Result> { - let version = self.current_version().await; + fn prepare_query_bodies( + &self, + query: &AnyQuery, + version: Option, + ) -> Result> { let mut base_body = serde_json::json!({ "version": version }); self.apply_branch_body(&mut base_body); @@ -1230,14 +1423,15 @@ async fn fetch_schema( client: &RestfulLanceDbClient, identifier: &str, table_name: &str, - version: Option, + read_snapshot: ReadSnapshot, branch: Option, - freshness_headers: FreshnessHeaders, + freshness: Arc>, ) -> Result { - let mut body = serde_json::json!({ "version": version }); + let mut body = serde_json::json!({ "version": read_snapshot.version }); if let Some(branch) = &branch { body["branch"] = serde_json::Value::String(branch.clone()); } + let freshness_headers = read_snapshot.freshness; let request = freshness_headers .apply(client.post(&format!("/v1/table/{}/describe/", identifier))) .json(&body); @@ -1257,6 +1451,7 @@ async fn fetch_schema( } let response = client.check_response(&request_id, response).await?; + freshness_headers.observe_headers(&freshness, response.headers()); let body = response.text().await.map_err(|e| { let status_code = e.status(); Error::Http { @@ -1271,6 +1466,12 @@ async fn fetch_schema( request_id, status_code: None, })?; + freshness_headers.observe_version(&freshness, description.version); + if !freshness_headers.is_current(&freshness) { + return Err(Error::Runtime { + message: SCHEMA_SELECTOR_CHANGED.to_string(), + }); + } let arrow_schema: arrow_schema::Schema = description.schema.try_into()?; Ok(Arc::new(arrow_schema)) @@ -1401,18 +1602,25 @@ impl RemoteTable { use crate::remote::retry::RetryCounter; let _guard = output.tracker.as_ref().map(|t| t.track_task()); + let freshness_request = self.snapshot_freshness_headers(); - let mut insert: Arc = Arc::new(RemoteWriteExec::new( - self.name.clone(), - self.identifier.clone(), - self.client.clone(), - output.plan, - WriteOp::Insert { - overwrite: output.overwrite, - }, - output.tracker.clone(), - self.branch.clone(), - )); + let mut insert: Arc = Arc::new( + RemoteWriteExec::new( + self.name.clone(), + self.identifier.clone(), + self.client.clone(), + output.plan, + WriteOp::Insert { + overwrite: output.overwrite, + }, + output.tracker.clone(), + self.branch.clone(), + ) + .with_freshness( + self.freshness.clone(), + self.client.read_consistency_interval, + ), + ); let mut retry_counter = RetryCounter::new(&self.client.retry_config, uuid::Uuid::new_v4().to_string()); @@ -1431,7 +1639,7 @@ impl RemoteTable { if output.overwrite { self.invalidate_schema_cache(); } - self.track_write_version(add_result.version); + self.track_write_version(freshness_request, add_result.version); return Ok(add_result); } @@ -1457,6 +1665,7 @@ impl RemoteTable { 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 @@ -1469,7 +1678,7 @@ impl RemoteTable { if output.overwrite { self.invalidate_schema_cache(); } - self.track_write_version(result.version); + self.track_write_version(freshness_request, result.version); return Ok(result); } Err(e) => { @@ -1525,18 +1734,24 @@ impl RemoteTable { )?, ) as Arc; - let insert = Arc::new(RemoteWriteExec::new_multipart( - self.name.clone(), - self.identifier.clone(), - self.client.clone(), - plan, - output.overwrite, - upload_id.to_string(), - output.tracker.clone(), - self.branch.clone(), - self.client.max_bytes_per_request(), - self.client.max_request_duration(), - )); + let insert = Arc::new( + RemoteWriteExec::new_multipart( + self.name.clone(), + self.identifier.clone(), + self.client.clone(), + plan, + output.overwrite, + upload_id.to_string(), + output.tracker.clone(), + self.branch.clone(), + self.client.max_bytes_per_request(), + self.client.max_request_duration(), + ) + .with_freshness( + self.freshness.clone(), + self.client.read_consistency_interval, + ), + ); let task_ctx = Arc::new(datafusion_execution::TaskContext::default()); let tracker = output.tracker.clone(); @@ -1599,6 +1814,38 @@ where } impl RemoteTable { + async fn index_stats_read_snapshot( + &self, + index_name: &str, + read_snapshot: ReadSnapshot, + ) -> Result> { + let encoded_name = urlencoding::encode(index_name); + let mut body = serde_json::json!({ "version": read_snapshot.version }); + self.apply_branch_body(&mut body); + let request = self + .client + .post(&format!( + "/v1/table/{}/index/{encoded_name}/stats/", + self.identifier + )) + .json(&body); + + let (request_id, response) = self + .send_with_freshness(request, true, read_snapshot.freshness) + .await?; + if response.status() == StatusCode::NOT_FOUND { + return Ok(None); + } + let response = self.check_table_response(&request_id, response).await?; + let body = response.text().await.err_to_http(request_id.clone())?; + let stats = serde_json::from_str(&body).map_err(|e| Error::Http { + source: format!("Failed to parse index statistics: {}", e).into(), + request_id, + status_code: None, + })?; + Ok(Some(stats)) + } + /// Parse the response from `/index/list/` into `IndexConfig` entries. /// /// When the server returns `index_type` inline, all enriched fields are @@ -1610,6 +1857,7 @@ impl RemoteTable { body: &str, request_id: &str, schema: &SchemaRef, + read_snapshot: ReadSnapshot, ) -> Result> { use crate::index::IndexType; @@ -1678,7 +1926,10 @@ impl RemoteTable { })) } else { // Legacy response: fetch index type via stats endpoint. - match self.index_stats(&entry.index_name).await { + match self + .index_stats_read_snapshot(&entry.index_name, read_snapshot) + .await + { Ok(Some(stats)) => Ok(Some(IndexConfig { name: entry.index_name, index_type: stats.index_type, @@ -1762,7 +2013,7 @@ impl BaseTable for RemoteTable { let request = self .client .post(&format!("/v1/table/{}/describe/", self.identifier)); - self.describe_with_request(request, Some(version)) + self.describe_with_request(request, Some(version), None) .await .map_err(|e| match e { // try to map the error to a more user-friendly error telling them @@ -1775,58 +2026,52 @@ impl BaseTable for RemoteTable { })?; let mut write_guard = self.version.write().await; + // Commit the selector and its freshness mode while holding the selector + // write lock, with no cancellation point between the two updates. + self.reset_freshness(None, true); *write_guard = Some(version); - drop(write_guard); - - // Explicit time-travel: drop any read-your-write / freshness - // constraints so the user sees exactly the requested version. - *self.freshness.lock().unwrap() = FreshnessState::default(); - - // Invalidate schema cache since we're switching versions self.invalidate_schema_cache(); + drop(write_guard); Ok(()) } async fn checkout_latest(&self) -> Result<()> { let mut write_guard = self.version.write().await; - *write_guard = None; - drop(write_guard); - // Drop any per-handle read/write tracking; subsequent reads use the // baseline timestamp captured now to guarantee freshness. - *self.freshness.lock().unwrap() = FreshnessState { - min_version: None, - checkout_baseline: Some(SystemTime::now()), - min_read_version: None, - }; - - // Invalidate schema cache since we're switching versions + self.reset_freshness(Some(SystemTime::now()), false); + *write_guard = None; self.invalidate_schema_cache(); + drop(write_guard); 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. - let version = match self.current_version().await { + let read_snapshot = self.snapshot_read_state().await; + let version = match read_snapshot.version { Some(version) => version, - None => self.describe().await?.version, + None => self.describe_read_snapshot(read_snapshot).await?.version, }; let snapshot = self.with_branch(self.branch.clone()); *snapshot.version.write().await = Some(version); + snapshot.reset_freshness(None, true); Ok(Some(Arc::new(snapshot))) } async fn restore(&self) -> Result<()> { let mut request = self .client .post(&format!("/v1/table/{}/restore/", self.identifier)); - let version = self.current_version().await; - let mut body = serde_json::json!({ "version": version }); + let read_snapshot = self.snapshot_read_state().await; + let mut body = serde_json::json!({ "version": read_snapshot.version }); self.apply_branch_body(&mut body); request = request.json(&body); - let (request_id, response) = self.send(request, true).await?; + let (request_id, response) = self + .send_with_freshness(request, true, read_snapshot.freshness) + .await?; self.check_table_response(&request_id, response).await?; self.checkout_latest().await?; Ok(()) @@ -1834,7 +2079,8 @@ impl BaseTable for RemoteTable { async fn list_versions(&self) -> Result> { let request = self.apply_branch_query( - self.post_read(&format!("/v1/table/{}/version/list/", self.identifier)), + self.client + .post(&format!("/v1/table/{}/version/list/", self.identifier)), ); let (request_id, response) = self.send(request, true).await?; let response = self.check_table_response(&request_id, response).await?; @@ -1898,31 +2144,42 @@ impl BaseTable for RemoteTable { } async fn schema(&self) -> Result { - if let Some(schema) = self.schema_cache.try_get() { - return Ok(schema); - } + loop { + let read_snapshot = self.snapshot_read_state().await; + if let Some(schema) = self.schema_cache.try_get() { + return Ok(schema); + } - let version = self.current_version().await; - let client = self.client.clone(); - let identifier = self.identifier.clone(); - let table_name = self.name.clone(); - let branch = self.branch.clone(); - let freshness_headers = self.snapshot_freshness_headers(); + let client = self.client.clone(); + let identifier = self.identifier.clone(); + let table_name = self.name.clone(); + let branch = self.branch.clone(); + let freshness = self.freshness.clone(); - self.schema_cache - .get(move || async move { - fetch_schema( - &client, - &identifier, - &table_name, - version, - branch, - freshness_headers, - ) + match self + .schema_cache + .get(move || async move { + fetch_schema( + &client, + &identifier, + &table_name, + read_snapshot, + branch, + freshness, + ) + .await + }) .await - }) - .await - .map_err(unwrap_shared_error) + { + Ok(schema) => return Ok(schema), + Err(error) + if matches!( + &*error, + Error::Runtime { message } if message == SCHEMA_SELECTOR_CHANGED + ) => {} + Err(error) => return Err(unwrap_shared_error(error)), + } + } } async fn create_branch( @@ -1964,7 +2221,7 @@ impl BaseTable for RemoteTable { // Send without retry so the expected 409 (branch already exists) is // surfaced as a response we can map, rather than being retried. - let (request_id, response) = self.send(request, false).await?; + let (request_id, response) = self.send_unfenced(request, false).await?; match response.status() { StatusCode::CONFLICT => { return Err(Error::TableAlreadyExists { @@ -2025,8 +2282,10 @@ impl BaseTable for RemoteTable { async fn list_branches(&self) -> Result> { use lance::dataset::refs::BranchContents; - let request = self.post_read(&format!("/v1/table/{}/branches/list/", self.identifier)); - let (request_id, response) = self.send(request, true).await?; + let request = self + .client + .post(&format!("/v1/table/{}/branches/list/", self.identifier)); + let (request_id, response) = self.send_unfenced(request, true).await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -2080,7 +2339,7 @@ impl BaseTable for RemoteTable { .client .post(&format!("/v1/table/{}/branches/diff/", self.identifier)) .json(&serde_json::json!({ "from_branch": from_branch })); - let (request_id, response) = self.send(request, true).await?; + let (request_id, response) = self.send_unfenced(request, true).await?; if response.status() == StatusCode::NOT_FOUND { return Err(Error::TableNotFound { name: format!("{} (branch: {})", self.name, from_branch), @@ -2106,6 +2365,12 @@ impl BaseTable for RemoteTable { message: "Branch name cannot be empty.".into(), }); } + let read_snapshot = self.snapshot_read_state().await; + let target_freshness = if self.branch.is_none() && read_snapshot.version.is_none() { + Some(read_snapshot.freshness) + } else { + None + }; let request = self .client .post(&format!( @@ -2117,7 +2382,7 @@ impl BaseTable for RemoteTable { "dry_run": dry_run, })); // No retry. HTTP 409 is CherryPickStatus::Failed with a body, not a transport error. - let (request_id, response) = self.send(request, false).await?; + let (request_id, response) = self.send_unfenced(request, false).await?; let status = response.status(); if status == StatusCode::NOT_FOUND { return Err(Error::TableNotFound { @@ -2135,7 +2400,7 @@ impl BaseTable for RemoteTable { }); } let body = response.text().await.err_to_http(request_id.clone())?; - serde_json::from_str(&body).map_err(|err| Error::Http { + let result: CherryPickResult = serde_json::from_str(&body).map_err(|err| Error::Http { source: format!( "Failed to parse cherry_pick response: {}, body: {}", err, body @@ -2143,7 +2408,15 @@ impl BaseTable for RemoteTable { .into(), request_id, status_code: Some(status), - }) + })?; + if !dry_run + && status == StatusCode::OK + && result.status == crate::table::CherryPickStatus::CherryPicked + && let (Some(freshness), Some(version)) = (target_freshness, result.main_version_after) + { + freshness.observe_version(&self.freshness, version); + } + Ok(result) } fn current_branch(&self) -> Option { @@ -2151,23 +2424,28 @@ impl BaseTable for RemoteTable { } async fn count_rows(&self, filter: Option) -> Result { - let mut request = self.post_read(&format!("/v1/table/{}/count_rows/", self.identifier)); + let mut request = self + .client + .post(&format!("/v1/table/{}/count_rows/", self.identifier)); - let version = self.current_version().await; + let read_snapshot = self.snapshot_read_state().await; let mut body = if let Some(filter) = filter { let filter_sql = match filter { Filter::Sql(sql) => sql.clone(), Filter::Datafusion(expr) => expr_to_sql_string(&expr)?, }; - serde_json::json!({ "predicate": filter_sql, "version": version }) + serde_json::json!({ "predicate": filter_sql, "version": read_snapshot.version }) } else { - serde_json::json!({ "version": version }) + serde_json::json!({ "version": read_snapshot.version }) }; self.apply_branch_body(&mut body); request = request.json(&body); - let (request_id, response) = match self.send(request, true).await { + let (request_id, response) = match self + .send_with_freshness(request, true, read_snapshot.freshness) + .await + { Ok((id, resp)) => { // check_table_response now handles error-based invalidation let response = self.check_table_response(&id, resp).await?; @@ -2179,7 +2457,6 @@ impl BaseTable for RemoteTable { } }; - self.track_read_version_from_headers(response.headers()); let body = response.text().await.err_to_http(request_id.clone())?; serde_json::from_str(&body).map_err(|e| Error::Http { @@ -2312,9 +2589,12 @@ impl BaseTable for RemoteTable { } async fn explain_plan(&self, query: &AnyQuery, verbose: bool) -> Result { - let base_request = self.post_read(&format!("/v1/table/{}/explain_plan/", self.identifier)); + let base_request = self + .client + .post(&format!("/v1/table/{}/explain_plan/", self.identifier)); - let query_bodies = self.prepare_query_bodies(query).await?; + let read_snapshot = self.snapshot_read_state().await; + let query_bodies = self.prepare_query_bodies(query, read_snapshot.version)?; let requests: Vec = query_bodies .into_iter() .map(|query_body| { @@ -2328,7 +2608,9 @@ impl BaseTable for RemoteTable { .collect::>(); let futures = requests.into_iter().map(|req| async move { - let (request_id, response) = self.send(req, true).await?; + let (request_id, response) = self + .send_with_freshness(req, true, read_snapshot.freshness) + .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -2359,7 +2641,9 @@ impl BaseTable for RemoteTable { query: &AnyQuery, options: QueryExecutionOptions, ) -> Result { - let mut request = self.post_read(&format!("/v1/table/{}/analyze_plan/", self.identifier)); + let mut request = self + .client + .post(&format!("/v1/table/{}/analyze_plan/", self.identifier)); if options.analyze_plan_distributed_metrics != AnalyzePlanDistributedMetrics::Aggregate { request = request.query(&[( @@ -2368,14 +2652,17 @@ impl BaseTable for RemoteTable { )]); } - let query_bodies = self.prepare_query_bodies(query).await?; + let read_snapshot = self.snapshot_read_state().await; + let query_bodies = self.prepare_query_bodies(query, read_snapshot.version)?; let requests: Vec = query_bodies .into_iter() .map(|body| request.try_clone().unwrap().json(&body)) .collect(); let futures = requests.into_iter().map(|req| async move { - let (request_id, response) = self.send(req, true).await?; + let (request_id, response) = self + .send_with_freshness(req, true, read_snapshot.freshness) + .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -2419,7 +2706,10 @@ impl BaseTable for RemoteTable { self.apply_branch_body(&mut body); let request = request.json(&body); - let (request_id, response) = self.send(request, true).await?; + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = self + .send_with_freshness(request, true, freshness_request) + .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -2438,7 +2728,7 @@ impl BaseTable for RemoteTable { status_code: None, })?; - self.track_write_version(update_response.version); + self.track_write_version(freshness_request, update_response.version); Ok(update_response) } @@ -2454,7 +2744,10 @@ impl BaseTable for RemoteTable { .client .post(&format!("/v1/table/{}/delete/", self.identifier)) .json(&body); - let (request_id, response) = self.send(request, true).await?; + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = self + .send_with_freshness(request, true, freshness_request) + .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; if body.trim().is_empty() { @@ -2470,7 +2763,7 @@ impl BaseTable for RemoteTable { request_id, status_code: None, })?; - self.track_write_version(delete_response.version); + self.track_write_version(freshness_request, delete_response.version); Ok(delete_response) } @@ -2480,7 +2773,13 @@ impl BaseTable for RemoteTable { async fn create_index_async(&self, index: IndexBuilder) -> Result { Ok(match self.submit_create_index(index).await? { - Some(job_id) => Job::new(Box::new(RemoteJob::new(self.client.clone(), job_id))), + Some(job_id) => Job::new(Box::new(FreshnessJob { + inner: RemoteJob::new(self.client.clone(), job_id), + freshness: self.freshness.clone(), + version: self.version.clone(), + track_refresh_result: false, + freshness_request: self.snapshot_freshness_headers(), + })), None => Job::new_done(), }) } @@ -2520,16 +2819,23 @@ impl BaseTable for RemoteTable { let rescannable = source.rescannable(); let input: Arc = Arc::new(crate::table::datafusion::scannable_exec::ScannableExec::new(source, None)); + let freshness_request = self.snapshot_freshness_headers(); - let mut merge: Arc = Arc::new(RemoteWriteExec::new( - self.name.clone(), - self.identifier.clone(), - self.client.clone(), - input, - WriteOp::MergeInsert { query, timeout }, - None, - self.branch.clone(), - )); + let mut merge: Arc = Arc::new( + RemoteWriteExec::new( + self.name.clone(), + self.identifier.clone(), + self.client.clone(), + input, + WriteOp::MergeInsert { query, timeout }, + None, + self.branch.clone(), + ) + .with_freshness( + self.freshness.clone(), + self.client.read_consistency_interval, + ), + ); let mut retry_counter = crate::remote::retry::RetryCounter::new( &self.client.retry_config, @@ -2547,7 +2853,7 @@ impl BaseTable for RemoteTable { .and_then(|m| m.merge_result()) .unwrap_or_default(); - self.track_write_version(merge_result.version); + self.track_write_version(freshness_request, merge_result.version); return Ok(merge_result); } Err(err) if rescannable && self.is_retryable_write_error(&err) => { @@ -2586,7 +2892,8 @@ impl BaseTable for RemoteTable { async fn get_lsm_stats(&self, include_generation_rows: bool) -> Result> { // Read-semantics POST, like `get_lsm_write_spec`. let request = self - .post_read(&format!("/v1/table/{}/get_lsm_stats/", self.identifier)) + .client + .post(&format!("/v1/table/{}/get_lsm_stats/", self.identifier)) .json(&serde_json::json!({ "include_generation_rows": include_generation_rows, })); @@ -2660,7 +2967,7 @@ impl BaseTable for RemoteTable { // re-encodes it into the same sophon-owned shape the set endpoint // accepts — no lance/lancedb types cross the wire. `lsm_write_spec` is // null when the LSM write path is not enabled for the table. - let request = self.post_read(&format!( + let request = self.client.post(&format!( "/v1/table/{}/get_lsm_write_spec/", self.identifier )); @@ -2726,18 +3033,17 @@ impl BaseTable for RemoteTable { let request = self .client .post(&format!("/v1/table/{}/tags/version/", self.identifier)); - let version = self.resolve_tag_version_with_request(tag, request).await?; + let version = self + .resolve_tag_version_with_request(tag, request, false) + .await?; let mut write_guard = self.version.write().await; + // Commit the selector and its freshness mode while holding the selector + // write lock, with no cancellation point between the two updates. + self.reset_freshness(None, true); *write_guard = Some(version); - drop(write_guard); - - // Explicit time-travel: drop any read-your-write / freshness - // constraints so the user sees exactly the tagged version. - *self.freshness.lock().unwrap() = FreshnessState::default(); - - // Invalidate schema cache since we're switching versions self.invalidate_schema_cache(); + drop(write_guard); Ok(()) } @@ -2774,7 +3080,10 @@ impl BaseTable for RemoteTable { .client .post(&format!("/v1/table/{}/add_columns/", self.identifier)) .json(&body); - let (request_id, response) = self.send(request, true).await?; + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = self + .send_with_freshness(request, true, freshness_request) + .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -2791,7 +3100,7 @@ impl BaseTable for RemoteTable { })?; self.invalidate_schema_cache(); - self.track_write_version(result.version); + self.track_write_version(freshness_request, result.version); Ok(result) } @@ -2827,7 +3136,10 @@ impl BaseTable for RemoteTable { .client .post(&format!("/v1/table/{}/add_columns/", self.identifier)) .json(&body); - let (request_id, response) = self.send(request, true).await?; + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = self + .send_with_freshness(request, true, freshness_request) + .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -2843,7 +3155,7 @@ impl BaseTable for RemoteTable { })?; self.invalidate_schema_cache(); - self.track_write_version(result.version); + self.track_write_version(freshness_request, result.version); Ok(result) } @@ -2886,7 +3198,10 @@ impl BaseTable for RemoteTable { .client .post(&format!("/v1/table/{}/add_columns/", self.identifier)) .json(&body); - let (request_id, response) = self.send(request, true).await?; + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = self + .send_with_freshness(request, true, freshness_request) + .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -2901,7 +3216,7 @@ impl BaseTable for RemoteTable { })?; self.invalidate_schema_cache(); - self.track_write_version(result.version); + self.track_write_version(freshness_request, result.version); Ok(result) } @@ -2923,7 +3238,8 @@ impl BaseTable for RemoteTable { let mut body = serde_json::json!({ "column": column }); self.apply_branch_body(&mut body); let request = self - .post_read(&format!("/v1/table/{}/backfill_column", self.identifier)) + .client + .post(&format!("/v1/table/{}/backfill_column", self.identifier)) .json(&body); let (request_id, response) = self.send(request, true).await?; let response = self.check_table_response(&request_id, response).await?; @@ -2943,6 +3259,8 @@ impl BaseTable for RemoteTable { inner: RemoteJob::new(self.client.clone(), response.job_id), freshness: self.freshness.clone(), version: self.version.clone(), + track_refresh_result: true, + freshness_request: self.snapshot_freshness_headers(), }))) } @@ -2974,7 +3292,10 @@ impl BaseTable for RemoteTable { .client .post(&format!("/v1/table/{}/alter_columns/", self.identifier)) .json(&body); - let (request_id, response) = self.send(request, true).await?; + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = self + .send_with_freshness(request, true, freshness_request) + .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -2990,7 +3311,7 @@ impl BaseTable for RemoteTable { })?; self.invalidate_schema_cache(); - self.track_write_version(result.version); + self.track_write_version(freshness_request, result.version); Ok(result) } @@ -3009,7 +3330,10 @@ impl BaseTable for RemoteTable { self.identifier )) .json(&body); - let (request_id, response) = self.send(request, true).await?; + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = self + .send_with_freshness(request, true, freshness_request) + .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -3021,7 +3345,7 @@ impl BaseTable for RemoteTable { })?; self.invalidate_schema_cache(); - self.track_write_version(result.version); + self.track_write_version(freshness_request, result.version); Ok(result) } @@ -3033,7 +3357,10 @@ impl BaseTable for RemoteTable { .client .post(&format!("/v1/table/{}/drop_columns/", self.identifier)) .json(&body); - let (request_id, response) = self.send(request, true).await?; + let freshness_request = self.snapshot_freshness_headers(); + let (request_id, response) = self + .send_with_freshness(request, true, freshness_request) + .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; @@ -3049,55 +3376,34 @@ impl BaseTable for RemoteTable { })?; self.invalidate_schema_cache(); - self.track_write_version(result.version); + self.track_write_version(freshness_request, result.version); Ok(result) } async fn list_indices(&self) -> Result> { - let mut request = self.post_read(&format!("/v1/table/{}/index/list/", self.identifier)); - let version = self.current_version().await; - let mut body = serde_json::json!({ "version": version }); + let mut request = self + .client + .post(&format!("/v1/table/{}/index/list/", self.identifier)); + let read_snapshot = self.snapshot_read_state().await; + let mut body = serde_json::json!({ "version": read_snapshot.version }); self.apply_branch_body(&mut body); request = request.json(&body); - let (request_id, response) = self.send(request, true).await?; + let (request_id, response) = self + .send_with_freshness(request, true, read_snapshot.freshness) + .await?; let response = self.check_table_response(&request_id, response).await?; let body = response.text().await.err_to_http(request_id.clone())?; - let schema = self.schema().await?; + let schema = self.schema_read_snapshot(read_snapshot).await?; - self.parse_index_list_response(&body, &request_id, &schema) + self.parse_index_list_response(&body, &request_id, &schema, read_snapshot) .await } async fn index_stats(&self, index_name: &str) -> Result> { - let encoded_name = urlencoding::encode(index_name); - let mut request = self.post_read(&format!( - "/v1/table/{}/index/{encoded_name}/stats/", - self.identifier - )); - let version = self.current_version().await; - let mut body = serde_json::json!({ "version": version }); - self.apply_branch_body(&mut body); - request = request.json(&body); - - let (request_id, response) = self.send(request, true).await?; - - if response.status() == StatusCode::NOT_FOUND { - return Ok(None); - } - - let response = self.check_table_response(&request_id, response).await?; - - let body = response.text().await.err_to_http(request_id.clone())?; - - let stats = serde_json::from_str(&body).map_err(|e| Error::Http { - source: format!("Failed to parse index statistics: {}", e).into(), - request_id, - status_code: None, - })?; - - Ok(Some(stats)) + self.index_stats_read_snapshot(index_name, self.snapshot_read_state().await) + .await } async fn drop_index(&self, index_name: &str) -> Result<()> { @@ -3187,7 +3493,9 @@ impl BaseTable for RemoteTable { } async fn stats(&self) -> Result { - let mut request = self.post_read(&format!("/v1/table/{}/stats/", self.identifier)); + let mut request = self + .client + .post(&format!("/v1/table/{}/stats/", self.identifier)); if let Some(branch) = &self.branch { request = request.json(&serde_json::json!({ "branch": branch })); } @@ -3209,15 +3517,21 @@ impl BaseTable for RemoteTable { write_params: lance::dataset::WriteParams, ) -> Result> { let overwrite = matches!(write_params.mode, lance::dataset::WriteMode::Overwrite); - Ok(Arc::new(insert::RemoteWriteExec::new( - self.name.clone(), - self.identifier.clone(), - self.client.clone(), - input, - WriteOp::Insert { overwrite }, - None, - self.branch.clone(), - ))) + Ok(Arc::new( + insert::RemoteWriteExec::new( + self.name.clone(), + self.identifier.clone(), + self.client.clone(), + input, + WriteOp::Insert { overwrite }, + None, + self.branch.clone(), + ) + .with_freshness( + self.freshness.clone(), + self.client.read_consistency_interval, + ), + )) } } @@ -7113,12 +7427,12 @@ mod tests { } /// The gate's reproducer: after a successful wait, a same-handle read - /// must carry a freshness baseline so a stale server cache cannot serve - /// the pre-backfill snapshot. + /// must carry the exact published version so a stale server cache cannot + /// serve the pre-backfill snapshot. #[tokio::test] async fn test_backfill_wait_establishes_read_freshness() { - let saw_min_timestamp = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let saw = saw_min_timestamp.clone(); + let saw_published_version = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let saw = saw_published_version.clone(); let table = Table::new_with_handler("my_table", move |request| match request.url().path() { "/v1/table/my_table/backfill_column" => http::Response::builder() @@ -7131,7 +7445,11 @@ mod tests { .unwrap(), "/v1/table/my_table/count_rows/" => { saw.store( - request.headers().contains_key("x-lancedb-min-timestamp"), + request + .headers() + .get("x-lancedb-min-read-version") + .and_then(|value| value.to_str().ok()) + == Some("8"), std::sync::atomic::Ordering::SeqCst, ); http::Response::builder() @@ -7148,8 +7466,8 @@ mod tests { assert_eq!(result.published_version, Some(8)); table.count_rows(None).await.unwrap(); assert!( - saw_min_timestamp.load(std::sync::atomic::Ordering::SeqCst), - "read after wait carried no freshness baseline" + saw_published_version.load(std::sync::atomic::Ordering::SeqCst), + "read after wait did not carry the published version" ); } @@ -7324,12 +7642,11 @@ mod tests { } /// checkout_latest keeps the handle on latest, so a completed backfill - /// must still establish its post-fill baseline -- strictly later than the - /// checkout's own, or a pre-fill cache could still serve. + /// must retain the checkout timestamp and add its exact published version. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn test_checkout_latest_during_submission_keeps_the_fence() { - let seen_min_timestamp = Arc::new(std::sync::Mutex::new(None::)); - let saw = seen_min_timestamp.clone(); + let seen_headers = Arc::new(std::sync::Mutex::new(None::)); + let saw = seen_headers.clone(); let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); let release_rx = Arc::new(std::sync::Mutex::new(release_rx)); let (arrived_tx, arrived_rx) = std::sync::mpsc::channel::<()>(); @@ -7353,10 +7670,7 @@ mod tests { .body(refresh_done("j-11")) .unwrap(), "/v1/table/my_table/count_rows/" => { - *saw.lock().unwrap() = request - .headers() - .get("x-lancedb-min-timestamp") - .map(|v| v.to_str().unwrap().to_string()); + *saw.lock().unwrap() = Some(request.headers().clone()); http::Response::builder() .status(200) .body("1".to_string()) @@ -7377,25 +7691,18 @@ mod tests { .await .unwrap(); table.checkout_latest().await.unwrap(); - let after_checkout = SystemTime::now(); - // Real separation between the checkout baseline and completion. - tokio::time::sleep(std::time::Duration::from_millis(50)).await; release_tx.send(()).unwrap(); let job = submit.await.unwrap().unwrap(); job.wait().await.unwrap(); table.count_rows(None).await.unwrap(); - let header = seen_min_timestamp - .lock() - .unwrap() - .clone() - .expect("no baseline"); - let sent: SystemTime = chrono::DateTime::parse_from_rfc3339(&header) - .unwrap() - .into(); - assert!( - sent > after_checkout, - "baseline {header} did not advance past the checkout" + let headers = seen_headers.lock().unwrap().clone().expect("no request"); + assert!(headers.contains_key("x-lancedb-min-timestamp")); + assert_eq!( + headers + .get("x-lancedb-min-read-version") + .and_then(|value| value.to_str().ok()), + Some("8") ); } @@ -8853,6 +9160,50 @@ mod tests { assert_ne!(Arc::as_ptr(&schema3), Arc::as_ptr(&schema1)); } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_schema_fetch_does_not_cross_checkout_generation() { + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let release_rx = Arc::new(std::sync::Mutex::new(release_rx)); + let (arrived_tx, arrived_rx) = std::sync::mpsc::channel::<()>(); + let arrived_tx = Arc::new(std::sync::Mutex::new(arrived_tx)); + let table = Table::new_with_handler("my_table", move |request| { + let body = request_body_json(&request); + let pinned = body["version"].as_u64() == Some(5); + if !pinned { + arrived_tx.lock().unwrap().send(()).unwrap(); + release_rx + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)) + .unwrap(); + } + let field = if pinned { "pinned" } else { "latest" }; + http::Response::builder() + .status(200) + .body(format!( + r#"{{"version":5,"schema":{{"fields":[{{"name":"{field}","type":{{"type":"int32"}},"nullable":false}}]}}}}"# + )) + .unwrap() + }); + + let schema_fetch = tokio::spawn({ + let table = table.clone(); + async move { table.schema().await } + }); + tokio::task::spawn_blocking(move || { + arrived_rx.recv_timeout(Duration::from_secs(10)).unwrap() + }) + .await + .unwrap(); + table.checkout(5).await.unwrap(); + release_tx.send(()).unwrap(); + + let schema = schema_fetch.await.unwrap().unwrap(); + assert!(schema.field_with_name("pinned").is_ok()); + let cached = table.schema().await.unwrap(); + assert!(cached.field_with_name("pinned").is_ok()); + } + /// Test that schema cache is invalidated after checkout_latest #[tokio::test] async fn test_schema_cache_invalidation_on_checkout_latest() { @@ -10087,6 +10438,7 @@ mod tests { min_version: None, checkout_baseline: Some(baseline), min_read_version: None, + ..FreshnessState::default() }; assert_eq!(compute_min_timestamp(&state, None, now), Some(baseline)); @@ -10112,6 +10464,7 @@ mod tests { min_version: None, checkout_baseline: Some(baseline), min_read_version: None, + ..FreshnessState::default() }; assert_eq!( compute_min_timestamp(&state, Some(Duration::from_secs(10)), now), @@ -10124,6 +10477,7 @@ mod tests { min_version: None, checkout_baseline: Some(recent_baseline), min_read_version: None, + ..FreshnessState::default() }; assert_eq!( compute_min_timestamp(&state, Some(Duration::from_secs(60)), now), @@ -10200,6 +10554,110 @@ mod tests { assert!(!headers.contains_key("x-lancedb-min-version")); } + #[tokio::test] + async fn test_checkout_disables_read_consistency_interval() { + let (handler, captured) = capturing_handler(|path| match path { + "/v1/table/my_table/describe/" => r#"{"version":5,"schema":{"fields":[]}}"#.to_string(), + "/v1/table/my_table/count_rows/" => "42".to_string(), + _ => panic!("unexpected path: {}", path), + }); + let table = + Table::new_with_handler_and_interval("my_table", handler, Some(Duration::from_secs(0))); + + table.checkout(5).await.unwrap(); + table.count_rows(None).await.unwrap(); + + let headers = captured.lock().unwrap().clone().unwrap(); + assert!(!headers.contains_key("x-lancedb-min-timestamp")); + assert!(!headers.contains_key("x-lancedb-min-version")); + assert!(!headers.contains_key("x-lancedb-min-read-version")); + } + + #[tokio::test] + async fn test_read_snapshot_keeps_selector_and_freshness_generation_bound() { + let table = RemoteTable::new_mock_with_consistency_interval( + "my_table".to_string(), + |_| { + http::Response::builder() + .status(200) + .body(r#"{"version":5,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + }, + Some(Duration::ZERO), + ); + + let latest = table.snapshot_read_state().await; + table.checkout(5).await.unwrap(); + + let latest_request = latest + .freshness + .apply( + table + .client + .post("/v1/table/my_table/count_rows/") + .json(&serde_json::json!({ "version": latest.version })), + ) + .build() + .unwrap(); + assert!(request_body_json(&latest_request)["version"].is_null()); + assert!(latest_request.headers().contains_key(MIN_TIMESTAMP_HEADER)); + + let pinned = table.snapshot_read_state().await; + let pinned_request = pinned + .freshness + .apply( + table + .client + .post("/v1/table/my_table/count_rows/") + .json(&serde_json::json!({ "version": pinned.version })), + ) + .build() + .unwrap(); + assert_eq!(request_body_json(&pinned_request)["version"], 5); + assert!(!pinned_request.headers().contains_key(MIN_TIMESTAMP_HEADER)); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_cancelled_checkout_keeps_latest_freshness_enabled() { + let (described_tx, described_rx) = std::sync::mpsc::channel::<()>(); + let table = Arc::new(RemoteTable::new_mock_with_consistency_interval( + "my_table".to_string(), + move |_| { + described_tx.send(()).unwrap(); + http::Response::builder() + .status(200) + .body(r#"{"version":5,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + }, + Some(Duration::from_secs(0)), + )); + + let version_guard = table.version.write().await; + let checkout = tokio::spawn({ + let table = table.clone(); + async move { table.checkout(5).await } + }); + tokio::task::spawn_blocking(move || { + described_rx.recv_timeout(Duration::from_secs(10)).unwrap() + }) + .await + .unwrap(); + for _ in 0..100 { + if table.freshness.lock().unwrap().pinned { + break; + } + tokio::task::yield_now().await; + } + assert!(!checkout.is_finished()); + + checkout.abort(); + assert!(checkout.await.unwrap_err().is_cancelled()); + drop(version_guard); + + assert_eq!(*table.version.read().await, None); + assert!(table.snapshot_freshness_headers().min_timestamp.is_some()); + } + #[tokio::test] async fn test_freshness_positive_interval_sends_now_minus_interval() { let (handler, captured) = capturing_handler(|_| "42".to_string()); @@ -10268,6 +10726,62 @@ mod tests { ); } + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_inflight_write_result_cannot_cross_checkout_generation() { + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let release_rx = Arc::new(std::sync::Mutex::new(release_rx)); + let (arrived_tx, arrived_rx) = std::sync::mpsc::channel::<()>(); + let arrived_tx = Arc::new(std::sync::Mutex::new(arrived_tx)); + let count_headers = Arc::new(std::sync::Mutex::new(None)); + let captured = count_headers.clone(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/update/" => { + arrived_tx.lock().unwrap().send(()).unwrap(); + release_rx + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)) + .unwrap(); + http::Response::builder() + .status(200) + .body(r#"{"rows_updated":1,"version":100}"#.to_string()) + .unwrap() + } + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(r#"{"version":5,"schema":{"fields":[]}}"#.to_string()) + .unwrap(), + "/v1/table/my_table/count_rows/" => { + *captured.lock().unwrap() = Some(request.headers().clone()); + http::Response::builder() + .status(200) + .body("1".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(Duration::from_secs(10)).unwrap() + }) + .await + .unwrap(); + table.checkout(5).await.unwrap(); + release_tx.send(()).unwrap(); + update.await.unwrap().unwrap(); + table.count_rows(None).await.unwrap(); + + let headers = count_headers.lock().unwrap(); + let headers = headers.as_ref().unwrap(); + assert!(!headers.contains_key("x-lancedb-min-version")); + assert!(!headers.contains_key("x-lancedb-min-read-version")); + } + /// A handler that records every request's headers and answers each read with /// an `x-lancedb-version` response header taken from `versions` (by call /// index, saturating at the last entry). An empty string means "no header". @@ -10314,6 +10828,164 @@ mod tests { ); } + #[tokio::test] + async fn test_schema_response_advances_read_watermark() { + let requests = Arc::new(std::sync::Mutex::new(Vec::new())); + let captured = requests.clone(); + let table = Table::new_with_handler("my_table", move |request| { + captured + .lock() + .unwrap() + .push((request.url().path().to_string(), request.headers().clone())); + match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .header("x-lancedb-version", "100") + .body(r#"{"version":100,"schema":{"fields":[]}}"#.to_string()) + .unwrap(), + "/v1/table/my_table/count_rows/" => http::Response::builder() + .status(200) + .body("42".to_string()) + .unwrap(), + path => panic!("unexpected path: {path}"), + } + }); + + table.schema().await.unwrap(); + assert_eq!(table.count_rows(None).await.unwrap(), 42); + + let requests = requests.lock().unwrap(); + let count_headers = &requests[1].1; + assert_eq!( + count_headers + .get("x-lancedb-min-read-version") + .and_then(|value| value.to_str().ok()), + Some("100") + ); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn test_inflight_schema_response_cannot_cross_checkout_generation() { + let (release_tx, release_rx) = std::sync::mpsc::channel::<()>(); + let release_rx = Arc::new(std::sync::Mutex::new(release_rx)); + let (arrived_tx, arrived_rx) = std::sync::mpsc::channel::<()>(); + let arrived_tx = Arc::new(std::sync::Mutex::new(arrived_tx)); + let count_headers = Arc::new(std::sync::Mutex::new(None)); + let captured = count_headers.clone(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/describe/" => { + let body = request_body_json(&request); + if body["version"].is_null() { + arrived_tx.lock().unwrap().send(()).unwrap(); + release_rx + .lock() + .unwrap() + .recv_timeout(Duration::from_secs(10)) + .unwrap(); + http::Response::builder() + .status(200) + .header("x-lancedb-version", "100") + .body(r#"{"version":100,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + } else { + http::Response::builder() + .status(200) + .body(r#"{"version":5,"schema":{"fields":[]}}"#.to_string()) + .unwrap() + } + } + "/v1/table/my_table/count_rows/" => { + *captured.lock().unwrap() = Some(request.headers().clone()); + http::Response::builder() + .status(200) + .body("1".to_string()) + .unwrap() + } + path => panic!("unexpected path: {path}"), + }); + + let schema = tokio::spawn({ + let table = table.clone(); + async move { table.schema().await } + }); + tokio::task::spawn_blocking(move || { + arrived_rx.recv_timeout(Duration::from_secs(10)).unwrap() + }) + .await + .unwrap(); + table.checkout(5).await.unwrap(); + release_tx.send(()).unwrap(); + schema.await.unwrap().unwrap(); + table.count_rows(None).await.unwrap(); + + assert!( + !count_headers + .lock() + .unwrap() + .as_ref() + .unwrap() + .contains_key("x-lancedb-min-read-version") + ); + } + + #[tokio::test] + async fn test_streaming_write_uses_and_advances_read_watermark() { + let data = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])), + vec![Arc::new(Int32Array::from(vec![1, 2, 3]))], + ) + .unwrap(); + let describe_body = serde_json::to_string(&json!({ + "version": 7, + "schema": JsonSchema::try_from(data.schema().as_ref()).unwrap(), + })) + .unwrap(); + let requests = Arc::new(std::sync::Mutex::new(Vec::new())); + let captured = requests.clone(); + let table = Table::new_with_handler("my_table", move |request| { + captured + .lock() + .unwrap() + .push((request.url().path().to_string(), request.headers().clone())); + match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(describe_body.clone()) + .unwrap(), + "/v1/table/my_table/insert/" => http::Response::builder() + .status(200) + .header("x-lancedb-version", "8") + .body(r#"{"version":8}"#.to_string()) + .unwrap(), + "/v1/table/my_table/count_rows/" => http::Response::builder() + .status(200) + .body("3".to_string()) + .unwrap(), + path => panic!("unexpected path: {path}"), + } + }); + + assert_eq!(table.add(data).execute().await.unwrap().version, 8); + assert_eq!(table.count_rows(None).await.unwrap(), 3); + + let requests = requests.lock().unwrap(); + let insert_headers = &requests[1].1; + assert_eq!( + insert_headers + .get("x-lancedb-min-read-version") + .and_then(|value| value.to_str().ok()), + Some("7") + ); + let count_headers = &requests[2].1; + assert_eq!( + count_headers + .get("x-lancedb-min-read-version") + .and_then(|value| value.to_str().ok()), + Some("8") + ); + } + #[tokio::test] async fn test_read_version_watermark_keeps_max() { // Server reports 100 then a stale 50; the watermark must not regress. @@ -10729,6 +11401,86 @@ mod tests { ); } + #[tokio::test] + async fn test_main_only_metadata_is_unfenced_from_branch_timeline() { + let requests = Arc::new(std::sync::Mutex::new(HashMap::new())); + let captured = requests.clone(); + let saw_delete_response_floor = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let saw_high_floor = saw_delete_response_floor.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| { + let path = request.url().path().to_string(); + captured + .lock() + .unwrap() + .insert(path.clone(), request.headers().clone()); + match path.as_str() { + "/v1/table/my_table/count_rows/" => { + saw_high_floor.store( + request + .headers() + .get("x-lancedb-min-read-version") + .and_then(|value| value.to_str().ok()) + == Some("100"), + std::sync::atomic::Ordering::SeqCst, + ); + http::Response::builder() + .status(200) + .header("x-lancedb-version", "2") + .body("1".to_string()) + .unwrap() + } + "/v1/table/my_table/tags/list/" => http::Response::builder() + .status(200) + .body("{}".to_string()) + .unwrap(), + "/v1/table/my_table/tags/version/" => http::Response::builder() + .status(200) + .body(r#"{"version":1}"#.to_string()) + .unwrap(), + "/v1/table/my_table/tags/delete/" => http::Response::builder() + .status(200) + .header("x-lancedb-version", "100") + .body("{}".to_string()) + .unwrap(), + "/v1/table/my_table/branches/list/" => http::Response::builder() + .status(200) + .body(r#"{"branches":{}}"#.to_string()) + .unwrap(), + path => panic!("unexpected path: {path}"), + } + }, + None, + ); + let branch = table.with_branch(Some("exp".to_string())); + + branch.count_rows(None).await.unwrap(); + let mut tags = branch.tags().await.unwrap(); + tags.list().await.unwrap(); + tags.get_version("v1").await.unwrap(); + tags.delete("v1").await.unwrap(); + branch.list_branches().await.unwrap(); + branch.count_rows(None).await.unwrap(); + + let requests = requests.lock().unwrap(); + for path in [ + "/v1/table/my_table/tags/list/", + "/v1/table/my_table/tags/version/", + "/v1/table/my_table/tags/delete/", + "/v1/table/my_table/branches/list/", + ] { + assert!( + !requests[path].contains_key("x-lancedb-min-read-version"), + "{path} inherited the branch timeline" + ); + } + assert!( + !saw_delete_response_floor.load(std::sync::atomic::Ordering::SeqCst), + "tag deletion contaminated the branch timeline" + ); + } + #[tokio::test] async fn test_delete_branch() { let table = Table::new_with_handler("my_table", |request| { @@ -10820,6 +11572,50 @@ mod tests { assert!(result.main_version_after.is_none()); } + #[tokio::test] + async fn test_successful_cherry_pick_advances_main_read_watermark() { + let count_headers = Arc::new(std::sync::Mutex::new(None)); + let captured = count_headers.clone(); + let table = + Table::new_with_handler("my_table", move |request| match request.url().path() { + "/v1/table/my_table/branches/cherry_pick/" => { + let response = serde_json::json!({ + "status": "cherryPicked", + "diff": serde_json::from_str::(sample_branch_diff_json()) + .unwrap(), + "preview": { "promotedColumns": ["tag"] }, + "mainVersionAfter": 2 + }); + http::Response::builder() + .status(200) + .body(response.to_string()) + .unwrap() + } + "/v1/table/my_table/count_rows/" => { + *captured.lock().unwrap() = Some(request.headers().clone()); + http::Response::builder() + .status(200) + .body("1".to_string()) + .unwrap() + } + path => panic!("unexpected path: {path}"), + }); + + let result = table.cherry_pick("exp", false).await.unwrap(); + assert_eq!(result.status, crate::table::CherryPickStatus::CherryPicked); + table.count_rows(None).await.unwrap(); + assert_eq!( + count_headers + .lock() + .unwrap() + .as_ref() + .unwrap() + .get("x-lancedb-min-read-version") + .and_then(|value| value.to_str().ok()), + Some("2") + ); + } + #[tokio::test] async fn test_cherry_pick_failed_returns_ok_with_body() { let table = Table::new_with_handler("my_table", |request| { diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index 387d3c6dc..597b41782 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -6,6 +6,7 @@ use std::ops::Range; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; use arrow_array::{Array, LargeBinaryArray}; use arrow_schema::DataType; @@ -20,7 +21,7 @@ use crate::error::Result; use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; use crate::table::BaseTable; -use super::{FreshnessHeaders, RemoteTable}; +use super::{FreshnessHeaders, FreshnessState, RemoteTable, freshness_headers_snapshot}; #[derive(Debug, Clone, Copy)] enum RangeRequestMode { @@ -43,7 +44,10 @@ struct TableBlobRangeRequester { path: String, version: Option, branch: Option, - freshness: FreshnessHeaders, + freshness: Arc>, + parent_freshness: Arc>, + parent_freshness_request: FreshnessHeaders, + read_consistency_interval: Option, } #[async_trait::async_trait] @@ -53,8 +57,9 @@ impl BlobRangeRequester for TableBlobRangeRequester { range_header: &str, mode: RangeRequestMode, ) -> Result<(String, Response)> { - let mut request = self - .freshness + let freshness_request = + freshness_headers_snapshot(&self.freshness, self.read_consistency_interval); + let mut request = freshness_request .apply(self.client.get(&self.path)) .header(header::RANGE, range_header); if let Some(version) = self.version { @@ -71,6 +76,9 @@ impl BlobRangeRequester for TableBlobRangeRequester { return Ok((request_id, response)); } let response = self.client.check_response(&request_id, response).await?; + freshness_request.observe_headers(&self.freshness, response.headers()); + self.parent_freshness_request + .observe_headers(&self.parent_freshness, response.headers()); Ok((request_id, response)) } } @@ -361,18 +369,21 @@ impl RemoteTable { message: "fetch_blobs is not supported on this LanceDB Cloud server".into(), }); } - let version = self.current_version().await; + let read_snapshot = self.snapshot_read_state().await; let mut body = serde_json::json!({ - "version": version, + "version": read_snapshot.version, "column": column, "row_ids": row_ids, }); self.apply_branch_body(&mut body); let request = self - .post_read(&format!("/v1/table/{}/fetch_blobs/", self.identifier)) + .client + .post(&format!("/v1/table/{}/fetch_blobs/", self.identifier)) .json(&body); - let (request_id, response) = self.send(request, true).await?; + let (request_id, response) = self + .send_with_freshness(request, true, read_snapshot.freshness) + .await?; let mut stream = self.read_arrow_response(&request_id, response).await?; let mut blob_chunks: Vec> = Vec::new(); @@ -448,8 +459,7 @@ impl RemoteTable { }); } - let version = self.current_version().await; - let freshness = self.snapshot_freshness_headers(); + let read_snapshot = self.snapshot_read_state().await; let encoded_column = urlencoding::encode(column); let requesters = row_ids .iter() @@ -461,9 +471,12 @@ impl RemoteTable { let requester: Arc = Arc::new(TableBlobRangeRequester { client: self.client.clone(), path, - version, + version: read_snapshot.version, branch: self.branch.clone(), - freshness, + freshness: Arc::new(std::sync::Mutex::new(read_snapshot.freshness_state)), + parent_freshness: self.freshness.clone(), + parent_freshness_request: read_snapshot.freshness, + read_consistency_interval: self.client.read_consistency_interval, }); requester }) @@ -685,6 +698,46 @@ mod tests { assert!(requests.lock().unwrap().contains(&"bytes=5-11".to_string())); } + #[tokio::test] + async fn remote_blob_file_keeps_the_open_timeline_after_parent_checkout() { + let range_requests = Arc::new(StdMutex::new(Vec::new())); + let captured = range_requests.clone(); + let table = RemoteTable::new_mock( + "my_table".to_string(), + move |request| match request.url().path() { + "/v1/table/my_table/describe/" => http::Response::builder() + .status(200) + .body(r#"{"version":5,"schema":{"fields":[]}}"#.as_bytes().to_vec()) + .unwrap(), + "/v1/table/my_table/blob/image/10/bytes" => { + captured.lock().unwrap().push(( + request.url().query().unwrap_or_default().to_string(), + request.headers().clone(), + )); + range_response(&request, PAYLOAD) + } + path => panic!("unexpected path: {path}"), + }, + Some(Version::new(0, 5, 0)), + ); + + table.checkout(5).await.unwrap(); + let file = table + .fetch_blob_files_impl("image", &[10]) + .await + .unwrap() + .pop() + .flatten() + .unwrap(); + table.checkout_latest().await.unwrap(); + file.read_range(5..12).await.unwrap(); + + let requests = range_requests.lock().unwrap(); + let (query, headers) = requests.last().unwrap(); + assert!(query.contains("version=5")); + assert!(!headers.contains_key("x-lancedb-min-timestamp")); + } + #[tokio::test] async fn remote_blob_file_reuses_sequential_response_until_seek() { let requests = Arc::new(StdMutex::new(Vec::new())); diff --git a/rust/lancedb/src/remote/table/insert.rs b/rust/lancedb/src/remote/table/insert.rs index a4a28a9c6..4e0e0d666 100644 --- a/rust/lancedb/src/remote/table/insert.rs +++ b/rust/lancedb/src/remote/table/insert.rs @@ -24,7 +24,10 @@ use lance::io::exec::utils::InstrumentedRecordBatchStreamAdapter; use crate::Error; use crate::remote::ARROW_STREAM_CONTENT_TYPE; use crate::remote::client::{HttpSend, RestfulLanceDbClient, Sender}; -use crate::remote::table::{MergeInsertRequest, REQUEST_TIMEOUT_HEADER, RemoteTable}; +use crate::remote::table::{ + FreshnessHeaders, FreshnessState, MergeInsertRequest, REQUEST_TIMEOUT_HEADER, RemoteTable, + freshness_headers_snapshot, +}; use crate::table::datafusion::insert::COUNT_SCHEMA; use crate::table::write_progress::WriteProgressTracker; use crate::table::{AddResult, MergeResult}; @@ -54,6 +57,38 @@ pub enum WriteResult { Merge(MergeResult), } +#[derive(Debug, Clone, Default)] +struct WriteFreshness { + state: Option>>, + read_consistency_interval: Option, +} + +impl WriteFreshness { + fn prepare( + &self, + request: reqwest::RequestBuilder, + ) -> (reqwest::RequestBuilder, Option) { + match &self.state { + Some(state) => { + let freshness_request = + freshness_headers_snapshot(state, self.read_consistency_interval); + (freshness_request.apply(request), Some(freshness_request)) + } + None => (request, None), + } + } + + fn observe( + &self, + freshness_request: Option, + headers: &reqwest::header::HeaderMap, + ) { + if let (Some(state), Some(freshness_request)) = (&self.state, freshness_request) { + freshness_request.observe_headers(state, headers); + } + } +} + /// ExecutionPlan for streaming a write (add or merge_insert) to a remote /// LanceDB table. /// @@ -71,6 +106,7 @@ pub struct RemoteWriteExec { table_name: String, identifier: String, client: RestfulLanceDbClient, + freshness: WriteFreshness, input: Arc, op: WriteOp, properties: Arc, @@ -170,6 +206,7 @@ impl RemoteWriteExec { table_name, identifier, client, + freshness: WriteFreshness::default(), input, op, properties: Arc::new(properties), @@ -183,6 +220,18 @@ impl RemoteWriteExec { } } + pub(super) fn with_freshness( + mut self, + state: Arc>, + read_consistency_interval: Option, + ) -> Self { + self.freshness = WriteFreshness { + state: Some(state), + read_consistency_interval, + }; + self + } + /// Get the add result after execution, if this exec ran an insert. pub fn add_result(&self) -> Option { match self @@ -285,6 +334,7 @@ impl RemoteWriteExec { /// each threading the same handful of arguments. struct PartRequestCtx<'a, S: HttpSend> { client: &'a RestfulLanceDbClient, + freshness: &'a WriteFreshness, identifier: &'a str, table_name: &'a str, upload_id: &'a str, @@ -352,7 +402,11 @@ impl PartRequestCtx<'_, S> { } /// Build the `/insert` request for a single multipart part. - fn build_part_request(&self, part_id: &str, body: reqwest::Body) -> reqwest::RequestBuilder { + fn build_part_request( + &self, + part_id: &str, + body: reqwest::Body, + ) -> (reqwest::RequestBuilder, Option) { let mut request = self .client .post(&format!("/v1/table/{}/insert/", self.identifier)) @@ -368,12 +422,16 @@ impl PartRequestCtx<'_, S> { if let Some(b) = self.branch { request = request.query(&[("branch", b)]); } - request.body(body) + self.freshness.prepare(request.body(body)) } /// Send a single part's request and drain the response, mapping HTTP and /// table-not-found errors into `DataFusionError`. - async fn send_part_request(&self, request: reqwest::RequestBuilder) -> DataFusionResult<()> { + async fn send_part_request( + &self, + request: reqwest::RequestBuilder, + freshness_request: Option, + ) -> DataFusionResult<()> { let (request_id, response) = self .client .send(request) @@ -388,6 +446,8 @@ impl PartRequestCtx<'_, S> { .check_response(&request_id, response) .await .map_err(|e| DataFusionError::External(Box::new(e)))?; + self.freshness + .observe(freshness_request, response.headers()); response.bytes().await.map_err(|e| { DataFusionError::External(Box::new(Error::Http { source: Box::new(e), @@ -419,7 +479,7 @@ impl PartRequestCtx<'_, S> { let body = reqwest::Body::wrap_stream(chunk_rx); let part_id = uuid::Uuid::new_v4().to_string(); - let request = self.build_part_request(&part_id, body); + 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. @@ -495,7 +555,7 @@ impl PartRequestCtx<'_, S> { Ok::(input_ended) }; - let send = self.send_part_request(request); + 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 @@ -569,7 +629,7 @@ impl ExecutionPlan for RemoteWriteExec { // Building a fresh exec (with a new, empty `result`) is what makes the // outer rescannable retry loop work: `reset_state()` clears the captured // result so a re-execution starts clean. - Ok(Arc::new(Self::new_inner( + let mut exec = Self::new_inner( self.table_name.clone(), self.identifier.clone(), self.client.clone(), @@ -580,7 +640,9 @@ impl ExecutionPlan for RemoteWriteExec { self.branch.clone(), self.max_bytes_per_request, self.max_request_duration, - ))) + ); + exec.freshness = self.freshness.clone(); + Ok(Arc::new(exec)) } fn execute( @@ -613,6 +675,7 @@ impl ExecutionPlan for RemoteWriteExec { &self.metrics, )); let client = self.client.clone(); + let freshness = self.freshness.clone(); let identifier = self.identifier.clone(); let op = self.op.clone(); let result_slot = self.result.clone(); @@ -634,6 +697,7 @@ impl ExecutionPlan for RemoteWriteExec { let overwrite = matches!(op, WriteOp::Insert { overwrite: true }); let ctx = PartRequestCtx { client: &client, + freshness: &freshness, identifier: &identifier, table_name: &table_name, upload_id, @@ -688,7 +752,7 @@ impl ExecutionPlan for RemoteWriteExec { let (error_tx, mut error_rx) = tokio::sync::oneshot::channel(); let body = Self::stream_as_http_body(input_stream, error_tx, tracker)?; - let request = request.body(body); + let (request, freshness_request) = freshness.prepare(request.body(body)); let result: DataFusionResult<(String, _)> = async { let (request_id, response) = client @@ -708,6 +772,7 @@ impl ExecutionPlan for RemoteWriteExec { .check_response(&request_id, response) .await .map_err(|e| DataFusionError::External(Box::new(e)))?; + freshness.observe(freshness_request, response.headers()); Ok((request_id, response)) } From 2fbf6d62113face594782e0030909740069a4313 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Wed, 26 Aug 2026 14:56:57 +0800 Subject: [PATCH 125/206] test(python): cover concurrent S3 table opens (#3833) ## Summary - add regression coverage for the reported synchronous Python workload with 32 simultaneous `open_table` calls - verify every independently opened S3-backed table handle can read through the connection's shared session and object-store client ## Root cause In Python v0.13.0, each synchronous table handle lazily constructed its own Lance dataset. Opening many handles in parallel therefore triggered independent S3 client construction and bucket-region resolution, which failed under thread pressure. The current Rust-backed connection path owns a shared Lance session and retains its object-store handle, so table opens reuse the existing S3 client; these tests lock in that behavior through the public Python API and a causal Session-registry invariant. ## Validation - `uvx --from 'ruff==0.15.20' ruff format --check python/tests/test_s3.py` - `uvx --from 'ruff==0.15.20' ruff check .` - `cargo fmt --all` - `cargo test --quiet --features remote -p lancedb test_concurrent_open_table_reuses_connection_object_store` - `cargo check --quiet --features remote --tests --examples` - equivalent 32-thread `open_table(...).count_rows()` workload against a local database - targeted S3 test collected successfully locally; execution requires the CI LocalStack service, which is unavailable in this runner Fixes #1786 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- python/python/tests/test_s3.py | 20 ++++++++++ rust/lancedb/src/database/listing.rs | 55 +++++++++++++++++++++++++++- 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/python/python/tests/test_s3.py b/python/python/tests/test_s3.py index 256ccb1d4..70b423adb 100644 --- a/python/python/tests/test_s3.py +++ b/python/python/tests/test_s3.py @@ -4,6 +4,7 @@ import asyncio import copy +from concurrent.futures import ThreadPoolExecutor from datetime import timedelta import threading @@ -86,6 +87,25 @@ def test_s3_lifecycle(s3_bucket: str): asyncio.run(test()) +@pytest.mark.s3_test +def test_concurrent_open_table(s3_bucket: str): + uri = f"s3://{s3_bucket}/test_concurrent_open_table" + db = lancedb.connect(uri, storage_options=copy.copy(CONFIG)) + db.create_table("test", pa.table({"x": [1, 2, 3]})) + + num_workers = 32 + barrier = threading.Barrier(num_workers) + + def open_and_count(_): + barrier.wait() + return db.open_table("test").count_rows() + + with ThreadPoolExecutor(max_workers=num_workers) as pool: + row_counts = list(pool.map(open_and_count, range(num_workers))) + + assert row_counts == [3] * num_workers + + @pytest.fixture() def kms_key(): kms = get_boto3_client("kms", endpoint_url=CONFIG["aws_endpoint"]) diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index 17dc82756..064b5d28f 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -1476,7 +1476,7 @@ mod tests { use crate::table::{AnyQuery, WriteOptions}; use arrow_array::{Int32Array, RecordBatch, StringArray}; use arrow_schema::{DataType, Field, Schema, SchemaRef}; - use futures::{TryStreamExt, stream::once}; + use futures::{TryStreamExt, future::try_join_all, stream::once}; use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; @@ -1614,6 +1614,59 @@ mod tests { ); } + #[tokio::test] + async fn test_concurrent_open_table_reuses_connection_object_store() { + let tempdir = tempdir().unwrap(); + let uri = tempdir.path().to_str().unwrap(); + let session = Arc::new(lance::session::Session::default()); + let request = ConnectRequest { + uri: uri.to_string(), + #[cfg(feature = "remote")] + client_config: Default::default(), + options: Default::default(), + namespace_client_properties: Default::default(), + manifest_enabled: false, + read_consistency_interval: None, + session: Some(session.clone()), + }; + let db = ListingDatabase::connect_with_options(&request) + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + db.create_table(CreateTableRequest { + name: "test".to_string(), + namespace_path: vec![], + data: Box::new(RecordBatch::new_empty(schema)) as Box, + mode: CreateTableMode::Create, + write_options: Default::default(), + location: None, + namespace_client: None, + }) + .await + .unwrap(); + + let before = session.store_registry().stats(); + let opened_tables = try_join_all((0..32).map(|_| { + db.open_table(OpenTableRequest { + name: "test".to_string(), + namespace_path: vec![], + index_cache_size: None, + lance_read_params: None, + location: None, + namespace_client: None, + managed_versioning: None, + }) + })) + .await + .unwrap(); + let after = session.store_registry().stats(); + + assert_eq!(opened_tables.len(), 32); + assert_eq!(after.misses, before.misses); + assert_eq!(after.active_stores, before.active_stores); + assert!(after.hits >= before.hits + 32); + } + #[tokio::test] async fn test_listing_database_root_ops_do_not_create_manifest() { let tempdir = tempdir().unwrap(); From 06872463cf3731fe24a1e4e35d466b5f45bd0d21 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Wed, 26 Aug 2026 06:29:43 -0700 Subject: [PATCH 126/206] feat: declare conda environments on Functions (#4057) A Function's remote environment can now be conda instead of pip. `@udf(conda=[...], conda_channels=[...])` registers one; pip and conda are exclusive, channels are priority-ordered and require conda. The Rust and Python `PythonEnvironmentSpec` models gain `channels`, dropped from the canonical JSON when empty so existing pip registrations keep their digests. --- python/python/lancedb/functions.py | 29 +++++++++++++++++-- .../tests/test_first_class_function_slice2.py | 20 +++++++++++++ rust/lancedb/src/function.rs | 26 +++++++++++++++++ 3 files changed, 72 insertions(+), 3 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 237ed73c2..8a19a9d37 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -222,6 +222,7 @@ class PythonEnvironmentSpec(_RemoteValue): kind: str packages: tuple[str, ...] = () + channels: tuple[str, ...] = () path: Optional[str] = None modules: tuple[str, ...] = () image: Optional[str] = None @@ -909,13 +910,25 @@ class UdfDefinition: pip: tuple[str, ...], env: Mapping[str, str], python_version: Optional[str], + conda: tuple[str, ...] = (), + conda_channels: tuple[str, ...] = (), ): function_name = name or function.__name__ if not _FUNCTION_NAME.fullmatch(function_name): raise ValueError(f"invalid Function name: {function_name!r}") - packages = tuple(sorted(set(pip))) + if pip and conda: + raise ValueError("a Function environment is pip or conda, not both") + if conda_channels and not conda: + raise ValueError("conda_channels requires conda packages") + packages = tuple(sorted(set(conda if conda else pip))) if any(not package or package != package.strip() for package in packages): - raise ValueError("pip requirements must be non-empty and trimmed") + raise ValueError("package requirements must be non-empty and trimmed") + if conda: + environment_spec = PythonEnvironmentSpec( + kind="conda", packages=packages, channels=tuple(conda_channels) + ) + else: + environment_spec = PythonEnvironmentSpec(kind="pip", packages=packages) environment = dict(env) if any( not isinstance(key, str) or not isinstance(value, str) @@ -929,7 +942,7 @@ class UdfDefinition: kind="python", python_version=python_version or f"{sys.version_info.major}.{sys.version_info.minor}", - environment=PythonEnvironmentSpec(kind="pip", packages=packages), + environment=environment_spec, env=environment, ) self._function = function @@ -976,6 +989,8 @@ def udf( pip: tuple[str, ...] | list[str] = (), env: Optional[Mapping[str, str]] = None, python_version: Optional[str] = None, + conda: tuple[str, ...] | list[str] = (), + conda_channels: tuple[str, ...] | list[str] = (), ) -> Callable[[Callable[..., Any]], UdfDefinition]: ... @@ -988,6 +1003,8 @@ def udf( pip: tuple[str, ...] | list[str] = (), env: Optional[Mapping[str, str]] = None, python_version: Optional[str] = None, + conda: tuple[str, ...] | list[str] = (), + conda_channels: tuple[str, ...] | list[str] = (), ): """Prepare a scalar Python callable for remote Function registration. @@ -1010,6 +1027,10 @@ def udf( provided together with ``input_schema``. pip : sequence of str, optional Pip requirements for the remote environment. + conda : sequence of str, optional + Conda packages for the remote environment, instead of ``pip``. + conda_channels : sequence of str, optional + Conda channels in priority order; requires ``conda``. env : mapping of str to str, optional Environment variables included in the Function definition. python_version : str, optional @@ -1049,6 +1070,8 @@ def udf( pip=tuple(pip), env={} if env is None else env, python_version=python_version, + conda=tuple(conda), + conda_channels=tuple(conda_channels), ) if function is None: diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 55257d322..7ce6b6b91 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -69,6 +69,26 @@ def _run_packaged(definition, *args): return namespace[definition.registration_request.artifact.entrypoint](*args) +def test_udf_conda_environment(): + @udf(conda=["scipy", "numpy"], conda_channels=["conda-forge", "defaults"]) + def halve(value: float) -> float: + return value / 2 + + request = json.loads(halve.registration_request.to_canonical_json()) + assert request["runtime"]["environment"] == { + "kind": "conda", + "packages": ["numpy", "scipy"], + "channels": ["conda-forge", "defaults"], + } + pip_request = json.loads(normalize_score.registration_request.to_canonical_json()) + 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) + with pytest.raises(ValueError, match="requires conda"): + udf(name="channels", conda_channels=["conda-forge"])(lambda value: value) + + def test_udf_packages_attribute_access_and_body_imports(): @udf def word_norm(body: str) -> float: diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 52c70a4b1..5366d984e 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -186,6 +186,9 @@ pub struct PythonEnvironmentSpec { pub kind: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub packages: Vec, + /// Conda channels in priority order; conda environments only. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub channels: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub path: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -583,3 +586,26 @@ impl RefreshColumnResult { } impl_json!(RefreshColumnResult); + +#[cfg(test)] +mod conda_environment_tests { + use super::PythonEnvironmentSpec; + + #[test] + fn conda_channels_round_trip_and_pip_stays_bare() { + let conda: PythonEnvironmentSpec = serde_json::from_str( + r#"{"kind":"conda","packages":["numpy"],"channels":["conda-forge"]}"#, + ) + .unwrap(); + assert_eq!(conda.channels, ["conda-forge"]); + assert!( + serde_json::to_string(&conda) + .unwrap() + .contains(r#""channels":["conda-forge"]"#) + ); + + let pip: PythonEnvironmentSpec = + serde_json::from_str(r#"{"kind":"pip","packages":["numpy"]}"#).unwrap(); + assert!(!serde_json::to_string(&pip).unwrap().contains("channels")); + } +} From b78f2a5044b8d946e6812d2e609f68a0622b5231 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 26 Aug 2026 23:27:39 +0800 Subject: [PATCH 127/206] feat: expose list-element FTS document granularity (#4050) ## Summary LanceDB could not request Lance's list-element FTS document granularity through Python or Remote APIs, and generic nested-field resolution exposed Arrow's internal `item` segment instead of the public field path. This exposes typed `row | list_element` configuration for Python FTS index creation and match/phrase queries, preserves `_doc_index`, and keeps nested FTS paths public (for example, `docs.content`). Remote list-element requests require server API version 0.6.0 so older servers cannot silently execute them with row semantics; explicit row requests remain compatible. ## Compatibility Omitted index and query parameters retain row granularity. Remote row index creation omits the new wire field. ## Tracking [ENT-2342](https://linear.app/lancedb/issue/ENT-2342/expose-list-element-fts-document-granularity-end-to-end) --- docs/src/python/python.md | 2 + python/python/lancedb/index.py | 12 ++ python/python/lancedb/query.py | 23 ++ python/python/lancedb/remote/table.py | 3 + python/python/lancedb/table.py | 14 +- python/python/tests/test_fts.py | 77 +++++++ python/python/tests/test_remote_db.py | 43 ++++ python/src/index.rs | 10 +- python/src/query.rs | 57 +++-- rust/lancedb/src/index/scalar.rs | 1 + rust/lancedb/src/remote/db.rs | 4 + rust/lancedb/src/remote/table.rs | 282 ++++++++++++++++++++++--- rust/lancedb/src/table.rs | 13 +- rust/lancedb/src/table/create_index.rs | 54 ++++- rust/lancedb/src/utils/mod.rs | 183 ++++++++++++++++ 15 files changed, 723 insertions(+), 55 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 3cbeee6f0..3cb996a15 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -159,6 +159,8 @@ and combined with [BooleanQuery][lancedb.query.BooleanQuery]. ::: lancedb.query.FullTextOperator +::: lancedb.query.DocumentGranularity + ::: lancedb.query.Occur ## Embeddings diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py index d2b63baf6..948342887 100644 --- a/python/python/lancedb/index.py +++ b/python/python/lancedb/index.py @@ -7,6 +7,7 @@ from typing import List, Literal, Optional from ._lancedb import ( IndexConfig, ) +from .query import DocumentGranularity from .types import BaseTokenizerType lang_mapping = { @@ -121,6 +122,11 @@ class FTS: >>> config = FTS(block_size=256) + Create an index that treats each deepest-list element as one document: + + >>> from lancedb.query import DocumentGranularity + >>> config = FTS(document_granularity=DocumentGranularity.LIST_ELEMENT) + Attributes ---------- with_position : bool, default False @@ -172,6 +178,11 @@ class FTS: roughly half of the available CPU cores. The effective value is limited by the available compute capacity. This build-only setting is not persisted with the index and does not apply to remote tables. + document_granularity : DocumentGranularity, default ROW + ``ROW`` treats the selected text in one table row as one document. + ``LIST_ELEMENT`` treats each element of the deepest list on the indexed + field path as one document and returns its physical coordinates in + ``_doc_index`` for matching queries. Notes ----- @@ -196,6 +207,7 @@ class FTS: custom_stop_words: Optional[List[str]] = None memory_limit: Optional[int] = None num_workers: Optional[int] = None + document_granularity: DocumentGranularity = DocumentGranularity.ROW @dataclass diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index bd5e2cea2..5dff2537e 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -375,6 +375,13 @@ class FullTextOperator(str, Enum): OR = "OR" +class DocumentGranularity(str, Enum): + """The unit treated as one full-text-search document.""" + + ROW = "row" + LIST_ELEMENT = "list_element" + + class Occur(str, Enum): SHOULD = "SHOULD" MUST = "MUST" @@ -478,6 +485,10 @@ class MatchQuery(FullTextQuery): prefix_length : int, optional The number of beginning characters being unchanged for fuzzy matching. This is useful to achieve prefix matching. + document_granularity : DocumentGranularity, optional + Explicitly select row or deepest-list-element documents. If omitted, + the indexed granularity is inferred. When both granularities are indexed + for the field, this must be specified. With no index, row granularity is used. """ query: str @@ -487,6 +498,9 @@ class MatchQuery(FullTextQuery): max_expansions: int = pydantic.Field(50, kw_only=True) operator: FullTextOperator = pydantic.Field(FullTextOperator.OR, kw_only=True) prefix_length: int = pydantic.Field(0, kw_only=True) + document_granularity: Optional[DocumentGranularity] = pydantic.Field( + None, kw_only=True + ) def query_type(self) -> FullTextQueryType: return FullTextQueryType.MATCH @@ -503,11 +517,20 @@ class PhraseQuery(FullTextQuery): The query string to match against. column : str The name of the column to match against. + slop : int, default 0 + The maximum number of intervening positions permitted in the phrase. + document_granularity : DocumentGranularity, optional + Explicitly select row or deepest-list-element documents. If omitted, + the indexed granularity is inferred. When both granularities are indexed + for the field, this must be specified. With no index, row granularity is used. """ query: str column: str slop: int = pydantic.Field(0, kw_only=True) + document_granularity: Optional[DocumentGranularity] = pydantic.Field( + None, kw_only=True + ) def query_type(self) -> FullTextQueryType: return FullTextQueryType.MATCH_PHRASE diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index d0bf9f67a..d9139396b 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -61,6 +61,7 @@ from lancedb.table import _normalize_progress from ..query import ( AnalyzePlanDistributedMetrics, + DocumentGranularity, LanceQueryBuilder, LanceTakeQueryBuilder, LanceVectorQueryBuilder, @@ -349,6 +350,7 @@ class RemoteTable(Table): ngram_max_length: int = 3, prefix_only: bool = False, block_size: int = 128, + document_granularity: DocumentGranularity = DocumentGranularity.ROW, name: Optional[str] = None, ): """Create a full-text search index on a column. @@ -371,6 +373,7 @@ class RemoteTable(Table): ngram_max_length=ngram_max_length, prefix_only=prefix_only, block_size=block_size, + document_granularity=document_granularity, ) LOOP.run( self._table.create_index( diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index b3cab006e..76d5fc825 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -85,6 +85,7 @@ from .query import ( AsyncQuery, AsyncTakeQuery, AsyncVectorQuery, + DocumentGranularity, FullTextQuery, LanceEmptyQueryBuilder, LanceFtsQueryBuilder, @@ -1168,6 +1169,7 @@ class Table(ABC): ngram_max_length: int = 3, prefix_only: bool = False, block_size: int = 128, + document_granularity: DocumentGranularity = DocumentGranularity.ROW, wait_timeout: Optional[timedelta] = None, name: Optional[str] = None, ): @@ -1246,6 +1248,11 @@ class Table(ABC): The number of documents per compressed posting block. Must be 128 or 256. A value of 256 uses the experimental FTS V3 format and may introduce breaking changes. + document_granularity: DocumentGranularity, default ROW + ``ROW`` treats the selected text in one table row as one document. + ``LIST_ELEMENT`` treats each element of the deepest list on the field + path as one document and returns its physical coordinates in + ``_doc_index`` for matching queries. wait_timeout: timedelta, optional The timeout to wait if indexing is asynchronous. name: str, optional @@ -3273,6 +3280,7 @@ class LanceTable(Table): ngram_max_length: int = 3, prefix_only: bool = False, block_size: int = 128, + document_granularity: DocumentGranularity = DocumentGranularity.ROW, name: Optional[str] = None, ): """Create a full-text search index on a column. @@ -3324,7 +3332,11 @@ class LanceTable(Table): tokenizer_configs = self.infer_tokenizer_configs(tokenizer_name) tokenizer_configs["custom_stop_words"] = custom_stop_words - config = FTS(block_size=block_size, **tokenizer_configs) + config = FTS( + block_size=block_size, + document_granularity=document_granularity, + **tokenizer_configs, + ) try: LOOP.run( diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index 625198d92..e5129dd9c 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -25,6 +25,7 @@ from lancedb.db import DBConnection from lancedb.index import FTS from lancedb.query import ( BoostQuery, + DocumentGranularity, MatchQuery, MultiMatchQuery, PhraseQuery, @@ -245,6 +246,55 @@ def test_create_inverted_index_rejects_invalid_block_size(table): table.create_index("text", config=FTS(block_size=129)) +def test_list_element_document_granularity(tmp_path): + docs_type = pa.list_(pa.struct([pa.field("content", pa.string())])) + docs = pa.array( + [ + [ + {"content": "alpha beta"}, + None, + {"content": ""}, + {"content": "the and"}, + {"content": "alpha beta"}, + ] + ], + type=docs_type, + ) + table = ldb.connect(tmp_path).create_table( + "list_element_docs", pa.table({"id": [0], "docs": docs}) + ) + row_table = ldb.connect(tmp_path).create_table( + "row_docs", pa.table({"id": [0], "docs": docs}) + ) + row_table.create_index("docs.content", config=FTS()) + row_result = row_table.search(MatchQuery("alpha", "docs.content")).to_arrow() + assert row_result.num_rows == 1 + assert "_doc_index" not in row_result.column_names + + granularity = DocumentGranularity.LIST_ELEMENT + table.create_index( + "docs.content", + config=FTS(with_position=True, document_granularity=granularity), + ) + assert table.list_indices()[0].columns == ["docs.content"] + + def coordinates(query): + result = table.search(query).limit(10).to_arrow() + doc_index_type = result.schema.field("_doc_index").type + assert pa.types.is_list(doc_index_type) + assert doc_index_type.value_type == pa.uint32() + return sorted(result["_doc_index"].to_pylist()) + + assert coordinates( + MatchQuery("alpha", "docs.content", document_granularity=granularity) + ) == [[0], [4]] + assert coordinates( + PhraseQuery("alpha beta", "docs.content", document_granularity=granularity) + ) == [[0], [4]] + assert coordinates(MatchQuery("alpha", "docs.content")) == [[0], [4]] + assert FTS().document_granularity is DocumentGranularity.ROW + + def test_create_inverted_index_respects_build_memory_limit(table): with pytest.raises(ValueError, match="exceeds worker memory limit"): table.create_index( @@ -1089,6 +1139,20 @@ def test_fts_query_to_json(): ) assert json_str == expected + # Test MatchQuery with list-element document granularity + match_query = MatchQuery( + "hello world", + "text", + document_granularity=DocumentGranularity.LIST_ELEMENT, + ) + json_str = match_query.to_json() + expected = ( + '{"match":{"column":"text","terms":"hello world","boost":1.0,' + '"fuzziness":0,"max_expansions":50,"operator":"Or","prefix_length":0,' + '"document_granularity":"list_element"}}' + ) + assert json_str == expected + # Test MatchQuery with options match_query = MatchQuery("puppy", "text", fuzziness=2, boost=1.5, prefix_length=3) json_str = match_query.to_json() @@ -1098,6 +1162,19 @@ def test_fts_query_to_json(): ) assert json_str == expected + # Test PhraseQuery with list-element document granularity + phrase_query = PhraseQuery( + "quick brown fox", + "title", + document_granularity=DocumentGranularity.LIST_ELEMENT, + ) + json_str = phrase_query.to_json() + expected = ( + '{"phrase":{"column":"title","terms":"quick brown fox","slop":0,' + '"document_granularity":"list_element"}}' + ) + assert json_str == expected + # Test PhraseQuery phrase_query = PhraseQuery("quick brown fox", "title") json_str = phrase_query.to_json() diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 2952f00a4..ab0df386d 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -1618,6 +1618,49 @@ def test_query_sync_fts(): ) +def test_query_sync_fts_document_granularity(): + from lancedb.query import DocumentGranularity, MatchQuery + + def handler(body): + assert body == { + "full_text_query": { + "query": { + "match": { + "column": "docs.content", + "terms": "alpha", + "boost": 1.0, + "fuzziness": 0, + "max_expansions": 50, + "operator": "Or", + "prefix_length": 0, + "document_granularity": "list_element", + } + } + }, + "k": 10, + "prefilter": True, + "vector": [], + "version": None, + } + return pa.table( + { + "id": [1, 1], + "_doc_index": pa.array([[0], [4]], type=pa.list_(pa.uint32())), + } + ) + + with query_test_table(handler, server_version=Version("0.6.0")) as table: + result = table.search( + MatchQuery( + "alpha", + "docs.content", + document_granularity=DocumentGranularity.LIST_ELEMENT, + ) + ).to_arrow() + + assert result["_doc_index"].to_pylist() == [[0], [4]] + + def test_query_sync_hybrid(): def handler(body): if "full_text_query" in body: diff --git a/python/src/index.rs b/python/src/index.rs index a5ca63c68..54b15f55e 100644 --- a/python/src/index.rs +++ b/python/src/index.rs @@ -8,7 +8,7 @@ use lancedb::index::vector::{ }; use lancedb::index::{ Index as LanceDbIndex, - scalar::{BTreeIndexBuilder, FmIndexBuilder, FtsIndexBuilder}, + scalar::{BTreeIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder}, }; use pyo3::IntoPyObject; use pyo3::types::PyStringMethods; @@ -60,7 +60,11 @@ pub fn extract_index_params(source: &Option>) -> PyResult, num_workers: Option, + document_granularity: String, } #[derive(FromPyObject)] @@ -481,6 +486,7 @@ mod tests { block_size = 128 memory_limit = 2048 num_workers = 7 + document_granularity = 'row' config = FTS()", None, diff --git a/python/src/query.rs b/python/src/query.rs index affbdf4fd..014e79e2d 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -16,8 +16,8 @@ use arrow::pyarrow::FromPyArrow; use arrow::pyarrow::IntoPyArrow; use arrow::pyarrow::ToPyArrow; use lancedb::index::scalar::{ - BooleanQuery, BoostQuery, FtsQuery, FullTextSearchQuery, MatchQuery, MultiMatchQuery, Occur, - Operator, PhraseQuery, + BooleanQuery, BoostQuery, DocumentGranularity, FtsQuery, FullTextSearchQuery, MatchQuery, + MultiMatchQuery, Occur, Operator, PhraseQuery, }; use lancedb::query::AnalyzePlanDistributedMetrics; use lancedb::query::QueryBase; @@ -76,8 +76,16 @@ impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB { let max_expansions = ob.getattr("max_expansions")?.extract()?; let operator = ob.getattr("operator")?.extract::()?; let prefix_length = ob.getattr("prefix_length")?.extract()?; + let document_granularity = ob + .getattr("document_granularity")? + .extract::>()? + .map(|value| { + DocumentGranularity::try_from(value.as_str()) + .map_err(|err| PyValueError::new_err(err.to_string())) + }) + .transpose()?; - Ok(Self( + let mut query = MatchQuery::new(query) .with_column(Some(column)) .with_boost(boost) @@ -86,21 +94,32 @@ impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB { .with_operator(Operator::try_from(operator.as_str()).map_err(|e| { PyValueError::new_err(format!("Invalid operator: {}", e)) })?) - .with_prefix_length(prefix_length) - .into(), - )) + .with_prefix_length(prefix_length); + if let Some(document_granularity) = document_granularity { + query = query.with_document_granularity(document_granularity); + } + Ok(Self(query.into())) } "PhraseQuery" => { let query = ob.getattr("query")?.extract()?; let column = ob.getattr("column")?.extract()?; let slop = ob.getattr("slop")?.extract()?; + let document_granularity = ob + .getattr("document_granularity")? + .extract::>()? + .map(|value| { + DocumentGranularity::try_from(value.as_str()) + .map_err(|err| PyValueError::new_err(err.to_string())) + }) + .transpose()?; - Ok(Self( - PhraseQuery::new(query) - .with_column(Some(column)) - .with_slop(slop) - .into(), - )) + let mut query = PhraseQuery::new(query) + .with_column(Some(column)) + .with_slop(slop); + if let Some(document_granularity) = document_granularity { + query = query.with_document_granularity(document_granularity); + } + Ok(Self(query.into())) } "BoostQuery" => { let positive: Self = ob.getattr("positive")?.extract()?; @@ -167,6 +186,13 @@ impl<'py> IntoPyObject<'py> for PyLanceDB { kwargs.set_item("max_expansions", query.max_expansions)?; kwargs.set_item::<_, &str>("operator", query.operator.into())?; kwargs.set_item("prefix_length", query.prefix_length)?; + if let Some(document_granularity) = query.document_granularity { + let value = match document_granularity { + DocumentGranularity::Row => "row", + DocumentGranularity::ListElement => "list_element", + }; + kwargs.set_item("document_granularity", value)?; + } namespace .getattr(intern!(py, "MatchQuery"))? .call((query.terms, query.column.unwrap()), Some(&kwargs)) @@ -174,6 +200,13 @@ impl<'py> IntoPyObject<'py> for PyLanceDB { FtsQuery::Phrase(query) => { let kwargs = PyDict::new(py); kwargs.set_item("slop", query.slop)?; + if let Some(document_granularity) = query.document_granularity { + let value = match document_granularity { + DocumentGranularity::Row => "row", + DocumentGranularity::ListElement => "list_element", + }; + kwargs.set_item("document_granularity", value)?; + } namespace .getattr(intern!(py, "PhraseQuery"))? .call((query.terms, query.column.unwrap()), Some(&kwargs)) diff --git a/rust/lancedb/src/index/scalar.rs b/rust/lancedb/src/index/scalar.rs index 10d835bb1..dba05b776 100644 --- a/rust/lancedb/src/index/scalar.rs +++ b/rust/lancedb/src/index/scalar.rs @@ -63,4 +63,5 @@ pub struct FmIndexBuilder {} pub use lance_index::scalar::FullTextSearchQuery; pub use lance_index::scalar::InvertedIndexParams as FtsIndexBuilder; pub use lance_index::scalar::InvertedIndexParams; +pub use lance_index::scalar::inverted::DocumentGranularity; pub use lance_index::scalar::inverted::query::*; diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 3f4216bc8..da9a4b09b 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -87,6 +87,10 @@ impl ServerVersion { pub fn support_blobs(&self) -> bool { self.0 >= semver::Version::new(0, 5, 0) } + + pub fn support_fts_document_granularity(&self) -> bool { + self.0 >= semver::Version::new(0, 6, 0) + } } pub const OPT_REMOTE_PREFIX: &str = "remote_database_"; diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index b1a02a260..fad04a098 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -14,6 +14,7 @@ use crate::data::scannable::{PeekedScannable, Scannable, estimate_write_partitio use crate::expr::expr_to_sql_string; use crate::index::Index; use crate::index::IndexStatistics; +use crate::index::scalar::FtsQuery; use crate::index::waiter::wait_for_index; use crate::job::Job; use crate::query::{QueryFilter, QueryRequest, Select, VectorQueryRequest}; @@ -39,7 +40,8 @@ use crate::table::{ use crate::table::{AnyQuery, Filter, Predicate, PreprocessingOutput, TableStatistics}; use crate::utils::background_cache::BackgroundCache; use crate::utils::{ - resolve_arrow_field_path, supported_btree_data_type, supported_vector_data_type, + resolve_arrow_field_path, resolve_arrow_fts_field_path, supported_btree_data_type, + supported_vector_data_type, }; use crate::{DistanceType, Error}; use crate::{ @@ -88,6 +90,32 @@ const SCHEMA_CACHE_TTL: Duration = Duration::from_secs(30); const SCHEMA_CACHE_REFRESH_WINDOW: Duration = Duration::from_secs(5); const SCHEMA_SELECTOR_CHANGED: &str = "table selector changed while fetching schema"; +fn fts_query_requires_document_granularity_support(query: &FtsQuery) -> bool { + match query { + FtsQuery::Match(query) => query + .document_granularity + .is_some_and(|granularity| granularity.is_list_element()), + FtsQuery::Phrase(query) => query + .document_granularity + .is_some_and(|granularity| granularity.is_list_element()), + FtsQuery::Boost(query) => { + fts_query_requires_document_granularity_support(&query.positive) + || fts_query_requires_document_granularity_support(&query.negative) + } + FtsQuery::MultiMatch(query) => query.match_queries.iter().any(|query| { + query + .document_granularity + .is_some_and(|granularity| granularity.is_list_element()) + }), + FtsQuery::Boolean(query) => query + .must + .iter() + .chain(&query.should) + .chain(&query.must_not) + .any(fts_query_requires_document_granularity_support), + } +} + /// Per-table state driving the freshness headers (`x-lancedb-min-version`, /// `x-lancedb-min-timestamp`, and `x-lancedb-min-read-version`) sent on table /// requests. @@ -480,8 +508,21 @@ impl RemoteTable { }); } }; + if matches!( + &index.index, + Index::FTS(params) if params.get_document_granularity().is_list_element() + ) && !self.server_version.support_fts_document_granularity() + { + return Err(Error::NotSupported { + message: "FTS document granularity requires remote server version 0.6.0 or later" + .into(), + }); + } let schema = self.schema().await?; - let (canonical_column, field) = resolve_arrow_field_path(&schema, &column)?; + let (canonical_column, field) = match &index.index { + Index::FTS(_) => resolve_arrow_fts_field_path(&schema, &column)?, + _ => resolve_arrow_field_path(&schema, &column)?, + }; let mut body = serde_json::json!({ "column": canonical_column }); @@ -517,7 +558,13 @@ impl RemoteTable { Index::Bitmap(p) => ("BITMAP", Some(to_json(p)?)), Index::LabelList(p) => ("LABEL_LIST", Some(to_json(p)?)), Index::Fm(p) => ("FM", Some(to_json(p)?)), - Index::FTS(p) => ("FTS", Some(to_json(p)?)), + Index::FTS(p) => { + let mut params = to_json(p)?; + if p.get_document_granularity().is_list_element() { + params["document_granularity"] = "list_element".into(); + } + ("FTS", Some(params)) + } Index::Auto => { if supported_vector_data_type(field.data_type()) { body[METRIC_TYPE_KEY] = @@ -999,6 +1046,18 @@ impl RemoteTable { }); } + let requires_document_granularity_support = + fts_query_requires_document_granularity_support(&full_text_search.query); + if requires_document_granularity_support + && !self.server_version.support_fts_document_granularity() + { + return Err(Error::NotSupported { + message: + "FTS document granularity requires remote server version 0.6.0 or later" + .into(), + }); + } + if self.server_version.support_structural_fts() { body["full_text_query"] = serde_json::json!({ "query": full_text_search.query.clone(), @@ -3629,7 +3688,7 @@ mod tests { use arrow_schema::{DataType, Field, Schema}; use chrono::{DateTime, Utc}; use futures::{StreamExt, TryFutureExt, future::BoxFuture}; - use lance_index::scalar::inverted::query::MatchQuery; + use lance_index::scalar::inverted::{DocumentGranularity, query::MatchQuery}; use lance_index::scalar::{FullTextSearchQuery, InvertedIndexParams}; use reqwest::Body; use rstest::rstest; @@ -3906,6 +3965,15 @@ mod tests { DataType::Struct(vec![Field::new("text", DataType::Utf8, false)].into()), false, ), + Field::new( + "docs", + DataType::List(Arc::new(Field::new( + "item", + DataType::Struct(vec![Field::new("content", DataType::Utf8, true)].into()), + true, + ))), + true, + ), Field::new( "meta-data", DataType::Struct(vec![Field::new("user-id", DataType::Int32, false)].into()), @@ -5534,7 +5602,7 @@ mod tests { #[tokio::test] async fn test_query_structured_fts() { let table = - Table::new_with_handler_version("my_table", semver::Version::new(0, 3, 0), |request| { + Table::new_with_handler_version("my_table", semver::Version::new(0, 6, 0), |request| { assert_eq!(request.method(), "POST"); assert_eq!(request.url().path(), "/v1/table/my_table/query/"); assert_eq!( @@ -5555,6 +5623,7 @@ mod tests { "max_expansions": 50, "operator": "Or", "prefix_length": 0, + "document_granularity": "list_element", }, } }, @@ -5584,6 +5653,7 @@ mod tests { .full_text_search(FullTextSearchQuery::new_query( MatchQuery::new("hello world".to_owned()) .with_column(Some("payload.text".to_owned())) + .with_document_granularity(DocumentGranularity::ListElement) .into(), )) .with_row_id() @@ -5593,6 +5663,76 @@ mod tests { .unwrap(); } + #[tokio::test] + async fn test_query_row_document_granularity_uses_structured_fts() { + let table = + Table::new_with_handler_version("my_table", semver::Version::new(0, 3, 0), |request| { + let body = request.body().unwrap().as_bytes().unwrap(); + let body: serde_json::Value = serde_json::from_slice(body).unwrap(); + assert_eq!( + body["full_text_query"]["query"]["match"]["document_granularity"], + "row" + ); + + let data = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])), + vec![Arc::new(Int32Array::from(vec![1]))], + ) + .unwrap(); + http::Response::builder() + .status(200) + .header(CONTENT_TYPE, ARROW_FILE_CONTENT_TYPE) + .body(write_ipc_file(&data)) + .unwrap() + }); + + table + .query() + .full_text_search(FullTextSearchQuery::new_query( + MatchQuery::new("hello world".to_owned()) + .with_column(Some("payload.text".to_owned())) + .with_document_granularity(DocumentGranularity::Row) + .into(), + )) + .execute() + .await + .unwrap(); + } + + #[rstest] + #[case(DEFAULT_SERVER_VERSION.clone())] + #[case(semver::Version::new(0, 3, 0))] + #[case(semver::Version::new(0, 5, 0))] + #[tokio::test] + async fn test_query_document_granularity_requires_server_support( + #[case] version: semver::Version, + ) { + let table = + Table::new_with_handler_version("my_table", version, |_| -> http::Response { + panic!("unsupported remote query must fail before sending a request") + }); + + let result = table + .query() + .full_text_search(FullTextSearchQuery::new_query( + MatchQuery::new("hello world".to_owned()) + .with_column(Some("payload.text".to_owned())) + .with_document_granularity(DocumentGranularity::ListElement) + .into(), + )) + .execute() + .await; + let err = match result { + Ok(_) => panic!("legacy remote query unexpectedly succeeded"), + Err(err) => err, + }; + + assert!( + err.to_string() + .contains("document granularity requires remote server version 0.6.0 or later") + ); + } + #[rstest] #[case(DEFAULT_SERVER_VERSION.clone())] #[case(semver::Version::new(0, 2, 0))] @@ -5871,40 +6011,56 @@ mod tests { "CAT".to_string(), ]))), ), + ( + "FTS", + { + let mut body = serde_json::to_value(InvertedIndexParams::default()).unwrap(); + body["document_granularity"] = "list_element".into(); + body + }, + Index::FTS( + InvertedIndexParams::default() + .document_granularity(DocumentGranularity::ListElement), + ), + ), ]; for (index_type, expected_body, index) in cases { - let table = Table::new_with_handler("my_table", move |request| { - assert_eq!(request.method(), "POST"); - match request.url().path() { - "/v1/table/my_table/describe/" => { - let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); - http::Response::builder() - .status(200) - .body(describe_response(&schema)) - .unwrap() - } - "/v1/table/my_table/create_index/" => { - assert_eq!( - request.headers().get("Content-Type").unwrap(), - JSON_CONTENT_TYPE - ); - let body = request.body().unwrap().as_bytes().unwrap(); - let body: serde_json::Value = serde_json::from_slice(body).unwrap(); - let mut expected_body = expected_body.clone(); - expected_body["column"] = "a".into(); - expected_body[INDEX_TYPE_KEY] = index_type.into(); + let table = Table::new_with_handler_version( + "my_table", + semver::Version::new(0, 6, 0), + move |request| { + assert_eq!(request.method(), "POST"); + match request.url().path() { + "/v1/table/my_table/describe/" => { + let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); + http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap() + } + "/v1/table/my_table/create_index/" => { + assert_eq!( + request.headers().get("Content-Type").unwrap(), + JSON_CONTENT_TYPE + ); + let body = request.body().unwrap().as_bytes().unwrap(); + let body: serde_json::Value = serde_json::from_slice(body).unwrap(); + let mut expected_body = expected_body.clone(); + expected_body["column"] = "a".into(); + expected_body[INDEX_TYPE_KEY] = index_type.into(); - assert_eq!(body, expected_body); + assert_eq!(body, expected_body); - http::Response::builder() - .status(200) - .body("{}".to_string()) - .unwrap() + http::Response::builder() + .status(200) + .body("{}".to_string()) + .unwrap() + } + path => panic!("Unexpected path: {}", path), } - path => panic!("Unexpected path: {}", path), - } - }); + }, + ); table.create_index(&["a"], index).execute().await.unwrap(); } @@ -6163,6 +6319,19 @@ mod tests { body["index_type"] = "FTS".into(); body }, + { + let mut body = serde_json::to_value(InvertedIndexParams::default()).unwrap(); + body["column"] = "docs.content".into(); + body["index_type"] = "FTS".into(); + body + }, + { + let mut body = serde_json::to_value(InvertedIndexParams::default()).unwrap(); + body["column"] = "docs.content".into(); + body["index_type"] = "FTS".into(); + body["document_granularity"] = "list_element".into(); + body + }, json!({ "column": "`meta-data`.`user-id`", "index_type": "BTREE", @@ -6173,7 +6342,7 @@ mod tests { }), ]); let request_idx = Arc::new(AtomicUsize::new(0)); - let table = Table::new_with_handler("my_table", { + let table = Table::new_with_handler_version("my_table", semver::Version::new(0, 6, 0), { let schema = schema.clone(); let expected_requests = expected_requests.clone(); let request_idx = request_idx.clone(); @@ -6238,6 +6407,22 @@ mod tests { .execute() .await .unwrap(); + table + .create_index(&["Docs.Content"], Index::FTS(Default::default())) + .execute() + .await + .unwrap(); + table + .create_index( + &["Docs.Content"], + Index::FTS( + InvertedIndexParams::default() + .document_granularity(DocumentGranularity::ListElement), + ), + ) + .execute() + .await + .unwrap(); table .create_index(&["`META-DATA`.`USER-ID`"], Index::BTree(Default::default())) .execute() @@ -6252,6 +6437,35 @@ mod tests { assert_eq!(request_idx.load(Ordering::SeqCst), expected_requests.len()); } + #[tokio::test] + async fn test_create_list_element_fts_requires_server_support() { + let table = Table::new_with_handler_version( + "my_table", + semver::Version::new(0, 5, 0), + |_| -> http::Response { + panic!("unsupported index creation must fail before sending a request") + }, + ); + + let result = table + .create_index( + &["docs.content"], + Index::FTS( + InvertedIndexParams::default() + .document_granularity(DocumentGranularity::ListElement), + ), + ) + .execute() + .await; + + assert!( + result + .unwrap_err() + .to_string() + .contains("document granularity requires remote server version 0.6.0 or later") + ); + } + #[tokio::test] async fn test_list_indices() { let schema = Schema::new(vec![ diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 6b5f687c7..182e3e1a7 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -59,7 +59,9 @@ use crate::index::{IndexConfig, IndexStatisticsImpl, IndexType}; use crate::job::Job; use crate::query::{IntoQueryVector, Query, QueryExecutionOptions, TakeQuery, VectorQuery}; use crate::table::datafusion::insert::InsertExec; -use crate::utils::{PatchReadParam, PatchWriteParam, resolve_arrow_field_path}; +use crate::utils::{ + PatchReadParam, PatchWriteParam, public_fts_field_path_by_id, resolve_arrow_field_path, +}; use self::dataset::DatasetConsistencyWrapper; use self::merge::MergeInsertBuilder; @@ -3559,7 +3561,14 @@ impl BaseTable for NativeTable { let field_ids = idx_desc.field_ids(); let mut columns = Vec::with_capacity(field_ids.len()); for field_id in field_ids { - let field_path = match dataset.schema().field_path(*field_id as i32) { + let field_path = match if index_type == crate::index::IndexType::FTS { + public_fts_field_path_by_id(dataset.schema(), *field_id as i32) + } else { + dataset + .schema() + .field_path(*field_id as i32) + .map_err(Into::into) + } { Ok(field_path) => field_path, Err(e) => { log::warn!( diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs index e373522bc..c7d6b5675 100644 --- a/rust/lancedb/src/table/create_index.rs +++ b/rust/lancedb/src/table/create_index.rs @@ -28,8 +28,9 @@ pub(super) type PreparedIndex = (String, Box, Ind use crate::index::Index; use crate::index::vector::{VectorIndex, suggested_num_sub_vectors}; use crate::utils::{ - supported_bitmap_data_type, supported_btree_data_type, supported_fm_data_type, - supported_fts_data_type, supported_label_list_data_type, supported_vector_data_type, + resolve_lance_fts_field_path, supported_bitmap_data_type, supported_btree_data_type, + supported_fm_data_type, supported_fts_data_type, supported_label_list_data_type, + supported_vector_data_type, }; use super::NativeTable; @@ -122,7 +123,20 @@ impl NativeTable { } self.dataset.ensure_mutable()?; let dataset = self.dataset.get().await?; - let (column, field) = Self::resolve_index_field(dataset.schema(), &opts.columns[0])?; + 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 { + return Err(Error::InvalidInput { + message: format!( + "FTS field path '{}' has no List layer and cannot use ListElement document granularity", + resolved.canonical_path + ), + }); + } + (resolved.canonical_path, resolved.field) + } else { + Self::resolve_index_field(dataset.schema(), &opts.columns[0])? + }; 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)) @@ -436,7 +450,7 @@ mod tests { use crate::connection::ConnectBuilder; use crate::index::Index; use crate::index::scalar::{ - BTreeIndexBuilder, BitmapIndexBuilder, FmIndexBuilder, FtsIndexBuilder, + BTreeIndexBuilder, BitmapIndexBuilder, DocumentGranularity, FmIndexBuilder, FtsIndexBuilder, }; use crate::index::vector::{ IvfHnswFlatIndexBuilder, IvfHnswPqIndexBuilder, IvfHnswSqIndexBuilder, @@ -553,6 +567,38 @@ mod tests { job.cancel().await.unwrap(); } + #[tokio::test] + async fn test_execute_async_validates_fts_input_before_starting_job() { + let conn = connect("memory://").execute().await.unwrap(); + let batch = + record_batch!(("id", Int32, [1, 2]), ("text", Utf8, ["alpha", "beta"])).unwrap(); + let table = conn.create_table("t", batch).execute().await.unwrap(); + + let missing = table + .create_index(&["missing"], Index::FTS(FtsIndexBuilder::default())) + .execute_async() + .await; + assert!(missing.is_err()); + + let invalid_type = table + .create_index(&["id"], Index::FTS(FtsIndexBuilder::default())) + .execute_async() + .await; + assert!(invalid_type.is_err()); + + let invalid_granularity = table + .create_index( + &["text"], + Index::FTS( + FtsIndexBuilder::default() + .document_granularity(DocumentGranularity::ListElement), + ), + ) + .execute_async() + .await; + assert!(invalid_granularity.is_err()); + } + /// Concurrent waiters, and a wait issued after the job settled, all /// succeed once the build does. #[tokio::test] diff --git a/rust/lancedb/src/utils/mod.rs b/rust/lancedb/src/utils/mod.rs index 8bd306988..07d1836a1 100644 --- a/rust/lancedb/src/utils/mod.rs +++ b/rust/lancedb/src/utils/mod.rs @@ -225,6 +225,159 @@ pub(crate) fn resolve_arrow_field_path(schema: &Schema, column: &str) -> Result< Ok((canonical_path, Field::from(*field))) } +pub(crate) struct ResolvedFtsField { + pub canonical_path: String, + pub field: Field, + pub list_depth: usize, +} + +/// Canonicalize a public FTS field path while keeping Arrow list item names hidden. +pub(crate) fn resolve_lance_fts_field_path( + schema: &lance_core::datatypes::Schema, + column: &str, +) -> Result { + let names = + lance_core::datatypes::parse_field_path(column).map_err(|e| Error::InvalidInput { + message: format!("Invalid field path `{}`: {}", column, e), + })?; + let (root_name, remaining_names) = names.split_first().ok_or_else(|| Error::InvalidInput { + message: "FTS field path cannot be empty".to_string(), + })?; + let mut field = schema + .fields + .iter() + .find(|field| field.name == *root_name) + .or_else(|| { + schema + .fields + .iter() + .find(|field| field.name.eq_ignore_ascii_case(root_name)) + }) + .ok_or_else(|| fts_field_not_found(schema, column))?; + let mut canonical_names = vec![field.name.clone()]; + let mut list_depth = 0; + + for name in remaining_names { + while matches!( + field.data_type(), + DataType::List(_) | DataType::LargeList(_) + ) { + list_depth += 1; + field = field.children.first().ok_or_else(|| Error::Schema { + message: format!( + "FTS field path `{}` has a list without an item field", + column + ), + })?; + } + if !matches!(field.data_type(), DataType::Struct(_)) { + return Err(fts_field_not_found(schema, column)); + } + field = field + .children + .iter() + .find(|field| field.name == *name) + .or_else(|| { + field + .children + .iter() + .find(|field| field.name.eq_ignore_ascii_case(name)) + }) + .ok_or_else(|| fts_field_not_found(schema, column))?; + canonical_names.push(field.name.clone()); + } + + let mut terminal = field; + while matches!( + terminal.data_type(), + DataType::List(_) | DataType::LargeList(_) + ) { + list_depth += 1; + terminal = terminal.children.first().ok_or_else(|| Error::Schema { + message: format!( + "FTS field path `{}` has a list without an item field", + column + ), + })?; + } + + let canonical_path = lance_core::datatypes::format_field_path( + &canonical_names + .iter() + .map(String::as_str) + .collect::>(), + ); + Ok(ResolvedFtsField { + canonical_path, + field: Field::from(field), + list_depth, + }) +} + +fn fts_field_not_found(schema: &lance_core::datatypes::Schema, column: &str) -> Error { + Error::Schema { + message: format!( + "Field path `{}` not found in schema. Available field paths: {}", + column, + schema.field_paths().join(", ") + ), + } +} + +fn find_public_fts_field_path_by_id( + field: &lance_core::datatypes::Field, + field_id: i32, + path: &mut Vec, +) -> bool { + if field.id == field_id { + return true; + } + match field.data_type() { + DataType::List(_) | DataType::LargeList(_) => field + .children + .first() + .is_some_and(|child| find_public_fts_field_path_by_id(child, field_id, path)), + DataType::Struct(_) => field.children.iter().any(|child| { + path.push(child.name.clone()); + let found = find_public_fts_field_path_by_id(child, field_id, path); + if !found { + path.pop(); + } + found + }), + _ => false, + } +} + +pub(crate) fn public_fts_field_path_by_id( + schema: &lance_core::datatypes::Schema, + field_id: i32, +) -> Result { + for root in &schema.fields { + let mut path = vec![root.name.clone()]; + if find_public_fts_field_path_by_id(root, field_id, &mut path) { + return Ok(lance_core::datatypes::format_field_path( + &path.iter().map(String::as_str).collect::>(), + )); + } + } + Err(Error::Schema { + message: format!("Field id `{}` not found in schema", field_id), + }) +} + +pub(crate) fn resolve_arrow_fts_field_path( + schema: &Schema, + column: &str, +) -> Result<(String, Field)> { + let lance_schema = + lance_core::datatypes::Schema::try_from(schema).map_err(|e| Error::Schema { + message: format!("Invalid schema: {}", e), + })?; + let resolved = resolve_lance_fts_field_path(&lance_schema, column)?; + Ok((resolved.canonical_path, resolved.field)) +} + pub fn supported_btree_data_type(dtype: &DataType) -> bool { dtype.is_integer() || dtype.is_floating() @@ -480,6 +633,36 @@ mod tests { use super::*; + #[test] + fn test_public_fts_field_path_prefers_exact_case() { + let text_list = || { + DataType::List(Arc::new(Field::new( + "item", + DataType::Struct(vec![Field::new("content", DataType::Utf8, true)].into()), + true, + ))) + }; + let schema = Schema::new(vec![ + Field::new("Docs", text_list(), true), + Field::new("docs", text_list(), true), + ]); + + let (path, _) = resolve_arrow_fts_field_path(&schema, "docs.content").unwrap(); + assert_eq!(path, "docs.content"); + + let lance_schema = lance_core::datatypes::Schema::try_from(&schema).unwrap(); + let field_id = lance_schema + .resolve_case_insensitive("docs.item.content") + .unwrap() + .last() + .unwrap() + .id; + assert_eq!( + public_fts_field_path_by_id(&lance_schema, field_id).unwrap(), + "docs.content" + ); + } + #[test] fn test_guess_default_column() { let schema_no_vector = Schema::new(vec![ From 8b7e13b0c610c586029b763337d5baf2c3edab16 Mon Sep 17 00:00:00 2001 From: Dan Tasse <105866+dantasse@users.noreply.github.com> Date: Wed, 26 Aug 2026 14:19:44 -0400 Subject: [PATCH 128/206] docs: add comments about metadata conventions (#4054) In LanceDB Enterprise, we've adopted these conventions to give some "canonical" metadata paths. This lets us display them in a certain way in the UI or let agents standardize on them, to assume they'll find info in a certain place. This PR (only comments/docs) just documents those choices. --- docs/src/js/classes/Table.md | 12 ++++++++++++ docs/src/js/interfaces/FieldMetadataUpdate.md | 3 ++- nodejs/lancedb/table.ts | 15 ++++++++++++++- python/python/lancedb/table.py | 13 +++++++++++++ rust/lancedb/src/table.rs | 18 +++++++++++++++++- rust/lancedb/src/table/schema_evolution.rs | 4 +++- 6 files changed, 61 insertions(+), 4 deletions(-) diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 9a85d0d96..159348450 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1292,6 +1292,18 @@ abstract updateFieldMetadata(updates): Promise Update per-field (column) metadata. +The following keys are treated specially, by convention, and should be +used when appropriate: + +- `lancedb:description`: for a human-readable description of a field. +- `lancedb:tag:`: for a user-defined key-value tag, where the suffix + names the tag category; e.g. `lancedb:tag:model: "clip"`. +- `lancedb:logical-column`: for a column grouping; e.g. `feature_v1` and + `feature_v2` might be in the same logical column. +- `lancedb:status`: for status options (`production`, `candidate`, + `deprecated`, `archived`) to designate the current life cycle state of + this column. + #### Parameters * **updates**: [`FieldMetadataUpdate`](../interfaces/FieldMetadataUpdate.md)[] diff --git a/docs/src/js/interfaces/FieldMetadataUpdate.md b/docs/src/js/interfaces/FieldMetadataUpdate.md index 38c675630..a85e3e7a0 100644 --- a/docs/src/js/interfaces/FieldMetadataUpdate.md +++ b/docs/src/js/interfaces/FieldMetadataUpdate.md @@ -17,7 +17,8 @@ metadata: Record; ``` Metadata key/value pairs. Merged into the field's existing metadata by -default; a value of `null` deletes that key. +default; a value of `null` deletes that key. See +[Table.updateFieldMetadata](../classes/Table.md#updatefieldmetadata) for the conventional `lancedb:*` keys. *** diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 82f23e2f2..dc062e337 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -630,6 +630,18 @@ export abstract class Table { /** * Update per-field (column) metadata. + * + * The following keys are treated specially, by convention, and should be + * used when appropriate: + * + * - `lancedb:description`: for a human-readable description of a field. + * - `lancedb:tag:`: for a user-defined key-value tag, where the suffix + * names the tag category; e.g. `lancedb:tag:model: "clip"`. + * - `lancedb:logical-column`: for a column grouping; e.g. `feature_v1` and + * `feature_v2` might be in the same logical column. + * - `lancedb:status`: for status options (`production`, `candidate`, + * `deprecated`, `archived`) to designate the current life cycle state of + * this column. * @param {FieldMetadataUpdate[]} updates One or more per-field updates. Each * update's metadata is merged into the field's existing metadata by default; * a value of `null` deletes that key, and `replace: true` swaps the whole map. @@ -1555,7 +1567,8 @@ export interface FieldMetadataUpdate { path: string; /** * Metadata key/value pairs. Merged into the field's existing metadata by - * default; a value of `null` deletes that key. + * default; a value of `null` deletes that key. See + * {@link Table.updateFieldMetadata} for the conventional `lancedb:*` keys. */ metadata: Record; /** If true, replace the field's entire metadata map instead of merging. */ diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 76d5fc825..c354a944e 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2127,12 +2127,25 @@ class Table(ABC): ---------- updates : dict One or more dicts, each with: + - "path": str — dot-path to the field (e.g. "embedding" or "a.b.c"). - "metadata": dict[str, str | None] — keys to set; a value of ``None`` deletes that key. - "replace": bool, optional — replace the field's whole metadata map instead of merging (default False). + The following keys are treated specially, by convention, and should + be used when appropriate: + + - "lancedb:description": for a human-readable description of a field. + - ``"lancedb:tag:"`` for a user-defined key-value tag, where the + suffix names the tag category; e.g. "lancedb:tag:model": "clip". + - "lancedb:logical-column" for a column grouping; e.g. "feature_v1" + and "feature_v2" might be in the same logical column. + - "lancedb:status" for status options ("production", "candidate", + "deprecated", "archived") to designate the current life cycle + state of this column. + Returns ------- UpdateFieldMetadataResult diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 182e3e1a7..af8bcb5e2 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1777,7 +1777,23 @@ impl Table { self.inner.alter_columns(alterations).await } - /// Update per-field metadata (merges by default). + /// Update per-field (column) metadata. + /// + /// Each [`FieldMetadataUpdate`] is merged into the field's existing metadata + /// by default; use [`FieldMetadataUpdate::remove`] to delete a key, or + /// [`FieldMetadataUpdate::replace`] to swap the field's entire metadata map. + /// + /// The following keys are treated specially, by convention, and should be + /// used when appropriate: + /// + /// - `lancedb:description`: for a human-readable description of a field. + /// - `lancedb:tag:`: for a user-defined key-value tag, where the suffix + /// names the tag category; e.g. `lancedb:tag:model: "clip"`. + /// - `lancedb:logical-column`: for a column grouping; e.g. `feature_v1` and + /// `feature_v2` might be in the same logical column. + /// - `lancedb:status`: for status options (`production`, `candidate`, + /// `deprecated`, `archived`) to designate the current life cycle state of + /// this column. pub async fn update_field_metadata( &self, updates: &[FieldMetadataUpdate], diff --git a/rust/lancedb/src/table/schema_evolution.rs b/rust/lancedb/src/table/schema_evolution.rs index d10a45eea..4f8dc811a 100644 --- a/rust/lancedb/src/table/schema_evolution.rs +++ b/rust/lancedb/src/table/schema_evolution.rs @@ -55,7 +55,9 @@ pub struct DropColumnsResult { pub struct FieldMetadataUpdate { /// Dot-separated path to the field (e.g. `"embedding"` or `"address.zip"`). pub path: String, - /// Keys to set (`Some`) or delete (`None`). + /// Keys to set (`Some`) or delete (`None`). See + /// [`Table::update_field_metadata`](crate::Table::update_field_metadata) for + /// the conventional `lancedb:*` keys. pub metadata: HashMap>, /// If `true`, replace the field's entire metadata map instead of merging. pub replace: bool, From ae81d735638d7efdea39c1f29055134383b46abb Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Thu, 27 Aug 2026 04:23:28 +0800 Subject: [PATCH 129/206] fix: share scans across batched vector queries (#3805) ## Summary - use the Lance native batch KNN path so fixed-size batch vector searches share one flat table scan - validate consistent query-vector dimensions and retain the per-vector plan when offsets require its existing semantics - add Rust and Python regressions and update Rust, Python, and TypeScript API documentation ## Root cause LanceDB expanded every vector in a batch into a separate scan plan and joined the plans with `UnionExec`. For unindexed tables on S3, a batch of ten vectors therefore ran ten concurrent full scans, amplifying CPU and retained data enough to produce the reported memory spike. The native Lance batch KNN path performs bounded-memory selection for all query vectors over one flat scan. LanceDB now supplies the vectors as a batch and avoids applying a global scanner limit to the combined per-query results. Batch queries with a nonzero offset keep the previous plan because the native batch API does not support per-query offsets. ## Validation - targeted Rust batch-query plan and execution tests - `cargo check --quiet --features remote --tests --examples` - `cargo clippy --quiet --features remote --tests --examples` - `cargo fmt --all -- --check` - targeted Python batch-vector regression after rebuilding the extension - Ruff formatting/checks for the touched Python files - Node.js build, lint, docs generation, and targeted batch-vector Jest test - `git diff --check` Fixes #2468 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- nodejs/lancedb/query.ts | 10 +-- python/python/lancedb/query.py | 11 +-- python/python/tests/test_query.py | 17 +++++ rust/lancedb/src/query.rs | 113 ++++++++++++++++++++++++++++-- rust/lancedb/src/table/query.rs | 72 ++++++++++++++----- 5 files changed, 187 insertions(+), 36 deletions(-) diff --git a/nodejs/lancedb/query.ts b/nodejs/lancedb/query.ts index f1d31eae1..75a787fcd 100644 --- a/nodejs/lancedb/query.ts +++ b/nodejs/lancedb/query.ts @@ -727,11 +727,11 @@ export class VectorQuery extends StandardQueryBase { * Add a query vector to the search * * This method can be called multiple times to add multiple query vectors - * to the search. If multiple query vectors are added, then they will be searched - * in parallel, and the results will be concatenated. A column called `query_index` - * will be added to indicate the index of the query vector that produced the result. - * - * Performance wise, this is equivalent to running multiple queries concurrently. + * to the search. A column called `query_index` will be added to indicate the index + * of the query vector that produced the result. Flat searches share one table scan + * across the query vectors, avoiding the scan and memory amplification of running + * multiple queries concurrently. Indexed searches may still perform per-vector + * index work. */ addQueryVector(vector: IntoVector): VectorQuery { if (vector instanceof Promise) { diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 5dff2537e..9301d7df8 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -3401,9 +3401,10 @@ class AsyncQuery(AsyncStandardQuery): pass in multiple vectors. When multiple vectors are passed in, if the vector column is with multivector type, then the vectors will be treated as a single query. Or the vectors will be treated as multiple queries, this can be useful - if you want to find the nearest vectors to multiple query vectors. - This is not expected to be faster than making multiple queries concurrently; - it is just a convenience method. If multiple vectors are passed in then + if you want to find the nearest vectors to multiple query vectors. Flat + searches share one table scan across the query vectors, avoiding the scan + and memory amplification of making multiple queries concurrently. If + multiple vectors are passed in then an additional column `query_index` will be added to the results. This column will contain the index of the query vector that the result is nearest to. """ @@ -3532,8 +3533,8 @@ class AsyncFTSQuery(AsyncStandardQuery): Typically, a single vector is passed in as the query. However, you can also pass in multiple vectors. This can be useful if you want to find the nearest - vectors to multiple query vectors. This is not expected to be faster than - making multiple queries concurrently; it is just a convenience method. + vectors to multiple query vectors. Flat searches share one table scan across + the query vectors instead of issuing concurrent full scans. If multiple vectors are passed in then an additional column `query_index` will be added to the results. This column will contain the index of the query vector that the result is nearest to. diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index d2629d1a8..4758f0e2d 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -897,6 +897,23 @@ def test_query_builder_batches(table): assert rs_list["id"][1] == 2 +def test_batch_vector_query_shares_filtered_flat_scan(table): + query = ( + table.search([[1.0, 2.0], [3.0, 4.0]]) + .where("id > 0", prefilter=True) + .limit(1) + .select(["id"]) + ) + + plan = query.explain_plan(verbose=True) + assert "KNNVectorDistance: queries=2" in plan + assert "UnionExec" not in plan + + results = query.to_arrow() + assert len(results) == 2 + assert results["query_index"].to_pylist() == [0, 1] + + def test_dynamic_projection(table): rs = ( LanceVectorQueryBuilder(table, [0, 0], "vector") diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 654777adb..2a1283f22 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -1174,12 +1174,12 @@ impl VectorQuery { /// Add another query vector to the search. /// - /// Multiple searches will be dispatched as part of the query. - /// This is a convenience method for adding multiple query vectors - /// to the search. It is not expected to be faster than issuing - /// multiple queries concurrently. + /// Multiple searches will be dispatched as a batch. Flat searches share + /// one table scan across the query vectors, avoiding the scan and memory + /// amplification of issuing the searches concurrently. Indexed searches + /// may still perform per-vector index work. /// - /// The output data will contain an additional columns `query_index` which + /// The output data will contain an additional column `query_index` which /// will contain the index of the query vector that was used to generate the /// result. pub fn add_query_vector(mut self, vector: impl IntoQueryVector) -> Result { @@ -1646,7 +1646,11 @@ mod tests { use std::{collections::HashSet, sync::Arc}; use super::*; - use arrow::{array::downcast_array, compute::concat_batches, datatypes::Int32Type}; + use arrow::{ + array::downcast_array, + compute::concat_batches, + datatypes::{Int32Type, UInt8Type}, + }; use arrow_array::{ FixedSizeListArray, Float32Array, Int32Array, RecordBatch, StringArray, cast::AsArray, types::Float32Type, @@ -2334,7 +2338,8 @@ mod tests { .limit(1); let plan = query.explain_plan(true).await.unwrap(); - assert!(plan.contains("UnionExec")); + assert!(plan.contains("KNNVectorDistance: queries=2")); + assert!(!plan.contains("UnionExec")); let results = query .execute() @@ -2349,6 +2354,100 @@ mod tests { // We don't guarantee order. assert!(query_index.values().contains(&0)); assert!(query_index.values().contains(&1)); + + // Batch KNN does not support a per-query offset, so offset queries keep + // the legacy per-vector plan to preserve their result semantics. + let offset_query = table + .query() + .nearest_to(&[0.1, 0.2, 0.3, 0.4]) + .unwrap() + .add_query_vector(&[0.5, 0.6, 0.7, 0.8]) + .unwrap() + .limit(1) + .offset(1); + assert!( + offset_query + .explain_plan(true) + .await + .unwrap() + .contains("UnionExec") + ); + let offset_results = offset_query + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + offset_results + .iter() + .map(RecordBatch::num_rows) + .sum::(), + 2 + ); + } + + #[tokio::test] + async fn test_multiple_binary_query_vectors() { + let vectors = FixedSizeListArray::from_iter_primitive::( + vec![ + Some(vec![Some(0), Some(0)]), + Some(vec![Some(255), Some(255)]), + ], + 2, + ); + let schema = Arc::new(ArrowSchema::new(vec![ + ArrowField::new("id", DataType::Int32, false), + ArrowField::new("vector", vectors.data_type().clone(), false), + ])); + let batch = RecordBatch::try_new( + schema, + vec![Arc::new(Int32Array::from(vec![0, 1])), Arc::new(vectors)], + ) + .unwrap(); + + let conn = connect("memory://").execute().await.unwrap(); + let table = conn + .create_table("binary_batch", batch) + .execute() + .await + .unwrap(); + let query = table + .query() + .nearest_to(&[0.0, 0.0]) + .unwrap() + .add_query_vector(&[255.0, 255.0]) + .unwrap() + .distance_type(DistanceType::Hamming) + .limit(1); + + // Binary queries retain the per-vector plan because Lance's binary + // nearest path requires primitive UInt8 query arrays. + assert!( + query + .explain_plan(true) + .await + .unwrap() + .contains("UnionExec") + ); + + let results = query + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let results = concat_batches(&results[0].schema(), &results).unwrap(); + assert_eq!(results.num_rows(), 2); + + let ids = results["id"].as_primitive::(); + assert!(ids.values().contains(&0)); + assert!(ids.values().contains(&1)); + let query_index = results["query_index"].as_primitive::(); + assert!(query_index.values().contains(&0)); + assert!(query_index.values().contains(&1)); } #[tokio::test] diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 629cb4e6f..2684ac5e2 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -21,7 +21,6 @@ use datafusion_physical_plan::ExecutionPlan; use datafusion_physical_plan::projection::ProjectionExec; use datafusion_physical_plan::repartition::RepartitionExec; use datafusion_physical_plan::union::UnionExec; -use futures::future::try_join_all; use lance::dataset::mem_wal::DatasetMemWalExt; use lance::dataset::scanner::DatasetRecordBatchStream; use lance::dataset::scanner::Scanner; @@ -170,6 +169,7 @@ pub async fn create_plan( let mut column = query.column.clone(); let mut query_vector = query.query_vector.first().cloned(); + let mut is_batch_query = false; if query.query_vector.len() > 1 { if column.is_none() { // Infer a vector column with the same dimension of the query vector. @@ -180,16 +180,37 @@ pub async fn create_plan( )?); } let vector_field = schema.field(column.as_ref().unwrap()).unwrap(); - if let DataType::List(_) = vector_field.data_type() { - // Multivector handling: concatenate into FixedSizeList> + let (_, element_type) = + lance::index::vector::utils::get_vector_type(schema, column.as_ref().unwrap())?; + let is_binary = matches!(element_type, DataType::UInt8); + if matches!(vector_field.data_type(), DataType::List(_)) + || (query.base.offset.unwrap_or(0) == 0 && !is_binary) + { + // Lance distinguishes these cases from the vector column type: a + // list-like query against a List column is one multivector query, + // while the same query against a FixedSizeList column is a batch of + // independent queries. The batch path shares a single flat scan and + // bounds retained candidate data instead of running one scan per + // query vector. let vectors = query .query_vector .iter() .map(|arr| arr.as_ref()) .collect::>(); let dim = vectors[0].len(); + if let Some((query_index, actual_dim)) = vectors + .iter() + .enumerate() + .find_map(|(index, vector)| (vector.len() != dim).then_some((index, vector.len()))) + { + return Err(Error::InvalidInput { + message: format!( + "query vector at index {query_index} has dimension {actual_dim}, expected {dim}" + ), + }); + } let mut fsl_builder = FixedSizeListBuilder::with_capacity( - Float32Builder::with_capacity(dim), + Float32Builder::with_capacity(dim * vectors.len()), dim as i32, vectors.len(), ); @@ -200,8 +221,12 @@ pub async fn create_plan( fsl_builder.append(true); } query_vector = Some(Arc::new(fsl_builder.finish())); + is_batch_query = !matches!(vector_field.data_type(), DataType::List(_)); } else { - // Multiple query vectors: create a plan for each and union them + // Lance's batch path has no per-query offset, and its binary path + // requires primitive UInt8 queries rather than a fixed-size list. + // Keep the prior plan shape for these cases so offsets are applied + // per query and binary query vectors retain their primitive shape. let query_vecs = query.query_vector.clone(); let plan_futures = query_vecs .into_iter() @@ -214,7 +239,7 @@ pub async fn create_plan( } }) .collect::>(); - let plans = try_join_all(plan_futures).await?; + let plans = futures::future::try_join_all(plan_futures).await?; return create_multi_vector_plan(plans); } } @@ -251,10 +276,14 @@ pub async fn create_plan( } } - scanner.limit( - query.base.limit.map(|limit| limit as i64), - query.base.offset.map(|offset| offset as i64), - )?; + // For a batch query, `nearest` already applies k to each query vector. + // Adding Scanner's global limit would truncate the combined result to k rows. + if !is_batch_query { + scanner.limit( + query.base.limit.map(|limit| limit as i64), + query.base.offset.map(|offset| offset as i64), + )?; + } if let Some(ef) = query.ef { scanner.ef(ef); @@ -1088,7 +1117,7 @@ mod tests { } #[tokio::test] - async fn test_create_plan_multivector_structure() { + async fn test_create_plan_batch_vector_uses_shared_scan() { use arrow_array::{Float32Array, RecordBatch}; use arrow_schema::{DataType, Field, Schema}; use datafusion_physical_plan::display::DisplayableExecutionPlan; @@ -1115,11 +1144,18 @@ mod tests { .unwrap(); let native_table = table.as_native().unwrap(); - // This triggers the "create_multi_vector_plan" logic branch + // A batch of vectors against a fixed-size vector column should use + // Lance's native batch KNN path instead of independent scan plans. let q1 = Arc::new(Float32Array::from(vec![1.0, 2.0])); let q2 = Arc::new(Float32Array::from(vec![3.0, 4.0])); let req = VectorQueryRequest { + base: QueryRequest { + filter: Some(QueryFilter::Sql("id >= 0".to_string())), + limit: Some(1), + select: Select::Columns(vec!["id".to_string()]), + ..Default::default() + }, column: Some("vector".to_string()), query_vector: vec![q1, q2], ..Default::default() @@ -1136,19 +1172,17 @@ mod tests { .indent(true) .to_string(); - // We expect a RepartitionExec wrapping a UnionExec assert!( - display.contains("RepartitionExec"), - "Plan should include Repartitioning" + display.contains("KNNVectorDistance: queries=2"), + "plan should use native batch KNN, got:\n{display}" ); assert!( - display.contains("UnionExec"), - "Plan should include a Union of multiple searches" + !display.contains("UnionExec"), + "flat batch KNN should share one scan, got:\n{display}" ); - // We expect the projection to add the 'query_index' column (logic inside multi_vector_plan) assert!( display.contains("query_index"), - "Plan should add query_index column" + "plan should add query_index column, got:\n{display}" ); } From 79f626b09edc71b41fb285ee695e6714e14eb63c Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Thu, 27 Aug 2026 06:17:28 +0800 Subject: [PATCH 130/206] fix: support double-quoted filter identifiers (#3825) ## Summary - tokenize predicates with the same GenericDialect lexical rules Lance delegates to - rewrite only SQL-standard double-quoted identifier tokens to Lance backticks - apply one predicate contract to query, count, update, delete, and both merge conditions - cover mixed-case identifiers, ordinary literals, comments, and every filter-bearing table operation ## Root cause Lance plans double-quoted tokens as string literals for compatibility. As a result, `"PartyAbbrev" = 'D'` compared two literals and silently evaluated to false instead of filtering the mixed-case column. ## Validation - `cargo fmt --all -- --check` - `cargo test --locked --quiet --features remote -p lancedb expr::sql::tests` - `cargo test --locked --quiet --features remote -p lancedb test_double_quoted_predicates_across_table_operations` - `cargo check --quiet --features remote --tests --examples` - `cargo clippy --quiet --features remote --tests --examples` Fixes #2057 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- nodejs/examples/basic.test.ts | 2 +- python/python/tests/docs/test_basic.py | 4 +- python/python/tests/docs/test_guide_tables.py | 4 +- rust/lancedb/src/expr.rs | 1 + rust/lancedb/src/expr/sql.rs | 113 ++++++++++- rust/lancedb/src/materialized_view.rs | 13 +- rust/lancedb/src/materialized_view/refresh.rs | 184 +++++++++++++++--- rust/lancedb/src/query.rs | 169 +++++++++++++++- rust/lancedb/src/remote/table.rs | 60 +++--- rust/lancedb/src/table.rs | 18 +- rust/lancedb/src/table/delete.rs | 3 +- rust/lancedb/src/table/merge.rs | 28 ++- rust/lancedb/src/table/query.rs | 28 ++- rust/lancedb/src/table/update.rs | 15 +- 14 files changed, 570 insertions(+), 72 deletions(-) diff --git a/nodejs/examples/basic.test.ts b/nodejs/examples/basic.test.ts index b56bb2f95..e45fd622a 100644 --- a/nodejs/examples/basic.test.ts +++ b/nodejs/examples/basic.test.ts @@ -170,7 +170,7 @@ test("basic table examples", async () => { // --8<-- [end:create_index] // --8<-- [start:delete_rows] - await tbl.delete('item = "fizz"'); + await tbl.delete("item = 'fizz'"); // --8<-- [end:delete_rows] // --8<-- [start:drop_table] diff --git a/python/python/tests/docs/test_basic.py b/python/python/tests/docs/test_basic.py index 2a824371f..35d7aac10 100644 --- a/python/python/tests/docs/test_basic.py +++ b/python/python/tests/docs/test_basic.py @@ -105,7 +105,7 @@ def test_quickstart(tmp_path): tbl.create_index(num_sub_vectors=1) # --8<-- [end:create_index] # --8<-- [start:delete_rows] - tbl.delete('item = "fizz"') + tbl.delete("item = 'fizz'") # --8<-- [end:delete_rows] # --8<-- [start:drop_table] db.drop_table("my_table") @@ -201,7 +201,7 @@ async def test_quickstart_async(tmp_path): await tbl.create_index("vector") # --8<-- [end:create_index_async] # --8<-- [start:delete_rows_async] - await tbl.delete('item = "fizz"') + await tbl.delete("item = 'fizz'") # --8<-- [end:delete_rows_async] # --8<-- [start:drop_table_async] await db.drop_table("my_table_async") diff --git a/python/python/tests/docs/test_guide_tables.py b/python/python/tests/docs/test_guide_tables.py index 9ae86d167..dab8d43e9 100644 --- a/python/python/tests/docs/test_guide_tables.py +++ b/python/python/tests/docs/test_guide_tables.py @@ -266,7 +266,7 @@ def test_table(): tbl.add(pydantic_model_items) # --8<-- [end:add_table_from_pydantic] # --8<-- [start:delete_row] - tbl.delete('item = "fizz"') + tbl.delete("item = 'fizz'") # --8<-- [end:delete_row] # --8<-- [start:delete_specific_row] data = [ @@ -538,7 +538,7 @@ async def test_table_async(): await async_tbl.add(pydantic_model_items) # --8<-- [end:add_table_async_from_pydantic] # --8<-- [start:delete_row_async] - await async_tbl.delete('item = "fizz"') + await async_tbl.delete("item = 'fizz'") # --8<-- [end:delete_row_async] # --8<-- [start:delete_specific_row_async] data = [ diff --git a/rust/lancedb/src/expr.rs b/rust/lancedb/src/expr.rs index 75cce443d..da69914e3 100644 --- a/rust/lancedb/src/expr.rs +++ b/rust/lancedb/src/expr.rs @@ -19,6 +19,7 @@ mod sql; +pub(crate) use sql::canonicalize_sql_predicate; pub use sql::expr_to_sql_string; use std::sync::Arc; diff --git a/rust/lancedb/src/expr/sql.rs b/rust/lancedb/src/expr/sql.rs index 23b89821a..24a676485 100644 --- a/rust/lancedb/src/expr/sql.rs +++ b/rust/lancedb/src/expr/sql.rs @@ -1,10 +1,16 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use std::any::TypeId; + use datafusion_common::ScalarValue; use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; use datafusion_expr::Expr; -use datafusion_sql::unparser::{self, dialect::Dialect}; +use datafusion_sql::sqlparser::{ + dialect::{Dialect as SqlParserDialect, GenericDialect}, + tokenizer::{Token, Tokenizer}, +}; +use datafusion_sql::unparser::{self, dialect::Dialect as UnparserDialect}; /// Unparser dialect that matches the quoting style expected by the Lance SQL /// parser. Lance uses backtick (`` ` ``) as the only delimited-identifier @@ -19,7 +25,7 @@ use datafusion_sql::unparser::{self, dialect::Dialect}; /// lower-case by the SQL parser, which would break case-sensitive schemas). struct LanceSqlDialect; -impl Dialect for LanceSqlDialect { +impl UnparserDialect for LanceSqlDialect { fn identifier_quote_style(&self, identifier: &str) -> Option { let needs_quote = identifier.chars().any(|c| c.is_ascii_uppercase()) || !identifier @@ -30,6 +36,61 @@ impl Dialect for LanceSqlDialect { } } +/// Lance's tokenizer dialect with SQL-standard double-quoted identifiers added. +/// +/// Keep this deliberately small: Lance's parser wraps `GenericDialect` and +/// delegates only identifier recognition, leaving every other dialect option at +/// its default. In particular, `/*! ... */` remains an ordinary block comment. +#[derive(Debug, Default)] +struct PredicateDialect(GenericDialect); + +impl SqlParserDialect for PredicateDialect { + fn dialect(&self) -> TypeId { + self.0.dialect() + } + + fn is_identifier_start(&self, ch: char) -> bool { + self.0.is_identifier_start(ch) + } + + fn is_identifier_part(&self, ch: char) -> bool { + self.0.is_identifier_part(ch) + } + + fn is_delimited_identifier_start(&self, ch: char) -> bool { + ch == '"' || ch == '`' + } +} + +/// Canonicalize a raw SQL predicate for Lance's parser. +/// +/// Lance wraps [`GenericDialect`] for identifier recognition while retaining the +/// default dialect behavior for every other lexical option. [`PredicateDialect`] +/// mirrors that contract and additionally recognizes `"` as an identifier +/// delimiter, allowing this function to rewrite only those identifier tokens. +pub fn canonicalize_sql_predicate(predicate: &str) -> crate::Result { + let dialect = PredicateDialect::default(); + let tokens = Tokenizer::new(&dialect, predicate) + .with_unescape(false) + .tokenize() + .map_err(|err| crate::Error::InvalidInput { + message: format!("invalid SQL predicate: {err}"), + })?; + + Ok(tokens + .into_iter() + .map(|token| match token { + Token::Word(word) if word.quote_style == Some('"') => { + // with_unescape(false) retains doubled double quotes. Decode + // those before escaping any backticks for Lance's delimiter. + let identifier = word.value.replace("\"\"", "\"").replace('`', "``"); + format!("`{identifier}`") + } + other => other.to_string(), + }) + .collect()) +} + /// Prefix for placeholder strings inserted in place of binary literals. Chosen /// to be extremely unlikely to occur in user data. const BINARY_PLACEHOLDER_PREFIX: &str = "__lancedb_binary_placeholder_"; @@ -113,3 +174,51 @@ pub fn expr_to_sql_string(expr: &Expr) -> crate::Result { } Ok(sql) } + +#[cfg(test)] +mod tests { + use super::canonicalize_sql_predicate; + + #[test] + fn normalizes_double_quoted_identifiers() { + assert_eq!( + canonicalize_sql_predicate(r#""PartyAbbrev" = 'D'"#).unwrap(), + "`PartyAbbrev` = 'D'" + ); + assert_eq!( + canonicalize_sql_predicate(r#""MetaData"."userId" = 5"#).unwrap(), + "`MetaData`.`userId` = 5" + ); + assert_eq!( + canonicalize_sql_predicate(r#""a""b" = 1"#).unwrap(), + "`a\"b` = 1" + ); + } + + #[test] + fn preserves_quotes_inside_literals_and_backticks() { + let filter = r#"name = 'Alice "Ace"' AND `quoted"field` = 1"#; + assert_eq!(canonicalize_sql_predicate(filter).unwrap(), filter); + } + + #[test] + fn preserves_literals_and_comments_using_lance_dialect_rules() { + let predicate = r#"path = '\' AND "PartyAbbrev" = 'D' -- unmatched " in comment"#; + assert_eq!( + canonicalize_sql_predicate(predicate).unwrap(), + r#"path = '\' AND `PartyAbbrev` = 'D' -- unmatched " in comment"# + ); + + let predicate = r#"id = 1 /* unmatched " in block comment */"#; + assert_eq!(canonicalize_sql_predicate(predicate).unwrap(), predicate); + + let predicate = r#"id = 1 /*! OR "PartyAbbrev" = 'D' */"#; + assert_eq!(canonicalize_sql_predicate(predicate).unwrap(), predicate); + } + + #[test] + fn rejects_unterminated_double_quoted_identifier() { + let error = canonicalize_sql_predicate(r#""PartyAbbrev = 'D'"#).unwrap_err(); + assert!(matches!(error, crate::Error::InvalidInput { .. })); + } +} diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index b28d52931..08d6c921e 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -170,6 +170,15 @@ pub(crate) fn plan( filter: Option<&str>, limit: Option, ) -> Result<(MaterializedViewDefinition, Vec, Lineage)> { + let filter = filter + .map(crate::expr::canonicalize_sql_predicate) + .transpose() + .map_err(|err| match err { + Error::InvalidInput { message } => Error::InvalidInput { + message: format!("invalid view filter: {message}"), + }, + err => err, + })?; let projections: Vec<(String, String)> = if projections.is_empty() { source_schema .fields() @@ -274,7 +283,7 @@ pub(crate) fn plan( declared.push(output); } - if let Some(filter) = filter { + if let Some(filter) = filter.as_deref() { let expr = planner .parse_filter(filter) .map_err(|e| Error::InvalidInput { @@ -314,7 +323,7 @@ pub(crate) fn plan( .into_iter() .map(|(output, expression)| ViewProjection { output, expression }) .collect(), - filter: filter.map(String::from), + filter, limit, inputs, }; diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index 735751c27..b967e81f8 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -46,8 +46,9 @@ use lance_table::format::Fragment; use serde::{Deserialize, Serialize}; use super::{ - INCARNATION_META_KEY, MaterializedViewDefinition, REFRESHED_AT_MS_META_KEY, - SOURCE_ROW_ID_COLUMN, SOURCE_VERSION_META_KEY, + DEFINITION_META_KEY, INCARNATION_META_KEY, MaterializedViewDefinition, + REFRESHED_AT_MS_META_KEY, SOURCE_ROW_ID_COLUMN, SOURCE_VERSION_META_KEY, + definition_to_metadata, }; use crate::database::OpenTableRequest; use crate::table::{NativeTable, NativeTableExt, Table}; @@ -197,8 +198,28 @@ pub(crate) async fn execute_refresh( ), }); } + let definition_changed = + definition.filter != replanned.filter || definition.inputs != replanned.inputs; let definition = &replanned; + // A watermark written for a legacy raw filter certifies the rows that + // filter produced, not the canonical predicate above. Rebuild instead of + // accepting or advancing it, and persist the migrated definition in the + // same metadata commit that certifies the replacement rows. + if definition_changed { + return rebuild( + view_native, + &view_ds, + &source_ds, + source_version, + source_ts, + definition, + true, + expected_incarnation, + ) + .await; + } + let metadata = &view_ds.schema().metadata; let watermark: Option = metadata .get(SOURCE_VERSION_META_KEY) @@ -257,6 +278,7 @@ pub(crate) async fn execute_refresh( source_version, source_ts, definition, + false, expected_incarnation, ) .await @@ -271,6 +293,7 @@ pub(crate) async fn execute_refresh( source_version, source_ts, definition, + false, expected_incarnation, ) .await @@ -683,6 +706,7 @@ async fn incremental( view_ds.clone(), source_version, source_ts, + None, expected_incarnation, ) .await?; @@ -704,6 +728,7 @@ async fn incremental( published, source_version, source_ts, + None, expected_incarnation, ) .await?; @@ -775,6 +800,7 @@ async fn incremental( published, source_version, source_ts, + None, expected_incarnation, ) .await?; @@ -824,12 +850,14 @@ async fn incremental( appended, source_version, source_ts, + None, expected_incarnation, ) .await?; Ok(Some(result)) } +#[allow(clippy::too_many_arguments)] async fn rebuild( view_native: &NativeTable, view_ds: &Dataset, @@ -837,6 +865,7 @@ async fn rebuild( source_version: u64, source_ts: u128, definition: &MaterializedViewDefinition, + persist_definition: bool, expected_incarnation: Option<&str>, ) -> Result { let rows_written = Arc::new(AtomicU64::new(0)); @@ -867,6 +896,7 @@ async fn rebuild( replaced, source_version, source_ts, + persist_definition.then_some(definition), expected_incarnation, ) .await?; @@ -981,6 +1011,7 @@ async fn stamp_watermark( mut dataset: Dataset, source_version: u64, source_ts: u128, + definition: Option<&MaterializedViewDefinition>, expected_incarnation: Option<&str>, ) -> Result { ensure_incarnation(&dataset, expected_incarnation, dataset.uri()).await?; @@ -993,27 +1024,32 @@ async fn stamp_watermark( .get(INCARNATION_META_KEY) .cloned() .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); - dataset - .update_schema_metadata([ - (INCARNATION_META_KEY.to_string(), Some(incarnation)), - ( - SOURCE_VERSION_META_KEY.to_string(), - Some(source_version.to_string()), - ), - ( - SOURCE_VERSION_TS_META_KEY.to_string(), - Some(source_ts.to_string()), - ), - ( - REFRESHED_AT_MS_META_KEY.to_string(), - Some(now_ms().to_string()), - ), - ( - VIEW_VERSION_META_KEY.to_string(), - Some(predicted.to_string()), - ), - ]) - .await?; + let mut metadata = vec![(INCARNATION_META_KEY.to_string(), Some(incarnation))]; + if let Some(definition) = definition { + metadata.push(( + DEFINITION_META_KEY.to_string(), + Some(definition_to_metadata(definition)?), + )); + } + metadata.extend([ + ( + SOURCE_VERSION_META_KEY.to_string(), + Some(source_version.to_string()), + ), + ( + SOURCE_VERSION_TS_META_KEY.to_string(), + Some(source_ts.to_string()), + ), + ( + REFRESHED_AT_MS_META_KEY.to_string(), + Some(now_ms().to_string()), + ), + ( + VIEW_VERSION_META_KEY.to_string(), + Some(predicted.to_string()), + ), + ]); + dataset.update_schema_metadata(metadata).await?; let actual = dataset.version().version; if actual != predicted { return Err(Error::Runtime { @@ -1585,6 +1621,106 @@ mod tests { assert_eq!(read(view.table(), "x").await, vec![20, 40]); } + #[tokio::test] + async fn test_mixed_case_filter_is_canonicalized_for_lineage_and_refresh() { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!( + ("id", Int32, [1, 2, 3]), + ("PartyAbbrev", Utf8, ["D", "R", "D"]) + ) + .unwrap(); + conn.create_table("src", batch) + .write_options(crate::materialized_view::tests::stable_row_ids()) + .execute() + .await + .unwrap(); + conn.create_materialized_view("democrats", "src") + .select([("id", "id")]) + .only_if(r#""PartyAbbrev" = 'D'"#) + .execute() + .await + .unwrap(); + + // Reopen from schema metadata so these assertions cover the stored + // predicate and lineage, not only the declaration-time handle. + let view = conn.open_materialized_view("democrats").await.unwrap(); + assert_eq!( + view.definition().filter.as_deref(), + Some("`PartyAbbrev` = 'D'") + ); + assert_eq!(view.definition().inputs, ["PartyAbbrev", "id"]); + + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.rows_written, 2); + assert_eq!(read(view.table(), "id").await, vec![1, 3]); + } + + #[tokio::test] + async fn test_legacy_raw_filter_rebuilds_and_persists_canonical_definition() { + let conn = connect("memory://").execute().await.unwrap(); + let batch = record_batch!( + ("id", Int32, [1, 2, 3]), + ("PartyAbbrev", Utf8, ["D", "R", "D"]) + ) + .unwrap(); + conn.create_table("legacy_src", batch) + .write_options(crate::materialized_view::tests::stable_row_ids()) + .execute() + .await + .unwrap(); + let view = conn + .create_materialized_view("legacy_view", "legacy_src") + .select([("id", "id")]) + .only_if(r#""PartyAbbrev" = 'X'"#) + .execute() + .await + .unwrap(); + assert_eq!(view.refresh().execute().await.unwrap().rows_written, 0); + + // Model a definition and up-to-date watermark written before filter + // canonicalization was applied to materialized views. + let mut legacy = view.definition().clone(); + legacy.filter = Some(r#""PartyAbbrev" = 'D'"#.into()); + legacy.inputs = vec!["id".into()]; + let native = view.table().as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + let predicted = dataset.version().version + 1; + dataset + .update_schema_metadata([ + ( + DEFINITION_META_KEY.to_string(), + Some(definition_to_metadata(&legacy).unwrap()), + ), + ( + VIEW_VERSION_META_KEY.to_string(), + Some(predicted.to_string()), + ), + ]) + .await + .unwrap(); + native.dataset.update(dataset); + + let reopened = conn.open_materialized_view("legacy_view").await.unwrap(); + let result = reopened.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Rebuild); + assert_eq!(result.rows_written, 2); + assert_eq!(read(reopened.table(), "id").await, vec![1, 3]); + + // A fresh handle proves the migration was stored alongside the new + // watermark and therefore happens only once. + let migrated = conn.open_materialized_view("legacy_view").await.unwrap(); + assert_eq!( + migrated.definition().filter.as_deref(), + Some("`PartyAbbrev` = 'D'") + ); + assert_eq!(migrated.definition().inputs, ["PartyAbbrev", "id"]); + assert_eq!( + migrated.refresh().execute().await.unwrap().mode, + RefreshMode::NoOp + ); + assert_eq!(read(migrated.table(), "id").await, vec![1, 3]); + } + #[tokio::test] async fn test_append_refreshes_incrementally() { let (_conn, source, view) = refreshed_doubled(vec![1, 2]).await; @@ -2767,7 +2903,7 @@ mod tests { let stale = view_native.dataset.get().await.unwrap().as_ref().clone(); view.table().delete("x = 1").await.unwrap(); - let err = stamp_watermark(view_native, stale, 99, 99, None).await; + let err = stamp_watermark(view_native, stale, 99, 99, None, None).await; assert!(err.is_err()); let result = view.refresh().execute().await.unwrap(); diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 2a1283f22..cd346f42e 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -399,6 +399,9 @@ pub trait QueryBase { /// x > 5 OR y = 'test' /// ``` /// + /// Identifiers may be delimited with SQL-standard double quotes or + /// backticks. String literals must use single quotes. + /// /// Filtering performance can often be improved by creating a scalar index /// on the filter column(s). /// @@ -913,6 +916,17 @@ impl QueryRequest { /// use different representations) the error is recorded and surfaced later /// by [`Self::check_filter`]. pub(crate) fn add_filter(&mut self, new: QueryFilter) { + let new = match new { + QueryFilter::Sql(filter) => match crate::expr::canonicalize_sql_predicate(&filter) { + Ok(filter) => QueryFilter::Sql(filter), + Err(err) => { + self.filter_error = Some(err.to_string()); + return; + } + }, + other => other, + }; + self.filter = Some(match self.filter.take() { None => new, Some(existing) => match and_filters(existing, new) { @@ -1652,8 +1666,8 @@ mod tests { datatypes::{Int32Type, UInt8Type}, }; use arrow_array::{ - FixedSizeListArray, Float32Array, Int32Array, RecordBatch, StringArray, cast::AsArray, - types::Float32Type, + FixedSizeListArray, Float32Array, Int32Array, RecordBatch, RecordBatchIterator, + StringArray, cast::AsArray, types::Float32Type, }; use arrow_schema::{DataType, Field as ArrowField, Schema as ArrowSchema}; use futures::{StreamExt, TryStreamExt}; @@ -1882,6 +1896,157 @@ mod tests { query.execute().await.unwrap(); } + #[tokio::test] + async fn test_double_quoted_predicates_across_table_operations() { + let tmp_dir = tempdir().unwrap(); + let dataset_path = tmp_dir.path().join("test.lance"); + let uri = dataset_path.to_str().unwrap(); + let schema = Arc::new(ArrowSchema::new(vec![ + ArrowField::new("id", DataType::Int32, false), + ArrowField::new("PartyAbbrev", DataType::Utf8, false), + ArrowField::new("path", DataType::Utf8, false), + ])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![1, 2, 3, 4])), + Arc::new(StringArray::from(vec!["D", "R", "R", "D"])), + Arc::new(StringArray::from(vec!["\\", "\\", "x", "x"])), + ], + ) + .unwrap(); + + let conn = connect(uri).execute().await.unwrap(); + let table = conn.create_table("parties", batch).execute().await.unwrap(); + let batches = table + .query() + .only_if(r#""PartyAbbrev" = 'D'"#) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 2); + assert_eq!( + table + .count_rows(Some(r#""PartyAbbrev" = 'D'"#.to_string())) + .await + .unwrap(), + 2 + ); + + // Public BaseTable dispatch cannot bypass canonicalization. + let query = AnyQuery::Query(QueryRequest { + filter: Some(QueryFilter::Sql(r#""PartyAbbrev" = 'D'"#.to_string())), + ..Default::default() + }); + let batches = table + .base_table() + .query(&query, Default::default()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 2); + assert_eq!( + table + .base_table() + .count_rows(Some(crate::table::Filter::Sql( + r#""PartyAbbrev" = 'D'"#.to_string(), + ))) + .await + .unwrap(), + 2 + ); + + for predicate in [ + r#"id = 1 -- unmatched " in a valid SQL comment"#, + r#"id = 1 /* unmatched " in a valid SQL comment */"#, + r#"id = 1 /*! OR "PartyAbbrev" = 'D' */"#, + r#"path = '\' AND "PartyAbbrev" = 'D'"#, + ] { + let batches = table + .query() + .only_if(predicate) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 1); + } + + // The same canonical predicate contract applies to both merge filters. + let source = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![1, 2, 3])), + Arc::new(StringArray::from(vec!["D", "R", "R"])), + Arc::new(StringArray::from(vec!["\\", "\\", "x"])), + ], + ) + .unwrap(); + let mut merge = table.merge_insert(&["id"]); + merge.when_not_matched_by_source_delete(Some(r#""PartyAbbrev" = 'D'"#.to_string())); + let result = table + .base_table() + .merge_insert( + merge, + Box::new(RecordBatchIterator::new(vec![Ok(source)], schema.clone())), + ) + .await + .unwrap(); + assert_eq!(result.num_deleted_rows, 1); + + let source = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int32Array::from(vec![1, 2, 3])), + Arc::new(StringArray::from(vec!["U", "U", "U"])), + Arc::new(StringArray::from(vec!["\\", "\\", "x"])), + ], + ) + .unwrap(); + let mut merge = table.merge_insert(&["id"]); + merge.when_matched_update_all(Some(r#"target."PartyAbbrev" = 'D'"#.to_string())); + merge + .execute(Box::new(RecordBatchIterator::new(vec![Ok(source)], schema))) + .await + .unwrap(); + assert_eq!( + table + .count_rows(Some(r#""PartyAbbrev" = 'U'"#.to_string())) + .await + .unwrap(), + 1 + ); + + let update = table + .update() + .only_if(r#""PartyAbbrev" = 'R'"#) + .column("PartyAbbrev", "'X'"); + table.base_table().update(update).await.unwrap(); + assert_eq!( + table + .count_rows(Some(r#""PartyAbbrev" = 'X'"#.to_string())) + .await + .unwrap(), + 2 + ); + + let result = table + .base_table() + .delete(crate::table::Predicate::String(r#""PartyAbbrev" = 'X'"#)) + .await + .unwrap(); + assert_eq!(result.num_deleted_rows, 2); + assert_eq!(table.count_rows(None).await.unwrap(), 1); + } + #[tokio::test] async fn test_select_with_transform() { let batches = make_non_empty_batches(); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index fad04a098..1afc2615a 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -1379,10 +1379,11 @@ impl RemoteTable { query: &AnyQuery, version: Option, ) -> Result> { + let query = query.canonicalized()?; let mut base_body = serde_json::json!({ "version": version }); self.apply_branch_body(&mut base_body); - match query { + match &query { AnyQuery::Query(query) => { let mut body = base_body.clone(); self.apply_query_params(&mut body, query)?; @@ -2491,7 +2492,7 @@ impl BaseTable for RemoteTable { let mut body = if let Some(filter) = filter { let filter_sql = match filter { - Filter::Sql(sql) => sql.clone(), + Filter::Sql(sql) => crate::expr::canonicalize_sql_predicate(&sql)?, Filter::Datafusion(expr) => expr_to_sql_string(&expr)?, }; serde_json::json!({ "predicate": filter_sql, "version": read_snapshot.version }) @@ -2747,7 +2748,8 @@ impl BaseTable for RemoteTable { Ok(final_analyze) } - async fn update(&self, update: UpdateBuilder) -> Result { + async fn update(&self, mut update: UpdateBuilder) -> Result { + update.canonicalize_filter()?; self.check_mutable().await?; let request = self .client @@ -2794,7 +2796,7 @@ impl BaseTable for RemoteTable { async fn delete(&self, predicate: Predicate<'_>) -> Result { self.check_mutable().await?; let predicate_sql = match predicate { - Predicate::String(s) => s.to_string(), + Predicate::String(s) => crate::expr::canonicalize_sql_predicate(s)?, Predicate::Expr(expr) => expr_to_sql_string(expr)?, }; let mut body = serde_json::json!({ "predicate": predicate_sql }); @@ -2851,9 +2853,10 @@ impl BaseTable for RemoteTable { async fn merge_insert( &self, - params: MergeInsertBuilder, + mut params: MergeInsertBuilder, new_data: Box, ) -> Result { + params.canonicalize_filters()?; self.check_mutable().await?; let timeout = params.timeout; @@ -3864,13 +3867,17 @@ mod tests { ); assert_eq!( request.body().unwrap().as_bytes().unwrap(), - br#"{"predicate":"a > 10","version":null}"# + br#"{"predicate":"`A` > 10","version":null}"# ); http::Response::builder().status(200).body("42").unwrap() }); - let count = table.count_rows(Some("a > 10".into())).await.unwrap(); + let count = table + .base_table() + .count_rows(Some(Filter::Sql(r#""A" > 10"#.into()))) + .await + .unwrap(); assert_eq!(count, 42); } @@ -4353,7 +4360,7 @@ mod tests { assert_eq!(expression, "b - 1"); let only_if = value.get("predicate").unwrap().as_str().unwrap(); - assert_eq!(only_if, "b > 10"); + assert_eq!(only_if, "`B` > 10"); } if old_server { @@ -4369,14 +4376,12 @@ mod tests { } }); - let result = table + let update = table .update() .column("a", "a + 1") .column("b", "b - 1") - .only_if("b > 10") - .execute() - .await - .unwrap(); + .only_if(r#""B" > 10"#); + let result = table.base_table().update(update).await.unwrap(); assert_eq!(result.version, if old_server { 0 } else { 43 }); assert_eq!(result.rows_updated, if old_server { 0 } else { 5 }); @@ -4463,10 +4468,10 @@ mod tests { let params = request.url().query_pairs().collect::>(); assert_eq!(params["on"], "some_col"); - assert_eq!(params["when_matched_update_all"], "false"); + assert_eq!(params["when_matched_update_all"], "true"); assert_eq!(params["when_not_matched_insert_all"], "false"); assert_eq!(params["when_not_matched_by_source_delete"], "false"); - assert!(!params.contains_key("when_matched_update_all_filt")); + assert_eq!(params["when_matched_update_all_filt"], "target.`A` > 0"); assert!(!params.contains_key("when_not_matched_by_source_delete_filt")); assert!(!params.contains_key("use_index")); @@ -4483,11 +4488,9 @@ mod tests { } }); - let result = table - .merge_insert(&["some_col"]) - .execute(data) - .await - .unwrap(); + let mut merge = table.merge_insert(&["some_col"]); + merge.when_matched_update_all(Some(r#"target."A" > 0"#.into())); + let result = table.base_table().merge_insert(merge, data).await.unwrap(); assert_eq!(result.version, if old_server { 0 } else { 43 }); if !old_server { @@ -4549,7 +4552,7 @@ mod tests { let body = request.body().unwrap().as_bytes().unwrap(); let body: serde_json::Value = serde_json::from_slice(body).unwrap(); let predicate = body.get("predicate").unwrap().as_str().unwrap(); - assert_eq!(predicate, "id in (1, 2, 3)"); + assert_eq!(predicate, "`ID` in (1, 2, 3)"); if old_server { http::Response::builder() @@ -4567,7 +4570,11 @@ mod tests { } }); - let result = table.delete("id in (1, 2, 3)").await.unwrap(); + let result = table + .base_table() + .delete(Predicate::String(r#""ID" in (1, 2, 3)"#)) + .await + .unwrap(); assert_eq!(result.version, if old_server { 0 } else { 43 }); } @@ -4659,6 +4666,7 @@ mod tests { let body = request.body().unwrap().as_bytes().unwrap(); let body: serde_json::Value = serde_json::from_slice(body).unwrap(); let expected_body = serde_json::json!({ + "filter": "`A` > 0", "k": isize::MAX as usize, "prefilter": true, "vector": [], // Empty vector means no vector query. @@ -4674,9 +4682,13 @@ mod tests { .unwrap() }); + let query = AnyQuery::Query(QueryRequest { + filter: Some(QueryFilter::Sql(r#""A" > 0"#.into())), + ..Default::default() + }); let data = table - .query() - .execute() + .base_table() + .query(&query, Default::default()) .await .unwrap() .collect::>() diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index af8bcb5e2..8436657ca 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1164,7 +1164,10 @@ impl Table { /// /// * `filter` if present, only count rows matching the filter pub async fn count_rows(&self, filter: Option) -> Result { - self.inner.count_rows(filter.map(Filter::Sql)).await + let filter = filter + .map(|predicate| crate::expr::canonicalize_sql_predicate(&predicate).map(Filter::Sql)) + .transpose()?; + self.inner.count_rows(filter).await } /// Names of the blob v2 columns in this table, in declaration order. @@ -1364,7 +1367,13 @@ impl Table { /// # }); /// ``` pub async fn delete(&self, predicate: impl Into>) -> Result { - self.inner.delete(predicate.into()).await + match predicate.into() { + Predicate::String(predicate) => { + let predicate = crate::expr::canonicalize_sql_predicate(predicate)?; + self.inner.delete(Predicate::String(&predicate)).await + } + predicate @ Predicate::Expr(_) => self.inner.delete(predicate).await, + } } /// Create an index on the provided column(s). @@ -3239,7 +3248,10 @@ impl BaseTable for NativeTable { let dataset = self.dataset.get().await?; match filter { None => Ok(dataset.count_rows(None).await?), - Some(Filter::Sql(sql)) => Ok(dataset.count_rows(Some(sql)).await?), + Some(Filter::Sql(sql)) => { + let sql = crate::expr::canonicalize_sql_predicate(&sql)?; + Ok(dataset.count_rows(Some(sql)).await?) + } Some(Filter::Datafusion(_)) => Err(Error::NotSupported { message: "Datafusion filters are not yet supported".to_string(), }), diff --git a/rust/lancedb/src/table/delete.rs b/rust/lancedb/src/table/delete.rs index 8f11ee019..cb1da03ae 100644 --- a/rust/lancedb/src/table/delete.rs +++ b/rust/lancedb/src/table/delete.rs @@ -31,8 +31,9 @@ pub(crate) async fn execute_delete( table.dataset.ensure_mutable()?; match predicate { Predicate::String(s) => { + let predicate = crate::expr::canonicalize_sql_predicate(s)?; let mut dataset = (*table.dataset.get().await?).clone(); - let delete_result = dataset.delete(s).boxed().await?; + let delete_result = dataset.delete(&predicate).boxed().await?; let num_deleted_rows = delete_result.num_deleted_rows; let version = dataset.version().version; table.dataset.update(dataset); diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index 3227e3edf..ef2af8fe0 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -220,9 +220,32 @@ impl MergeInsertBuilder { /// /// Returns version and statistics about the merge operation including the number of rows /// inserted, updated, and deleted. - pub async fn execute(self, new_data: Box) -> Result { + pub async fn execute( + mut self, + new_data: Box, + ) -> Result { + self.canonicalize_filters()?; self.table.clone().merge_insert(self, new_data).await } + + pub(crate) fn canonicalize_filters(&mut self) -> Result<()> { + self.when_matched_update_all_filt = + canonicalize_merge_filter(self.when_matched_update_all_filt.take())?; + self.when_not_matched_by_source_delete_filt = + canonicalize_merge_filter(self.when_not_matched_by_source_delete_filt.take())?; + Ok(()) + } +} + +fn canonicalize_merge_filter(filter: Option) -> Result> { + filter + .map(|filter| match filter { + MergeFilter::Sql(predicate) => { + crate::expr::canonicalize_sql_predicate(&predicate).map(MergeFilter::Sql) + } + filter @ MergeFilter::Expr(_) => Ok(filter), + }) + .transpose() } /// Internal implementation of the merge insert logic @@ -230,9 +253,10 @@ impl MergeInsertBuilder { /// This logic was moved from NativeTable::merge_insert to keep table.rs clean. pub(crate) async fn execute_merge_insert( table: &NativeTable, - params: MergeInsertBuilder, + mut params: MergeInsertBuilder, new_data: Box, ) -> Result { + params.canonicalize_filters()?; super::computed_columns::ensure_no_function_bindings_for_mutation( table.schema().await?.as_ref(), "merge_insert", diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 2684ac5e2..b413b2e17 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -44,6 +44,22 @@ impl AnyQuery { Self::VectorQuery(query) => &query.base, } } + + fn base_mut(&mut self) -> &mut QueryRequest { + match self { + Self::Query(query) => query, + Self::VectorQuery(query) => &mut query.base, + } + } + + /// Canonicalize any raw SQL filter immediately before backend dispatch. + pub(crate) fn canonicalized(&self) -> Result { + let mut query = self.clone(); + if let Some(QueryFilter::Sql(predicate)) = &mut query.base_mut().filter { + *predicate = crate::expr::canonicalize_sql_predicate(predicate)?; + } + Ok(query) + } } //Decide between namespace or local @@ -52,15 +68,16 @@ pub async fn execute_query( query: &AnyQuery, options: QueryExecutionOptions, ) -> Result { + let query = query.canonicalized()?; // QueryTable pushdown runs the query server-side, but only on the main // branch: the namespace request carries no branch yet, so a branch handle // must fall through to local execution. - if can_execute_namespace_query(table, query).await? + if can_execute_namespace_query(table, &query).await? && let Some(ref namespace_client) = table.namespace_client { - return execute_namespace_query(table, namespace_client.clone(), query, options).await; + return execute_namespace_query(table, namespace_client.clone(), &query, options).await; } - execute_generic_query(table, query, options).await + execute_generic_query(table, &query, options).await } async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> Result { @@ -135,9 +152,10 @@ pub async fn create_plan( query: &AnyQuery, options: QueryExecutionOptions, ) -> Result> { + let query = query.canonicalized()?; let query = match query { - AnyQuery::VectorQuery(query) => query.clone(), - AnyQuery::Query(query) => VectorQueryRequest::from_plain_query(query.clone()), + AnyQuery::VectorQuery(query) => query, + AnyQuery::Query(query) => VectorQueryRequest::from_plain_query(query), }; query.base.check_filter()?; diff --git a/rust/lancedb/src/table/update.rs b/rust/lancedb/src/table/update.rs index 98050dfe8..f10594f23 100644 --- a/rust/lancedb/src/table/update.rs +++ b/rust/lancedb/src/table/update.rs @@ -62,22 +62,33 @@ impl UpdateBuilder { } /// Executes the update operation. - pub async fn execute(self) -> Result { + pub async fn execute(mut self) -> Result { if self.columns.is_empty() { Err(Error::InvalidInput { message: "at least one column must be specified in an update operation".to_string(), }) } else { + self.canonicalize_filter()?; self.parent.clone().update(self).await } } + + pub(crate) fn canonicalize_filter(&mut self) -> Result<()> { + self.filter = self + .filter + .take() + .map(|predicate| crate::expr::canonicalize_sql_predicate(&predicate)) + .transpose()?; + Ok(()) + } } /// Internal implementation of the update logic pub(crate) async fn execute_update( table: &NativeTable, - update: UpdateBuilder, + mut update: UpdateBuilder, ) -> Result { + update.canonicalize_filter()?; table.dataset.ensure_mutable()?; // 1. Snapshot the current dataset From 5153e5a023d0a81b1b16b4b389850be29a61f30c Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Wed, 26 Aug 2026 16:18:57 -0700 Subject: [PATCH 131/206] fix(node): preserve JSON field metadata when adding data (#4064) ## Summary - preserve Arrow field metadata when matching record data to a provided schema - retain metadata on partially reconstructed nested struct fields - add a regression test for lance.json metadata through Arrow IPC serialization ## Root cause The TypeScript schema inferrer rebuilt fields selected from a provided schema without copying their metadata. JSON columns therefore kept their LargeBinary physical type but lost the lance.json extension marker before insert, causing the schema mismatch reported in the issue. ## Validation - pnpm lint - pnpm build - pnpm tsc - pnpm run docs - pnpm test --runInBand (18 suites and 798 tests passed; 5 tests skipped) Fixes #4062 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- nodejs/__test__/arrow.test.ts | 21 +++++++++++++++++++++ nodejs/__test__/table.test.ts | 21 +++++++++++++++++++++ nodejs/lancedb/schema.ts | 3 ++- 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/nodejs/__test__/arrow.test.ts b/nodejs/__test__/arrow.test.ts index c5bbbf169..cb56cb5ae 100644 --- a/nodejs/__test__/arrow.test.ts +++ b/nodejs/__test__/arrow.test.ts @@ -6,6 +6,9 @@ import * as arrow17 from "apache-arrow-17"; import * as arrow18 from "apache-arrow-18"; import { + Field as CurrentField, + LargeBinary as CurrentLargeBinary, + Schema as CurrentSchema, Vector as CurrentVector, convertToTable, tableFromIPC as currentTableFromIPC, @@ -36,6 +39,24 @@ function sampleRecords(): Array> { }, ]; } + +it("preserves field metadata from a provided schema", async function () { + const jsonMetadata = new Map([["ARROW:extension:name", "lance.json"]]); + const schema = new CurrentSchema([ + new CurrentField("meta", new CurrentLargeBinary(), true, jsonMetadata), + ]); + + const table = makeArrowTable( + [{ meta: Buffer.from(JSON.stringify({ source: "test" })) }], + { schema }, + ); + + expect(table.schema.fields[0].metadata).toEqual(jsonMetadata); + + const roundTripped = currentTableFromIPC(await fromTableToBuffer(table)); + expect(roundTripped.schema.fields[0].metadata).toEqual(jsonMetadata); +}); + describe.each([arrow15, arrow16, arrow17, arrow18])( "Arrow", ( diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index dae640850..554c7fcd3 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -3561,6 +3561,27 @@ describe("when creating an empty table", () => { expect((actualSchema.fields[1].type as Float64).precision).toBe(2); }); + it("can add and query JSON data", async () => { + const schema = new Schema([ + new Field("id", new Int32(), true), + new Field( + "meta", + new Utf8(), + true, + new Map([["ARROW:extension:name", "arrow.json"]]), + ), + ]); + const table = await con.createEmptyTable("json", schema); + const meta = JSON.stringify({ x: 1 }); + + await table.add([{ id: 1, meta }]); + + const rows = await table.query().toArray(); + expect(rows).toHaveLength(1); + expect(rows[0].id).toBe(1); + expect(rows[0].meta).toBe(meta); + }); + it("can create an empty table from schema that specifies field types by name", async () => { const schemaLike = { fields: [ diff --git a/nodejs/lancedb/schema.ts b/nodejs/lancedb/schema.ts index e4749ef37..3a3ee9316 100644 --- a/nodejs/lancedb/schema.ts +++ b/nodejs/lancedb/schema.ts @@ -406,10 +406,11 @@ function matchingFields(fields: Field[], tree: FieldTree): Field[] { field.name, new Struct(matchingFields(struct.children, value)), field.nullable, + field.metadata, ), ); } else { - matches.push(new Field(field.name, value as DataType, field.nullable)); + matches.push(field); } } return matches; From ead4d27bfc60d6be42fbde15471aa55807b8bbbf Mon Sep 17 00:00:00 2001 From: Lance Release Date: Thu, 27 Aug 2026 04:31:22 +0000 Subject: [PATCH 132/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.10=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.11?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package-lock.json | 4 ++-- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 1c4aea809..2e0b78bf3 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.10" +current_version = "0.38.0-beta.11" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index e27f9f271..822689a0c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.10" +version = "0.38.0-beta.11" dependencies = [ "ahash", "anyhow", @@ -5490,7 +5490,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.10" +version = "0.38.0-beta.11" dependencies = [ "arrow-array", "arrow-buffer", @@ -5515,7 +5515,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.10" +version = "0.38.0-beta.11" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 06dc267f3..1ce012522 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.38.0-beta.10 + 0.38.0-beta.11 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 25e3b10e3..c6acc7dfe 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.10 + 0.38.0-beta.11 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index a2cec19c0..0b85b69df 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.10 + 0.38.0-beta.11 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index fd08e7a5e..6496c6384 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.10" +version = "0.38.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 ff6347c4d..38b3db7d7 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.38.0-beta.10", + "version": "0.38.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 ed99fee05..a256cb1ee 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.38.0-beta.10", + "version": "0.38.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 5b215dcc0..567b785b0 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.38.0-beta.10", + "version": "0.38.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 e0f5a9f26..4443a2748 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.38.0-beta.10", + "version": "0.38.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 d42541707..5c0710d56 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.38.0-beta.10", + "version": "0.38.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 496a40720..648c985f1 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.38.0-beta.10", + "version": "0.38.0-beta.11", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 734013343..1f3bfdeb8 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.38.0-beta.10", + "version": "0.38.0-beta.11", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index 732a7c01c..d46f08628 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.10", + "version": "0.38.0-beta.11", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.10", + "version": "0.38.0-beta.11", "cpu": [ "x64", "arm64" diff --git a/nodejs/package.json b/nodejs/package.json index 262d4c4a7..665e2a522 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.10", + "version": "0.38.0-beta.11", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 3a8a05522..b97fad0ed 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.10" +version = "0.38.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 8276e5bb3..a71e3c948 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.10" +version = "0.38.0-beta.11" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 2deccf21cf4ec30e915584c44065c2275614653b Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Thu, 27 Aug 2026 13:42:30 +0800 Subject: [PATCH 133/206] fix(node): read Python embedding metadata (#3836) ## Summary - normalize Python snake_case and TypeScript camelCase embedding metadata - use the normalized metadata for schema validation and embedding lookup - cover appending through `Table.add()` with a Python-authored schema fixture ## Root cause Python writes embedding source and vector column names as `source_column` and `vector_column`, but the TypeScript SDK only read `sourceColumn` and `vectorColumn`. The missing source name reached the add path as `undefined`, preventing JavaScript rows from being embedded and appended. ## Validation - `pnpm lint` - `pnpm test __test__/embedding.test.ts __test__/arrow.test.ts __test__/registry.test.ts --runInBand` (201 passed, 1 skipped) - `pnpm build` - `pnpm run docs` Fixes #1289 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- nodejs/__test__/embedding.test.ts | 52 +++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/nodejs/__test__/embedding.test.ts b/nodejs/__test__/embedding.test.ts index 2a8494e0f..45d171a3d 100644 --- a/nodejs/__test__/embedding.test.ts +++ b/nodejs/__test__/embedding.test.ts @@ -187,6 +187,58 @@ describe("embedding functions", () => { const vector0 = JSON.parse(JSON.stringify(arr[0].vector)); expect(vector0).toEqual([1, 2, 3]); }); + it("should append multiple Python embeddings with the same alias", async () => { + @register("python-mock") + // biome-ignore lint/correctness/noUnusedVariables: the decorator registers this class + class MockEmbeddingFunction extends EmbeddingFunction { + ndims() { + return 3; + } + embeddingDataType(): Float { + return new Float32(); + } + async computeQueryEmbeddings(_data: string) { + return [1, 2, 3]; + } + async computeSourceEmbeddings(data: string[]) { + return data.map((value) => + value === "hello world" ? [1, 2, 3] : [4, 5, 6], + ); + } + } + + const metadata = new Map([ + [ + "embedding_functions", + '[{"source_column":"text1","vector_column":"vector1","name":"python-mock","model":{}},{"source_column":"text2","vector_column":"vector2","name":"python-mock","model":{}}]', + ], + ]); + const schema = new Schema( + [ + new Field("text1", new Utf8(), true), + new Field("text2", new Utf8(), true), + new Field( + "vector1", + new FixedSizeList(3, new Field("item", new Float32(), true)), + true, + ), + new Field( + "vector2", + new FixedSizeList(3, new Field("item", new Float32(), true)), + true, + ), + ], + metadata, + ); + + const db = await connect(tmpDir.name); + const table = await db.createEmptyTable("test", schema); + await table.add([{ text1: "hello world", text2: "goodbye world" }]); + + const rows = await table.query().toArray(); + expect(JSON.parse(JSON.stringify(rows[0].vector1))).toEqual([1, 2, 3]); + expect(JSON.parse(JSON.stringify(rows[0].vector2))).toEqual([4, 5, 6]); + }); it("should append generated vectors to a non-nullable schema", async () => { @register("non_nullable_schema_test") From d24b2dcacc4a3cbf8b62948941baba38dce5ce9a Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Thu, 27 Aug 2026 15:47:18 +0800 Subject: [PATCH 134/206] fix: show nested fields in query schema errors (#3849) ## Summary - enrich local query field-not-found errors with recursively qualified Arrow struct leaf paths - preserve all other Lance and DataFusion errors unchanged - add a regression test for the Python-visible filter error described in the issue ## Root cause DataFusion builds `FieldNotFound` candidates from the top-level Arrow schema even though Lance supports dotted struct-field filters. As a result, the error listed only the struct container and hid its valid nested leaves. ## Validation - `cargo test --quiet --features remote -p lancedb table::query::tests::test_missing_filter_field_lists_nested_fields -- --exact` - `cargo check --quiet --features remote --tests --examples` - `cargo clippy --quiet --features remote --tests --examples` (passes with pre-existing unrelated warnings) - `cargo fmt --all -- --check` Fixes #951 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- rust/lancedb/src/table/query.rs | 263 +++++++++++++++++++++++++++- rust/lancedb/src/table/query/lsm.rs | 24 ++- 2 files changed, 280 insertions(+), 7 deletions(-) diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index b413b2e17..6f6bbf372 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -17,6 +17,7 @@ use arrow::array::{AsArray, FixedSizeListBuilder, Float32Builder}; use arrow::datatypes::{Float32Type, UInt8Type}; use arrow_array::Array; use arrow_schema::{DataType, Schema}; +use datafusion_common::{Column, DataFusionError, SchemaError}; use datafusion_physical_plan::ExecutionPlan; use datafusion_physical_plan::projection::ProjectionExec; use datafusion_physical_plan::repartition::RepartitionExec; @@ -191,7 +192,7 @@ pub async fn create_plan( if query.query_vector.len() > 1 { if column.is_none() { // Infer a vector column with the same dimension of the query vector. - let arrow_schema = Schema::from(ds_ref.schema()); + let arrow_schema = Schema::from(schema); column = Some(default_vector_column( &arrow_schema, Some(query.query_vector[0].len() as i32), @@ -268,7 +269,7 @@ pub async fn create_plan( let column = if let Some(col) = column { col } else { - let arrow_schema = Schema::from(ds_ref.schema()); + let arrow_schema = Schema::from(schema); default_vector_column(&arrow_schema, Some(query_vector.len() as i32))? }; @@ -374,7 +375,97 @@ pub async fn create_plan( scanner.order_by(Some(order_by.clone()))?; } - Ok(scanner.create_plan().await?) + scanner + .create_plan() + .await + .map_err(|error| enrich_lance_field_not_found(error, schema)) +} + +/// Replace DataFusion's top-level field candidates with qualified leaf paths. +/// +/// DataFusion resolves nested fields but its `FieldNotFound` error only lists the +/// top-level Arrow fields. This makes a missing leaf look unavailable even when it +/// exists below a struct. Keep every other Lance/DataFusion error unchanged and +/// enrich only this one schema error at the LanceDB query boundary. +fn enrich_lance_field_not_found( + error: lance::Error, + schema: &lance_core::datatypes::Schema, +) -> Error { + let Some(field) = find_missing_field(&error) else { + return error.into(); + }; + field_not_found_error(field, &Schema::from(schema)) +} + +fn field_not_found_diagnostic( + error: &(dyn std::error::Error + 'static), + schema: &Schema, +) -> Option { + let field = find_missing_field(error)?; + Some(field_not_found_error(field, schema)) +} + +fn field_not_found_error(field: &Column, schema: &Schema) -> Error { + let valid_fields = leaf_field_paths(schema); + let mut message = format!("Schema error: No field named {}", field.quoted_flat_name()); + if !valid_fields.is_empty() { + message.push_str(". Valid fields are "); + message.push_str(&valid_fields.join(", ")); + } + message.push('.'); + + Error::InvalidInput { message } +} + +fn find_missing_field<'a>(error: &'a (dyn std::error::Error + 'static)) -> Option<&'a Column> { + if let Some(DataFusionError::SchemaError(schema_error, _)) = + error.downcast_ref::() + && let SchemaError::FieldNotFound { field, .. } = schema_error.as_ref() + { + return Some(field); + } + + error.source().and_then(find_missing_field) +} + +fn leaf_field_paths(schema: &Schema) -> Vec { + fn format_segment(segment: &str) -> String { + // Quote every segment instead of maintaining a SQL keyword list. Bare + // lowercase names such as `true` can be parsed as expressions rather + // than identifiers, while backticks preserve all field names in both + // local SQL parsers. + format!("`{}`", segment.replace('`', "``")) + } + + fn visit(fields: &arrow_schema::Fields, path: &mut Vec, paths: &mut Vec) { + for field in fields { + // Neither local planner can address an empty field-path segment, + // even when it is backtick-quoted. Do not advertise leaves beneath + // such a segment as valid filter fields. + if field.name().is_empty() { + continue; + } + path.push(field.name().clone()); + match field.data_type() { + DataType::Struct(children) if !children.is_empty() => { + visit(children, path, paths); + } + _ => { + paths.push( + path.iter() + .map(|segment| format_segment(segment)) + .collect::>() + .join("."), + ); + } + } + path.pop(); + } + } + + let mut paths = Vec::new(); + visit(schema.fields(), &mut Vec::new(), &mut paths); + paths } //Helper functions below @@ -734,7 +825,10 @@ async fn parse_arrow_ipc_response(bytes: bytes::Bytes) -> Result, dimension: i32) -> FixedSizeListArray { @@ -884,7 +978,6 @@ mod tests { async fn test_execute_query_local_routing() { use crate::connect; use crate::table::query::execute_query; - use arrow_array::{Int32Array, RecordBatch}; use arrow_schema::{DataType, Field, Schema}; let conn = connect("memory://").execute().await.unwrap(); @@ -924,6 +1017,164 @@ mod tests { assert_eq!(count, 2); // 4 and 5 } + #[tokio::test] + async fn test_missing_filter_field_lists_nested_fields_in_local_planners() { + use crate::connect; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let metadata = Arc::new(StructArray::from(vec![ + ( + Arc::new(Field::new("year", DataType::Int32, false)), + Arc::new(Int32Array::from(vec![2024])) as ArrayRef, + ), + ( + Arc::new(Field::new("genre", DataType::Utf8, false)), + Arc::new(StringArray::from(vec!["fiction"])) as ArrayRef, + ), + ( + Arc::new(Field::new("Title", DataType::Int32, false)), + Arc::new(Int32Array::from(vec![7])) as ArrayRef, + ), + ( + Arc::new(Field::new("true", DataType::Int32, false)), + Arc::new(Int32Array::from(vec![8])) as ArrayRef, + ), + ( + Arc::new(Field::new("", DataType::Int32, false)), + Arc::new(Int32Array::from(vec![10])) as ArrayRef, + ), + ])); + let vector = Arc::new(fixed_size_list_array(vec![0.0, 1.0], 2)); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("vector", vector.data_type().clone(), false), + Field::new("content", DataType::Utf8, false), + Field::new("metadata", metadata.data_type().clone(), false), + ])); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(Int32Array::from(vec![1])), + vector, + Arc::new(StringArray::from(vec!["example"])), + metadata, + ], + ) + .unwrap(); + let table = conn + .create_table("nested_error", batch) + .execute() + .await + .unwrap(); + + let error = table + .query() + .only_if("year = 2024") + .execute() + .await + .err() + .expect("query should reject the unqualified nested field"); + let case_sensitive_path = "`metadata`.`Title`"; + let keyword_path = "`metadata`.`true`"; + let expected = format!( + "No field named year. Valid fields are `id`, `vector`, `content`, `metadata`.`year`, `metadata`.`genre`, {case_sensitive_path}, {keyword_path}." + ); + + assert!( + error.to_string().contains(&expected), + "unexpected error: {error}" + ); + for (path, value) in [(case_sensitive_path, 7), (keyword_path, 8)] { + table + .query() + .only_if(format!("{path} = {value}")) + .execute() + .await + .expect("the path advertised by the diagnostic should be reusable"); + } + + table.set_unenforced_primary_key(["id"]).await.unwrap(); + table + .set_lsm_write_spec(crate::table::LsmWriteSpec::unsharded()) + .await + .unwrap(); + let lsm_error = table + .query() + .only_if("year = 2024") + .execute() + .await + .err() + .expect("LSM query should reject the unqualified nested field"); + + assert!( + lsm_error.to_string().contains(&expected), + "unexpected LSM error: {lsm_error}" + ); + for (path, value) in [(case_sensitive_path, 7), (keyword_path, 8)] { + table + .query() + .only_if(format!("{path} = {value}")) + .execute() + .await + .expect("the path advertised by the diagnostic should be reusable in LSM queries"); + } + } + + #[test] + fn test_leaf_field_paths_preserve_arbitrary_depth() { + use arrow_schema::{DataType, Field, Schema}; + + fn nested_field(path: &[&str]) -> Field { + let mut segments = path.iter().rev(); + let mut field = Field::new( + *segments.next().expect("path must have a leaf"), + DataType::Int32, + false, + ); + for segment in segments { + field = Field::new(*segment, DataType::Struct(vec![field].into()), false); + } + field + } + + let schema = Schema::new(vec![ + nested_field(&["a", "b", "c", "d", "e"]), + nested_field(&["metadata", "child.with.dot"]), + nested_field(&["metadata", "Title"]), + nested_field(&["metadata", "123child"]), + nested_field(&["metadata", "child`tick"]), + nested_field(&["metadata", ""]), + nested_field(&["", "child"]), + ]); + + assert_eq!( + leaf_field_paths(&schema), + vec![ + "`a`.`b`.`c`.`d`.`e`", + "`metadata`.`child.with.dot`", + "`metadata`.`Title`", + "`metadata`.`123child`", + "`metadata`.`child``tick`", + ] + ); + + let source = DataFusionError::SchemaError( + Box::new(SchemaError::FieldNotFound { + field: Box::new(Column::from_name("missing")), + valid_fields: Vec::new(), + }), + Box::new(None), + ); + let error = field_not_found_diagnostic(&source, &schema).unwrap(); + assert!( + error.to_string().contains( + "Valid fields are `a`.`b`.`c`.`d`.`e`, `metadata`.`child.with.dot`, `metadata`.`Title`, `metadata`.`123child`, `metadata`.`child``tick`" + ), + "unexpected error: {error}" + ); + } + #[derive(Debug, Default)] struct CountingNamespaceClient { query_table_calls: AtomicUsize, diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index 5c340cc35..86c1fe5f2 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -27,6 +27,8 @@ use std::sync::Arc; use arrow_array::Array; use arrow_schema::{DataType, Schema as ArrowSchema}; +use datafusion::common::{DataFusionError, ToDFSchema}; +use datafusion::prelude::SessionContext; use datafusion_physical_plan::expressions::Column; use datafusion_physical_plan::projection::ProjectionExec; use datafusion_physical_plan::{ExecutionPlan, PhysicalExpr}; @@ -391,7 +393,21 @@ fn base_scanner( } if let Some(filter) = &query.base.filter { scanner = match filter { - QueryFilter::Sql(sql) => scanner.filter(sql)?, + QueryFilter::Sql(sql) => { + // Parse here instead of inside `LsmScanner::filter` so the typed + // DataFusion `FieldNotFound` error is still available for the + // same nested-field enrichment used by the ordinary scanner. + let schema = ArrowSchema::from(dataset.schema()); + let df_schema = schema.clone().to_dfschema().map_err(|error| { + enrich_filter_error(error, &schema, "Failed to create DFSchema") + })?; + let expr = SessionContext::new() + .parse_sql_expr(sql, &df_schema) + .map_err(|error| { + enrich_filter_error(error, &schema, "Failed to parse filter expression") + })?; + scanner.filter_expr(expr) + } QueryFilter::Datafusion(expr) => scanner.filter_expr(expr.clone()), QueryFilter::Substrait(_) => { return Err(Error::NotSupported { @@ -403,6 +419,12 @@ fn base_scanner( Ok(scanner) } +fn enrich_filter_error(error: DataFusionError, schema: &ArrowSchema, context: &str) -> Error { + super::field_not_found_diagnostic(&error, schema).unwrap_or_else(|| Error::InvalidInput { + message: format!("{context}: {error}"), + }) +} + /// Plain scan: filter / projection / limit over base ∪ SSTables ∪ in-memory. /// The plain scan applies limit and offset inside the planner. async fn plain_plan( From 0dd9dfdfc745f002afd24facc918744a8fe1ccfc Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Thu, 27 Aug 2026 17:10:51 +0800 Subject: [PATCH 135/206] test(python): cover arithmetic with distance projections (#3862) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary - add Python regression coverage for integer and double arithmetic against the generated _distance column - merge the current main base containing Lance v11.0.0-beta.3 from #3896 - verify both expressions retain the generated scoring field Float32 type and compute the expected values ## Root cause Lance parsed dynamic projection expressions before vector search added its generated Float32 _distance field. Without a typed provisional field, expression discovery rejected mixed numeric arithmetic. Lance upstream fixed discovery and final-schema replanning in lance-format/lance#8163, and the current base consumes that fix through Lance v11.0.0-beta.3. ## Validation - uv run --extra tests pytest python/tests/test_query.py::test_select_arithmetic_with_distance -vv --maxfail=2 — 2 passed - python/.venv/bin/ruff format --check python/python/tests/test_query.py - python/.venv/bin/ruff check . Fixes #2618 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- python/python/tests/test_query.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 4758f0e2d..ff62b2b51 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -675,6 +675,21 @@ def test_distance_range(table: lancedb.table.Table): assert res["_distance"].to_pylist() == [min_dist, max_dist] +@pytest.mark.parametrize("expression", ["1 - _distance", "1.0 - _distance"]) +def test_select_arithmetic_with_distance(table, expression): + result = ( + table.search([10, 10]) + .select({"similarity": expression, "_distance": "_distance"}) + .distance_type("cosine") + .to_arrow() + ) + + assert result.schema.field("similarity").type == pa.float32() + assert result["similarity"].to_pylist() == pytest.approx( + [1 - distance for distance in result["_distance"].to_pylist()] + ) + + @pytest.mark.asyncio async def test_distance_range_async(table_async: AsyncTable): q = [0, 0] From 25645d82d42e27fc4db8c386aa3decac7b4f2f97 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Thu, 27 Aug 2026 20:28:21 +0800 Subject: [PATCH 136/206] feat(python): accept expressions in update filters (#3876) ## Summary - allow Python sync, async, and remote table updates to accept type-safe `Expr` filters - serialize expression filters before invoking the existing update implementation - cover numeric-looking text and apostrophe-containing text in sync and async regression tests ## Root cause `Table.update` was the remaining Python write path that required callers to construct a raw SQL predicate. Dynamic text interpolated without SQL literal encoding could therefore be parsed as an integer, float, or unterminated string instead of Utf8. The expression API already encodes literals safely for query and delete filters. ## Validation - `cd python && .venv/bin/pytest python/tests/test_table.py::test_update_async python/tests/test_table.py::test_update_expr_filter_literals_async python/tests/test_table.py::test_update python/tests/test_table.py::test_update_expr_filter_literals -q` - `cd python && .venv/bin/pytest python/tests/test_expr.py -q` - `cd python && .venv/bin/ruff format --check .` - `cd python && .venv/bin/ruff check .` Fixes #1869 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- python/python/lancedb/_blob.py | 6 +- python/python/lancedb/_lancedb.pyi | 2 + python/python/lancedb/expr.py | 6 +- python/python/lancedb/query.py | 16 +- python/python/lancedb/remote/table.py | 11 +- python/python/lancedb/table.py | 42 +++-- python/python/tests/test_blob.py | 73 ++++++- python/python/tests/test_expr.py | 42 ++--- python/python/tests/test_table.py | 158 ++++++++++++++++ python/src/expr.rs | 8 + python/src/query.rs | 23 +++ rust/lancedb/src/expr.rs | 124 +++++++++++- rust/lancedb/src/expr/sql.rs | 262 +++++++++++++++++++++----- 13 files changed, 678 insertions(+), 95 deletions(-) diff --git a/python/python/lancedb/_blob.py b/python/python/lancedb/_blob.py index 926769f48..5b4c0c343 100644 --- a/python/python/lancedb/_blob.py +++ b/python/python/lancedb/_blob.py @@ -270,7 +270,8 @@ def _iter_projection_pairs( if isinstance(expr, str): yield name, expr elif isinstance(expr, Expr): - yield name, expr.to_sql() + source = expr._column_name() + yield name, source if source is not None else expr.to_sql() return for column in projection: if isinstance(column, str): @@ -280,7 +281,8 @@ def _iter_projection_pairs( if isinstance(expr, str): yield name, expr elif isinstance(expr, Expr): - yield name, expr.to_sql() + source = expr._column_name() + yield name, source if source is not None else expr.to_sql() def _set_blob_column(tbl: pa.Table, output_name: str, blobs: pa.Array) -> pa.Table: diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 593bceffa..7d7ca7f2a 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -87,6 +87,7 @@ class PyExpr: def contains(self, substr: "PyExpr") -> "PyExpr": ... def isin(self, values: List["PyExpr"]) -> "PyExpr": ... def cast(self, data_type: pa.DataType) -> "PyExpr": ... + def column_name(self) -> Optional[str]: ... def to_sql(self) -> str: ... def expr_col(name: str) -> PyExpr: ... @@ -608,6 +609,7 @@ class PyQueryRequest: filter: Optional[Union[str, bytes]] full_text_search: Optional[FullTextQuery] select: Optional[Union[str, List[str]]] + select_source_columns: Optional[Dict[str, str]] fast_search: Optional[bool] with_row_id: Optional[bool] use_lsm: Optional[bool] diff --git a/python/python/lancedb/expr.py b/python/python/lancedb/expr.py index d16ba95d7..80d01e29a 100644 --- a/python/python/lancedb/expr.py +++ b/python/python/lancedb/expr.py @@ -249,6 +249,10 @@ class Expr: # ── utilities ──────────────────────────────────────────────────────────── + def _column_name(self) -> str | None: + """Return the source name when this is a bare column expression.""" + return self._inner.column_name() + def to_sql(self) -> str: """Render the expression as a SQL string (useful for debugging).""" return self._inner.to_sql() @@ -312,7 +316,7 @@ def func(name: str, *args: ExprLike) -> Expr: -------- >>> from lancedb.expr import col, func >>> func("lower", col("name")) - Expr(lower(name)) + Expr(lower(`name`)) """ inner_args = [_coerce(a)._inner for a in args] return Expr(expr_func(name, inner_args)) diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 9301d7df8..451384ad1 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -167,6 +167,12 @@ def _projection_to_scanner_kwargs(columns: QueryProjection) -> Dict[str, Any]: return {"columns": projection} +def _query_request_projection(req: "PyQueryRequest") -> QueryProjection: + if req.select_source_columns is not None: + return req.select_source_columns + return req.select + + def _scanner_kwargs_for_query( query: Query, blob_mode: BlobMode, @@ -2799,15 +2805,16 @@ class AsyncQueryBase(object): req = self._inner.to_query_request() schema = await self._table.schema() + projection = _query_request_projection(req) self._blob_auto_row_id = blob_auto_row_id_for_scan( schema, - req.select, + 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, req.select).keys()) + self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys()) self._inner.with_row_id() def select(self, columns: Union[List[str], dict[str, str]]) -> Self: @@ -3894,14 +3901,15 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): 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, - req.select, + projection, with_row_id=self._with_row_id, ) if blob_auto_row_id: blob_paths = tuple( - blob_v2_projection_sources(schema, req.select).keys() + blob_v2_projection_sources(schema, projection).keys() ) self._blob_auto_row_id = blob_auto_row_id self._blob_paths = blob_paths diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index d9139396b..02748b9bc 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -36,6 +36,7 @@ from lancedb._lancedb import ( UpdateResult, ) from lancedb.embeddings.base import EmbeddingFunctionConfig +from lancedb.expr import Expr from lancedb.index import ( FTS, BTree, @@ -863,7 +864,7 @@ class RemoteTable(Table): def update( self, - where: Optional[str] = None, + where: Optional[Union[str, Expr]] = None, values: Optional[dict] = None, *, values_sql: Optional[Dict[str, str]] = None, @@ -874,9 +875,11 @@ class RemoteTable(Table): Parameters ---------- - where: str, optional - The SQL where clause to use when updating rows. For example, 'x = 2' - or 'x IN (1, 2, 3)'. The filter must not be empty, or it will error. + where: str or [Expr][lancedb.expr.Expr], optional + The filter condition. Can be a SQL string or a type-safe + [Expr][lancedb.expr.Expr] built with [col][lancedb.expr.col] and + [lit][lancedb.expr.lit]. The filter must not be empty, or it will + error. values: dict, optional The values to update. The keys are the column names and the values are the values to set. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index c354a944e..765b7fa14 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1744,7 +1744,7 @@ class Table(ABC): @abstractmethod def update( self, - where: Optional[str] = None, + where: Optional[Union[str, Expr]] = None, values: Optional[dict] = None, *, values_sql: Optional[Dict[str, str]] = None, @@ -1759,9 +1759,11 @@ class Table(ABC): Parameters ---------- - where: str, optional - The SQL where clause to use when updating rows. For example, 'x = 2' - or 'x IN (1, 2, 3)'. The filter must not be empty, or it will error. + where: str or [Expr][lancedb.expr.Expr], optional + The filter condition. Can be a SQL string or a type-safe + [Expr][lancedb.expr.Expr] built with [col][lancedb.expr.col] and + [lit][lancedb.expr.lit]. The filter must not be empty, or it will + error. values: dict, optional The values to update. The keys are the column names and the values are the values to set. @@ -1779,6 +1781,7 @@ class Table(ABC): Examples -------- >>> import lancedb + >>> from lancedb.expr import col >>> import pandas as pd >>> data = pd.DataFrame({"x": [1, 2, 3], "vector": [[1.0, 2], [3, 4], [5, 6]]}) >>> db = lancedb.connect("./.lancedb") @@ -1788,7 +1791,7 @@ class Table(ABC): 0 1 [1.0, 2.0] 1 2 [3.0, 4.0] 2 3 [5.0, 6.0] - >>> table.update(where="x = 2", values={"vector": [10.0, 10]}) + >>> table.update(where=col("x") == 2, values={"vector": [10.0, 10]}) UpdateResult(rows_updated=1, version=2) >>> table.to_pandas() x vector @@ -3841,7 +3844,7 @@ class LanceTable(Table): def update( self, - where: Optional[str] = None, + where: Optional[Union[str, Expr]] = None, values: Optional[dict] = None, *, values_sql: Optional[Dict[str, str]] = None, @@ -3852,9 +3855,11 @@ class LanceTable(Table): Parameters ---------- - where: str, optional - The SQL where clause to use when updating rows. For example, 'x = 2' - or 'x IN (1, 2, 3)'. The filter must not be empty, or it will error. + where: str or [Expr][lancedb.expr.Expr], optional + The filter condition. Can be a SQL string or a type-safe + [Expr][lancedb.expr.Expr] built with [col][lancedb.expr.col] and + [lit][lancedb.expr.lit]. The filter must not be empty, or it will + error. values: dict, optional The values to update. The keys are the column names and the values are the values to set. @@ -3872,6 +3877,7 @@ class LanceTable(Table): Examples -------- >>> import lancedb + >>> from lancedb.expr import col >>> import pandas as pd >>> data = pd.DataFrame({"x": [1, 2, 3], "vector": [[1.0, 2], [3, 4], [5, 6]]}) >>> db = lancedb.connect("./.lancedb") @@ -3881,7 +3887,7 @@ class LanceTable(Table): 0 1 [1.0, 2.0] 1 2 [3.0, 4.0] 2 3 [5.0, 6.0] - >>> table.update(where="x = 2", values={"vector": [10.0, 10]}) + >>> table.update(where=col("x") == 2, values={"vector": [10.0, 10]}) UpdateResult(rows_updated=1, version=2) >>> table.to_pandas() x vector @@ -5995,7 +6001,7 @@ class AsyncTable: self, updates: Optional[Dict[str, Any]] = None, *, - where: Optional[str] = None, + where: Optional[Union[str, Expr]] = None, updates_sql: Optional[Dict[str, str]] = None, ) -> UpdateResult: """ @@ -6010,9 +6016,11 @@ class AsyncTable: The updates to apply. The keys should be the name of the column to update. The values should be the new values to assign. This is required unless updates_sql is supplied. - where: str, optional - An SQL filter that controls which rows are updated. For example, 'x = 2' - or 'x IN (1, 2, 3)'. Only rows that satisfy this filter will be udpated. + where: str or [Expr][lancedb.expr.Expr], optional + The filter condition. Can be a SQL string or a type-safe + [Expr][lancedb.expr.Expr] built with [col][lancedb.expr.col] and + [lit][lancedb.expr.lit]. Only rows that satisfy this filter will + be updated. updates_sql: dict, optional The updates to apply, expressed as SQL expression strings. The keys should be column names. The values should be SQL expressions. These can be SQL @@ -6030,13 +6038,14 @@ class AsyncTable: -------- >>> import asyncio >>> import lancedb + >>> from lancedb.expr import col >>> import pandas as pd >>> async def demo_update(): ... data = pd.DataFrame({"x": [1, 2], "vector": [[1, 2], [3, 4]]}) ... db = await lancedb.connect_async("./.lancedb") ... table = await db.create_table("my_table", data) ... # x is [1, 2], vector is [[1, 2], [3, 4]] - ... await table.update({"vector": [10, 10]}, where="x = 2") + ... await table.update({"vector": [10, 10]}, where=col("x") == 2) ... # x is [1, 2], vector is [[1, 2], [10, 10]] ... await table.update(updates_sql={"x": "x + 1"}) ... # x is [2, 3], vector is [[1, 2], [10, 10]] @@ -6050,7 +6059,8 @@ class AsyncTable: if updates is not None: updates_sql = {k: value_to_sql(v) for k, v in updates.items()} - return await self._inner.update(updates_sql, where) + predicate = where.to_sql() if isinstance(where, Expr) else where + return await self._inner.update(updates_sql, predicate) async def add_columns( self, diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index 5d7682f24..351769ff6 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -8,7 +8,12 @@ import pyarrow.compute as pc import pytest import lancedb -from lancedb._blob import read_row_ids_from_hits, stash_auto_row_ids +from lancedb._blob import ( + blob_v2_projection_sources, + read_row_ids_from_hits, + stash_auto_row_ids, +) +from lancedb.expr import col from lancedb.index import FTS from lancedb.schema import blob_column_paths, blob_v2_column_paths @@ -70,6 +75,14 @@ def test_blob_v2_column_paths_include_list_children(): ] +def test_blob_v2_projection_sources_use_typed_column_name(): + schema = pa.schema([lancedb.blob("blob")]) + + assert blob_v2_projection_sources(schema, {"blob_alias": col("blob")}) == { + "blob_alias": "blob" + } + + def _legacy_v1_table(name): db = lancedb.connect("memory:///") schema = pa.schema( @@ -166,6 +179,20 @@ async def test_async_table_to_pandas_descriptions_mode_omits_row_id(): assert set(descriptor.keys()) == {"kind", "position", "size", "blob_id", "blob_uri"} +@pytest.mark.asyncio +async def test_async_typed_blob_projection_preserves_source_column(): + db = await lancedb.connect_async("memory:///typed_blob_projection") + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("blob")]) + table = await db.create_table("typed_blob_projection", schema=schema) + await table.add([{"id": 1, "blob": b"alpha"}]) + + hits = await table.query().select({"blob_alias": col("blob")}).to_arrow() + + assert "_lance_row_id" in hits.schema.field("blob_alias").type.names + blobs = await table.fetch_blobs("blob", hits) + assert blobs.to_pylist() == [b"alpha"] + + def test_fetch_blobs_round_trip(): table = _blob_table( "round_trip", @@ -403,6 +430,50 @@ async def test_blob_v2_hybrid_fetch_blobs_async(): assert {blobs[i].as_py() for i in range(len(blobs))} == {b"alpha", b"beta"} +@pytest.mark.asyncio +async def test_async_hybrid_typed_blob_projection_preserves_source_column(): + db = await lancedb.connect_async("memory:///hybrid_typed_blob") + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("text", pa.utf8()), + pa.field("vector", pa.list_(pa.float32(), list_size=2)), + lancedb.blob("blob"), + ] + ) + table = await db.create_table("hybrid_typed_blob", schema=schema) + await table.add( + [ + { + "id": 1, + "text": "hello alpha", + "vector": [1.0, 0.0], + "blob": b"alpha", + }, + { + "id": 2, + "text": "hello beta", + "vector": [0.9, 0.1], + "blob": b"beta", + }, + ] + ) + await table.create_index("text", config=FTS(with_position=False)) + + hits = await ( + table.query() + .nearest_to([1.0, 0.0]) + .nearest_to_text("hello") + .select({"blob_alias": col("blob")}) + .limit(2) + .to_arrow() + ) + + assert "_lance_row_id" in hits.schema.field("blob_alias").type.names + blobs = await table.fetch_blobs("blob", hits) + assert {blobs[i].as_py() for i in range(len(blobs))} == {b"alpha", b"beta"} + + def test_blob_file_seek_read_and_read_range(): payload = _identifiable_payload(1024) table = _blob_table("seek_read", [{"id": 1, "image": payload}]) diff --git a/python/python/tests/test_expr.py b/python/python/tests/test_expr.py index 0eb6f8929..0f49231f1 100644 --- a/python/python/tests/test_expr.py +++ b/python/python/tests/test_expr.py @@ -52,7 +52,7 @@ class TestExprConstruction: def test_func(self): e = func("lower", col("name")) assert isinstance(e, Expr) - assert e.to_sql() == "lower(name)" + assert e.to_sql() == "lower(`name`)" def test_func_unknown_raises(self): with pytest.raises(Exception): @@ -115,7 +115,7 @@ class TestExprOperators: def test_and_operator(self): e = (col("age") > lit(18)) & (col("status") == lit("active")) assert isinstance(e, Expr) - assert e.to_sql() == "((age > 18) AND (status = 'active'))" + assert e.to_sql() == "((age > 18) AND (`status` = 'active'))" def test_or_operator(self): e = (col("a") == lit(1)) | (col("b") == lit(2)) @@ -166,7 +166,7 @@ class TestExprOperators: def test_coerce_plain_str(self): e = col("name") == "alice" assert isinstance(e, Expr) - assert e.to_sql() == "(name = 'alice')" + assert e.to_sql() == "(`name` = 'alice')" def test_reflexive_comparisons(self): # 10 < col("age") swaps to col("age") > 10 @@ -198,85 +198,85 @@ class TestExprBytesLiteral: def test_bytes_equality_expr_sql(self): e = col("data") == lit(b"\xca\xfe") - assert e.to_sql() == "(data = X'CAFE')" + assert e.to_sql() == "(`data` = X'CAFE')" def test_bytes_ne_expr_sql(self): e = col("data") != lit(b"\xff") - assert e.to_sql() == "(data <> X'FF')" + assert e.to_sql() == "(`data` <> X'FF')" def test_bytes_compound_expr_sql(self): e = (col("data") == lit(b"\x01")) & (col("id") > lit(5)) - assert e.to_sql() == "((data = X'01') AND (id > 5))" + assert e.to_sql() == "((`data` = X'01') AND (id > 5))" def test_bytes_in_function_call(self): # Regression test: binary literals inside scalar function calls # used to fail because DataFusion's unparser does not support Binary # scalars. Now handled via a placeholder-substitution rewrite. e = func("contains", col("data"), lit(b"\xff")) - assert e.to_sql() == "contains(data, X'FF')" + assert e.to_sql() == "contains(`data`, X'FF')" def test_bytes_in_not(self): e = ~(col("data") == lit(b"\xff")) - assert e.to_sql() == "NOT (data = X'FF')" + assert e.to_sql() == "NOT (`data` = X'FF')" class TestExprStringMethods: def test_lower(self): e = col("name").lower() assert isinstance(e, Expr) - assert e.to_sql() == "lower(name)" + assert e.to_sql() == "lower(`name`)" def test_upper(self): e = col("name").upper() assert isinstance(e, Expr) - assert e.to_sql() == "upper(name)" + assert e.to_sql() == "upper(`name`)" def test_contains(self): e = col("text").contains(lit("hello")) assert isinstance(e, Expr) - assert e.to_sql() == "contains(text, 'hello')" + assert e.to_sql() == "contains(`text`, 'hello')" def test_contains_with_str_coerce(self): e = col("text").contains("hello") assert isinstance(e, Expr) - assert e.to_sql() == "contains(text, 'hello')" + assert e.to_sql() == "contains(`text`, 'hello')" def test_chained_lower_eq(self): e = col("name").lower() == lit("alice") assert isinstance(e, Expr) - assert e.to_sql() == "(lower(name) = 'alice')" + assert e.to_sql() == "(lower(`name`) = 'alice')" class TestExprCast: def test_cast_string(self): e = col("id").cast("string") assert isinstance(e, Expr) - assert e.to_sql() == "CAST(id AS VARCHAR)" + assert e.to_sql() == "arrow_cast(id, 'Utf8')" def test_cast_int32(self): e = col("score").cast("int32") assert isinstance(e, Expr) - assert e.to_sql() == "CAST(score AS INTEGER)" + assert e.to_sql() == "arrow_cast(score, 'Int32')" def test_cast_float64(self): e = col("val").cast("float64") assert isinstance(e, Expr) - assert e.to_sql() == "CAST(val AS DOUBLE)" + assert e.to_sql() == "arrow_cast(val, 'Float64')" def test_cast_pyarrow_type(self): e = col("score").cast(pa.int32()) assert isinstance(e, Expr) - assert e.to_sql() == "CAST(score AS INTEGER)" + assert e.to_sql() == "arrow_cast(score, 'Int32')" def test_cast_pyarrow_float64(self): e = col("val").cast(pa.float64()) assert isinstance(e, Expr) - assert e.to_sql() == "CAST(val AS DOUBLE)" + assert e.to_sql() == "arrow_cast(val, 'Float64')" def test_cast_pyarrow_string(self): e = col("id").cast(pa.string()) assert isinstance(e, Expr) - assert e.to_sql() == "CAST(id AS VARCHAR)" + assert e.to_sql() == "arrow_cast(id, 'Utf8')" def test_cast_pyarrow_and_string_equivalent(self): # pa.int32() and "int32" should produce equivalent SQL @@ -597,14 +597,14 @@ class TestExprIsin: def test_isin_strs(self): assert ( col("status").isin(["active", "pending"]).to_sql() - == "status IN ('active', 'pending')" + == "`status` IN ('active', 'pending')" ) def test_isin_coerces_and_mixes(self): assert col("id").isin([lit(1), 2]).to_sql() == "id IN (1, 2)" def test_isin_empty(self): - assert col("id").isin([]).to_sql() == "id IN ()" + assert col("id").isin([]).to_sql() == "false" def test_isin_filter(self, simple_table): result = simple_table.search().where(col("id").isin([1, 3, 5])).to_arrow() diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 56e0eacfd..0be9e139d 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -11,6 +11,7 @@ import warnings import weakref from concurrent.futures import ThreadPoolExecutor from datetime import date, datetime, timedelta +from decimal import Decimal from time import sleep from typing import List from unittest.mock import patch @@ -336,6 +337,21 @@ async def test_update_async(mem_db_async: AsyncConnection): assert await table.count_rows("id == 10") == 1 +@pytest.mark.asyncio +async def test_update_expr_filter_literals_async(mem_db_async: AsyncConnection): + values = ["5", "4.66e-84", "it's"] + table = await mem_db_async.create_table( + "update_expr_literals", + data=[{"field": value, "result": "original"} for value in values], + ) + + for value in values: + update_res = await table.update({"result": value}, where=col("field") == value) + assert update_res.rows_updated == 1 + + assert (await table.to_arrow())["result"].to_pylist() == values + + def test_create_table(mem_db: DBConnection): schema = pa.schema( { @@ -2343,6 +2359,148 @@ def test_update(mem_db: DBConnection): assert np.allclose(v, np.array([[1.2, 1.9], [1.1, 1.1]])) +def test_update_expr_filter_literals(mem_db: DBConnection): + values = ["5", "4.66e-84", "it's"] + table = mem_db.create_table( + "update_expr_literals", + data=[{"field": value, "result": "original"} for value in values], + ) + + for value in values: + update_res = table.update(where=col("field") == value, values={"result": value}) + assert update_res.rows_updated == 1 + + assert table.to_arrow()["result"].to_pylist() == values + + +def test_update_expr_filter_preserves_typed_semantics(mem_db: DBConnection): + low = Decimal("1.234567890123456789") + high = Decimal("1.234567890123456790") + decimal_schema = pa.schema( + [("val", pa.decimal128(19, 18)), ("result", pa.string())] + ) + decimal_table = mem_db.create_table( + "update_expr_decimal", + pa.table( + {"val": [low, high], "result": ["old", "old"]}, + schema=decimal_schema, + ), + ) + predicate = col("val") < lit(high) + assert decimal_table.search().where(predicate).to_arrow().num_rows == 1 + result = decimal_table.update(where=predicate, values={"result": "new"}) + assert result.rows_updated == 1 + + keyword_table = mem_db.create_table( + "update_expr_keyword", [{"null": 1, "result": "old"}] + ) + predicate = col("null") == 1 + assert keyword_table.search().where(predicate).to_arrow().num_rows == 1 + result = keyword_table.update(where=predicate, values={"result": "new"}) + assert result.rows_updated == 1 + + empty_in_table = mem_db.create_table( + "update_expr_empty_in", [{"id": 1, "result": "old"}] + ) + predicate = col("id").isin([]) + assert empty_in_table.search().where(predicate).to_arrow().num_rows == 0 + result = empty_in_table.update(where=predicate, values={"result": "new"}) + assert result.rows_updated == 0 + + marker = "__lancedb_binary_placeholder_0__" + binary_schema = pa.schema( + [("payload", pa.binary()), ("text", pa.string()), ("result", pa.string())] + ) + binary_table = mem_db.create_table( + "update_expr_binary", + pa.table( + { + "payload": [b"\x01", b"\x02"], + "text": ["other", marker], + "result": ["old", "old"], + }, + schema=binary_schema, + ), + ) + predicate = (col("payload") == lit(b"\x01")) | (col("text") == marker) + assert binary_table.search().where(predicate).to_arrow().num_rows == 2 + result = binary_table.update(where=predicate, values={"result": "new"}) + assert result.rows_updated == 2 + + nonfinite_table = mem_db.create_table( + "update_expr_nonfinite", + [{"x": 1.0, "result": "old"}, {"x": 2.0, "result": "old"}], + ) + predicate = col("x") < float("inf") + assert nonfinite_table.search().where(predicate).to_arrow().num_rows == 2 + result = nonfinite_table.update(where=predicate, values={"result": "new"}) + assert result.rows_updated == 2 + + float16_table = mem_db.create_table( + "update_expr_float16", + [{"x": 1.0, "result": "old"}, {"x": 3.0, "result": "old"}], + ) + predicate = col("x").cast(pa.float16()) < 2.0 + assert float16_table.search().where(predicate).to_arrow().num_rows == 1 + result = float16_table.update(where=predicate, values={"result": "new"}) + assert result.rows_updated == 1 + + string_cast_table = mem_db.create_table( + "update_expr_string_cast", + [{"x": 1, "result": "old"}, {"x": 2, "result": "old"}], + ) + predicate = col("x").cast("string") == "1" + assert string_cast_table.search().where(predicate).to_arrow().num_rows == 1 + result = string_cast_table.update(where=predicate, values={"result": "new"}) + assert result.rows_updated == 1 + + quoted_identifier_schema = pa.schema( + [("payload", pa.binary()), ("odd'name", pa.int64()), ("result", pa.string())] + ) + quoted_identifier_table = mem_db.create_table( + "update_expr_quoted_identifier", + pa.table( + {"payload": [b"\x01"], "odd'name": [1], "result": ["old"]}, + schema=quoted_identifier_schema, + ), + ) + predicate = (col("payload") == lit(b"\x01")) & (col("odd'name") == 1) + assert quoted_identifier_table.search().where(predicate).to_arrow().num_rows == 1 + result = quoted_identifier_table.update(where=predicate, values={"result": "new"}) + assert result.rows_updated == 1 + + decimal256_schema = pa.schema( + [("val", pa.decimal256(40, 2)), ("result", pa.string())] + ) + decimal256_table = mem_db.create_table( + "update_expr_decimal256", + pa.table( + { + "val": [Decimal("1.00"), Decimal("3.00")], + "result": ["old", "old"], + }, + schema=decimal256_schema, + ), + ) + predicate = col("val") < lit(Decimal("2.00")).cast(pa.decimal256(40, 2)) + assert decimal256_table.search().where(predicate).to_arrow().num_rows == 1 + result = decimal256_table.update(where=predicate, values={"result": "new"}) + assert result.rows_updated == 1 + + binary_empty_table = mem_db.create_table( + "update_expr_binary_empty", + pa.table( + {"payload": [b"\x01", b"\x02"], "result": ["old", "old"]}, + schema=pa.schema([("payload", pa.binary()), ("result", pa.string())]), + ), + ) + predicate = (col("payload") == lit(b"\x01")).isin([]) + assert binary_empty_table.search().where(predicate).to_arrow().num_rows == 0 + assert predicate.to_sql() == "false" + result = binary_empty_table.update(where=predicate, values={"result": "new"}) + assert result.rows_updated == 0 + + def test_update_with_arrow_scalar(mem_db: DBConnection): schema = pa.schema({"id": pa.int64(), "vector": pa.list_(pa.float32(), 4)}) table = mem_db.create_table("my_table", schema=schema) diff --git a/python/src/expr.rs b/python/src/expr.rs index eae1d96ec..79b448fdf 100644 --- a/python/src/expr.rs +++ b/python/src/expr.rs @@ -130,6 +130,14 @@ impl PyExpr { // ── utilities ──────────────────────────────────────────────────────────── + /// Return the referenced column name for a bare column expression. + fn column_name(&self) -> Option { + match &self.0 { + DfExpr::Column(column) if column.relation.is_none() => Some(column.name.clone()), + _ => None, + } + } + /// Render the expression as a SQL string (useful for debugging). fn to_sql(&self) -> PyResult { lancedb::expr::expr_to_sql_string(&self.0).map_err(|e| PyValueError::new_err(e.to_string())) diff --git a/python/src/query.rs b/python/src/query.rs index 014e79e2d..38153729f 100644 --- a/python/src/query.rs +++ b/python/src/query.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; use std::time::Duration; @@ -325,6 +326,7 @@ pub struct PyQueryRequest { pub filter: Option, pub full_text_search: Option>, pub select: PySelect, + pub select_source_columns: Option>, pub fast_search: Option, pub with_row_id: Option, pub use_lsm: Option, @@ -355,6 +357,7 @@ impl From for PyQueryRequest { full_text_search: query_request .full_text_search .map(|fts| PyLanceDB(fts.query)), + select_source_columns: PySelect::source_columns(&query_request.select), select: PySelect(query_request.select), fast_search: Some(query_request.fast_search), with_row_id: Some(query_request.with_row_id), @@ -380,6 +383,7 @@ impl From for PyQueryRequest { offset: vector_query.base.offset, filter: vector_query.base.filter.map(PyQueryFilter), full_text_search: None, + select_source_columns: PySelect::source_columns(&vector_query.base.select), select: PySelect(vector_query.base.select), fast_search: Some(vector_query.base.fast_search), with_row_id: Some(vector_query.base.with_row_id), @@ -412,6 +416,25 @@ impl From for PyQueryRequest { #[derive(Clone)] pub struct PySelect(Select); +impl PySelect { + fn source_columns(select: &Select) -> Option> { + match select { + Select::Expr(pairs) => Some( + pairs + .iter() + .filter_map(|(output, expr)| match expr { + lancedb::expr::DfExpr::Column(column) if column.relation.is_none() => { + Some((output.clone(), column.name.clone())) + } + _ => None, + }) + .collect(), + ), + _ => None, + } + } +} + impl<'py> IntoPyObject<'py> for PySelect { type Target = PyAny; type Output = Bound<'py, Self::Target>; diff --git a/rust/lancedb/src/expr.rs b/rust/lancedb/src/expr.rs index da69914e3..1625d9632 100644 --- a/rust/lancedb/src/expr.rs +++ b/rust/lancedb/src/expr.rs @@ -157,7 +157,7 @@ mod tests { use datafusion_common::ScalarValue; let expr = col("data").eq(lit(ScalarValue::Binary(Some(vec![0xca, 0xfe])))); let sql = expr_to_sql_string(&expr).unwrap(); - assert_eq!(sql, "(data = X'CAFE')"); + assert_eq!(sql, "(`data` = X'CAFE')"); } #[test] @@ -167,7 +167,7 @@ mod tests { let int_expr = col("id").gt(lit(5i64)); let combined = bin_expr.and(int_expr); let sql = expr_to_sql_string(&combined).unwrap(); - assert_eq!(sql, "((data = X'01') AND (id > 5))"); + assert_eq!(sql, "((`data` = X'01') AND (id > 5))"); } #[test] @@ -185,7 +185,7 @@ mod tests { // serialized correctly (regression test for placeholder rewrite path). let expr = contains(col("data"), lit(ScalarValue::Binary(Some(vec![0xff])))); let sql = expr_to_sql_string(&expr).unwrap(); - assert_eq!(sql, "contains(data, X'FF')"); + assert_eq!(sql, "contains(`data`, X'FF')"); } #[test] @@ -196,7 +196,7 @@ mod tests { .eq(lit(ScalarValue::Binary(Some(vec![0xab, 0xcd])))) .not(); let sql = expr_to_sql_string(&expr).unwrap(); - assert_eq!(sql, "NOT (data = X'ABCD')"); + assert_eq!(sql, "NOT (`data` = X'ABCD')"); } #[test] @@ -206,6 +206,122 @@ mod tests { assert!(sql.contains("IN"), "expected IN in: {}", sql); } + #[test] + fn test_empty_is_in() { + let expr = is_in(col("id"), vec![]); + assert_eq!(expr_to_sql_string(&expr).unwrap(), "false"); + } + + #[test] + fn test_empty_is_in_discards_binary_children() { + use datafusion_common::ScalarValue; + + let expr = is_in( + col("payload").eq(lit(ScalarValue::Binary(Some(vec![0x01])))), + vec![], + ); + assert_eq!(expr_to_sql_string(&expr).unwrap(), "false"); + } + + #[test] + fn test_keyword_identifier() { + let expr = col("null").eq(lit(1i64)); + assert_eq!(expr_to_sql_string(&expr).unwrap(), "(`null` = 1)"); + } + + #[test] + fn test_decimal_literal_preserves_type() { + use datafusion_common::ScalarValue; + + let expr = col("val").lt(lit(ScalarValue::Decimal128( + Some(1_234_567_890_123_456_790), + 19, + 18, + ))); + let sql = expr_to_sql_string(&expr).unwrap(); + assert_eq!( + sql, + "(val < arrow_cast('1.234567890123456790', 'Decimal128(19, 18)'))" + ); + } + + #[test] + fn test_non_finite_float_literal_preserves_type() { + let expr = col("x").lt(lit(f64::INFINITY)); + assert_eq!( + expr_to_sql_string(&expr).unwrap(), + "(x < arrow_cast('inf', 'Float64'))" + ); + } + + #[test] + fn test_cast_uses_arrow_type_name() { + let string = expr_cast(col("x"), DataType::Utf8); + assert_eq!( + expr_to_sql_string(&string).unwrap(), + "arrow_cast(x, 'Utf8')" + ); + + let int32 = expr_cast(col("x"), DataType::Int32); + assert_eq!( + expr_to_sql_string(&int32).unwrap(), + "arrow_cast(x, 'Int32')" + ); + + let expr = expr_cast(col("x"), DataType::Float16).lt(lit(2.0)); + assert_eq!( + expr_to_sql_string(&expr).unwrap(), + "(arrow_cast(x, 'Float16') < 2.0)" + ); + + let decimal = expr_cast(lit("2.00"), DataType::Decimal256(40, 2)); + assert_eq!( + expr_to_sql_string(&decimal).unwrap(), + "arrow_cast('2.00', 'Decimal256(40, 2)')" + ); + } + + #[test] + fn test_binary_placeholder_does_not_rewrite_user_string() { + use datafusion_common::ScalarValue; + + let marker = "__lancedb_binary_placeholder_0__"; + let expr = col("payload") + .eq(lit(ScalarValue::Binary(Some(vec![0x01])))) + .or(col("text").eq(lit(marker))); + assert_eq!( + expr_to_sql_string(&expr).unwrap(), + "((payload = X'01') OR (`text` = '__lancedb_binary_placeholder_0__'))" + ); + } + + #[test] + fn test_binary_binding_skips_quoted_identifiers() { + use datafusion_common::ScalarValue; + + let expr = col("payload") + .eq(lit(ScalarValue::Binary(Some(vec![0x01])))) + .and(col("odd'name").eq(lit(1i64))) + .and(col("odd`'name").eq(lit(2i64))); + assert_eq!( + expr_to_sql_string(&expr).unwrap(), + "(((payload = X'01') AND (`odd'name` = 1)) AND (`odd``'name` = 2))" + ); + } + + #[test] + fn test_binary_placeholder_collision_search_is_linear() { + use datafusion_common::ScalarValue; + + let collision_shaped = format!("__lancedb_binary_placeholder_0__{}", "_".repeat(64_000)); + let expr = col("payload") + .eq(lit(ScalarValue::Binary(Some(vec![0x01])))) + .and(col("text").eq(lit(collision_shaped.clone()))); + let sql = expr_to_sql_string(&expr).unwrap(); + assert!(sql.contains("X'01'")); + assert!(sql.contains(&format!("'{collision_shaped}'"))); + } + #[test] fn test_multiple_binary_literals() { use datafusion_common::ScalarValue; diff --git a/rust/lancedb/src/expr/sql.rs b/rust/lancedb/src/expr/sql.rs index 24a676485..2a1ca201d 100644 --- a/rust/lancedb/src/expr/sql.rs +++ b/rust/lancedb/src/expr/sql.rs @@ -1,13 +1,24 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use std::any::TypeId; +use std::{ + any::TypeId, + collections::{HashMap, HashSet}, +}; +use arrow_array::types::{ + Decimal32Type, Decimal64Type, Decimal128Type, Decimal256Type, DecimalType, +}; +use arrow_schema::DataType; use datafusion_common::ScalarValue; use datafusion_common::tree_node::{Transformed, TreeNode, TreeNodeRecursion}; use datafusion_expr::Expr; +use datafusion_functions::core::expr_fn::{ + arrow_cast as datafusion_arrow_cast, arrow_try_cast as datafusion_arrow_try_cast, +}; use datafusion_sql::sqlparser::{ dialect::{Dialect as SqlParserDialect, GenericDialect}, + keywords::ALL_KEYWORDS, tokenizer::{Token, Tokenizer}, }; use datafusion_sql::unparser::{self, dialect::Dialect as UnparserDialect}; @@ -27,11 +38,13 @@ struct LanceSqlDialect; impl UnparserDialect for LanceSqlDialect { fn identifier_quote_style(&self, identifier: &str) -> Option { - let needs_quote = identifier.chars().any(|c| c.is_ascii_uppercase()) - || !identifier - .chars() - .enumerate() - .all(|(i, c)| c == '_' || c.is_ascii_alphabetic() || (i > 0 && c.is_ascii_digit())); + let identifier_upper = identifier.to_ascii_uppercase(); + let needs_quote = + (identifier_upper != "ID" && ALL_KEYWORDS.contains(&identifier_upper.as_str())) + || identifier.chars().any(|c| c.is_ascii_uppercase()) + || !identifier.chars().enumerate().all(|(i, c)| { + c == '_' || c.is_ascii_alphabetic() || (i > 0 && c.is_ascii_digit()) + }); if needs_quote { Some('`') } else { None } } } @@ -100,24 +113,128 @@ fn bytes_to_hex_sql(bytes: &[u8]) -> String { format!("X'{hex}'") } -/// Returns true if *expr* contains a `Binary` or `LargeBinary` scalar literal -/// anywhere in its subtree. DataFusion's SQL unparser cannot serialize those -/// variants, so we route such expressions through a placeholder-substitution -/// path that emits SQL `X'...'` byte-string literals. -fn has_binary_literal(expr: &Expr) -> bool { - let mut found = false; +fn string_literals(expr: &Expr) -> HashSet { + let mut literals = HashSet::new(); let _ = expr.apply(&mut |e: &Expr| { - if matches!( - e, - Expr::Literal(ScalarValue::Binary(_) | ScalarValue::LargeBinary(_), _) - ) { - found = true; - Ok(TreeNodeRecursion::Stop) - } else { - Ok(TreeNodeRecursion::Continue) + if let Expr::Literal( + ScalarValue::Utf8(Some(value)) + | ScalarValue::LargeUtf8(Some(value)) + | ScalarValue::Utf8View(Some(value)), + _, + ) = e + { + literals.insert(value.clone()); } + Ok(TreeNodeRecursion::Continue) }); - found + literals +} + +fn typed_string_literal(value: String, data_type: DataType) -> Expr { + datafusion_arrow_cast( + Expr::Literal(ScalarValue::Utf8(Some(value)), None), + Expr::Literal(ScalarValue::Utf8(Some(data_type.to_string())), None), + ) +} + +fn next_binary_placeholder(user_strings: &HashSet, next_id: &mut usize) -> String { + loop { + let placeholder = format!("{BINARY_PLACEHOLDER_PREFIX}{}__", *next_id); + *next_id += 1; + if !user_strings.contains(&placeholder) { + return placeholder; + } + } +} + +fn bind_binary_literals( + sql: &str, + mut bindings: HashMap>, +) -> crate::Result { + let bytes = sql.as_bytes(); + let mut output = Vec::with_capacity(bytes.len()); + let mut index = 0; + + // Walk SQL string tokens once. Placeholders are plain, unescaped string + // literals, so this remains linear even when user strings are large or + // deliberately resemble the placeholder prefix. + while index < bytes.len() { + if bytes[index] == b'`' { + let identifier_start = index; + index += 1; + let mut identifier_end = None; + while index < bytes.len() { + if bytes[index] == b'`' { + if index + 1 < bytes.len() && bytes[index + 1] == b'`' { + index += 2; + } else { + index += 1; + identifier_end = Some(index); + break; + } + } else { + index += 1; + } + } + + let Some(identifier_end) = identifier_end else { + return Err(crate::Error::InvalidInput { + message: "unterminated identifier while binding binary literal".to_string(), + }); + }; + output.extend_from_slice(&bytes[identifier_start..identifier_end]); + continue; + } + + if bytes[index] != b'\'' { + output.push(bytes[index]); + index += 1; + continue; + } + + let literal_start = index; + index += 1; + let content_start = index; + let mut escaped = false; + let mut content_end = None; + while index < bytes.len() { + if bytes[index] == b'\'' { + if index + 1 < bytes.len() && bytes[index + 1] == b'\'' { + escaped = true; + index += 2; + } else { + content_end = Some(index); + index += 1; + break; + } + } else { + index += 1; + } + } + + let Some(content_end) = content_end else { + return Err(crate::Error::InvalidInput { + message: "unterminated string while binding binary literal".to_string(), + }); + }; + + let placeholder = &sql[content_start..content_end]; + if !escaped && let Some(value) = bindings.remove(placeholder) { + output.extend_from_slice(bytes_to_hex_sql(&value).as_bytes()); + } else { + output.extend_from_slice(&bytes[literal_start..index]); + } + } + + if !bindings.is_empty() { + return Err(crate::Error::InvalidInput { + message: "failed to bind binary literal while serializing expression".to_string(), + }); + } + + String::from_utf8(output).map_err(|e| crate::Error::InvalidInput { + message: format!("failed to bind binary literal: {e}"), + }) } fn run_unparser(expr: &Expr) -> crate::Result { @@ -130,25 +247,37 @@ fn run_unparser(expr: &Expr) -> crate::Result { } pub fn expr_to_sql_string(expr: &Expr) -> crate::Result { - // Fast path: no binary literals — DataFusion's unparser handles everything. - if !has_binary_literal(expr) { - return run_unparser(expr); - } - - // Slow path: DataFusion's unparser cannot serialize `Binary`/`LargeBinary` - // scalars, so we rewrite each one to a unique string-literal placeholder, - // let the unparser do the rest of the work, then substitute the SQL - // `X'...'` byte-string literal back in. This keeps the operator/function - // serialization logic centralized in DataFusion and works for every - // expression node type the unparser supports. - let mut bindings: Vec> = Vec::new(); + // DataFusion's unparser needs a few adaptations before its SQL can be + // reparsed by Lance without changing the typed expression's semantics: + // + // * decimal literals need an explicit cast to preserve precision and scale; + // * casts need exact Arrow type names rather than SQL type aliases; + // * an empty IN list is valid in DataFusion but invalid SQL; + // * binary literals are unsupported by the unparser and need placeholders. + // Eliminate empty membership expressions before visiting their children. + // Otherwise a discarded binary child could leave behind a stale binding. let rewritten = expr .clone() + .transform(|e: Expr| match e { + Expr::InList(in_list) if in_list.list.is_empty() => Ok(Transformed::yes( + Expr::Literal(ScalarValue::Boolean(Some(in_list.negated)), None), + )), + other => Ok(Transformed::no(other)), + }) + .map_err(|e| crate::Error::InvalidInput { + message: format!("failed to rewrite expression: {e}"), + })? + .data; + + let user_strings = string_literals(&rewritten); + let mut next_placeholder_id = 0; + let mut binary_bindings = HashMap::new(); + let rewritten = rewritten .transform(|e: Expr| match e { Expr::Literal(ScalarValue::Binary(Some(bytes)), m) | Expr::Literal(ScalarValue::LargeBinary(Some(bytes)), m) => { - let placeholder = format!("{}{}__", BINARY_PLACEHOLDER_PREFIX, bindings.len()); - bindings.push(bytes); + let placeholder = next_binary_placeholder(&user_strings, &mut next_placeholder_id); + binary_bindings.insert(placeholder.clone(), bytes); Ok(Transformed::yes(Expr::Literal( ScalarValue::Utf8(Some(placeholder)), m, @@ -158,6 +287,57 @@ pub fn expr_to_sql_string(expr: &Expr) -> crate::Result { | Expr::Literal(ScalarValue::LargeBinary(None), m) => { Ok(Transformed::yes(Expr::Literal(ScalarValue::Null, m))) } + Expr::Literal(ScalarValue::Decimal32(Some(value), precision, scale), _m) => { + let value = Decimal32Type::format_decimal(value, precision, scale); + Ok(Transformed::yes(typed_string_literal( + value, + DataType::Decimal32(precision, scale), + ))) + } + Expr::Literal(ScalarValue::Decimal64(Some(value), precision, scale), _m) => { + let value = Decimal64Type::format_decimal(value, precision, scale); + Ok(Transformed::yes(typed_string_literal( + value, + DataType::Decimal64(precision, scale), + ))) + } + Expr::Literal(ScalarValue::Decimal128(Some(value), precision, scale), _m) => { + let value = Decimal128Type::format_decimal(value, precision, scale); + Ok(Transformed::yes(typed_string_literal( + value, + DataType::Decimal128(precision, scale), + ))) + } + Expr::Literal(ScalarValue::Decimal256(Some(value), precision, scale), _m) => { + let value = Decimal256Type::format_decimal(value, precision, scale); + Ok(Transformed::yes(typed_string_literal( + value, + DataType::Decimal256(precision, scale), + ))) + } + Expr::Literal(ScalarValue::Float16(Some(value)), _m) if !value.is_finite() => Ok( + Transformed::yes(typed_string_literal(value.to_string(), DataType::Float16)), + ), + Expr::Literal(ScalarValue::Float32(Some(value)), _m) if !value.is_finite() => Ok( + Transformed::yes(typed_string_literal(value.to_string(), DataType::Float32)), + ), + Expr::Literal(ScalarValue::Float64(Some(value)), _m) if !value.is_finite() => Ok( + Transformed::yes(typed_string_literal(value.to_string(), DataType::Float64)), + ), + Expr::Cast(cast) => Ok(Transformed::yes(datafusion_arrow_cast( + *cast.expr, + Expr::Literal( + ScalarValue::Utf8(Some(cast.field.data_type().to_string())), + None, + ), + ))), + Expr::TryCast(cast) => Ok(Transformed::yes(datafusion_arrow_try_cast( + *cast.expr, + Expr::Literal( + ScalarValue::Utf8(Some(cast.field.data_type().to_string())), + None, + ), + ))), other => Ok(Transformed::no(other)), }) .map_err(|e| crate::Error::InvalidInput { @@ -165,14 +345,12 @@ pub fn expr_to_sql_string(expr: &Expr) -> crate::Result { })? .data; - let mut sql = run_unparser(&rewritten)?; - for (i, bytes) in bindings.iter().enumerate() { - // The unparser quotes string literals with single quotes, so the - // placeholder appears as `'__lancedb_binary_placeholder___'`. - let quoted = format!("'{}{}__'", BINARY_PLACEHOLDER_PREFIX, i); - sql = sql.replace("ed, &bytes_to_hex_sql(bytes)); + let sql = run_unparser(&rewritten)?; + if binary_bindings.is_empty() { + Ok(sql) + } else { + bind_binary_literals(&sql, binary_bindings) } - Ok(sql) } #[cfg(test)] From 9d3962686e847be3e81a48005642b01f7ad9698f Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Thu, 27 Aug 2026 23:35:02 +0800 Subject: [PATCH 137/206] fix(node): accept Arrow metadata across JavaScript realms (#3904) ## Summary - accept genuine Arrow metadata maps created in another JavaScript realm - validate every metadata entry and clone it into a local Map - cover an Arrow 15 VM-realm table through the public fromDataToBuffer boundary - retain structural typing for nested and dictionary Arrow data ## Root cause The sanitizer used a local-realm instanceof Map check for schema and field metadata. A genuine Map created in another JavaScript realm has the required internal Map state but fails that identity check, so fromDataToBuffer rejected the foreign table before serializing its rows. ## Scope This fixes the distinct JavaScript-realm sanitizer failure identified during review. It does not establish the cause of the S3/compaction panic reported in #1525, so that issue remains open. ## Validation - pnpm test --runInBand (707 passed, 5 skipped) - pnpm test --runInBand __test__/arrow.test.ts (189 passed) - pnpm build - pnpm lint - pnpm run docs Related to #1525 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- nodejs/__test__/arrow.test.ts | 37 +++++++++++++++++++++++++++++++++++ nodejs/lancedb/arrow.ts | 4 ++-- nodejs/lancedb/sanitize.ts | 15 ++++++++++---- 3 files changed, 50 insertions(+), 6 deletions(-) diff --git a/nodejs/__test__/arrow.test.ts b/nodejs/__test__/arrow.test.ts index cb56cb5ae..83b4fae46 100644 --- a/nodejs/__test__/arrow.test.ts +++ b/nodejs/__test__/arrow.test.ts @@ -1,5 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +import * as fs from "node:fs"; +import * as vm from "node:vm"; import * as arrow15 from "apache-arrow-15"; import * as arrow16 from "apache-arrow-16"; import * as arrow17 from "apache-arrow-17"; @@ -40,6 +42,41 @@ function sampleRecords(): Array> { ]; } +it("serializes an Arrow Table created in another JavaScript realm", async () => { + const context = vm.createContext({ + TextDecoder, + TextEncoder, + console, + setTimeout, + clearTimeout, + }); + vm.runInContext( + fs.readFileSync( + require.resolve("apache-arrow-15/Arrow.es2015.min"), + "utf8", + ), + context, + ); + const foreignTable: unknown = vm.runInContext( + "Arrow.tableFromArrays({ id: new Int32Array([1, 2, 3]), text: ['foo', 'bar', 'baz'] })", + context, + ); + + const foreignMetadata = ( + foreignTable as { schema: { metadata: Map } } + ).schema.metadata; + expect(foreignMetadata).not.toBeInstanceOf(Map); + + const buf = await fromDataToBuffer( + foreignTable as Parameters[0], + ); + const actual = currentTableFromIPC(buf); + + expect(actual.numRows).toBe(3); + expect(actual.getChild("id")?.toJSON()).toEqual([1, 2, 3]); + expect(actual.getChild("text")?.toJSON()).toEqual(["foo", "bar", "baz"]); +}); + it("preserves field metadata from a provided schema", async function () { const jsonMetadata = new Map([["ARROW:extension:name", "lance.json"]]); const schema = new CurrentSchema([ diff --git a/nodejs/lancedb/arrow.ts b/nodejs/lancedb/arrow.ts index b52ab50ef..1b6b98cc9 100644 --- a/nodejs/lancedb/arrow.ts +++ b/nodejs/lancedb/arrow.ts @@ -72,8 +72,7 @@ export type FieldLike = }; export type DataLike = - // biome-ignore lint/suspicious/noExplicitAny: - | import("apache-arrow").Data> + | import("apache-arrow").Data | { // biome-ignore lint/suspicious/noExplicitAny: type: any; @@ -82,6 +81,7 @@ export type DataLike = stride: number; nullable: boolean; children: DataLike[]; + dictionary?: { data: readonly DataLike[] }; get nullCount(): number; // biome-ignore lint/suspicious/noExplicitAny: values: Buffers[BufferType.DATA]; diff --git a/nodejs/lancedb/sanitize.ts b/nodejs/lancedb/sanitize.ts index 8fb2f1a0a..454c82247 100644 --- a/nodejs/lancedb/sanitize.ts +++ b/nodejs/lancedb/sanitize.ts @@ -94,17 +94,24 @@ export function sanitizeMetadata( if (metadataLike === undefined || metadataLike === null) { return undefined; } - if (!(metadataLike instanceof Map)) { + + let entries: IterableIterator<[unknown, unknown]>; + try { + entries = Map.prototype.entries.call(metadataLike); + } catch { throw Error("Expected metadata, if present, to be a Map"); } - for (const item of metadataLike) { - if (typeof item[0] !== "string" || typeof item[1] !== "string") { + + const metadata = new Map(); + for (const [key, value] of entries) { + if (typeof key !== "string" || typeof value !== "string") { throw Error( "Expected metadata, if present, to be a Map but it had non-string keys or values", ); } + metadata.set(key, value); } - return metadataLike as Map; + return metadata; } export function sanitizeInt(typeLike: object) { From b85776c22a7605047bf14c2a7f7d036648d501dd Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 27 Aug 2026 15:52:41 -0700 Subject: [PATCH 138/206] fix(listing)!: page table listings from the store's own cursor (#3979) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BREAKING CHANGE: list_tables now provides tables in arbitrary order and the page token is now completely opaque. `table_names` retains the old behavior of lexical ordering and `start-after` semantics. Listing the tables in a directory database cost what the database held rather than what the page held. `ListingDatabase::list_tables` enumerated every child directory of the base path, sorted the names, then discarded all but the requested page — on every request, for every page. On object storage that is one full listing per page. This PR pages the store instead. `list_tables` asks for one page at a time through `ObjectStore::read_dir_page`, carrying the store's own continuation token, so a page is one request. Non-table children can leave a page short of its limit, so the walk continues until the page is full or the store runs out. --------- Co-authored-by: Claude Opus 5 (1M context) --- rust/lancedb/src/database/listing.rs | 283 +++++++++++++++++++++++---- 1 file changed, 248 insertions(+), 35 deletions(-) diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index 064b5d28f..c22b73dd7 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -13,7 +13,7 @@ use lance::dataset::{ReadParams, WriteMode, builder::DatasetBuilder}; use lance::io::{ObjectStore, ObjectStoreParams, WrappingObjectStore}; use lance_datafusion::utils::StreamingWriteSource; use lance_file::version::LanceFileVersion; -use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider}; +use lance_io::object_store::{ReadDirOptions, StorageOptionsAccessor, StorageOptionsProvider}; use lance_table::io::commit::commit_handler_from_url; use object_store::local::LocalFileSystem; use snafu::ResultExt; @@ -281,6 +281,22 @@ impl std::fmt::Display for ListingDatabase { } const LANCE_EXTENSION: &str = "lance"; + +/// The table a listed child of the database names, or `None` if the child is not a table. +/// +/// A table is the directory `.lance`; a loose file or any other directory under the +/// database prefix belongs to something else. `dir_suffix` is `.lance`, built once by the +/// caller rather than per child. +/// The table a listed child directory holds, or `None` if it is not a table at all. +/// +/// Only directories are considered, so a loose object named like a table is not one. +fn table_name(location: &object_store::path::Path, dir_suffix: &str) -> Option { + location + .filename()? + .strip_suffix(dir_suffix) + .map(String::from) + .filter(|name| !name.is_empty()) +} const ENGINE: &str = "engine"; const MIRRORED_STORE: &str = "mirroredStore"; @@ -944,51 +960,72 @@ impl Database for ListingDatabase { Ok(f) } + /// List the tables in the database, a page at a time. + /// + /// The page_token is opaque, unlike the `start_after` parameter of [`Self::table_names()`]. + /// + /// When there are no more results, the returned page_token will be None. + /// + /// `limit` is the maximum number of tables to return in the response. But it is possible + /// for the response to contain fewer than `limit` tables, even when there are more tables + /// to return. Clients should check the returned page_token to determine if there are + /// more results, rather than relying on the number of tables returned. + /// + /// The order that results are returned in not guaranteed to be stable across calls, + /// so clients should not rely on it. async fn list_tables(&self, request: ListTablesRequest) -> Result { if request.id.as_ref().map(|v| !v.is_empty()).unwrap_or(false) { return self.namespace_database().list_tables(request).await; } - let mut f = self - .object_store - .read_dir(self.base_path.clone()) - .await? - .iter() - .map(Path::new) - .filter(|path| { - let is_lance = path - .extension() - .and_then(|e| e.to_str()) - .map(|e| e == LANCE_EXTENSION); - is_lance.unwrap_or(false) - }) - .filter_map(|p| p.file_stem().and_then(|s| s.to_str().map(String::from))) - .collect::>(); - f.sort(); + let limit = request.limit.map(|limit| limit.max(0) as usize); + let dir_suffix = format!(".{LANCE_EXTENSION}"); + let mut tables = Vec::new(); + let mut page_token = request.page_token.filter(|token| !token.is_empty()); - // Handle pagination with page_token - if let Some(ref page_token) = request.page_token { - let index = f - .iter() - .position(|name| name.as_str() > page_token.as_str()) - .unwrap_or(f.len()); - f.drain(0..index); + // A page of nothing: the store rejects a limit of zero, and no table was handed over + // for a token to resume after. + if limit == Some(0) { + return Ok(ListTablesResponse { + context: None, + tables, + page_token: None, + }); } - // Determine if there's a next page. The token is the last name of this page, - // not the first of the next one: the next page resumes strictly after the - // token, so naming the next page's first entry would skip it. - let next_page_token = match request.limit { - Some(limit) if f.len() > limit as usize => { - f.truncate(limit as usize); - f.last().cloned() + loop { + // Ask only for what the page still has room for, so a database holding more + // than one page costs one request per page rather than one per table. + let listing = self + .object_store + .read_dir_page( + self.base_path.clone(), + ReadDirOptions { + page_token: page_token.take(), + limit: limit.map(|limit| limit - tables.len()), + }, + ) + .await?; + page_token = listing.page_token; + // Only child directories can be tables, and the store already separates them + // out, so the objects in the page are not looked at. + tables.extend( + listing + .result + .common_prefixes + .iter() + .filter_map(|location| table_name(location, &dir_suffix)), + ); + // Children that are not tables leave the page short of the limit, so keep + // going until the page is full or the database runs out. + if page_token.is_none() || limit.is_none_or(|limit| tables.len() >= limit) { + break; } - _ => None, - }; + } Ok(ListTablesResponse { context: None, - tables: f, - page_token: next_page_token, + tables, + page_token, }) } @@ -1484,6 +1521,182 @@ mod tests { use tokio::sync::Barrier; use tokio::time::timeout; + async fn create_tables(db: &ListingDatabase, names: &[&str]) { + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + for name in names { + db.create_table(CreateTableRequest { + name: name.to_string(), + namespace_path: vec![], + data: Box::new(RecordBatch::new_empty(schema.clone())) as Box, + mode: CreateTableMode::Create, + write_options: Default::default(), + location: None, + namespace_client: None, + }) + .await + .unwrap(); + } + } + + /// Every table in the database, taken `limit` at a time, which is how a caller walks a + /// listing: the token ends the walk, never a short page. + async fn walk(db: &ListingDatabase, limit: Option) -> Vec { + let mut seen = Vec::new(); + let mut page_token = None; + loop { + let page = db + .list_tables(ListTablesRequest { + limit, + page_token, + ..Default::default() + }) + .await + .unwrap(); + seen.extend(page.tables); + page_token = page.page_token; + if page_token.is_none() { + return seen; + } + assert!( + seen.len() < 100, + "the walk is serving tables more than once" + ); + } + } + + /// Paging with the returned token has to visit every table exactly once, whatever the + /// page size, with nothing lost or repeated at a boundary. + #[rstest::rstest] + #[tokio::test] + async fn test_list_tables_pages_over_every_table_once(#[values(1, 2, 3, 5, 10)] limit: i32) { + let (_tempdir, db) = setup_database().await; + create_tables(&db, &["a", "b", "c", "d", "e"]).await; + + assert_eq!(walk(&db, Some(limit)).await, vec!["a", "b", "c", "d", "e"]); + } + + /// The token is opaque: it is whatever resumes the store the database sits on, not a + /// table name. Callers hand it back and nothing else. + /// + /// Nothing validates a token, so one invented by a caller is read as a position rather + /// than refused — which is why the token has to come back from a previous page. + #[tokio::test] + async fn test_the_page_token_is_not_a_table_name() { + let (_tempdir, db) = setup_database().await; + create_tables(&db, &["a", "b", "c"]).await; + + let page = db + .list_tables(ListTablesRequest { + limit: Some(1), + ..Default::default() + }) + .await + .unwrap(); + + assert_eq!(page.tables, vec!["a"]); + let token = page.page_token.expect("two tables are still to come"); + assert_ne!(token, "a"); + + // Handing it back is the only thing a caller does with it, and it resumes. + let rest = db + .list_tables(ListTablesRequest { + page_token: Some(token), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(rest.tables, vec!["b", "c"]); + } + + /// A limit the listing does not fill leaves no token behind, so a caller paging by token + /// stops without asking for an empty page. + #[tokio::test] + async fn test_a_listing_that_runs_out_has_no_token() { + let (_tempdir, db) = setup_database().await; + create_tables(&db, &["a", "b"]).await; + + let page = db + .list_tables(ListTablesRequest { + limit: Some(10), + ..Default::default() + }) + .await + .unwrap(); + + assert_eq!(page.tables, vec!["a", "b"]); + assert_eq!(page.page_token, None); + } + + /// An empty page token means "from the start", which is how a client looping on a token + /// spells its first request. + #[tokio::test] + async fn test_an_empty_page_token_lists_from_the_start() { + let (_tempdir, db) = setup_database().await; + create_tables(&db, &["a", "b"]).await; + + let page = db + .list_tables(ListTablesRequest { + page_token: Some(String::new()), + ..Default::default() + }) + .await + .unwrap(); + + assert_eq!(page.tables, vec!["a", "b"]); + } + + /// Listing follows the order the object store lists directories in, so a name that + /// extends another comes first: the `-` of `users-archive.lance` sorts below the `.` of + /// `users.lance`. Pagination pushes its cursor into the list request, so it cannot report + /// an order other than the one it resumes in. + #[tokio::test] + async fn test_listing_order_follows_the_store_not_the_table_name() { + let (_tempdir, db) = setup_database().await; + create_tables(&db, &["users", "users-archive", "users.old"]).await; + + assert_eq!( + walk(&db, None).await, + vec!["users-archive", "users", "users.old"] + ); + // And paging reports the same order, so a walk sees each table once. + assert_eq!( + walk(&db, Some(1)).await, + vec!["users-archive", "users", "users.old"] + ); + } + + /// Only directories named `.lance` are tables; loose files and other directories + /// under the database prefix are not. A page spent on them is filled from the next one, + /// so a page holding only non-tables does not read as an empty database. + #[tokio::test] + async fn test_listing_ignores_non_table_children() { + let (tempdir, db) = setup_database().await; + create_tables(&db, &["real"]).await; + std::fs::write(tempdir.path().join("aaa-loose.lance"), b"not a table").unwrap(); + create_dir_all(tempdir.path().join("aaa-scratch")).unwrap(); + + let page = db + .list_tables(ListTablesRequest { + limit: Some(1), + ..Default::default() + }) + .await + .unwrap(); + + assert_eq!(page.tables, vec!["real"]); + } + + #[tokio::test] + async fn listing_ignores_empty_table_name() { + let (tempdir, db) = setup_database().await; + create_dir_all(tempdir.path().join(".lance")).unwrap(); + let page = db.list_tables(ListTablesRequest::default()).await.unwrap(); + assert!( + page.tables.is_empty(), + "invalid empty table name was listed" + ); + } + async fn setup_database() -> (tempfile::TempDir, ListingDatabase) { let tempdir = tempdir().unwrap(); let uri = tempdir.path().to_str().unwrap(); From 83cff3ab93c1998e9e546efbc6a62adfdbc00b7b Mon Sep 17 00:00:00 2001 From: Drew Date: Thu, 27 Aug 2026 17:07:29 -0700 Subject: [PATCH 139/206] fix(python): use one blobv2 type and coerce blob writes by metadata (#4065) --- docs/src/python/python.md | 8 +- python/python/lancedb/__init__.py | 17 +- python/python/lancedb/_blob.py | 8 +- python/python/lancedb/schema.py | 135 +++-- python/python/lancedb/table.py | 292 ++++++++--- python/python/tests/test_blob.py | 480 ++++++++++++++++++ python/python/tests/test_util.py | 160 ++++++ .../src/table/datafusion/blob_coerce.rs | 22 +- 8 files changed, 1022 insertions(+), 100 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 3cb996a15..5f359f4b7 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -223,9 +223,13 @@ tokens = list( Blob columns store large binary values out of line so they can be read lazily instead of being materialized with the rest of the row. -::: lancedb.blob +`lancedb.BlobType` is `lance.blob.BlobType` when pylance is installed. Without +pylance, LanceDB uses a matching `lance.blob.v2` extension type so blob columns +still work. Queries return descriptors. Call +[`fetch_blob_files`][lancedb.table.Table.fetch_blob_files] for lazy reads or +[`fetch_blobs`][lancedb.table.Table.fetch_blobs] for eager bytes. -::: lancedb.BlobType +::: lancedb.blob ::: lancedb._blob.BlobFile options: diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 8cb85a3ed..21ffc8860 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -6,7 +6,7 @@ import importlib.metadata import os from concurrent.futures import ThreadPoolExecutor from datetime import timedelta -from typing import Dict, Optional, Union, Any, List, Iterable +from typing import Dict, Optional, Union, Any, List, Iterable, TYPE_CHECKING __version__ = importlib.metadata.version("lancedb") @@ -20,7 +20,7 @@ from .db import AsyncConnection, DBConnection, LanceDBConnection from .remote import ClientConfig from .remote.db import RemoteDBConnection from .expr import Expr, col, lit, func -from .schema import blob, vector, BlobType +from .schema import blob, vector from .job import AsyncJob, Job from .functions import ( FunctionArtifactRequest as FunctionArtifactRequest, @@ -49,6 +49,19 @@ from .namespace import ( ) +if TYPE_CHECKING: + from lance.blob import BlobType as BlobType + + +def __getattr__(name: str): + if name == "BlobType": + from .schema import BlobType + + globals()["BlobType"] = BlobType + return BlobType + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + def _check_s3_bucket_with_dots( uri: str, storage_options: Optional[Dict[str, str]] ) -> None: diff --git a/python/python/lancedb/_blob.py b/python/python/lancedb/_blob.py index 5b4c0c343..dc4ed37df 100644 --- a/python/python/lancedb/_blob.py +++ b/python/python/lancedb/_blob.py @@ -12,7 +12,7 @@ from typing import TYPE_CHECKING, Optional, Union import pyarrow as pa from .expr import Expr -from .schema import blob_v2_column_paths +from .schema import row_addressable_blob_v2_paths from .types import BlobMode, QueryProjection, QueryProjectionSpec if TYPE_CHECKING: @@ -119,7 +119,7 @@ def blob_v2_projection_sources( schema: pa.Schema, projection: QueryProjection, ) -> dict[str, str]: - blob_columns = blob_v2_column_paths(schema) + blob_columns = row_addressable_blob_v2_paths(schema) if not blob_columns: return {} columns = set(blob_columns) @@ -140,7 +140,9 @@ def v2_projection_needs_row_id( ) -> bool: if with_row_id: return False - return projection_includes_blob_column(projection, blob_v2_column_paths(schema)) + return projection_includes_blob_column( + projection, row_addressable_blob_v2_paths(schema) + ) def blob_auto_row_id_for_scan( diff --git a/python/python/lancedb/schema.py b/python/python/lancedb/schema.py index 33adbbae3..4dce09f0f 100644 --- a/python/python/lancedb/schema.py +++ b/python/python/lancedb/schema.py @@ -4,30 +4,34 @@ """Schema helpers for Lance blob columns.""" +import importlib +from typing import TYPE_CHECKING + import pyarrow as pa +import pyarrow.ipc + +if TYPE_CHECKING: + from lance.blob import BlobType as BlobType _BLOB_EXTENSION_NAME = "lance.blob.v2" _BLOB_V1_KEY = "lance-encoding:blob" _ARROW_EXT_NAME_KEY = "ARROW:extension:name" +_BLOB_V2_STORAGE_TYPE = pa.struct( + [ + pa.field("data", pa.large_binary(), nullable=True), + pa.field("uri", pa.utf8(), nullable=True), + pa.field("position", pa.uint64(), nullable=True), + pa.field("size", pa.uint64(), nullable=True), + ] +) +_resolved_blob_type = None -class BlobType(pa.ExtensionType): - """PyArrow extension type for a Lance blob v2 column. - - Queries return descriptors; call :meth:`~lancedb.table.Table.fetch_blob_files` - for lazy reads or :meth:`~lancedb.table.Table.fetch_blobs` for eager bytes. - """ +class _FallbackBlobType(pa.ExtensionType): + """lance.blob.v2 extension type used when pylance is not installed.""" def __init__(self) -> None: - storage_type = pa.struct( - [ - pa.field("data", pa.large_binary(), nullable=True), - pa.field("uri", pa.utf8(), nullable=True), - pa.field("position", pa.uint64(), nullable=True), - pa.field("size", pa.uint64(), nullable=True), - ] - ) - super().__init__(storage_type, _BLOB_EXTENSION_NAME) + pa.ExtensionType.__init__(self, _BLOB_V2_STORAGE_TYPE, _BLOB_EXTENSION_NAME) def __arrow_ext_serialize__(self) -> bytes: return b"" @@ -35,23 +39,16 @@ class BlobType(pa.ExtensionType): @classmethod def __arrow_ext_deserialize__( cls, storage_type: pa.DataType, serialized: bytes - ) -> "BlobType": + ) -> "_FallbackBlobType": return cls() def __reduce__(self): - # Ensure pickle round-trips on older pyarrow (apache/arrow#35599). return type(self).__arrow_ext_deserialize__, ( self.storage_type, self.__arrow_ext_serialize__(), ) -try: - pa.register_extension_type(BlobType()) # type: ignore[arg-type] -except pa.ArrowKeyError: - pass - - def _metadata_value(metadata: dict, key: str): return metadata.get(key.encode()) or metadata.get(key) @@ -92,43 +89,105 @@ def is_blob_like_field(field: pa.Field) -> bool: return is_blob_v2_field(field) or _metadata_marks_legacy_blob(field.metadata or {}) -def _collect_blob_paths(schema: pa.Schema, is_blob) -> list[str]: - paths: list[str] = [] +def _collect_blob_paths(schema: pa.Schema, is_blob) -> list[tuple[str, bool]]: + """Walk the schema and return (path, has_list_ancestor) for each blob field.""" + paths: list[tuple[str, bool]] = [] - def walk(fields, prefix: str) -> None: + def walk(fields, prefix: str, has_list_ancestor: bool) -> None: for field in fields: path = f"{prefix}.{field.name}" if prefix else field.name if is_blob(field): - paths.append(path) + paths.append((path, has_list_ancestor)) elif pa.types.is_struct(field.type): - walk(field.type, path) + walk(field.type, path, has_list_ancestor) elif ( pa.types.is_list(field.type) or pa.types.is_large_list(field.type) or pa.types.is_fixed_size_list(field.type) ): - walk([field.type.value_field], path) + walk([field.type.value_field], path, True) - walk(schema, "") + walk(schema, "", False) return paths def blob_column_paths(schema: pa.Schema) -> list[str]: """Dotted paths of blob-like columns (v2 extension or legacy metadata).""" - return _collect_blob_paths(schema, is_blob_like_field) + return [path for path, _ in _collect_blob_paths(schema, is_blob_like_field)] def blob_v2_column_paths(schema: pa.Schema) -> list[str]: - return _collect_blob_paths(schema, is_blob_v2_field) + return [path for path, _ in _collect_blob_paths(schema, is_blob_v2_field)] + + +def row_addressable_blob_v2_paths(schema: pa.Schema) -> list[str]: + """Blob v2 paths with one blob addressable by table row id. + + ``fetch_blobs`` and the descriptor row-id ride-along address one blob per + row, so a blob inside a list container has no row-id slot and no fetch + path. Those columns still store and query as raw descriptors. + """ + return [ + path + for path, has_list_ancestor in _collect_blob_paths(schema, is_blob_v2_field) + if not has_list_ancestor + ] def schema_has_blob_field(schema: pa.Schema) -> bool: return bool(blob_column_paths(schema)) +def _deserialize_registered_type(extension_type: pa.ExtensionType) -> pa.DataType: + """Return the type Arrow reconstructs for this extension name.""" + schema = pa.schema([pa.field("value", extension_type)]) + restored = pa.ipc.read_schema(schema.serialize()) + return restored.field("value").type + + +def _resolve_blob_type(): + """Return the BlobType class this process should use. + + pylance's class when it owns the lance.blob.v2 registry entry, + otherwise LanceDB's fallback. A different registered class is an error. + """ + global _resolved_blob_type + if _resolved_blob_type is not None: + return _resolved_blob_type + try: + blob_module = importlib.import_module("lance.blob") + except ModuleNotFoundError as err: + if err.name not in ("lance", "lance.blob"): + raise + else: + blob_type = getattr(blob_module, "BlobType", None) + if blob_type is not None: + registered_type = _deserialize_registered_type(blob_type()) + if type(registered_type) is not blob_type: + registered_cls = type(registered_type) + raise ValueError( + "lance.blob.v2 is already registered by " + f"{registered_cls.__module__}.{registered_cls.__qualname__}" + ) + _resolved_blob_type = blob_type + return blob_type + try: + pa.register_extension_type(_FallbackBlobType()) # type: ignore[arg-type] + except pa.ArrowKeyError as err: + raise ValueError( + "lance.blob.v2 is already registered by another extension class" + ) from err + _resolved_blob_type = _FallbackBlobType + return _resolved_blob_type + + def blob(name: str, nullable: bool = True) -> pa.Field: - """Create a Lance blob v2 column field.""" - return pa.field(name, BlobType(), nullable=nullable) + """Create a Lance blob v2 column field. + + When pylance is installed this is ``lance.blob.BlobType``. + """ + blob_type = _resolve_blob_type() + return pa.field(name, blob_type(), nullable=nullable) def vector(dimension: int, value_type: pa.DataType = pa.float32()) -> pa.DataType: @@ -155,3 +214,11 @@ def vector(dimension: int, value_type: pa.DataType = pa.float32()) -> pa.DataTyp ... ]) """ return pa.list_(value_type, dimension) + + +def __getattr__(name: str): + if name == "BlobType": + blob_type = _resolve_blob_type() + globals()["BlobType"] = blob_type + return blob_type + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 765b7fa14..535ed7c0d 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -104,7 +104,12 @@ from .util import ( value_to_sql, ) from .index import lang_mapping -from .schema import blob_v2_column_paths, schema_has_blob_field +from .schema import ( + blob_v2_column_paths, + is_blob_v2_field, + row_addressable_blob_v2_paths, + schema_has_blob_field, +) def _should_push_down_query_table( @@ -426,6 +431,7 @@ def _cast_to_target_schema( def gen(): for batch in reader: + batch = _coerce_blob_write_columns(batch, reordered_schema) # Table but not RecordBatch has cast. cast_batches = ( pa.Table.from_batches([batch]).cast(reordered_schema).to_batches() @@ -438,6 +444,166 @@ def _cast_to_target_schema( return pa.RecordBatchReader.from_batches(reordered_schema, gen()) +def _coerce_blob_write_columns( + batch: pa.RecordBatch, target_schema: pa.Schema +) -> pa.RecordBatch: + """Materialize blob storage structs before the stream leaves Python. + + merge_insert requires its source reader to already match the table's + physical schema. Unlike add and insert, it does not pass through + LanceDB's Rust blob coercion, so preserving binary input here would + reach Lance as binary and fail the schema check. + """ + columns = [] + fields = [] + changed = False + for field, column in zip(batch.schema, batch.columns): + target_field = target_schema.field(field.name) + coerced = _coerce_blob_value(column, target_field) + if coerced is not column: + column = coerced + field = pa.field( + field.name, + coerced.type, + field.nullable, + target_field.metadata, + ) + changed = True + columns.append(column) + fields.append(field) + if not changed: + return batch + return pa.RecordBatch.from_arrays( + columns, schema=pa.schema(fields, metadata=batch.schema.metadata) + ) + + +def _coerce_blob_value(column: pa.Array, target_field: pa.Field) -> pa.Array: + if is_blob_v2_field(target_field) and _can_coerce_to_blob(column.type): + return _coerce_value_to_blob(column, target_field) + + target_type = target_field.type + if pa.types.is_struct(target_type) and pa.types.is_struct(column.type): + children = [] + fields = [] + changed = False + for source_field in column.type: + source_column = column.field(source_field.name) + nested_target = next( + (field for field in target_type if field.name == source_field.name), + None, + ) + if nested_target is None: + children.append(source_column) + fields.append(source_field) + continue + coerced = _coerce_blob_value(source_column, nested_target) + if coerced is not source_column: + changed = True + child_array, child_type = _physical_array_and_type(coerced) + children.append(child_array) + fields.append( + pa.field( + source_field.name, + child_type, + source_field.nullable, + nested_target.metadata, + ) + ) + if not changed: + return column + return pa.StructArray.from_arrays( + children, + fields=fields, + mask=column.is_null() if column.null_count else None, + ) + + if _is_list_like(target_type) and _is_list_like(column.type): + return _coerce_blob_list_values(column, target_type.value_field) + + return column + + +def _coerce_blob_list_values( + column: pa.Array, target_value_field: pa.Field +) -> pa.Array: + """Coerce blob values inside a list column, preserving offsets and nulls. + + Works on the raw child values window instead of ``pc.list_flatten`` because + flatten drops values spanned by null slots, which would misalign offsets. + """ + mask = column.is_null() if column.null_count else None + if pa.types.is_fixed_size_list(column.type): + list_size = column.type.list_size + values = column.values.slice(column.offset * list_size, len(column) * list_size) + coerced = _coerce_blob_value(values, target_value_field) + if coerced is values: + return column + physical_values, _ = _physical_array_and_type(coerced) + return pa.FixedSizeListArray.from_arrays(physical_values, list_size, mask=mask) + offsets = column.offsets + first_offset = offsets[0].as_py() + values = column.values.slice( + first_offset, + offsets[-1].as_py() - first_offset, + ) + coerced = _coerce_blob_value(values, target_value_field) + if coerced is values: + return column + physical_values, _ = _physical_array_and_type(coerced) + if first_offset: + offsets = pc.subtract(offsets, pa.scalar(first_offset, offsets.type)) + if pa.types.is_large_list(column.type): + return pa.LargeListArray.from_arrays(offsets, physical_values, mask=mask) + return pa.ListArray.from_arrays(offsets, physical_values, mask=mask) + + +def _coerce_value_to_blob(values: pa.Array, target_field: pa.Field) -> pa.Array: + if pa.types.is_null(values.type): + data = pa.nulls(len(values), type=pa.large_binary()) + elif pa.types.is_large_binary(values.type): + data = values + else: + data = values.cast(pa.large_binary()) + length = len(values) + storage_type = target_field.type + if isinstance(storage_type, pa.ExtensionType): + storage_type = storage_type.storage_type + storage_fields = list(storage_type) + children = [] + for storage_field in storage_fields: + if storage_field.name == "data": + children.append(data) + else: + children.append(pa.nulls(length, type=storage_field.type)) + storage = pa.StructArray.from_arrays( + children, + fields=storage_fields, + mask=values.is_null() if values.null_count else None, + ) + if isinstance(target_field.type, pa.ExtensionType): + return pa.ExtensionArray.from_storage(target_field.type, storage) + return storage + + +def _physical_array_and_type(array: pa.Array) -> tuple[pa.Array, pa.DataType]: + if isinstance(array.type, pa.ExtensionType): + return array.storage, array.type.storage_type + return array, array.type + + +def _can_coerce_to_blob(data_type: pa.DataType) -> bool: + return _is_binary_like(data_type) or pa.types.is_null(data_type) + + +def _is_binary_like(data_type: pa.DataType) -> bool: + return ( + pa.types.is_binary(data_type) + or pa.types.is_large_binary(data_type) + or pa.types.is_binary_view(data_type) + ) + + def _field_extension_name(field: pa.Field) -> Optional[str]: extension_name = getattr(field.type, "extension_name", None) if extension_name is not None: @@ -464,63 +630,71 @@ def _align_field_types( target_field = next((f for f in target_fields if f.name == field.name), None) if target_field is None: raise ValueError(f"Field '{field.name}' not found in target schema") - # Preserve arrow.json input until it reaches Lance. LanceDB exposes stored - # JSON columns as lance.json (JSONB-backed LargeBinary), but casting the - # input to that storage type here merely relabels the raw JSON bytes as - # JSONB. Lance must see arrow.json so it can perform the JSONB encoding. - if ( - _field_extension_name(field) == "arrow.json" - and _field_extension_name(target_field) == "lance.json" - ): - new_fields.append(field) - continue - if pa.types.is_struct(target_field.type): - if pa.types.is_struct(field.type): - new_type = pa.struct( - _align_field_types( - field.type.fields, - target_field.type.fields, - ) + new_fields.append(_align_field(field, target_field)) + return new_fields + + +def _align_list_value_field( + value_field: pa.Field, target_value_field: pa.Field +) -> pa.Field: + # A list has exactly one child, so the inferred child name ("item") aligns + # positionally and adopts the table's child name; pa.Table.cast renames it. + return _align_field(value_field, target_value_field).with_name( + target_value_field.name + ) + + +def _align_field(field: pa.Field, target_field: pa.Field) -> pa.Field: + # Preserve arrow.json input until it reaches Lance. LanceDB exposes stored + # JSON columns as lance.json (JSONB-backed LargeBinary), but casting the + # input to that storage type here merely relabels the raw JSON bytes as + # JSONB. Lance must see arrow.json so it can perform the JSONB encoding. + if ( + _field_extension_name(field) == "arrow.json" + and _field_extension_name(target_field) == "lance.json" + ): + return field + if pa.types.is_struct(target_field.type): + if pa.types.is_struct(field.type): + new_type = pa.struct( + _align_field_types( + field.type.fields, + target_field.type.fields, ) - else: - new_type = target_field.type - elif pa.types.is_list(target_field.type): - if _is_list_like(field.type): - new_type = pa.list_( - _align_field_types( - [field.type.value_field], - [target_field.type.value_field], - )[0] - ) - else: - new_type = target_field.type - elif pa.types.is_large_list(target_field.type): - if _is_list_like(field.type): - new_type = pa.large_list( - _align_field_types( - [field.type.value_field], - [target_field.type.value_field], - )[0] - ) - else: - new_type = target_field.type - elif pa.types.is_fixed_size_list(target_field.type): - if _is_list_like(field.type): - new_type = pa.list_( - _align_field_types( - [field.type.value_field], - [target_field.type.value_field], - )[0], - target_field.type.list_size, - ) - else: - new_type = target_field.type + ) else: new_type = target_field.type - new_fields.append( - pa.field(field.name, new_type, field.nullable, target_field.metadata) - ) - return new_fields + elif pa.types.is_list(target_field.type): + if _is_list_like(field.type): + new_type = pa.list_( + _align_list_value_field( + field.type.value_field, target_field.type.value_field + ) + ) + else: + new_type = target_field.type + elif pa.types.is_large_list(target_field.type): + if _is_list_like(field.type): + new_type = pa.large_list( + _align_list_value_field( + field.type.value_field, target_field.type.value_field + ) + ) + else: + new_type = target_field.type + elif pa.types.is_fixed_size_list(target_field.type): + if _is_list_like(field.type): + new_type = pa.list_( + _align_list_value_field( + field.type.value_field, target_field.type.value_field + ), + target_field.type.list_size, + ) + else: + new_type = target_field.type + else: + new_type = target_field.type + return pa.field(field.name, new_type, field.nullable, target_field.metadata) def _infer_subschema( @@ -589,7 +763,7 @@ def sanitize_create_table( schema = data.schema else: if schema is not None: - data = pa.Table.from_pylist([], schema) + data = pa.Table.from_batches([], schema=schema) if schema is None: if data is None: raise ValueError("Either data or schema must be provided") @@ -2698,7 +2872,7 @@ class LanceTable(Table): arrow_tbl = self.to_arrow() if blob_mode == "descriptions": arrow_tbl = strip_auto_row_ids( - arrow_tbl, blob_v2_column_paths(self.schema) + arrow_tbl, row_addressable_blob_v2_paths(self.schema) ) return arrow_tbl.to_pandas(**kwargs) @@ -5102,7 +5276,9 @@ class AsyncTable: if blob_mode == "descriptions" or not schema_has_blob_field(schema): arrow_tbl = await self.to_arrow() if blob_mode == "descriptions": - arrow_tbl = strip_auto_row_ids(arrow_tbl, blob_v2_column_paths(schema)) + arrow_tbl = strip_auto_row_ids( + arrow_tbl, row_addressable_blob_v2_paths(schema) + ) return arrow_tbl.to_pandas(**kwargs) if blob_mode == "lazy" and get_uri_scheme(await self.uri()) == "memory": diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index 351769ff6..c9694277c 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -2,10 +2,15 @@ # SPDX-FileCopyrightText: Copyright The LanceDB Authors import io +import subprocess +import sys +import textwrap +import lance import pyarrow as pa import pyarrow.compute as pc import pytest +from lance.blob import BlobType as LanceBlobType import lancedb from lancedb._blob import ( @@ -18,6 +23,20 @@ from lancedb.index import FTS from lancedb.schema import blob_column_paths, blob_v2_column_paths +_HIDE_LANCE_BLOB = """\ +import importlib.abc +import sys + +class _MissingLanceBlob(importlib.abc.MetaPathFinder): + def find_spec(self, fullname, path, target=None): + if fullname == "lance.blob" or fullname.startswith("lance.blob."): + raise ModuleNotFoundError(fullname, name="lance.blob") + +sys.modules.pop("lance.blob", None) +sys.meta_path.insert(0, _MissingLanceBlob()) +""" + + def _blob_table(name, rows): db = lancedb.connect("memory:///") schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) @@ -51,6 +70,181 @@ def test_blob_factory_declares_v2_field(): field = lancedb.blob("image") assert isinstance(field.type, pa.ExtensionType) assert field.type.extension_name == "lance.blob.v2" + assert lancedb.BlobType is LanceBlobType + assert type(field.type) is LanceBlobType + + +def test_blob_type_works_without_pylance(): + script = _HIDE_LANCE_BLOB + textwrap.dedent( + """\ + import lancedb + import pyarrow as pa + + field = lancedb.blob("image") + if not isinstance(field.type, pa.ExtensionType): + raise SystemExit("expected an extension type") + if field.type.extension_name != "lance.blob.v2": + raise SystemExit(field.type.extension_name) + if lancedb.BlobType is not type(field.type): + raise SystemExit("BlobType is not the field type class") + if lancedb.BlobType.__module__ != "lancedb.schema": + raise SystemExit(lancedb.BlobType.__module__) + + db = lancedb.connect("memory:///") + table = db.create_table( + "images", + schema=pa.schema([pa.field("id", pa.int64()), field]), + ) + table.add([{"id": 1, "image": b"hello"}]) + result = ( + table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute([{"id": 1, "image": b"updated"}, {"id": 2, "image": b"inserted"}]) + ) + if result.num_updated_rows != 1 or result.num_inserted_rows != 1: + raise SystemExit( + f"merge_insert rows updated={result.num_updated_rows} " + f"inserted={result.num_inserted_rows}" + ) + """ + ) + result = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr + + +def test_blob_resolves_pylance_type_without_eager_import(): + script = textwrap.dedent( + """\ + import sys + import lancedb + + if "lance.blob" in sys.modules: + raise SystemExit("import lancedb imported lance.blob") + field = lancedb.blob("image") + from lance.blob import BlobType + + if type(field.type) is not BlobType: + raise SystemExit(f"{type(field.type)} is not {BlobType}") + import lance + + image = lance.blob_array([b"x"]) + if type(image.type) is not BlobType: + raise SystemExit("blob_array used a different class") + if type(image.type) is not type(field.type): + raise SystemExit("field and array classes differ") + """ + ) + result = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr + + +def test_blob_fallback_fails_if_name_already_registered(): + script = _HIDE_LANCE_BLOB + textwrap.dedent( + """\ + import pyarrow as pa + + class OtherBlobType(pa.ExtensionType): + def __init__(self): + super().__init__( + pa.struct([pa.field("data", pa.large_binary())]), + "lance.blob.v2", + ) + + def __arrow_ext_serialize__(self): + return b"" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized): + return cls() + + pa.register_extension_type(OtherBlobType()) + import lancedb + + try: + lancedb.blob("image") + except ValueError as err: + if "already registered" not in str(err): + raise SystemExit(err) + else: + raise SystemExit("expected ValueError") + """ + ) + result = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr + + +def test_blob_type_rejects_competing_registration_with_pylance(): + script = textwrap.dedent( + """\ + import pyarrow as pa + import pyarrow.ipc + + class OtherBlobType(pa.ExtensionType): + def __init__(self): + super().__init__( + pa.struct( + [ + pa.field("data", pa.large_binary()), + pa.field("uri", pa.utf8()), + pa.field("position", pa.uint64()), + pa.field("size", pa.uint64()), + ] + ), + "lance.blob.v2", + ) + + def __arrow_ext_serialize__(self): + return b"" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized): + return cls() + + pa.register_extension_type(OtherBlobType()) + + from lance.blob import BlobType + + if BlobType is OtherBlobType: + raise SystemExit("pylance BlobType was replaced") + schema = pa.schema([pa.field("value", BlobType())]) + restored = pa.ipc.read_schema(schema.serialize()) + if type(restored.field("value").type) is not OtherBlobType: + raise SystemExit(type(restored.field("value").type)) + + import lancedb + + try: + lancedb.blob("image") + except ValueError as err: + if "__main__.OtherBlobType" not in str(err): + raise SystemExit(err) + else: + raise SystemExit("expected ValueError") + """ + ) + result = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr def test_blob_v2_column_paths_include_list_children(): @@ -203,6 +397,292 @@ def test_fetch_blobs_round_trip(): assert [blobs[0].as_py(), blobs[1].as_py()] == [b"alpha", b"beta"] +def test_merge_insert_writes_python_bytes(): + table = _blob_table("merge_bytes", [{"id": 1, "image": b"before"}]) + result = ( + table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute([{"id": 1, "image": b"updated"}, {"id": 2, "image": b"inserted"}]) + ) + assert result.num_updated_rows == 1 + assert result.num_inserted_rows == 1 + by_id = _row_ids_by_id(table) + blobs = table.fetch_blobs("image", [by_id[1], by_id[2]]) + assert blobs.to_pylist() == [b"updated", b"inserted"] + + +def test_merge_insert_bytes_after_reopen_without_touching_blob_type(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + table = db.create_table("images", schema=schema) + table.add([{"id": 1, "image": b"hello"}]) + + script = textwrap.dedent( + f"""\ + import lancedb + + db = lancedb.connect({str(tmp_path)!r}) + table = db.open_table("images") + image_type = table.schema.field("image").type + if type(image_type).__name__ != "StructType": + raise SystemExit(f"expected StructType, got {{type(image_type)}}") + result = ( + table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute( + [{{"id": 1, "image": b"updated"}}, {{"id": 2, "image": b"inserted"}}] + ) + ) + if result.num_updated_rows != 1 or result.num_inserted_rows != 1: + raise SystemExit( + f"rows updated={{result.num_updated_rows}} " + f"inserted={{result.num_inserted_rows}}" + ) + hits = table.search().with_row_id(True).limit(10).to_arrow() + by_id = dict(zip(hits["id"].to_pylist(), hits["_rowid"].to_pylist())) + blobs = table.fetch_blobs("image", [by_id[1], by_id[2]]) + if blobs.to_pylist() != [b"updated", b"inserted"]: + raise SystemExit(blobs.to_pylist()) + """ + ) + result = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr + + +def test_merge_insert_bytes_after_reopen_without_pylance(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + table = db.create_table("images", schema=schema) + table.add([{"id": 1, "image": b"hello"}]) + + script = _HIDE_LANCE_BLOB + textwrap.dedent( + f"""\ + import lancedb + + db = lancedb.connect({str(tmp_path)!r}) + table = db.open_table("images") + image_type = table.schema.field("image").type + if type(image_type).__name__ != "StructType": + raise SystemExit(f"expected StructType, got {{type(image_type)}}") + result = ( + table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute( + [{{"id": 1, "image": b"updated"}}, {{"id": 2, "image": b"inserted"}}] + ) + ) + if result.num_updated_rows != 1 or result.num_inserted_rows != 1: + raise SystemExit( + f"rows updated={{result.num_updated_rows}} " + f"inserted={{result.num_inserted_rows}}" + ) + hits = table.search().with_row_id(True).limit(10).to_arrow() + by_id = dict(zip(hits["id"].to_pylist(), hits["_rowid"].to_pylist())) + blobs = table.fetch_blobs("image", [by_id[1], by_id[2]]) + if blobs.to_pylist() != [b"updated", b"inserted"]: + raise SystemExit(blobs.to_pylist()) + """ + ) + result = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr + + +def test_merge_insert_blob_array_into_reopened_unregistered_table(tmp_path): + db = lancedb.connect(tmp_path) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + table = db.create_table("images", schema=schema) + table.add([{"id": 1, "image": b"before"}]) + + script = textwrap.dedent( + f"""\ + import pyarrow as pa + import lancedb + + db = lancedb.connect({str(tmp_path)!r}) + table = db.open_table("images") + image_type = table.schema.field("image").type + if type(image_type).__name__ != "StructType": + raise SystemExit( + f"expected StructType before lance import, got {{type(image_type)}}" + ) + + import lance + + updates = pa.Table.from_arrays( + [ + pa.array([1, 2], type=pa.int64()), + lance.blob_array([b"updated", b"inserted"]), + ], + names=["id", "image"], + ) + result = ( + table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute(updates) + ) + if result.num_updated_rows != 1 or result.num_inserted_rows != 1: + raise SystemExit( + f"rows updated={{result.num_updated_rows}} " + f"inserted={{result.num_inserted_rows}}" + ) + hits = table.search().with_row_id(True).limit(10).to_arrow() + by_id = dict(zip(hits["id"].to_pylist(), hits["_rowid"].to_pylist())) + blobs = table.fetch_blobs("image", [by_id[1], by_id[2]]) + if blobs.to_pylist() != [b"updated", b"inserted"]: + raise SystemExit(blobs.to_pylist()) + """ + ) + result = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr + + +def test_add_all_null_blob_column(): + db = lancedb.connect("memory:///") + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + table = db.create_table("all_null", schema=schema) + table.add([{"id": 1, "image": None}, {"id": 2, "image": None}]) + by_id = _row_ids_by_id(table) + blobs = table.fetch_blobs("image", [by_id[1], by_id[2]]) + assert blobs.to_pylist() == [None, None] + + +def test_create_table_nested_blob_schema_without_rows(): + db = lancedb.connect("memory:///") + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("info", pa.struct([lancedb.blob("blob")])), + pa.field("images", pa.list_(lancedb.blob("image"))), + ] + ) + table = db.create_table("nested_empty", schema=schema) + assert table.count_rows() == 0 + + +def test_merge_insert_nested_blob_dicts(): + db = lancedb.connect("memory:///") + info = pa.StructArray.from_arrays( + [ + pa.array(["first"], type=pa.string()), + _blob_array("blob", [b"before"]), + ], + names=["name", "blob"], + ) + data = pa.Table.from_arrays( + [pa.array([1], type=pa.int64()), info], + names=["id", "info"], + ) + table = db.create_table("nested_merge", data=data) + result = ( + table.merge_insert("id") + .when_matched_update_all() + .execute([{"id": 1, "info": {"name": "first", "blob": b"after"}}]) + ) + assert result.num_updated_rows == 1 + by_id = _row_ids_by_id(table) + blobs = table.fetch_blobs("info.blob", [by_id[1]]) + assert blobs.to_pylist() == [b"after"] + + +def _list_blob_table(name): + db = lancedb.connect("memory:///") + blob_field = lancedb.blob("image") + images = pa.ListArray.from_arrays( + pa.array([0, 1], type=pa.int32()), _blob_array("image", [b"before"]) + ) + data = pa.Table.from_arrays( + [pa.array([1], type=pa.int64()), images], + schema=pa.schema( + [pa.field("id", pa.int64()), pa.field("images", pa.list_(blob_field))] + ), + ) + return db.create_table(name, data=data) + + +def test_merge_insert_list_blob_dicts(): + table = _list_blob_table("list_merge") + result = ( + table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute([{"id": 1, "images": [b"one", b"two"]}, {"id": 2, "images": None}]) + ) + assert result.num_updated_rows == 1 + assert result.num_inserted_rows == 1 + hits = table.search().limit(10).to_arrow() + sizes = { + row["id"]: None if row["images"] is None else [d["size"] for d in row["images"]] + for row in hits.to_pylist() + } + assert sizes == {1: [3, 3], 2: None} + + +def test_list_blob_column_queries_as_raw_descriptors(): + table = _list_blob_table("list_query") + hits = table.search().limit(10).to_arrow() + element = hits.schema.field("images").type.value_type + assert pa.types.is_struct(element) + assert "_lance_row_id" not in element.names + with pytest.raises(ValueError, match="expected struct before segment"): + table.fetch_blobs("images.image", [0]) + + +def test_row_addressable_paths_exclude_list_children(): + from lancedb.schema import row_addressable_blob_v2_paths + + schema = pa.schema( + [ + pa.field("id", pa.int64()), + pa.field("info", pa.struct([lancedb.blob("blob")])), + pa.field("images", pa.list_(lancedb.blob("image"))), + ] + ) + assert blob_v2_column_paths(schema) == ["info.blob", "images.image"] + assert row_addressable_blob_v2_paths(schema) == ["info.blob"] + + +def test_merge_insert_writes_pylance_blob_array(): + table = _blob_table("merge_pylance", [{"id": 1, "image": b"before"}]) + image = lance.blob_array([b"updated", b"inserted"]) + assert type(image.type) is LanceBlobType + assert type(image.type) is type(lancedb.BlobType()) + updates = pa.Table.from_arrays( + [pa.array([1, 2], type=pa.int64()), image], names=["id", "image"] + ) + + result = ( + table.merge_insert("id") + .when_matched_update_all() + .when_not_matched_insert_all() + .execute(updates) + ) + + assert result.num_updated_rows == 1 + assert result.num_inserted_rows == 1 + by_id = _row_ids_by_id(table) + blobs = table.fetch_blobs("image", [by_id[1], by_id[2]]) + assert blobs.to_pylist() == [b"updated", b"inserted"] + + def test_fetch_blobs_accepts_query_result(): table = _blob_table("from_result", [{"id": 1, "image": b"gamma"}]) hits = table.search().limit(10).to_arrow() diff --git a/python/python/tests/test_util.py b/python/python/tests/test_util.py index a9b66b2dd..acdef8eac 100644 --- a/python/python/tests/test_util.py +++ b/python/python/tests/test_util.py @@ -7,6 +7,7 @@ import pathlib from typing import Optional import lance +from lance.blob import BlobType as LanceBlobType from lancedb.conftest import MockTextEmbeddingFunction from lancedb.embeddings.base import EmbeddingFunctionConfig from lancedb.embeddings.registry import EmbeddingFunctionRegistry @@ -907,6 +908,165 @@ def test_cast_to_target_schema(): assert output == expected +def test_cast_to_target_schema_coerces_binary_to_blob_v2(): + data = pa.table({"image": pa.array([b"hello", None], type=pa.binary())}) + target = pa.schema([lancedb.blob("image")]) + + output = _cast_to_target_schema(data.to_reader(), target).read_all() + + image = output["image"].chunk(0) + assert type(image.type) is lancedb.BlobType + assert image.storage.to_pylist() == [ + {"data": b"hello", "uri": None, "position": None, "size": None}, + None, + ] + + +def test_cast_to_target_schema_coerces_binary_to_metadata_blob_struct(): + storage = lancedb.blob("image").type.storage_type + target = pa.schema( + [ + pa.field( + "image", + storage, + metadata={ + b"ARROW:extension:name": b"lance.blob.v2", + b"ARROW:extension:metadata": b"", + }, + ) + ] + ) + data = pa.table({"image": pa.array([b"hello", None], type=pa.binary())}) + + output = _cast_to_target_schema(data.to_reader(), target).read_all() + + image = output["image"].chunk(0) + assert not isinstance(image.type, pa.ExtensionType) + assert image.to_pylist() == [ + {"data": b"hello", "uri": None, "position": None, "size": None}, + None, + ] + + +def test_cast_to_target_schema_coerces_nested_binary_blob(): + data = pa.table( + { + "info": pa.array( + [{"blob": b"hello"}, {"blob": None}], + type=pa.struct([pa.field("blob", pa.binary())]), + ) + } + ) + target = pa.schema([pa.field("info", pa.struct([lancedb.blob("blob")]))]) + + output = _cast_to_target_schema(data.to_reader(), target).read_all() + + blob = output["info"].chunk(0).field("blob") + assert type(blob.type) is lancedb.BlobType + assert blob.storage.to_pylist() == [ + {"data": b"hello", "uri": None, "position": None, "size": None}, + None, + ] + + +def test_cast_to_target_schema_coerces_list_binary_blob_with_inferred_child_name(): + data = pa.table( + {"images": pa.array([[b"a", b"b"], None], type=pa.list_(pa.binary()))} + ) + target = pa.schema([pa.field("images", pa.list_(lancedb.blob("image")))]) + + output = _cast_to_target_schema(data.to_reader(), target).read_all() + + images = output["images"].chunk(0) + assert images.type.value_field.name == "image" + assert type(images.type.value_type) is lancedb.BlobType + assert images.to_pylist()[1] is None + assert images.values.storage.to_pylist() == [ + {"data": b"a", "uri": None, "position": None, "size": None}, + {"data": b"b", "uri": None, "position": None, "size": None}, + ] + + +def test_list_blob_coercion_preserves_null_slots_with_nonzero_extent(): + child = pa.field("image", pa.binary()) + source = pa.ListArray.from_arrays( + pa.array([0, 2, 4], type=pa.int32()), + pa.array([b"a", b"b", b"dead", b"beef"], type=pa.binary()), + mask=pa.array([False, True]), + ).cast(pa.list_(child)) + target = pa.schema([pa.field("images", pa.list_(lancedb.blob("image")))]) + + output = _cast_to_target_schema( + pa.table({"images": source}).to_reader(), target + ).read_all() + + images = output["images"].chunk(0) + assert images.to_pylist()[1] is None + assert [b["data"] for b in images.to_pylist()[0]] == [b"a", b"b"] + + +def test_fixed_size_list_blob_coercion_keeps_null_rows(): + child = pa.field("frame", pa.binary()) + source = ( + pa.FixedSizeListArray.from_arrays( + pa.array([b"a", b"b", b"c", b"d"], type=pa.binary()), 2 + ) + .take(pa.array([0, None], type=pa.int32())) + .cast(pa.list_(child, 2)) + ) + target = pa.schema([pa.field("frames", pa.list_(lancedb.blob("frame"), 2))]) + + output = _cast_to_target_schema( + pa.table({"frames": source}).to_reader(), target + ).read_all() + + frames = output["frames"].chunk(0) + assert frames.to_pylist()[1] is None + assert [b["data"] for b in frames.to_pylist()[0]] == [b"a", b"b"] + + +def test_cast_to_target_schema_accepts_pylance_blob_v2(): + target_type = lancedb.BlobType() + source = lance.blob_array([b"hello", None]) + assert type(source.type) is LanceBlobType + assert type(source.type) is type(target_type) + data = pa.table({"image": source}) + target = pa.schema([pa.field("image", target_type)]) + + output = _cast_to_target_schema(data.to_reader(), target).read_all() + + image = output["image"].chunk(0) + assert type(image.type) is LanceBlobType + assert image.type == target_type + assert image.storage.to_pylist() == [ + {"data": b"hello", "uri": None, "position": None, "size": None}, + None, + ] + + +def test_cast_to_target_schema_rejects_different_blob_v2_class(): + class OtherBlobType(pa.ExtensionType): + def __init__(self): + super().__init__(lancedb.BlobType().storage_type, "lance.blob.v2") + + def __arrow_ext_serialize__(self) -> bytes: + return b"" + + @classmethod + def __arrow_ext_deserialize__( + cls, storage_type: pa.DataType, serialized: bytes + ) -> "OtherBlobType": + return cls() + + storage = lance.blob_array([b"hello"]).storage + source = pa.ExtensionArray.from_storage(OtherBlobType(), storage) + data = pa.table({"image": source}) + target = pa.schema([lancedb.blob("image")]) + + with pytest.raises(pa.ArrowTypeError, match="different extension type"): + _cast_to_target_schema(data.to_reader(), target).read_all() + + def test_sanitize_data_stream(): # Make sure we don't collect the whole stream when running sanitize_data schema = pa.schema({"a": pa.int32()}) diff --git a/rust/lancedb/src/table/datafusion/blob_coerce.rs b/rust/lancedb/src/table/datafusion/blob_coerce.rs index cb984f7f4..0596e7a2d 100644 --- a/rust/lancedb/src/table/datafusion/blob_coerce.rs +++ b/rust/lancedb/src/table/datafusion/blob_coerce.rs @@ -36,6 +36,14 @@ pub(super) fn coerce_blob_expr( }; let input_shape = match input_field.data_type() { + DataType::Null => { + let expr: Arc = Arc::new(CastExpr::new( + input_expr, + table_field.data_type().clone(), + None, + )); + return Ok((expr, table_field.clone())); + } DataType::Binary | DataType::LargeBinary | DataType::BinaryView => BlobInputShape::Bytes, DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => BlobInputShape::String, DataType::Struct(children) => { @@ -155,7 +163,7 @@ mod tests { use crate::blob::blob; use arrow_array::{ Array, ArrayRef, BinaryArray, BinaryViewArray, Int32Array, Int64Array, LargeBinaryArray, - RecordBatch, StringArray, StringViewArray, StructArray, UInt8Array, UInt64Array, + NullArray, RecordBatch, StringArray, StringViewArray, StructArray, UInt8Array, UInt64Array, }; use arrow_schema::Schema; use datafusion::prelude::SessionContext; @@ -279,6 +287,18 @@ mod tests { assert_eq!(data.value(0), b"view"); } + #[tokio::test] + async fn null_column_coerces_to_all_null_blob_struct() { + let batch = batch_with_image( + Field::new("image", DataType::Null, true), + Arc::new(NullArray::new(2)), + ); + let coerced = coerce(batch, &blob_table_schema()).await; + let image = image_struct(&coerced); + assert!(image.is_null(0)); + assert!(image.is_null(1)); + } + #[tokio::test] async fn binary_nulls_stay_null_after_coercion() { let batch = batch_with_image( From 84f46df876b988aeb22a05eff6eb671d174b87a6 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 27 Aug 2026 17:35:06 -0700 Subject: [PATCH 140/206] ci(nodejs): fix nightly OOM on the aarch64 publish legs (#4077) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The nightly `NPM Publish` run has failed every night since at least Aug 23, always on the same two legs: `aarch64-unknown-linux-gnu` and `aarch64-unknown-linux-musl`. The other five targets pass. rustc is OOM-killed during the fat-LTO codegen of the cdylib — `signal: 9` with no diagnostic, about 27 minutes in — and on the musl leg that takes the whole runner down with `The runner has received a shutdown signal`. Both legs now pass: | leg | before | peak memory | wall time | | --- | --- | --- | --- | | `aarch64-unknown-linux-gnu` | OOM-killed at ~27 min | 31391 → 22851 MiB | 38m43s → 22m04s | | `aarch64-unknown-linux-musl` | runner killed at ~28 min | >32 GiB → 16516 MiB | ~40 min → 20m50s | **ThinLTO** is most of that. Fat LTO is single-threaded, and its peak is consumed inside rustc's LLVM before any linker process is spawned — which is why it is the whole fix on musl, and why lld alone left the gnu leg still peaking at 31391 MiB against the runner's 32 GiB. Both legs now use the `lto: thin` / `codegen_units: 16` settings that darwin and both Windows legs already use, at a cost of a few percent runtime performance. **lld** covers the rest, on the gnu leg. arm64 Linux otherwise links through GNU `ld` where x86_64 already defaults to `rust-lld`, which is why only the arm64 legs hit this at all; on a comparable arm64 build (`lancedb/sophon#7313`) it cut the largest single linker process from 7.0 to 4.0 GiB and wall time by 35%. The flags live in a small wrapper script used as the linker rather than in `-C link-arg`, because the per-target rustflags variable does not reach every unit that links: dependency crates linking a dylib (`crc-fast`, `lance-arrow`) were invoked as bare `clang`, which targets the x86_64 host and fails with `Relocations in generic ELF (EM: 183)`. Separately, and affecting five legs rather than two: the three ThinLTO targets exported `CARGO_PROFILE_RELEASE_LTO` and `CARGO_PROFILE_RELEASE_CODEGEN_UNITS` from `pre_build`, which runs inside the build step — after the cache step. `Swatinem/rust-cache` computes its key when the action runs, before any step, so step-local values are invisible to it. The result is a loop that never converges: the key never changes, so restores are exact hits, an exact hit makes the post-run save a no-op, and cargo invalidates the restored artifacts anyway because the flags differ. Those legs have been rebuilding cold on every run. Both values move to job-level `env:` ahead of the cache step, driven by new `lto:`/`codegen_units:` matrix fields, and are forwarded into the containers with `-e` since `docker run` inherits nothing. Every leg's cache key shifts once as a result, so expect one cold rebuild. A `Report peak memory` step is added so whether these legs fit is a number rather than an inference from whether the runner survived. It produced the figures above. ## Not included Moving these legs to native arm64 runners. It would retire the zig cross path, the `AT_HWCAP2` workaround and the `TARGET_CC` override, and arm64 runners are billed roughly 37% below x64 at equal core count — but the `lts-debian-aarch64` image exists to link against the manylinux2014 sysroot's glibc 2.17, and building natively on ubuntu-24.04 would raise the minimum glibc for every published aarch64 binary. That is a user-facing decision, not a CI cleanup. Dropping these legs to smaller runners, which is where the real cost saving is — larger runners are billed even on public repos. On these numbers it is not available yet: musl at 16516 MiB is about 130 MiB over what a 16 GB standard runner has. Worth revisiting as a follow-up. ## Testing Cargo's rustflags precedence was checked locally rather than taken from the docs, since getting it wrong would silently change the published binaries. With a throwaway crate carrying both a `target.'cfg(all())'` and a per-target rustflags table: setting `RUSTFLAGS` discards both, and setting it to the empty string discards them too. That rules out routing the linker flag through a job-level `RUSTFLAGS`, because `env:` keys cannot be conditionally omitted and every other leg would then silently lose the `target-cpu`/`target-feature` settings in `.cargo/config.toml` — `+avx2` on x86_64 and `-crt-static` on aarch64-musl. --------- Co-authored-by: Claude Opus 5 (1M context) --- .github/workflows/npm-publish.yml | 102 ++++++++++++++++++++++-------- 1 file changed, 74 insertions(+), 28 deletions(-) diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index 72ef5ad13..ee6906e00 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -40,40 +40,31 @@ jobs: - target: aarch64-apple-darwin host: macos-latest features: fp16kernels + # Fat LTO was ~111 of this job's ~113 minutes. + lto: thin + codegen_units: 16 pre_build: |- brew install protobuf - # Fat LTO (the workspace default in .cargo/config.toml) is - # single-threaded and is the peak-memory step of the build. On - # this runner it accounted for ~111 of the job's ~113 minutes, - # making it the critical path of the entire publish pipeline. - # ThinLTO parallelizes it across the runner's cores, for a few - # percent of runtime performance. - export CARGO_PROFILE_RELEASE_LTO=thin - export CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 - target: x86_64-pc-windows-msvc host: windows-2025 features: "," + # The lower peak also keeps this on the standard 4-core runner. + lto: thin + codegen_units: 16 pre_build: |- choco install --no-progress protoc ninja nasm tail -n 1000 /c/ProgramData/chocolatey/logs/chocolatey.log # There is an issue where choco doesn't add nasm to the path export PATH="$PATH:/c/Program Files/NASM" nasm -v - # See the ThinLTO note on aarch64-apple-darwin above. Keeping - # peak memory down is also what lets this run on the standard - # 4-core runner: the 8-core larger runner was only needed to - # stop fat LTO from OOMing rustc-LLVM. - export CARGO_PROFILE_RELEASE_LTO=thin - export CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 - target: aarch64-pc-windows-msvc host: windows-2025 features: "," + lto: thin + codegen_units: 16 pre_build: |- choco install --no-progress protoc rustup target add aarch64-pc-windows-msvc - # See the ThinLTO note on aarch64-apple-darwin above. - export CARGO_PROFILE_RELEASE_LTO=thin - export CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 - target: x86_64-unknown-linux-gnu host: ubuntu-latest features: fp16kernels @@ -103,6 +94,14 @@ jobs: # https://github.com/napi-rs/napi-rs/blob/main/debian-aarch64.Dockerfile docker: ghcr.io/napi-rs/napi-rs/nodejs-rust:lts-debian-aarch64 features: "fp16kernels" + # Fat LTO OOM-killed rustc every nightly; even with lld it peaked + # at 31391 MiB of the runner's 32 GiB. + lto: thin + codegen_units: 16 + # arm64 Linux links through GNU `ld` where x86_64 defaults to + # `rust-lld`, which is why only arm64 OOM'd. lld cut the largest + # linker process 7.0 -> 4.0 GiB (lancedb/sophon#7313). + linker: /tmp/aarch64-lld-clang pre_build: |- set -e && apt-get update && @@ -112,9 +111,30 @@ jobs: # AT_HWCAP2 (added in Linux 3.17). Define it for aws-lc-sys. export CFLAGS="$CFLAGS -DAT_HWCAP2=26" && rustup target add aarch64-unknown-linux-gnu + # Not `&&`-chained: in dash, errexit does not fire for a + # non-final command in an `&&` list, so failures were ignored. + # + # A wrapper rather than `-C link-arg` because the per-target + # rustflags variable does not reach every unit that links, while + # the linker variable does. `clang` because GCC silently ignores + # `-fuse-ld=lld` unless built with lld support. Two echoes + # because printf's newline escape gets rewritten to `;` between + # here and the container. + echo '#!/bin/sh' > /tmp/aarch64-lld-clang + echo 'exec clang --target=aarch64-unknown-linux-gnu --sysroot=/usr/aarch64-unknown-linux-gnu/aarch64-unknown-linux-gnu/sysroot --gcc-toolchain=/usr/aarch64-unknown-linux-gnu -fuse-ld=lld "$@"' >> /tmp/aarch64-lld-clang + chmod 0755 /tmp/aarch64-lld-clang + # Fail now, not at the cdylib link ~30 minutes later. Linking at + # all also proves lld resolved; clang errors out when it cannot. + echo 'int main(void){return 0;}' > /tmp/probe.c + /tmp/aarch64-lld-clang /tmp/probe.c -o /tmp/probe + readelf -h /tmp/probe | grep AArch64 - target: aarch64-unknown-linux-musl host: ubuntu-2404-8x-x64 features: "," + # Fat LTO took the whole runner down. lld cannot help: it died + # inside rustc's LLVM, before any linker was spawned. + lto: thin + codegen_units: 16 pre_build: |- set -e && sudo apt-get update && @@ -123,6 +143,19 @@ jobs: export EXTRA_ARGS="-x" name: build - ${{ matrix.settings.target }} runs-on: ${{ matrix.settings.host }} + # On the job, not exported from `pre_build`: `Swatinem/rust-cache` hashes + # `CARGO_*` into its cache key before any step runs, so a step-local export + # leaves the key unchanged while cargo still rebuilds cold. The ThinLTO + # legs had been doing that every run. + # + # Not `RUSTFLAGS`: setting it, even to "", discards every config-file + # rustflag, silently dropping .cargo/config.toml's `target-cpu` and + # `target-feature` from the published binaries. + env: + CARGO_PROFILE_RELEASE_LTO: ${{ matrix.settings.lto || 'fat' }} + CARGO_PROFILE_RELEASE_CODEGEN_UNITS: ${{ matrix.settings.codegen_units || '1' }} + # Empty elsewhere: a per-target variable is only read for that triple. + CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: ${{ matrix.settings.linker }} defaults: run: working-directory: nodejs @@ -169,19 +202,15 @@ jobs: # creating ref). The nightly cadence also keeps entries inside # GitHub's 7-day eviction window, which a tag-only trigger would not. save-if: ${{ github.ref == 'refs/heads/main' }} - # Docker builds can use rust-cache too. `target/` already lives on the - # host because the whole workspace is bind-mounted into the container, and - # rust-cache's prune and save run host-side, so they can manage it -- which - # is what keeps the entry to dependency artifacts rather than a multi-GB - # copy of everything. + # Docker builds can use rust-cache too: the workspace is bind-mounted, so + # `target/` lives on the host and rust-cache's prune keeps the entry + # small. # # Two differences from the native builds. The container's CARGO_HOME is - # bind-mounted from `.cargo-cache` rather than the host's ~/.cargo, so that - # has to be cached explicitly. And the key is derived from the *host* rustc - # version, which is not the compiler that produced these artifacts; that is - # safe because cargo fingerprints the real compiler and rebuilds on a - # mismatch, it just means a base-image toolchain bump costs one cold build - # instead of invalidating the key. + # bind-mounted from `.cargo-cache` rather than ~/.cargo, so that is cached + # explicitly. And the key uses the *host* rustc version, not the compiler + # 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 if: ${{ matrix.settings.docker }} @@ -210,9 +239,14 @@ jobs: # cache step above saves. Previously the registry mounts pointed at # `.cargo/...`, a path nothing cached, so the container re-downloaded # the whole crate registry on every run. + # + # `docker run` inherits nothing; `-e NAME` carries the job's `env:` in. options: "--user 0:0 -v ${{ github.workspace }}/.cargo-cache/git/db:/usr/local/cargo/git/db \ -v ${{ github.workspace }}/.cargo-cache/registry/cache:/usr/local/cargo/registry/cache \ -v ${{ github.workspace }}/.cargo-cache/registry/index:/usr/local/cargo/registry/index \ + -e CARGO_PROFILE_RELEASE_LTO \ + -e CARGO_PROFILE_RELEASE_CODEGEN_UNITS \ + -e CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER \ -v ${{ github.workspace }}:/build -w /build/nodejs" run: | set -e @@ -256,6 +290,18 @@ jobs: if: always() run: df -h shell: bash + - name: Report peak memory + if: always() && runner.os == 'Linux' + shell: bash + run: | + peak=$(find /sys/fs/cgroup -name memory.peak -readable \ + -exec cat {} + 2>/dev/null | sort -n | tail -1) + if [ -n "$peak" ]; then + echo "peak memory: $((peak / 1024 / 1024)) MiB" + else + echo "peak memory: unavailable (no readable cgroup v2 memory.peak)" + fi + free -g || true - name: Upload artifact uses: actions/upload-artifact@v7 with: From 6c8aa22704690bf9875ef446897c43e864bfc502 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Thu, 27 Aug 2026 17:47:27 -0700 Subject: [PATCH 141/206] feat: let a computed-column batch read its own earlier declarations (#4072) `add_columns().computed()` accepted several columns in one call but bound each against the table's schema as it stood before the call, so `a` and `b = a + 1` had to be two commits. A server staging declarations behind other schema work has no atomic way to do that, and a caller reading the builder's plural signature reasonably expects the batch to be one. Each accepted column now joins the schema the next one resolves against, so the batch is planned and committed as one. Order is the dependency order; reading ahead is still an unknown column. `validate_declarations` exposes the schema-level checks -- the Function-binding guard and the planning -- without a commit, for callers that must reject before earlier work in the same request lands; LSM state is table state and stays a commit-time check. Refresh order matters for a dependent column: `b = coalesce(a, 0)` refreshed before `a` would bake zeros from `a`'s placeholder null, and the fill-once contract keeps them. Refresh now refuses, naming the input, while a computed input still has rows a refresh of it would fill -- the same probe refresh already uses to detect a no-op. Otherwise it is one snapshot and one commit, as before; a concurrent append is not in the commit and waits for the next refresh. Refreshing dependencies on the caller's behalf was considered and rejected: it is not how materialized views or our own backfill scheduler behave, and it needs multi-commit fencing that an explicit per-row fill marker would make unnecessary. --- rust/lancedb/src/table/computed_columns.rs | 105 +++++++++++- rust/lancedb/src/table/refresh.rs | 190 +++++++++++++++++++-- 2 files changed, 270 insertions(+), 25 deletions(-) diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 2b95cb34c..0f89ca612 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -22,7 +22,7 @@ use std::collections::{BTreeSet, HashMap}; use std::sync::Arc; -use arrow_schema::{DataType, Field as ArrowField, Schema as ArrowSchema, SchemaRef}; +use arrow_schema::{DataType, Field as ArrowField, Fields, Schema as ArrowSchema, SchemaRef}; use datafusion_common::tree_node::TreeNode; use datafusion_physical_plan::PhysicalExpr; use lance::dataset::NewColumnTransform; @@ -1273,6 +1273,11 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< /// refresh time: that the expression parses, that every column it reads /// exists, and that the target name is free. A declaration that survives this /// is one a refresh can always act on. +/// +/// Each accepted column joins the schema the next one resolves against, so a +/// 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. pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result> { if columns.is_empty() { return Err(Error::InvalidInput { @@ -1280,11 +1285,11 @@ pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result = Vec::with_capacity(columns.len()); for (name, expression) in columns { - if schema.field_with_name(name).is_ok() || declared.contains(&name.as_str()) { + if schema.field_with_name(name).is_ok() { return Err(Error::ColumnAlreadyExists { name: name.clone() }); } @@ -1292,16 +1297,50 @@ pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result(), + schema.metadata().clone(), + )); + fields.push(field); } Ok(fields) } +/// Run the schema-level checks of +/// [`AddColumnsBuilder::computed`](super::AddColumnsBuilder::computed) against +/// `schema` without committing: the Function-binding guard and the planning of +/// every declaration. For callers that stage declarations behind other work +/// and need those rejections before any of it lands. +/// +/// Only the schema is consulted. Declaring also refuses a table with an LSM +/// write spec or retained SSTables; that is table state, checked at commit. +/// +/// ``` +/// # use std::sync::Arc; +/// # use arrow_schema::{DataType, Field, Schema}; +/// use lancedb::table::computed_columns::validate_declarations; +/// +/// let schema = Arc::new(Schema::new(vec![Field::new("x", DataType::Int32, false)])); +/// let declarations = vec![ +/// ("a".to_string(), "x + 1".to_string()), +/// ("b".to_string(), "a * 2".to_string()), +/// ]; +/// assert!(validate_declarations(schema.clone(), &declarations).is_ok()); +/// assert!(validate_declarations(schema, &[("c".into(), "random()".into())]).is_err()); +/// ``` +pub fn validate_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result<()> { + ensure_no_function_bindings_for_mutation(schema.as_ref(), "schema evolution")?; + plan(schema, columns).map(drop) +} + /// Build the transform that declares `columns` against `schema`. /// /// An all-null column is how a binding with no values yet is carried into a @@ -1340,6 +1379,22 @@ pub(super) async fn add_foreign_kind(table: &crate::Table, name: &str, kind: &st #[cfg(test)] mod tests { + /// 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. + #[test] + fn test_validate_declarations_matches_schema_admission_barriers() { + let schema = Arc::new(ArrowSchema::new_with_metadata( + vec![ArrowField::new("x", DataType::Int32, true)], + HashMap::from([( + FUNCTION_BINDINGS_META_KEY.to_string(), + "not valid binding metadata".to_string(), + )]), + )); + let declarations = vec![("a".to_string(), "x + 1".to_string())]; + assert!(super::validate_declarations(schema, &declarations).is_err()); + } + #[test] fn output_arrow_type_grammar_matches_the_shared_golden() { let golden: serde_json::Value = serde_json::from_str(include_str!( @@ -1582,6 +1637,40 @@ mod tests { assert!(declared(&table).await.is_empty()); } + /// A batch may build on itself: one commit, and the later entry's inputs + /// name the earlier one. + #[tokio::test] + async fn test_a_declaration_may_read_one_declared_before_it() { + let table = table_with_ints("chain").await; + let before = table.version().await.unwrap(); + add_computed( + &table, + &[("a".into(), "x + 1".into()), ("b".into(), "a * 2".into())], + ) + .await + .unwrap(); + assert_eq!(table.version().await.unwrap(), before + 1); + let declared = declared(&table).await; + assert_eq!(declared[1].name, "b"); + assert_eq!(declared[1].inputs, vec!["a".to_string()]); + + // Order is the dependency order; reading ahead is still unknown. + let err = add_computed( + &table, + &[("c".into(), "d + 1".into()), ("d".into(), "x + 1".into())], + ) + .await + .unwrap_err(); + assert!(matches!(err, Error::InvalidExpression { column, .. } if column == "c")); + assert!( + validate_declarations( + table.schema().await.unwrap(), + &[("e".into(), "random()".into())] + ) + .is_err() + ); + } + /// A column added by an ordinary transform is materialized, not bound, so /// it carries no declaration to report. #[tokio::test] diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 35f883411..bc2cc38d1 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -7,6 +7,16 @@ //! therefore idempotent and does not observe input mutation -- once a row is //! filled, changing what the expression reads leaves the stored result alone. //! +//! A column's computed inputs are filled first -- the dependency graph is +//! walked once, each reachable column filled once in dependency order, each +//! fill its own commit. Every fill in the pass, the requested column's +//! included, covers only the fragments of the snapshot the pass started +//! from: a commit may rebase over a concurrent append, and the fragment that +//! admits carries placeholder nulls no earlier fill covered, so it waits for +//! a later refresh rather than being read as values. Two concurrent fills of +//! one input collide on its field in lance's conflict check, so a dependent +//! fill can only commit over inputs that were durable when it read them. +//! //! Two passes per fragment. The first scans only the unfilled live rows and //! evaluates the expression over them, which yields the exact fill count and //! decides whether the fragment is staged at all -- a fragment where nothing @@ -41,7 +51,8 @@ use crate::{Error, Result}; /// The result of refreshing a computed column. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] pub struct RefreshColumnResult { - /// Rows that had a value computed. + /// Rows that had a value computed, in the requested column only; inputs + /// filled on its behalf are not counted. #[serde(default)] pub rows_filled: u64, /// The commit version associated with the operation. @@ -52,6 +63,7 @@ pub struct RefreshColumnResult { struct RefreshExecution { result: RefreshColumnResult, source_version: u64, + published_version: Option, } /// Internal implementation of the refresh logic. @@ -74,7 +86,12 @@ async fn execute_refresh_column_with_source( let expression = declared_expression(&dataset, column)?; let schema = Arc::new(ArrowSchema::from(dataset.schema())); - let bound = Arc::new(super::computed_columns::bind(schema, column, &expression)?); + let bound = Arc::new(super::computed_columns::bind( + schema.clone(), + column, + &expression, + )?); + ensure_inputs_filled(&dataset, &schema, column, &bound).await?; let field = dataset .schema() .field(column) @@ -100,25 +117,25 @@ async fn execute_refresh_column_with_source( replacements.push(fragment.write_columns(values, &column_schema).await?); } + let source_version = dataset.version().version; if replacements.is_empty() { - let source_version = dataset.version().version; return Ok(RefreshExecution { result: RefreshColumnResult { rows_filled: 0, version: source_version, }, source_version, + published_version: None, }); } - let read_version = dataset.version().version; // The dataset's own session, so registrations and caches survive the // commit being installed on the handle. let session = dataset.session(); let new_dataset = Dataset::commit( WriteDestination::Dataset(dataset.clone()), Operation::DataReplacement { replacements }, - Some(read_version), + Some(source_version), None, None, session, @@ -133,10 +150,52 @@ async fn execute_refresh_column_with_source( rows_filled, version, }, - source_version: read_version, + source_version, + published_version: Some(version), }) } +/// Refuse while a computed input still has rows a refresh of it would fill: +/// read now, its placeholder null would be evaluated as a value and kept. +async fn ensure_inputs_filled( + dataset: &Dataset, + schema: &Arc, + column: &str, + bound: &BoundExpression, +) -> Result<()> { + for input in &bound.roots { + let Some(declaration) = schema + .field_with_name(input) + .ok() + .and_then(computed_column_from_field) + else { + continue; + }; + let ComputedColumnKind::Sql { expression } = &declaration.kind else { + return Err(Error::NotSupported { + message: format!( + "computed column '{column}' reads '{input}', whose fill state this \ + refresh cannot check; refresh '{input}' first" + ), + }); + }; + let input_bound = super::computed_columns::bind(schema.clone(), input, expression)?; + let mut unfilled = 0u64; + for fragment in dataset.get_fragments() { + unfilled += count_fragment_gains(dataset, &fragment, &input_bound, input).await?; + } + if unfilled > 0 { + return Err(Error::InvalidInput { + message: format!( + "computed column '{column}' reads '{input}', which has {unfilled} unfilled \ + rows; refresh '{input}' first" + ), + }); + } + } + Ok(()) +} + /// Run the refresh as a [`Job`] in this process. pub(crate) async fn execute_refresh_column_async( table: &NativeTable, @@ -160,8 +219,7 @@ pub(crate) async fn execute_refresh_column_async( rows_failed: 0, rows_remaining: 0, source_version: execution.source_version, - published_version: (execution.result.rows_filled > 0) - .then_some(execution.result.version), + published_version: execution.published_version, }) }))) } @@ -384,7 +442,8 @@ mod tests { .version) } - async fn read(table: &Table, column: &str) -> Vec> { + async fn read(table: &Table, column: &str) -> Vec> { + use arrow_array::{Array, Int64Array}; let batches = table .query() .select(Select::columns(&[column])) @@ -394,15 +453,19 @@ mod tests { .try_collect::>() .await .unwrap(); - let mut values: Vec> = batches + let mut values: Vec> = batches .iter() .flat_map(|batch| { - batch[column] - .as_any() - .downcast_ref::() - .unwrap() - .iter() - .collect::>() + let array = &batch[column]; + match array.as_any().downcast_ref::() { + Some(ints) => ints.iter().map(|v| v.map(i64::from)).collect::>(), + None => array + .as_any() + .downcast_ref::() + .unwrap() + .iter() + .collect::>(), + } }) .collect(); values.sort(); @@ -414,6 +477,98 @@ mod tests { table.add(batch).execute().await.unwrap(); } + /// The gate's reproducer: `b = coalesce(a, 0)` refreshed before `a` + /// must not bake zeros from `a`'s placeholder null. It is refused, and + /// names the input, until `a` is filled -- after every append too. + #[tokio::test] + async fn test_dependent_refresh_refuses_an_unfilled_input() { + let table = table_with("dependent_refresh_order", vec![1, 2, 3]).await; + table + .add_columns() + .computed("a", "x + 1") + .computed("b", "coalesce(a, 0)") + .execute() + .await + .unwrap(); + + let err = table.refresh_column("b").await.unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("refresh 'a' first")), + "{err}" + ); + assert_eq!(read(&table, "b").await, vec![None, None, None]); + + assert_eq!(table.refresh_column("a").await.unwrap().rows_filled, 3); + assert_eq!(table.refresh_column("b").await.unwrap().rows_filled, 3); + assert_eq!(read(&table, "b").await, vec![Some(2), Some(3), Some(4)]); + + append(&table, vec![10]).await; + assert!(table.refresh_column("b").await.is_err()); + table.refresh_column("a").await.unwrap(); + assert_eq!(table.refresh_column("b").await.unwrap().rows_filled, 1); + assert_eq!( + table.count_rows(Some("b = 0".to_string())).await.unwrap(), + 0 + ); + } + + /// Names that need quoting, and a nested input, survive the trip through + /// declaration metadata and the dependency check: the recorded inputs + /// are matched by name, never re-parsed as SQL. + #[tokio::test] + async fn test_dependent_refresh_handles_awkward_column_names() { + use arrow_array::{Int32Array, StructArray}; + use arrow_schema::{DataType, Field, Fields}; + + let conn = connect("memory://").execute().await.unwrap(); + let age_fields = Fields::from(vec![Field::new("age", DataType::Int32, true)]); + let meta = StructArray::new( + age_fields.clone(), + vec![Arc::new(Int32Array::from(vec![10, 20])) as _], + None, + ); + let schema = Arc::new(arrow_schema::Schema::new(vec![ + Field::new("camelCase", DataType::Int32, true), + Field::new("with-hyphen", DataType::Int32, true), + Field::new("meta", DataType::Struct(age_fields), true), + ])); + let batch = arrow_array::RecordBatch::try_new( + schema, + vec![ + Arc::new(Int32Array::from(vec![1, 2])) as _, + Arc::new(Int32Array::from(vec![100, 200])) as _, + Arc::new(meta) as _, + ], + ) + .unwrap(); + let table = conn + .create_table("awkward_names", batch) + .execute() + .await + .unwrap(); + + table + .add_columns() + .computed("y", "`camelCase` * 2") + .computed("z", "coalesce(y, 0) + `with-hyphen` + meta.age") + .execute() + .await + .unwrap(); + let z = crate::table::computed_columns::computed_columns( + table.schema().await.unwrap().as_ref(), + ) + .into_iter() + .find(|c| c.name == "z") + .unwrap(); + assert_eq!(z.inputs, vec!["meta.age", "with-hyphen", "y"]); + + let err = table.refresh_column("z").await.unwrap_err(); + assert!(err.to_string().contains("refresh 'y' first"), "{err}"); + assert_eq!(table.refresh_column("y").await.unwrap().rows_filled, 2); + assert_eq!(table.refresh_column("z").await.unwrap().rows_filled, 2); + assert_eq!(read(&table, "z").await, vec![Some(112), Some(224)]); + } + #[tokio::test] async fn test_refresh_fills_a_declared_column() { let table = table_with("refresh_fills", vec![1, 2, 3]).await; @@ -651,7 +806,8 @@ mod tests { let read_back = read(&table, "doubled").await; assert_eq!(read_back.len(), 20_000); - let mut expected: Vec> = values.iter().map(|v| Some(v * 2)).collect(); + let mut expected: Vec> = + values.iter().map(|v| Some(i64::from(v * 2))).collect(); expected.sort(); assert_eq!(read_back, expected); } From c94d9a2a166eca9606c8308d6d25946c44f1b6a5 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Fri, 28 Aug 2026 00:51:15 +0000 Subject: [PATCH 142/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.11=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.12?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package-lock.json | 4 ++-- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 17 files changed, 20 insertions(+), 20 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 2e0b78bf3..3d57dc0fe 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.11" +current_version = "0.38.0-beta.12" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 822689a0c..f12988efa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.11" +version = "0.38.0-beta.12" dependencies = [ "ahash", "anyhow", @@ -5490,7 +5490,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.11" +version = "0.38.0-beta.12" dependencies = [ "arrow-array", "arrow-buffer", @@ -5515,7 +5515,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.11" +version = "0.38.0-beta.12" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 1ce012522..e19880e29 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.38.0-beta.11 + 0.38.0-beta.12 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index c6acc7dfe..3864ed127 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.11 + 0.38.0-beta.12 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 0b85b69df..b3521f9c6 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.11 + 0.38.0-beta.12 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 6496c6384..c3b69424f 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.11" +version = "0.38.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 38b3db7d7..2b8d43c3d 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.38.0-beta.11", + "version": "0.38.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 a256cb1ee..6656fdd5c 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.38.0-beta.11", + "version": "0.38.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 567b785b0..f8f3e151f 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.38.0-beta.11", + "version": "0.38.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 4443a2748..20efa860a 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.38.0-beta.11", + "version": "0.38.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 5c0710d56..4b735a687 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.38.0-beta.11", + "version": "0.38.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 648c985f1..35fee5ee0 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.38.0-beta.11", + "version": "0.38.0-beta.12", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 1f3bfdeb8..925211fbe 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.38.0-beta.11", + "version": "0.38.0-beta.12", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json index d46f08628..b996b0810 100644 --- a/nodejs/package-lock.json +++ b/nodejs/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.11", + "version": "0.38.0-beta.12", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lancedb/lancedb", - "version": "0.38.0-beta.11", + "version": "0.38.0-beta.12", "cpu": [ "x64", "arm64" diff --git a/nodejs/package.json b/nodejs/package.json index 665e2a522..19c7f4d32 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.11", + "version": "0.38.0-beta.12", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index b97fad0ed..0ee561977 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.11" +version = "0.38.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 a71e3c948..881a5017e 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.11" +version = "0.38.0-beta.12" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 6ab3b9eb30d449d61ae8e1ca76744babb9052af5 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Thu, 27 Aug 2026 19:06:07 -0700 Subject: [PATCH 143/206] ci: upgrade chacha20 to 0.10.2 (#4078) The pinned version was yanked due to UB in some SIMD kernels. Upgrading. --- Cargo.lock | 4 ++-- deny.toml | 12 +----------- 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f12988efa..cff38a304 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1597,9 +1597,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "chacha20" -version = "0.10.0" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if 1.0.4", "cpufeatures 0.3.0", diff --git a/deny.toml b/deny.toml index 3672321d0..20510adc2 100644 --- a/deny.toml +++ b/deny.toml @@ -131,18 +131,13 @@ allow = [ "BSD-3-Clause", "ISC", "Unicode-3.0", - "Unicode-DFS-2016", "Zlib", "CC0-1.0", "MPL-2.0", "BSL-1.0", - "OpenSSL", # 0BSD ("BSD Zero Clause") is effectively public domain — no attribution # required. Pulled in by `mock_instant`. "0BSD", - # bzip2-1.0.6 is the permissive upstream bzip2 license (BSD-like). Pulled - # in by `libbz2-rs-sys`, the pure-Rust bzip2 implementation. - "bzip2-1.0.6", # CDLA-Permissive-2.0 is a permissive data license used by `webpki-roots` # for the Mozilla CA root bundle. Data-only, distribution-compatible. "CDLA-Permissive-2.0", @@ -150,12 +145,7 @@ allow = [ confidence-threshold = 0.8 # Per-crate license exceptions: allow a license for a specific crate only, # rather than globally via the `allow` list above. -exceptions = [ - # CDDL-1.0 (copyleft) is pulled in only as a dev/profiling dependency via - # `inferno` -> `pprof` -> `lance-testing`; it is a test dependency that we - # do not distribute, so scope the allowance to `inferno` alone. - { allow = ["CDDL-1.0"], crate = "inferno" }, -] +exceptions = [] # Crates whose license cannot be determined from Cargo metadata but whose # license we've manually confirmed from upstream. Keep this list minimal. [[licenses.clarify]] From 0559108fa94b29cc5db4d390d8b37794b9fcc41c Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 28 Aug 2026 17:23:49 +0800 Subject: [PATCH 144/206] feat: support blob computed column refresh (#4081) Computed-column planning currently sees Blob v2 storage descriptors, so expressions cannot consume payload bytes or preserve Blob semantics in their outputs. A computed declaration now derives its output field from its expression. A direct projection of a Blob v2 field inherits the source field's Blob metadata; other expressions retain their ordinary Arrow-inferred type. Declarations remain ordered, so the same rule applies across chained projections. Refresh materializes referenced Blob inputs as `LargeBinary` payload bytes and publishes inherited Blob outputs through Lance's Blob conversion path. Remote requests remain within the shared namespace contract as `{name, computed}`; the server planner is being updated in tandem to implement the same Blob-aware planning semantics, and remote enablement must be aligned with that server rollout. The existing null-as-unfilled contract remains unchanged. Row-level freshness and cell flags remain follow-up work. --- python/python/lancedb/remote/table.py | 10 +- python/python/lancedb/table.py | 15 +- python/python/tests/test_table.py | 23 + rust/lancedb/src/remote/table.rs | 8 +- rust/lancedb/src/table.rs | 4 +- rust/lancedb/src/table/computed_columns.rs | 289 ++++++++++-- rust/lancedb/src/table/refresh.rs | 522 ++++++++++++++++++++- 7 files changed, 821 insertions(+), 50 deletions(-) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 02748b9bc..55014a423 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -67,7 +67,15 @@ from ..query import ( LanceTakeQueryBuilder, LanceVectorQueryBuilder, ) -from ..table import AsyncTable, BlobMode, Branches, IndexStatistics, Query, Table, Tags +from ..table import ( + AsyncTable, + BlobMode, + Branches, + IndexStatistics, + Query, + Table, + Tags, +) from ..types import BaseTokenizerType diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 535ed7c0d..36c5b727d 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2165,9 +2165,11 @@ class Table(ABC): Function columns are supported only on LanceDB Cloud and Enterprise. computed: Dict[str, str], optional - A map of column name to a SQL expression defining the column. The - column's type and inputs are derived from the expression, so no - data type is supplied. + A mapping from output column names to SQL expressions derives each + output field from its expression. A direct projection of a Blob v2 + field inherits Blob v2 semantics; other expressions derive their + ordinary Arrow type. Mapping order is declaration and dependency + order. Unlike ``transforms``, the expression is stored rather than evaluated now: the column is committed with no values, and rows get @@ -6268,8 +6270,11 @@ class AsyncTable: Function columns are supported only on LanceDB Cloud and Enterprise. computed: Dict[str, str], optional - A map of column name to a SQL expression defining the column. The - column's type and inputs are derived from the expression. + A mapping from output column names to SQL expressions derives each + output field from its expression. A direct projection of a Blob v2 + field inherits Blob v2 semantics; other expressions derive their + ordinary Arrow type. Mapping order is declaration and dependency + order. Unlike ``transforms``, the expression is stored rather than evaluated now: the column is committed with no values, and rows get diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 0be9e139d..fbdfac5d8 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -4087,6 +4087,29 @@ def test_computed_column_rejects_transforms_and_computed_together(tmp_path): table.add_columns({"a": "x + 1"}, computed={"b": "x * 2"}) +def test_computed_column_blob_projection_inherits_semantics(tmp_path): + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + db = lancedb.connect(tmp_path) + table = db.create_table("computed_column_blob", schema=schema) + table.add( + [ + {"id": 1, "image": b"hello"}, + {"id": 2, "image": b""}, + {"id": 3, "image": None}, + ] + ) + + table.add_columns(computed={"image_copy": "image", "second_copy": "image_copy"}) + assert table.refresh_column("image_copy").rows_filled == 2 + assert table.refresh_column("second_copy").rows_filled == 2 + assert table.blob_columns() == ["image", "image_copy", "second_copy"] + + hits = table.search().with_row_id(True).limit(10).to_arrow() + rows = sorted(zip(hits["id"].to_pylist(), hits["_rowid"].to_pylist())) + copied = table.fetch_blobs("second_copy", [row_id for _, row_id in rows]) + assert copied.to_pylist() == [b"hello", b"", None] + + @pytest.mark.asyncio async def test_computed_column_async(tmp_path): db = await lancedb.connect_async(tmp_path) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 1afc2615a..57d2dc47d 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -3180,8 +3180,8 @@ impl BaseTable for RemoteTable { self.schema().await?.as_ref(), "schema evolution", )?; - // The server plans the declaration: expression validation, type - // inference and the persisted binding all happen there. + // The server plans the declaration against its table schema, including + // Blob v2 semantics inherited by a direct field projection. let entries = columns .iter() .map( @@ -7388,8 +7388,8 @@ mod tests { assert_eq!(result.version, if old_server { 0 } else { 43 }); } - /// A declaration is sent as `{name, computed}` entries for the server to - /// plan; the client never types the expression itself. + /// A declaration is sent as `{name, computed}` for the server to plan; the + /// client never types the expression itself. #[tokio::test] async fn test_add_computed_columns_sends_the_expression() { let table = Table::new_with_handler("my_table", |request| match request.url().path() { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 8436657ca..70b86f3cf 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -750,8 +750,8 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { /// Declare computed columns, each defined by a SQL expression. /// /// Where the declaration is planned depends on the backend: a local table - /// validates and types the expression itself, a remote one sends the text - /// for the server to plan. + /// validates and types the expression itself, while a remote one sends the + /// expression for the server to plan. async fn add_computed_columns( &self, _columns: &[(String, String)], diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 0f89ca612..4e8d8211e 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -9,29 +9,35 @@ //! refresh fills the rows. //! //! The rule is tagged by kind ([`ComputedColumnKind`]) because kinds differ in -//! where the column's type and inputs come from. A SQL expression is -//! self-describing -- both are derived from the expression, so a caller writes -//! neither -- while a kind resolved through a registry cannot be typed without -//! consulting it. Registered Functions use an exact remote version plus a -//! schema-level Function binding; unknown newer kinds remain readable and fail -//! closed before mutation. +//! where the column's type and inputs come from. A SQL expression determines +//! its inputs and physical result type. A direct projection of a Blob v2 field +//! also inherits that field's semantic type while execution continues to use +//! `LargeBinary`. A kind resolved through a registry cannot be typed without +//! consulting it. +//! Registered Functions use an exact remote version plus a schema-level +//! Function binding; unknown newer kinds remain readable and fail closed +//! before mutation. //! //! [`computed_columns`] and [`computed_column_from_field`] read declarations //! back off a schema. -use std::collections::{BTreeSet, HashMap}; +use std::collections::{BTreeSet, HashMap, HashSet}; use std::sync::Arc; use arrow_schema::{DataType, Field as ArrowField, Fields, Schema as ArrowSchema, SchemaRef}; -use datafusion_common::tree_node::TreeNode; +use datafusion_common::{ScalarValue, tree_node::TreeNode}; +use datafusion_expr::Expr; use datafusion_physical_plan::PhysicalExpr; use lance::dataset::NewColumnTransform; +use lance_arrow::FieldExt; +use lance_core::datatypes::{BLOB_V2_DESC_FIELD, format_field_path_minimal, parse_field_path}; use lance_datafusion::planner::Planner; use lance_namespace::models::{JsonArrowDataType, JsonArrowField, JsonArrowSchema}; use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::function::{FunctionApplication, FunctionBinding}; +use crate::utils::resolve_arrow_field_path; use crate::{Error, Result}; /// Field metadata key marking a column as computed. The value is `"true"`. @@ -1106,15 +1112,20 @@ pub(crate) fn ensure_no_foreign_declarations<'a>( fields: impl IntoIterator>, ) -> Result<()> { for field in fields { - if field.metadata().keys().any(|k| is_declaration_key(k)) { - return Err(Error::InvalidInput { - message: format!( - "field '{}' carries computed-column metadata; declare computed columns \ - with add_columns().computed()", - field.name() - ), - }); - } + ensure_no_foreign_declaration(field)?; + } + Ok(()) +} + +fn ensure_no_foreign_declaration(field: &ArrowField) -> Result<()> { + if field.metadata().keys().any(|k| is_declaration_key(k)) { + return Err(Error::InvalidInput { + message: format!( + "field '{}' carries computed-column metadata; declare computed columns \ + with add_columns().computed()", + field.name() + ), + }); } Ok(()) } @@ -1162,15 +1173,154 @@ pub(crate) struct BoundExpression { /// The columns the expression names, as written; nested inputs keep /// their dotted path. pub inputs: Vec, - /// The top-level columns evaluation reads, in [`Self::read_schema`] - /// order. A nested input appears through its root. + /// The top-level columns evaluation reads, in physical-expression order. + /// A nested input appears through its root. pub roots: Vec, - /// The projected schema evaluation runs against. - pub read_schema: SchemaRef, /// The compiled expression. pub physical: Arc, /// The type the expression yields. pub data_type: DataType, + /// Blob v2 leaves the scan must materialize as `LargeBinary`. + pub blob_paths: Vec, + /// A directly projected Blob v2 field whose semantics the output inherits. + projected_blob_field: Option, +} + +fn is_direct_field_projection(expr: &Expr) -> bool { + match expr { + Expr::Column(_) => true, + Expr::ScalarFunction(function) + if function.name() == "get_field" && function.args.len() == 2 => + { + is_direct_field_projection(&function.args[0]) + && matches!( + &function.args[1], + Expr::Literal(ScalarValue::Utf8(Some(_)), _) + ) + } + _ => false, + } +} + +fn projected_blob_field(schema: &ArrowSchema, expr: &Expr) -> Result> { + if !is_direct_field_projection(expr) { + return Ok(None); + } + let paths = Planner::column_names_in_expr(expr); + let [path] = paths.as_slice() else { + return Ok(None); + }; + let (_, field) = resolve_arrow_field_path(schema, path)?; + Ok(field.is_blob_v2().then_some(field)) +} + +fn collect_blob_paths(field: &ArrowField, parent: &[String], paths: &mut Vec>) { + let mut path = parent.to_vec(); + path.push(field.name().clone()); + if field.is_blob_v2() { + paths.push(path); + return; + } + match field.data_type() { + DataType::Struct(children) => { + for child in children { + collect_blob_paths(child, &path, paths); + } + } + DataType::List(child) + | DataType::LargeList(child) + | DataType::FixedSizeList(child, _) + | DataType::Map(child, _) => collect_blob_paths(child, &path, paths), + _ => {} + } +} + +fn schema_blob_paths(schema: &ArrowSchema) -> Vec> { + let mut paths = Vec::new(); + for field in schema.fields() { + collect_blob_paths(field, &[], &mut paths); + } + paths +} + +fn transform_blob_field( + field: &ArrowField, + parent: &[String], + materialized: &HashSet>, +) -> ArrowField { + let mut path = parent.to_vec(); + path.push(field.name().clone()); + if field.is_blob_v2() { + if materialized.contains(&path) { + return ArrowField::new(field.name(), DataType::LargeBinary, field.is_nullable()); + } + return ArrowField::new( + field.name(), + BLOB_V2_DESC_FIELD.data_type().clone(), + field.is_nullable(), + ) + .with_metadata(BLOB_V2_DESC_FIELD.metadata().clone()); + } + + let data_type = match field.data_type() { + DataType::Struct(children) => DataType::Struct( + children + .iter() + .map(|child| Arc::new(transform_blob_field(child, &path, materialized))) + .collect(), + ), + DataType::List(child) => { + DataType::List(Arc::new(transform_blob_field(child, &path, materialized))) + } + DataType::LargeList(child) => { + DataType::LargeList(Arc::new(transform_blob_field(child, &path, materialized))) + } + DataType::FixedSizeList(child, size) => DataType::FixedSizeList( + Arc::new(transform_blob_field(child, &path, materialized)), + *size, + ), + DataType::Map(child, sorted) => DataType::Map( + Arc::new(transform_blob_field(child, &path, materialized)), + *sorted, + ), + _ => return field.clone(), + }; + ArrowField::new(field.name(), data_type, field.is_nullable()) + .with_metadata(field.metadata().clone()) +} + +fn blob_runtime_schema(schema: &ArrowSchema, materialized: &HashSet>) -> SchemaRef { + Arc::new(ArrowSchema::new_with_metadata( + schema + .fields() + .iter() + .map(|field| Arc::new(transform_blob_field(field, &[], materialized))) + .collect::(), + schema.metadata().clone(), + )) +} + +fn referenced_blob_paths(schema: &ArrowSchema, inputs: &[String]) -> Result>> { + let input_paths = inputs + .iter() + .map(|input| { + parse_field_path(input).map_err(|error| Error::InvalidInput { + message: format!("invalid computed-column input path '{input}': {error}"), + }) + }) + .collect::>>()?; + Ok(schema_blob_paths(schema) + .into_iter() + .filter(|blob_path| { + input_paths.iter().any(|input_path| { + input_path.len() <= blob_path.len() + && input_path + .iter() + .zip(blob_path) + .all(|(input, blob)| input == blob) + }) + }) + .collect()) } /// Parse, resolve and compile `expression` against `schema`. @@ -1185,10 +1335,18 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< message, }; - let planner = Planner::new(schema.clone()); + // Blob v2 is a semantic type whose runtime expression ABI is + // `LargeBinary`. Parse against that ABI first so a direct Blob reference + // is not mistaken for its storage descriptor struct. + let all_blob_paths = schema_blob_paths(schema.as_ref()) + .into_iter() + .collect::>(); + let parsing_schema = blob_runtime_schema(schema.as_ref(), &all_blob_paths); + let planner = Planner::new(parsing_schema); let parsed = planner .parse_expr(expression) .map_err(|e| invalid(e.to_string()))?; + let projected_blob_field = projected_blob_field(schema.as_ref(), &parsed)?; // A declaration is evaluated more than once -- staging and writing are // separate passes, and a refresh years later replays the same text -- so @@ -1218,13 +1376,19 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< inputs.sort(); inputs.dedup(); + let blob_paths = referenced_blob_paths(schema.as_ref(), &inputs)?; + let runtime_schema = blob_runtime_schema( + schema.as_ref(), + &blob_paths.iter().cloned().collect::>(), + ); + // A nested input is recorded by its path but read through its root // column; Schema::index_of resolves top-level names only. Resolved here // rather than left to the planner so an unknown column names itself in // the error instead of surfacing as a plan failure. let mut indices = Vec::with_capacity(inputs.len()); for input in &inputs { - let index = schema + let index = runtime_schema .index_of(root(input)) .map_err(|_| invalid(format!("unknown column '{input}'")))?; if !indices.contains(&index) { @@ -1237,7 +1401,7 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< // compiles the expression has to be built on the projected schema // evaluation will actually read. let read_schema = Arc::new( - schema + runtime_schema .project(&indices) .map_err(|e| invalid(e.to_string()))?, ); @@ -1247,7 +1411,8 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< .map(|field| field.name().clone()) .collect(); - let optimized = planner + let runtime_planner = Planner::new(runtime_schema); + let optimized = runtime_planner .optimize_expr(parsed) .map_err(|e| invalid(e.to_string()))?; let physical = Planner::new(read_schema.clone()) @@ -1260,9 +1425,16 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result< Ok(BoundExpression { inputs, roots, - read_schema, physical, data_type, + blob_paths: blob_paths + .iter() + .map(|path| { + let segments = path.iter().map(String::as_str).collect::>(); + format_field_path_minimal(&segments) + }) + .collect(), + projected_blob_field, }) } @@ -1278,7 +1450,7 @@ 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. -pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result> { +fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result> { if columns.is_empty() { return Err(Error::InvalidInput { message: "at least one computed column is required".into(), @@ -1290,15 +1462,28 @@ pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result { + 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) + } + None => ArrowField::new(name, bound.data_type, true).with_metadata(computed_metadata), + }; schema = Arc::new(ArrowSchema::new_with_metadata( schema .fields() @@ -1314,6 +1499,10 @@ pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result Result> { + plan_declarations(schema, columns) +} + /// Run the schema-level checks of /// [`AddColumnsBuilder::computed`](super::AddColumnsBuilder::computed) against /// `schema` without committing: the Function-binding guard and the planning of @@ -1352,7 +1541,7 @@ pub(crate) fn declare( schema: SchemaRef, columns: &[(String, String)], ) -> Result { - let fields = plan(schema, columns)?; + let fields = plan_declarations(schema, columns)?; Ok(NewColumnTransform::AllNulls(Arc::new(ArrowSchema::new( fields, )))) @@ -1478,6 +1667,44 @@ mod tests { ); } + #[test] + fn test_direct_blob_projection_inherits_semantics() { + let schema = Arc::new(ArrowSchema::new(vec![crate::blob("image", false)])); + let fields = plan( + schema, + &[ + ("first".to_string(), "image".to_string()), + ("second".to_string(), "first".to_string()), + ], + ) + .unwrap(); + + for field in &fields { + assert!(field.is_blob_v2()); + assert!(field.is_nullable()); + } + assert_eq!( + fields[1] + .metadata() + .get(EXPRESSION_META_KEY) + .map(String::as_str), + Some("first") + ); + } + + #[test] + fn test_blob_expression_transformation_does_not_inherit_semantics() { + let schema = Arc::new(ArrowSchema::new(vec![crate::blob("image", true)])); + let fields = plan( + schema, + &[("payload".to_string(), "coalesce(image, image)".to_string())], + ) + .unwrap(); + + assert!(!fields[0].is_blob_v2()); + assert_eq!(fields[0].data_type(), &DataType::LargeBinary); + } + /// The binding reaches the schema only if `AllNulls` carries per-field /// metadata through the commit. The whole representation rests on it. #[tokio::test] diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index bc2cc38d1..511fce8ff 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -29,10 +29,14 @@ //! inputs masked to null first, so a poison value in a row nobody is filling //! cannot fail the refresh. +use std::collections::HashSet; use std::sync::Arc; -use arrow_array::{ArrayRef, BooleanArray, RecordBatch, RecordBatchOptions}; -use arrow_schema::Schema as ArrowSchema; +use arrow_array::{ + Array, ArrayRef, BooleanArray, LargeBinaryArray, RecordBatch, RecordBatchOptions, StructArray, + new_null_array, +}; +use arrow_schema::{DataType, Field as ArrowField, Schema as ArrowSchema}; use datafusion_expr::ColumnarValue; use futures::{Stream, StreamExt, TryStreamExt}; use lance::Dataset; @@ -40,7 +44,7 @@ use lance::dataset::WriteDestination; use lance::dataset::fragment::FileFragment; use lance::dataset::transaction::Operation; use lance_core::ROW_ID; -use lance_core::datatypes::Schema as LanceSchema; +use lance_core::datatypes::{BlobHandling, Schema as LanceSchema}; use serde::{Deserialize, Serialize}; use super::computed_columns::{BoundExpression, ComputedColumnKind, computed_column_from_field}; @@ -104,6 +108,7 @@ async fn execute_refresh_column_with_source( fields: vec![field.clone()], metadata: Default::default(), }; + let output_is_blob = field.is_blob_v2(); let mut rows_filled = 0u64; let mut replacements = Vec::new(); @@ -113,7 +118,8 @@ async fn execute_refresh_column_with_source( continue; } rows_filled += gained; - let values = fill_stream(&dataset, &fragment, bound.clone(), column).await?; + let values = + fill_stream(&dataset, &fragment, bound.clone(), column, output_is_blob).await?; replacements.push(fragment.write_columns(values, &column_schema).await?); } @@ -294,12 +300,15 @@ fn evaluation_batch( mask_out: Option<&BooleanArray>, ) -> lance_core::Result { let mut columns = Vec::with_capacity(bound.roots.len()); + let mut fields = Vec::with_capacity(bound.roots.len()); for name in &bound.roots { - let column = batch.column_by_name(name).ok_or_else(|| { + let index = batch.schema_ref().index_of(name).map_err(|_| { lance_core::Error::invalid_input(format!( "refreshing a computed column read no {name} column" )) })?; + let column = batch.column(index); + fields.push(batch.schema_ref().field(index).clone()); // Rows outside the mask must not reach the expression: a value in a // deleted or already-filled row can be one it would choke on. columns.push(match mask_out { @@ -308,7 +317,7 @@ fn evaluation_batch( }); } Ok(RecordBatch::try_new_with_options( - bound.read_schema.clone(), + Arc::new(ArrowSchema::new(fields)), columns, &RecordBatchOptions::new().with_row_count(Some(batch.num_rows())), )?) @@ -329,6 +338,99 @@ fn evaluate(bound: &BoundExpression, batch: &RecordBatch) -> lance_core::Result< } } +fn materialized_blob_ids(schema: &LanceSchema, paths: &[String]) -> Result> { + paths + .iter() + .map(|path| { + let field = schema + .resolve(path) + .and_then(|fields| fields.last().copied()) + .ok_or_else(|| Error::InvalidInput { + message: format!("computed Blob input '{path}' no longer exists"), + })?; + if !field.is_blob_v2() { + return Err(Error::InvalidInput { + message: format!("computed Blob input '{path}' is no longer Blob v2"), + }); + } + u32::try_from(field.id).map_err(|_| Error::InvalidInput { + message: format!( + "computed Blob input '{path}' has invalid field id {}", + field.id + ), + }) + }) + .collect() +} + +fn configure_blob_inputs( + scanner: &mut lance::dataset::scanner::Scanner, + schema: &LanceSchema, + bound: &BoundExpression, + extra_blob_id: Option, +) -> Result<()> { + let mut ids = materialized_blob_ids(schema, &bound.blob_paths)?; + ids.extend(extra_blob_id); + scanner.blob_handling(BlobHandling::SomeBlobsBinary(ids)); + Ok(()) +} + +fn blob_array_from_binary( + array: &ArrayRef, + target_field: &ArrowField, +) -> lance_core::Result { + let values = array + .as_any() + .downcast_ref::() + .ok_or_else(|| { + lance_core::Error::invalid_input(format!( + "a Blob v2 computed output produced {}, expected LargeBinary", + array.data_type() + )) + })?; + let mut builder = lance::blob::BlobArrayBuilder::new(values.len()); + for index in 0..values.len() { + if values.is_null(index) { + builder.push_null()?; + } else { + builder.push_bytes(values.value(index))?; + } + } + let minimal = builder.finish()?; + let minimal = minimal + .as_any() + .downcast_ref::() + .ok_or_else(|| lance_core::Error::internal("Blob builder returned a non-struct array"))?; + let DataType::Struct(target_fields) = target_field.data_type() else { + return Err(lance_core::Error::invalid_input(format!( + "Blob v2 output field '{}' has non-struct type {}", + target_field.name(), + target_field.data_type() + ))); + }; + let columns = target_fields + .iter() + .map(|field| match field.name().as_str() { + "data" | "uri" => minimal + .column_by_name(field.name()) + .cloned() + .ok_or_else(|| { + lance_core::Error::internal(format!("Blob builder omitted '{}'", field.name())) + }), + "position" | "size" => Ok(new_null_array(field.data_type(), minimal.len())), + name => Err(lance_core::Error::invalid_input(format!( + "Blob v2 output field '{}' has unsupported logical child '{name}'", + target_field.name() + ))), + }) + .collect::>>()?; + Ok(Arc::new(StructArray::try_new( + target_fields.clone(), + columns, + minimal.nulls().cloned(), + )?)) +} + /// How many rows of one fragment would gain a value. /// /// Scans only the unfilled live rows -- deleted rows never reach the @@ -347,6 +449,7 @@ async fn count_fragment_gains( .with_row_id() .filter(&format!("{} IS NULL", quote_identifier(column)))? .project(&bound.roots)?; + configure_blob_inputs(&mut scanner, dataset.schema(), bound, None)?; let mut gained = 0u64; let mut batches = scanner.try_into_stream().await?; @@ -368,6 +471,7 @@ async fn fill_stream( fragment: &FileFragment, bound: Arc, column: &str, + output_is_blob: bool, ) -> Result> + Send + use<>> { let mut projection: Vec = bound.roots.clone(); projection.push(column.to_string()); @@ -377,6 +481,20 @@ async fn fill_stream( .with_row_id() .include_deleted_rows() .project(&projection)?; + let output_blob_id = output_is_blob + .then(|| { + dataset + .schema() + .field(column) + .and_then(|field| u32::try_from(field.id).ok()) + }) + .flatten(); + configure_blob_inputs( + &mut scanner, + dataset.schema(), + bound.as_ref(), + output_blob_id, + )?; let projected = Arc::new(ArrowSchema::new(vec![ ArrowSchema::from(dataset.schema()) @@ -412,6 +530,11 @@ async fn fill_stream( let computed = evaluate(&bound, &evaluation_batch(&batch, &bound, Some(&keep))?)?; let merged = arrow_select::zip::zip(&fill, &computed, existing)?; + let merged = if output_is_blob { + blob_array_from_binary(&merged, projected.field(0))? + } else { + merged + }; Ok(RecordBatch::try_new(projected.clone(), vec![merged])?) })) } @@ -420,8 +543,12 @@ async fn fill_stream( mod tests { use std::sync::Arc; - use arrow_array::{Int32Array, record_batch}; + use arrow_array::{ + Array, ArrayRef, Int32Array, LargeBinaryArray, RecordBatch, StructArray, record_batch, + }; + use arrow_schema::Field as ArrowField; use futures::TryStreamExt; + use lance_core::ROW_ID; use crate::connect; use crate::query::{ExecutableQuery, QueryBase, Select}; @@ -477,6 +604,25 @@ mod tests { table.add(batch).execute().await.unwrap(); } + #[test] + fn test_blob_output_matches_complete_logical_field() { + let values: ArrayRef = Arc::new(LargeBinaryArray::from(vec![ + Some(b"hello".as_slice()), + None, + ])); + let field = ArrowField::new( + "image", + lance_core::datatypes::BLOB_V2_LOGICAL_TYPE.clone(), + true, + ); + + let output = super::blob_array_from_binary(&values, &field).unwrap(); + assert_eq!(output.data_type(), field.data_type()); + let output = output.as_any().downcast_ref::().unwrap(); + assert_eq!(output.column_by_name("position").unwrap().null_count(), 2); + assert_eq!(output.column_by_name("size").unwrap().null_count(), 2); + } + /// The gate's reproducer: `b = coalesce(a, 0)` refreshed before `a` /// must not bake zeros from `a`'s placeholder null. It is refused, and /// names the input, until `a` is filled -- after every append too. @@ -1164,4 +1310,366 @@ mod tests { let err = table.refresh_column("embedding").await.unwrap_err(); assert!(matches!(err, Error::NotSupported { message } if message.contains("udf"))); } + + fn blob_batch(ids: Vec, payloads: Vec>) -> RecordBatch { + use arrow_array::Int32Array; + use arrow_schema::{Field, Schema}; + + let mut builder = lance::blob::BlobArrayBuilder::new(payloads.len()); + for payload in payloads { + match payload { + Some(payload) => builder.push_bytes(payload).unwrap(), + None => builder.push_null().unwrap(), + } + } + RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", arrow_schema::DataType::Int32, false), + crate::blob("image", true), + ])), + vec![Arc::new(Int32Array::from(ids)), builder.finish().unwrap()], + ) + .unwrap() + } + + async fn create_blob_table(path: &std::path::Path, batch: RecordBatch) -> Table { + let conn = connect(path.to_str().unwrap()).execute().await.unwrap(); + conn.create_table("blobs", batch).execute().await.unwrap() + } + + #[tokio::test] + async fn test_refresh_inherits_and_publishes_blob_output() { + use arrow_array::UInt64Array; + use lance_arrow::{ + BLOB_DEDICATED_SIZE_THRESHOLD_META_KEY, BLOB_INLINE_SIZE_THRESHOLD_META_KEY, + }; + use lance_core::datatypes::BlobKind; + + use crate::table::schema_evolution::FieldMetadataUpdate; + + let tmp = tempfile::tempdir().unwrap(); + let table = create_blob_table( + tmp.path(), + blob_batch( + vec![1, 2, 3, 4], + vec![Some(b"hello"), Some(b"ab"), Some(b""), None], + ), + ) + .await; + table + .add_columns() + .computed("image_copy", "image") + .execute() + .await + .unwrap(); + table + .update_field_metadata(&[FieldMetadataUpdate::new("image_copy") + .set(BLOB_INLINE_SIZE_THRESHOLD_META_KEY, "1") + .set(BLOB_DEDICATED_SIZE_THRESHOLD_META_KEY, "4")]) + .await + .unwrap(); + + let first_refresh = table.refresh_column("image_copy").await.unwrap(); + assert_eq!(first_refresh.rows_filled, 3); + assert_eq!( + table.blob_columns().await.unwrap(), + vec!["image".to_string(), "image_copy".to_string()] + ); + + let batches = table + .query() + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let batch = arrow_select::concat::concat_batches(&batches[0].schema(), &batches).unwrap(); + assert!( + batch + .column_by_name("image_copy") + .unwrap() + .as_any() + .is::() + ); + let row_ids = batch + .column_by_name(ROW_ID) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec(); + let original = table.fetch_blobs("image", &row_ids).await.unwrap(); + let copied = table.fetch_blobs("image_copy", &row_ids).await.unwrap(); + assert_eq!(original, copied); + let ids = batch + .column_by_name("id") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + let files = table + .fetch_blob_files("image_copy", &row_ids) + .await + .unwrap(); + let mut layouts = ids + .values() + .iter() + .copied() + .zip(files) + .map(|(id, file)| (id, file.and_then(|file| file.kind()))) + .collect::>(); + layouts.sort_by_key(|(id, _)| *id); + assert_eq!( + layouts, + vec![ + (1, Some(BlobKind::Dedicated)), + (2, Some(BlobKind::Packed)), + (3, Some(BlobKind::Inline)), + (4, None), + ] + ); + + table + .add(blob_batch(vec![5], vec![Some(b"appended")])) + .execute() + .await + .unwrap(); + table + .optimize(crate::table::OptimizeAction::Compact { + options: crate::table::CompactionOptions::default(), + remap_options: None, + }) + .await + .unwrap(); + assert_eq!( + table + .refresh_column("image_copy") + .await + .unwrap() + .rows_filled, + 1 + ); + assert_eq!( + table + .refresh_column("image_copy") + .await + .unwrap() + .rows_filled, + 0 + ); + + table.checkout(first_refresh.version).await.unwrap(); + assert_eq!(table.count_rows(None).await.unwrap(), 4); + assert_eq!( + table.blob_columns().await.unwrap(), + vec!["image".to_string(), "image_copy".to_string()] + ); + table.checkout_latest().await.unwrap(); + } + + #[tokio::test] + async fn test_refresh_inherits_nested_struct_blob_input() { + use arrow_array::{Int32Array, StructArray, UInt64Array}; + use arrow_schema::{DataType, Field, Fields, Schema}; + + let tmp = tempfile::tempdir().unwrap(); + let mut blob_builder = lance::blob::BlobArrayBuilder::new(2); + blob_builder.push_bytes(b"nested").unwrap(); + blob_builder.push_null().unwrap(); + let blob_field = crate::blob("image", true); + let metadata_fields = Fields::from(vec![blob_field.clone()]); + let metadata = StructArray::new( + metadata_fields.clone(), + vec![blob_builder.finish().unwrap()], + None, + ); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("metadata", DataType::Struct(metadata_fields), true), + ])), + vec![Arc::new(Int32Array::from(vec![1, 2])), Arc::new(metadata)], + ) + .unwrap(); + let table = create_blob_table(tmp.path(), batch).await; + table + .add_columns() + .computed("payload_copy", "metadata.image") + .execute() + .await + .unwrap(); + + assert_eq!( + table + .refresh_column("payload_copy") + .await + .unwrap() + .rows_filled, + 1 + ); + assert_eq!( + table.blob_columns().await.unwrap(), + vec!["metadata.image".to_string(), "payload_copy".to_string()] + ); + let batches = table + .query() + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let row_ids = batches[0] + .column_by_name(ROW_ID) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .values(); + let payloads = table.fetch_blobs("payload_copy", row_ids).await.unwrap(); + assert_eq!(payloads.value(0), b"nested"); + assert!(payloads.is_null(1)); + } + + #[tokio::test] + async fn test_refresh_preserves_list_shape_when_materializing_blob_input() { + use arrow_array::{Int32Array, ListArray}; + use arrow_buffer::{OffsetBuffer, ScalarBuffer}; + use arrow_schema::{DataType, Field, Schema}; + + let tmp = tempfile::tempdir().unwrap(); + let mut blob_builder = lance::blob::BlobArrayBuilder::new(3); + blob_builder.push_bytes(b"a").unwrap(); + blob_builder.push_bytes(b"bb").unwrap(); + blob_builder.push_null().unwrap(); + let item = Arc::new(crate::blob("item", true)); + let images = ListArray::new( + item.clone(), + OffsetBuffer::new(ScalarBuffer::from(vec![0, 2, 3])), + blob_builder.finish().unwrap(), + None, + ); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("images", DataType::List(item), true), + ])), + vec![Arc::new(Int32Array::from(vec![1, 2])), Arc::new(images)], + ) + .unwrap(); + let table = create_blob_table(tmp.path(), batch).await; + table + .add_columns() + .computed("image_payloads", "images") + .execute() + .await + .unwrap(); + + assert_eq!( + table + .refresh_column("image_payloads") + .await + .unwrap() + .rows_filled, + 2 + ); + let batches = table + .query() + .select(Select::columns(&["image_payloads"])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let output = batches[0] + .column_by_name("image_payloads") + .unwrap() + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(output.value_offsets(), &[0, 2, 3]); + assert!(output.values().as_any().is::()); + } + + #[tokio::test] + async fn test_refresh_inherits_external_blob_input() { + use arrow_array::{Int32Array, StringArray, UInt64Array}; + use arrow_schema::{DataType, Field, Schema}; + + let tmp = tempfile::tempdir().unwrap(); + let payload = b"external-payload"; + let path = tmp.path().join("payload.bin"); + std::fs::write(&path, payload).unwrap(); + let uri = url::Url::from_file_path(path).unwrap().to_string(); + let conn = connect(tmp.path().join("db").to_str().unwrap()) + .execute() + .await + .unwrap(); + let table = conn + .create_empty_table( + "external", + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + crate::blob("image", true), + ])), + ) + .execute() + .await + .unwrap(); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("image", DataType::Utf8, true), + ])), + vec![ + Arc::new(Int32Array::from(vec![1])), + Arc::new(StringArray::from(vec![Some(uri)])), + ], + ) + .unwrap(); + table + .add(batch) + .allow_external_blob_outside_bases(true) + .execute() + .await + .unwrap(); + table + .add_columns() + .computed("payload_copy", "image") + .execute() + .await + .unwrap(); + + assert_eq!( + table + .refresh_column("payload_copy") + .await + .unwrap() + .rows_filled, + 1 + ); + let batches = table + .query() + .with_row_id() + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let row_ids = batches[0] + .column_by_name(ROW_ID) + .unwrap() + .as_any() + .downcast_ref::() + .unwrap() + .values(); + let payloads = table.fetch_blobs("payload_copy", row_ids).await.unwrap(); + assert_eq!(payloads.value(0), payload); + } } From a87cada90e0b4a7c7f6bfc5b82ec95f0f57765d2 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Fri, 28 Aug 2026 09:47:47 -0700 Subject: [PATCH 145/206] feat(node)!: require Node >= 22 and drop npm lockfiles (#4074) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The bindings are built, installed and published with pnpm everywhere, but a parallel npm dependency graph was still being maintained beside it. This removes it, raises the supported Node floor to the versions we actually test, and gives Dependabot the npm coverage it was missing. ## Dropping npm `nodejs/package-lock.json` was regenerated by `ci/update_lockfiles.sh` on every release commit and read by nothing — no workflow runs `npm ci` or `npm install` in `nodejs/`, and npm never publishes a lockfile in a package tarball. It could not even agree with the real install, since npm does not see pnpm's `overrides`. Because GitHub's dependency graph parses `package-lock.json`, it was also reporting vulnerabilities for a tree we neither install nor ship. `docs/package.json`, `docs/package-lock.json` and `docs/tsconfig.json` go too. They depend on `file:../node` and `file:../node/node_modules/apache-arrow` — the `node/` directory was removed long ago — the tsconfig compiles `src/*.ts` where no TypeScript files exist, and nothing installs any of it. `docs.yml` only referenced the lockfile to configure an npm cache for an install it never ran. Two `workflow_dispatch` workflows for regenerating those lockfiles are removed as well. Both were already broken: they `uses:` composite actions at `.github/workflows/update_package_lock{,_nodejs}` that do not exist, so dispatching either failed immediately. The remaining `npx` calls become direct `node_modules/.bin/...` invocations. These were already running locally installed binaries rather than resolving anything, but naming the binary removes the npm CLI from the loop and does not depend on which Node version is active. `dev.yml`'s commitlint check was the last place doing real npm dependency resolution — an unpinned `npm install @commitlint/config-conventional` that also bypassed the `minimumReleaseAge` hold configured for `nodejs/` — and is now a pinned `pnpm dlx`. ## Node support Node 18 and 20 both reached end-of-life, in April 2025 and April 2026. The matrix moves to 22, 24 and 26, and `engines` rises from `>= 18` to `>= 22` so the declared floor is one the matrix actually covers. Node 22 is LTS until April 2027; 24 is LTS; 26 is Current and becomes LTS in October 2026. This also removes the reason the workflows reached for `npx` in the first place: pnpm 11 requires Node >= 22.13, which every matrix version now satisfies. The prebuilt-binary smoke test in `npm-publish.yml` moves from Node 20 to Node 22 — the floor, where a napi ABI problem would surface first — rather than fanning out across all three, to keep the publish matrix from tripling. ## Dependabot There were no npm-ecosystem entries at all, which is why the advisories behind #4073 went unnoticed. Both pnpm lockfiles are now watched — `nodejs/` and `nodejs/examples/`, which is a separate install — using the same `lockfile-only` strategy as the existing cargo and pip entries, so version ranges in `package.json` are left alone. ## Pre-commit biome The hook ran `npx @biomejs/biome@1.8.3` while `nodejs/package.json` resolved 1.9.4. The two disagree about formatting, so the hook rejected code that `pnpm lint` accepts, and failed on unmodified `main` for anyone touching `nodejs/`. It now uses the pnpm-managed biome, which fixes the drift with no source changes. ## Testing `dev.yml`'s commitlint job does not check out the repo, so it runs in an empty workspace, and I could not verify `pnpm/action-setup` there locally. It triggers on `pull_request_target`, so this PR exercises it directly — worth confirming green before merge. I did verify the `pnpm dlx` invocation itself locally: it accepts a conventional title and rejects a non-conventional one with exit 1. Node 26 is new enough that the examples job may surface gaps in prebuilt native binaries (`onnxruntime-node`, `sharp`) before their maintainers publish for it. ## Not included `nodejs/examples/` still pins `sharp: "0.33.5"` and has its own audit findings. Raising the Node floor unblocks that work — sharp 0.35 requires Node >= 20.9, which the matrix now satisfies — but it is a dependency bump rather than tooling cleanup, so it is left separate. ## Breaking changes `@lancedb/lancedb` now requires Node >= 22; previously >= 18. The `@types/node` peer range moves from `>=18` to `>=22` to match. Users on Node 18 or 20 must upgrade their runtime; both have been end-of-life for some time. Existing installs are unaffected, since `engines` is only checked on install. --------- Co-authored-by: Claude Opus 5 (1M context) --- .github/dependabot.yml | 24 + .github/workflows/dev.yml | 14 +- .github/workflows/docs-link-check.yml | 2 +- .github/workflows/docs.yml | 4 +- .github/workflows/nodejs.yml | 24 +- .github/workflows/npm-publish.yml | 15 +- .github/workflows/update_package_lock_run.yml | 22 - .../update_package_lock_run_nodejs.yml | 22 - .pre-commit-config.yaml | 5 +- AGENTS.md | 6 +- Makefile | 2 +- ci/update_lockfiles.sh | 8 +- docs/README.md | 19 +- docs/package-lock.json | 135 - docs/package.json | 20 - docs/tsconfig.json | 17 - nodejs/__test__/package.test.ts | 4 +- nodejs/__test__/remote.test.ts | 11 +- nodejs/examples/package.json | 3 +- nodejs/package-lock.json | 11106 ---------------- nodejs/package.json | 4 +- 21 files changed, 90 insertions(+), 11377 deletions(-) delete mode 100644 .github/workflows/update_package_lock_run.yml delete mode 100644 .github/workflows/update_package_lock_run_nodejs.yml delete mode 100644 docs/package-lock.json delete mode 100644 docs/package.json delete mode 100644 docs/tsconfig.json delete mode 100644 nodejs/package-lock.json diff --git a/.github/dependabot.yml b/.github/dependabot.yml index eee966f76..d625b0698 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -44,3 +44,27 @@ updates: python-deps: 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: + patterns: + - "*" + + - package-ecosystem: npm + directory: /nodejs/examples + schedule: + interval: weekly + versioning-strategy: lockfile-only + groups: + nodejs-examples-deps: + patterns: + - "*" diff --git a/.github/workflows/dev.yml b/.github/workflows/dev.yml index f77ba5f77..eac4cc4fc 100644 --- a/.github/workflows/dev.yml +++ b/.github/workflows/dev.yml @@ -29,12 +29,14 @@ jobs: steps: - uses: actions/setup-node@v6 with: - node-version: "18" + node-version: "24" + - uses: pnpm/action-setup@v6 + with: + version: 11.1.1 # These rules are disabled because Github will always ensure there # is a blank line between the title and the body and Github will # word wrap the description field to ensure a reasonable max line # length. - - run: npm install @commitlint/config-conventional - run: > echo 'module.exports = { "rules": { @@ -43,7 +45,11 @@ jobs: "body-leading-blank": [0, "always"] } }' > .commitlintrc.js - - run: npx commitlint --extends @commitlint/config-conventional --verbose <<< $COMMIT_MSG + - run: > + pnpm dlx + --package @commitlint/cli@21.2.2 + --package @commitlint/config-conventional@21.2.2 + commitlint --extends @commitlint/config-conventional --verbose <<< $COMMIT_MSG env: COMMIT_MSG: > ${{ github.event.pull_request.title }} @@ -54,7 +60,7 @@ jobs: with: script: | const message = `**ACTION NEEDED** - + Lance follows the [Conventional Commits specification](https://www.conventionalcommits.org/en/v1.0.0/) for release automation. The PR title and description are used as the merge commit message.\ diff --git a/.github/workflows/docs-link-check.yml b/.github/workflows/docs-link-check.yml index 1286819bc..afa48a14a 100644 --- a/.github/workflows/docs-link-check.yml +++ b/.github/workflows/docs-link-check.yml @@ -56,7 +56,7 @@ jobs: uses: lycheeverse/lychee-action@e7477775783ea5526144ba13e8db5eec57747ce8 # v2.9.0 with: # Restricted to http(s) on purpose. Much of docs/src is generated - # API reference (the js/ tree comes from `npm run docs` in nodejs) + # API reference (the js/ tree comes from `pnpm run docs` in nodejs) # and the hand-written pages use mkdocstrings cross-references and # nav-relative paths that only resolve in the site mkdocs builds, # not in this checkout, so relative links would be reported as diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index e787afb7f..d0ec583bf 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -55,9 +55,7 @@ jobs: - name: Set up node uses: actions/setup-node@v6 with: - node-version: 20 - cache: 'npm' - cache-dependency-path: docs/package-lock.json + node-version: 24 - name: Install node dependencies working-directory: nodejs run: | diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index e82cf71c9..55c050a7d 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -47,9 +47,8 @@ jobs: version: 11.1.1 - uses: actions/setup-node@v6 with: - # pnpm 11 requires Node >= 22.13; use 24 since 22 hits EOL - # in October. The library itself still supports Node >= 18 - # (see test matrix below). + # Build on a supported LTS; the matrix job below covers every + # Node version the library claims to support. node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml @@ -84,7 +83,7 @@ jobs: timeout-minutes: 30 strategy: matrix: - node-version: [ "18", "20" ] + node-version: [ "22", "24", "26" ] runs-on: "ubuntu-22.04" defaults: run: @@ -101,9 +100,9 @@ jobs: - uses: actions/setup-node@v6 name: Setup Node.js 24 for build with: - # pnpm 11 requires Node >= 22.13; use 24 since 22 hits EOL - # in October. Build/install runs on Node 24; tests run on the - # matrix version below using direct jest invocation. + # Build and install once on a fixed version so the generated docs + # are identical across matrix legs; the tests below then run on each + # supported Node version. node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml @@ -152,9 +151,9 @@ jobs: S3_TEST: "1" # Newer @smithy/core uses dynamic ESM imports. NODE_OPTIONS: "--experimental-vm-modules" - # Invoke jest directly because pnpm 11 itself requires Node 22+ - # while the matrix tests on older Node versions. - run: npx jest --verbose + # Invoke the installed jest binary directly; the pnpm shim is set up + # against the build-phase Node, not the version selected above. + run: node_modules/.bin/jest --verbose - name: Test examples working-directory: ./ env: @@ -164,7 +163,7 @@ jobs: run: | python ci/mock_openai.py & cd nodejs/examples - npx jest --testEnvironment jest-environment-node-single-context --verbose + node_modules/.bin/jest --testEnvironment jest-environment-node-single-context --verbose macos: timeout-minutes: 30 # macos-15 ships a newer linker; the older macos-14 linker fails to insert @@ -185,8 +184,7 @@ jobs: version: 11.1.1 - uses: actions/setup-node@v6 with: - # pnpm 11 requires Node >= 22.13; use 24 since 22 hits EOL - # in October. + # pnpm 11 requires Node >= 22.13. node-version: 24 cache: 'pnpm' cache-dependency-path: nodejs/pnpm-lock.yaml diff --git a/.github/workflows/npm-publish.yml b/.github/workflows/npm-publish.yml index ee6906e00..c3724de8d 100644 --- a/.github/workflows/npm-publish.yml +++ b/.github/workflows/npm-publish.yml @@ -168,8 +168,7 @@ jobs: - name: Setup node uses: actions/setup-node@v6 with: - # pnpm 11 requires Node >= 22.13; use 24 since 22 hits EOL - # in October. + # pnpm 11 requires Node >= 22.13. node-version: 24 cache: pnpm cache-dependency-path: nodejs/pnpm-lock.yaml @@ -251,7 +250,7 @@ jobs: run: | set -e ${{ matrix.settings.pre_build }} - npx napi build --platform --release \ + node_modules/.bin/napi build --platform --release \ --features ${{ matrix.settings.features }} \ --target ${{ matrix.settings.target }} \ --dts ../lancedb/native.d.ts \ @@ -271,7 +270,7 @@ jobs: - name: Build run: | ${{ matrix.settings.pre_build }} - npx napi build --platform --release \ + node_modules/.bin/napi build --platform --release \ --features ${{ matrix.settings.features }} \ --target ${{ matrix.settings.target }} \ --dts ../lancedb/native.d.ts \ @@ -339,7 +338,7 @@ jobs: - target: aarch64-unknown-linux-gnu host: ubuntu-2404-8x-arm64 node: - - '20' + - '22' runs-on: ${{ matrix.settings.host }} defaults: run: @@ -385,9 +384,9 @@ jobs: - name: Move built files run: cp dist/native.d.ts dist/native.js dist/*.node lancedb/ - name: Test bindings - # Invoke jest directly because pnpm 11 itself requires Node 22+ - # while the matrix tests on older Node versions. - run: npx jest --verbose + # Invoke the installed jest binary directly; the pnpm shim is set up + # against the install-phase Node, not the version selected above. + run: node_modules/.bin/jest --verbose publish: name: Publish runs-on: ubuntu-latest diff --git a/.github/workflows/update_package_lock_run.yml b/.github/workflows/update_package_lock_run.yml deleted file mode 100644 index 35836a86f..000000000 --- a/.github/workflows/update_package_lock_run.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: Update package-lock.json - -on: - workflow_dispatch: - -permissions: - contents: read - -jobs: - publish: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v6 - with: - ref: main - persist-credentials: false - fetch-depth: 0 - lfs: true - - uses: ./.github/workflows/update_package_lock - with: - github_token: ${{ secrets.LANCEDB_RELEASE_TOKEN }} diff --git a/.github/workflows/update_package_lock_run_nodejs.yml b/.github/workflows/update_package_lock_run_nodejs.yml deleted file mode 100644 index 227a94ecc..000000000 --- a/.github/workflows/update_package_lock_run_nodejs.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: Update NodeJs package-lock.json - -on: - workflow_dispatch: - -permissions: - contents: read - -jobs: - publish: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v6 - with: - ref: main - persist-credentials: false - fetch-depth: 0 - lfs: true - - uses: ./.github/workflows/update_package_lock_nodejs - with: - github_token: ${{ secrets.LANCEDB_RELEASE_TOKEN }} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index bef53f90e..7c98a344c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -20,7 +20,10 @@ repos: hooks: - id: local-biome-check name: biome check - entry: npx @biomejs/biome@1.8.3 check --config-path nodejs/biome.json nodejs/ + # Use the biome from nodejs/package.json rather than a separately + # pinned one: the two drifted apart and disagreed on formatting, so + # this hook rejected code that `pnpm lint` accepted. + entry: nodejs/node_modules/.bin/biome check --config-path nodejs/biome.json nodejs/ language: system types: [text] files: "nodejs/.*" diff --git a/AGENTS.md b/AGENTS.md index 1e072446a..f6d01db03 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,7 +38,7 @@ Before committing changes, run formatting for every language you touched. At min * Rust changes: run `cargo fmt --all`. * Python changes: run `ruff format .` and `ruff check .` from the repository root, and run targeted tests through `cd python && uv run ...`. -* TypeScript changes: run the relevant `npm`/`pnpm` lint, format, build, and docs commands in `nodejs`. +* TypeScript changes: run the relevant `pnpm` lint, format, build, and docs commands in `nodejs`. Before creating a PR, the exact value passed to `gh pr create --title` must follow Conventional Commits, such as `fix: support nested field paths in native index creation` @@ -101,12 +101,12 @@ Python bindings changes: TypeScript bindings changes: 1. Add napi-rs method binding on `Table` in `nodejs/src/table.rs`. -2. Run `npm run build` to generate TypeScript definitions. +2. Run `pnpm build` to generate TypeScript definitions. 3. Add typescript method on abstract class `Table` in `nodejs/src/table.ts`. 4. Add concrete method on `LocalTable` class in `nodejs/src/native_table.ts`. * Note: despite the name, this class is also used for remote tables. 5. Add test in `nodejs/__test__/table.test.ts`. -6. Run `npm run docs` to generate TypeScript documentation. +6. Run `pnpm run docs` to generate TypeScript documentation. ## Python API reference diff --git a/Makefile b/Makefile index b558e6ee3..2e665ee28 100644 --- a/Makefile +++ b/Makefile @@ -5,5 +5,5 @@ licenses: cd python && cargo about generate ../about.hbs -o RUST_THIRD_PARTY_LICENSES.html -c ../about.toml cd python && uv sync --all-extras && uv tool run pip-licenses --python .venv/bin/python --format=markdown --with-urls --output-file=PYTHON_THIRD_PARTY_LICENSES.md cd nodejs && cargo about generate ../about.hbs -o RUST_THIRD_PARTY_LICENSES.html -c ../about.toml - cd nodejs && npx license-checker --markdown --out NODEJS_THIRD_PARTY_LICENSES.md + cd nodejs && pnpm dlx license-checker@25 --markdown --out NODEJS_THIRD_PARTY_LICENSES.md cd java && ./mvnw license:aggregate-add-third-party -q diff --git a/ci/update_lockfiles.sh b/ci/update_lockfiles.sh index 9defa6ddc..ddf5fae79 100755 --- a/ci/update_lockfiles.sh +++ b/ci/update_lockfiles.sh @@ -12,16 +12,12 @@ done # This updates the lockfile without building cargo metadata --quiet > /dev/null -pushd nodejs || exit 1 -npm install --package-lock-only --silent -popd - if git diff --quiet --exit-code; then echo "No lockfile changes to commit; skipping amend." elif $AMEND; then - git add Cargo.lock nodejs/package-lock.json + git add Cargo.lock git commit --amend --no-edit else - git add Cargo.lock nodejs/package-lock.json + git add Cargo.lock git commit -m "Update lockfiles" fi diff --git a/docs/README.md b/docs/README.md index c0171f6cb..bce1ec668 100644 --- a/docs/README.md +++ b/docs/README.md @@ -47,22 +47,24 @@ pytest -vv python/tests/docs ### Checking typescript examples -The `@lancedb/lancedb` package must be built before running the tests: +The examples depend on `@lancedb/lancedb` at `file:../dist`, so the package must be +built before running the tests. This uses pnpm; see the +[Typescript contributing guide](../nodejs/CONTRIBUTING.md) for the toolchain setup. ```shell pushd nodejs -npm ci -npm run build +pnpm install +pnpm build popd ``` -Then you can run the examples by going to the `nodejs/examples` directory and -running the tests like a normal npm package: +Then you can run the examples by going to the `nodejs/examples` directory, which is a +separate pnpm package with its own lockfile: ```shell pushd nodejs/examples -npm ci -npm test +pnpm install +pnpm test popd ``` @@ -84,6 +86,7 @@ The new files should be checked into the repository. ```shell pushd nodejs -npm run docs +# `pnpm docs` would invoke pnpm's built-in `docs` command, not the script. +pnpm run docs popd ``` diff --git a/docs/package-lock.json b/docs/package-lock.json deleted file mode 100644 index e87f3e0ee..000000000 --- a/docs/package-lock.json +++ /dev/null @@ -1,135 +0,0 @@ -{ - "name": "lancedb-docs-test", - "version": "1.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "lancedb-docs-test", - "version": "1.0.0", - "license": "Apache 2", - "dependencies": { - "apache-arrow": "file:../node/node_modules/apache-arrow", - "vectordb": "file:../node" - }, - "devDependencies": { - "@types/node": "^20.11.8", - "typescript": "^5.3.3" - } - }, - "../node": { - "name": "vectordb", - "version": "0.21.2-beta.0", - "cpu": [ - "x64", - "arm64" - ], - "license": "Apache-2.0", - "os": [ - "darwin", - "linux", - "win32" - ], - "dependencies": { - "@neon-rs/load": "^0.0.74", - "axios": "^1.4.0" - }, - "devDependencies": { - "@neon-rs/cli": "^0.0.160", - "@types/chai": "^4.3.4", - "@types/chai-as-promised": "^7.1.5", - "@types/mocha": "^10.0.1", - "@types/node": "^18.16.2", - "@types/sinon": "^10.0.15", - "@types/temp": "^0.9.1", - "@types/uuid": "^9.0.3", - "@typescript-eslint/eslint-plugin": "^5.59.1", - "apache-arrow-old": "npm:apache-arrow@13.0.0", - "cargo-cp-artifact": "^0.1", - "chai": "^4.3.7", - "chai-as-promised": "^7.1.1", - "eslint": "^8.39.0", - "eslint-config-standard-with-typescript": "^34.0.1", - "eslint-plugin-import": "^2.26.0", - "eslint-plugin-n": "^15.7.0", - "eslint-plugin-promise": "^6.1.1", - "mocha": "^10.2.0", - "openai": "^4.24.1", - "sinon": "^15.1.0", - "temp": "^0.9.4", - "ts-node": "^10.9.1", - "ts-node-dev": "^2.0.0", - "typedoc": "^0.24.7", - "typedoc-plugin-markdown": "^3.15.3", - "typescript": "^5.1.0", - "uuid": "^9.0.0" - }, - "optionalDependencies": { - "@lancedb/vectordb-darwin-arm64": "0.21.2-beta.0", - "@lancedb/vectordb-darwin-x64": "0.21.2-beta.0", - "@lancedb/vectordb-linux-arm64-gnu": "0.21.2-beta.0", - "@lancedb/vectordb-linux-x64-gnu": "0.21.2-beta.0", - "@lancedb/vectordb-win32-x64-msvc": "0.21.2-beta.0" - }, - "peerDependencies": { - "@apache-arrow/ts": "^14.0.2", - "apache-arrow": "^14.0.2" - } - }, - "../node/node_modules/apache-arrow": { - "version": "14.0.2", - "license": "Apache-2.0", - "dependencies": { - "@types/command-line-args": "5.2.0", - "@types/command-line-usage": "5.0.2", - "@types/node": "20.3.0", - "@types/pad-left": "2.1.1", - "command-line-args": "5.2.1", - "command-line-usage": "7.0.1", - "flatbuffers": "23.5.26", - "json-bignum": "^0.0.3", - "pad-left": "^2.1.0", - "tslib": "^2.5.3" - }, - "bin": { - "arrow2csv": "bin/arrow2csv.js" - } - }, - "node_modules/@types/node": { - "version": "20.11.8", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.8.tgz", - "integrity": "sha512-i7omyekpPTNdv4Jb/Rgqg0RU8YqLcNsI12quKSDkRXNfx7Wxdm6HhK1awT3xTgEkgxPn3bvnSpiEAc7a7Lpyow==", - "dev": true, - "dependencies": { - "undici-types": "~5.26.4" - } - }, - "node_modules/apache-arrow": { - "resolved": "../node/node_modules/apache-arrow", - "link": true - }, - "node_modules/typescript": { - "version": "5.3.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.3.3.tgz", - "integrity": "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==", - "dev": true, - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/undici-types": { - "version": "5.26.5", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", - "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", - "dev": true - }, - "node_modules/vectordb": { - "resolved": "../node", - "link": true - } - } -} diff --git a/docs/package.json b/docs/package.json deleted file mode 100644 index 041e55247..000000000 --- a/docs/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "lancedb-docs-test", - "version": "1.0.0", - "description": "auto-generated tests from doc", - "author": "dev@lancedb.com", - "license": "Apache 2", - "dependencies": { - "apache-arrow": "file:../node/node_modules/apache-arrow", - "vectordb": "file:../node" - }, - "scripts": { - "build": "tsc -b && cd ../node && npm run build-release", - "example": "npm run build && node", - "test": "npm run build && ls dist/*.js | xargs -n 1 node" - }, - "devDependencies": { - "@types/node": "^20.11.8", - "typescript": "^5.3.3" - } -} diff --git a/docs/tsconfig.json b/docs/tsconfig.json deleted file mode 100644 index 23a30f8b7..000000000 --- a/docs/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "include": [ - "src/*.ts", - ], - "compilerOptions": { - "target": "es2022", - "module": "nodenext", - "declaration": true, - "outDir": "./dist", - "strict": true, - "allowJs": true, - "resolveJsonModule": true, - }, - "exclude": [ - "./dist/*", - ] -} diff --git a/nodejs/__test__/package.test.ts b/nodejs/__test__/package.test.ts index 7743d73d6..90e750321 100644 --- a/nodejs/__test__/package.test.ts +++ b/nodejs/__test__/package.test.ts @@ -5,8 +5,8 @@ import packageJson = require("../package.json"); describe("package metadata", () => { it("requires Node.js type declarations compatible with the runtime", () => { - expect(packageJson.engines.node).toBe(">= 18"); - expect(packageJson.peerDependencies["@types/node"]).toBe(">=18"); + expect(packageJson.engines.node).toBe(">= 22"); + expect(packageJson.peerDependencies["@types/node"]).toBe(">=22"); expect(packageJson.peerDependenciesMeta["@types/node"]).toEqual({ optional: true, }); diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index c51cbbbb7..708559b7b 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -3,6 +3,7 @@ import * as http from "http"; import { RequestListener } from "http"; +import packageJson = require("../package.json"); import { ClientConfig, Connection, @@ -70,7 +71,13 @@ async function withMockDatabase( try { await callback(db); } finally { - server.close(); + // `close()` alone leaves the port bound until keep-alive sockets drain, so + // a single failing test would cascade into EADDRINUSE for every test after + // it. Destroy the connections and wait for the port to actually be free. + await new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }); } } @@ -131,7 +138,7 @@ describe("remote connection", () => { (req, res) => { expect(req.headers["x-api-key"]).toEqual("fake"); expect(req.headers["user-agent"]).toEqual( - `LanceDB-Node-Client/${process.env.npm_package_version}`, + `LanceDB-Node-Client/${packageJson.version}`, ); const body = JSON.stringify({ tables: [] }); diff --git a/nodejs/examples/package.json b/nodejs/examples/package.json index 0dce03ac0..c3f962b79 100644 --- a/nodejs/examples/package.json +++ b/nodejs/examples/package.json @@ -8,7 +8,8 @@ "//1": "--experimental-vm-modules is needed to run jest with sentence-transformers", "//2": "--testEnvironment is needed to run jest with sentence-transformers", "//3": "See: https://github.com/huggingface/transformers.js/issues/57", - "test": "node --experimental-vm-modules node_modules/.bin/jest --testEnvironment jest-environment-node-single-context --verbose", + "//4": "jest is invoked by its JS entry, not node_modules/.bin/jest: under pnpm that path is a shell shim, which `node` cannot execute", + "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --testEnvironment jest-environment-node-single-context --verbose", "lint": "biome check *.ts && biome format *.ts", "lint-ci": "biome ci .", "lint-fix": "biome check --write *.ts && pnpm format", diff --git a/nodejs/package-lock.json b/nodejs/package-lock.json deleted file mode 100644 index b996b0810..000000000 --- a/nodejs/package-lock.json +++ /dev/null @@ -1,11106 +0,0 @@ -{ - "name": "@lancedb/lancedb", - "version": "0.38.0-beta.12", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "@lancedb/lancedb", - "version": "0.38.0-beta.12", - "cpu": [ - "x64", - "arm64" - ], - "license": "Apache-2.0", - "os": [ - "darwin", - "linux", - "win32" - ], - "dependencies": { - "@opentelemetry/api": "^1.9.0", - "reflect-metadata": "^0.2.2" - }, - "devDependencies": { - "@aws-sdk/client-dynamodb": "3.1003.0", - "@aws-sdk/client-kms": "3.1003.0", - "@aws-sdk/client-s3": "3.1003.0", - "@biomejs/biome": "^1.7.3", - "@jest/globals": "^29.7.0", - "@napi-rs/cli": "3.7.0", - "@opentelemetry/sdk-metrics": "^1.30.0", - "@types/axios": "^0.14.0", - "@types/jest": "^29.1.2", - "@types/node": "22.7.4", - "@types/tmp": "^0.2.6", - "apache-arrow-15": "npm:apache-arrow@15.0.0", - "apache-arrow-16": "npm:apache-arrow@16.0.0", - "apache-arrow-17": "npm:apache-arrow@17.0.0", - "apache-arrow-18": "npm:apache-arrow@18.0.0", - "eslint": "^8.57.0", - "jest": "^29.7.0", - "shx": "^0.3.4", - "tmp": "^0.2.3", - "ts-jest": "^29.1.2", - "typedoc": "0.26.4", - "typedoc-plugin-markdown": "4.2.1", - "typescript": "5.5.4", - "typescript-eslint": "^7.1.0" - }, - "engines": { - "node": ">= 18" - }, - "optionalDependencies": { - "@huggingface/transformers": "3.0.2", - "openai": "4.29.2" - }, - "peerDependencies": { - "@types/node": ">=18", - "apache-arrow": ">=15.0.0 <=18.1.0" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@aws-crypto/crc32": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@aws-crypto/crc32/-/crc32-5.2.0.tgz", - "integrity": "sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/util": "^5.2.0", - "@aws-sdk/types": "^3.222.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-crypto/crc32c": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@aws-crypto/crc32c/-/crc32c-5.2.0.tgz", - "integrity": "sha512-+iWb8qaHLYKrNvGRbiYRHSdKRWhto5XlZUEBwDjYNf+ly5SVYG6zEoYIdxvf5R3zyeP16w4PLBn3rH1xc74Rag==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/util": "^5.2.0", - "@aws-sdk/types": "^3.222.0", - "tslib": "^2.6.2" - } - }, - "node_modules/@aws-crypto/sha1-browser": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@aws-crypto/sha1-browser/-/sha1-browser-5.2.0.tgz", - "integrity": "sha512-OH6lveCFfcDjX4dbAvCFSYUjJZjDr/3XJ3xHtjn3Oj5b9RjojQo8npoLeA/bNwkOkrSQ0wgrHzXk4tDRxGKJeg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/supports-web-crypto": "^5.2.0", - "@aws-crypto/util": "^5.2.0", - "@aws-sdk/types": "^3.222.0", - "@aws-sdk/util-locate-window": "^3.0.0", - "@smithy/util-utf8": "^2.0.0", - "tslib": "^2.6.2" - } - }, - "node_modules/@aws-crypto/sha1-browser/node_modules/@smithy/util-utf8": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", - "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/util-buffer-from": "^2.2.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@aws-crypto/sha256-browser": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-browser/-/sha256-browser-5.2.0.tgz", - "integrity": "sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/sha256-js": "^5.2.0", - "@aws-crypto/supports-web-crypto": "^5.2.0", - "@aws-crypto/util": "^5.2.0", - "@aws-sdk/types": "^3.222.0", - "@aws-sdk/util-locate-window": "^3.0.0", - "@smithy/util-utf8": "^2.0.0", - "tslib": "^2.6.2" - } - }, - "node_modules/@aws-crypto/sha256-browser/node_modules/@smithy/util-utf8": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", - "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/util-buffer-from": "^2.2.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@aws-crypto/sha256-js": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz", - "integrity": "sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/util": "^5.2.0", - "@aws-sdk/types": "^3.222.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/@aws-crypto/supports-web-crypto": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@aws-crypto/supports-web-crypto/-/supports-web-crypto-5.2.0.tgz", - "integrity": "sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "tslib": "^2.6.2" - } - }, - "node_modules/@aws-crypto/util": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/@aws-crypto/util/-/util-5.2.0.tgz", - "integrity": "sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "^3.222.0", - "@smithy/util-utf8": "^2.0.0", - "tslib": "^2.6.2" - } - }, - "node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-2.3.0.tgz", - "integrity": "sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/util-buffer-from": "^2.2.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@aws-sdk/client-dynamodb": { - "version": "3.1003.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-dynamodb/-/client-dynamodb-3.1003.0.tgz", - "integrity": "sha512-tUN5kKCvaXeXnw3nqckhRq9m3bAKsYL2WaNotYEFrKQrFW3WAEu6jxRwsRr+pasSEEYvX4B03J9tlaxfPR8rZA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "^3.973.18", - "@aws-sdk/credential-provider-node": "^3.972.17", - "@aws-sdk/dynamodb-codec": "^3.972.19", - "@aws-sdk/middleware-endpoint-discovery": "^3.972.7", - "@aws-sdk/middleware-host-header": "^3.972.7", - "@aws-sdk/middleware-logger": "^3.972.7", - "@aws-sdk/middleware-recursion-detection": "^3.972.7", - "@aws-sdk/middleware-user-agent": "^3.972.18", - "@aws-sdk/region-config-resolver": "^3.972.7", - "@aws-sdk/types": "^3.973.5", - "@aws-sdk/util-endpoints": "^3.996.4", - "@aws-sdk/util-user-agent-browser": "^3.972.7", - "@aws-sdk/util-user-agent-node": "^3.973.3", - "@smithy/config-resolver": "^4.4.10", - "@smithy/core": "^3.23.8", - "@smithy/fetch-http-handler": "^5.3.13", - "@smithy/hash-node": "^4.2.11", - "@smithy/invalid-dependency": "^4.2.11", - "@smithy/middleware-content-length": "^4.2.11", - "@smithy/middleware-endpoint": "^4.4.22", - "@smithy/middleware-retry": "^4.4.39", - "@smithy/middleware-serde": "^4.2.12", - "@smithy/middleware-stack": "^4.2.11", - "@smithy/node-config-provider": "^4.3.11", - "@smithy/node-http-handler": "^4.4.14", - "@smithy/protocol-http": "^5.3.11", - "@smithy/smithy-client": "^4.12.2", - "@smithy/types": "^4.13.0", - "@smithy/url-parser": "^4.2.11", - "@smithy/util-base64": "^4.3.2", - "@smithy/util-body-length-browser": "^4.2.2", - "@smithy/util-body-length-node": "^4.2.3", - "@smithy/util-defaults-mode-browser": "^4.3.38", - "@smithy/util-defaults-mode-node": "^4.2.41", - "@smithy/util-endpoints": "^3.3.2", - "@smithy/util-middleware": "^4.2.11", - "@smithy/util-retry": "^4.2.11", - "@smithy/util-utf8": "^4.2.2", - "@smithy/util-waiter": "^4.2.11", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/client-kms": { - "version": "3.1003.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-kms/-/client-kms-3.1003.0.tgz", - "integrity": "sha512-XO11qsl/p+WTzOTf4o9w6aZZ0lh2QHwwpuv9en2fgtVL4PnibndWC4Ln/5CB9fJpeUsQo8dLAys1PVhTh4lcGQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "^3.973.18", - "@aws-sdk/credential-provider-node": "^3.972.17", - "@aws-sdk/middleware-host-header": "^3.972.7", - "@aws-sdk/middleware-logger": "^3.972.7", - "@aws-sdk/middleware-recursion-detection": "^3.972.7", - "@aws-sdk/middleware-user-agent": "^3.972.18", - "@aws-sdk/region-config-resolver": "^3.972.7", - "@aws-sdk/types": "^3.973.5", - "@aws-sdk/util-endpoints": "^3.996.4", - "@aws-sdk/util-user-agent-browser": "^3.972.7", - "@aws-sdk/util-user-agent-node": "^3.973.3", - "@smithy/config-resolver": "^4.4.10", - "@smithy/core": "^3.23.8", - "@smithy/fetch-http-handler": "^5.3.13", - "@smithy/hash-node": "^4.2.11", - "@smithy/invalid-dependency": "^4.2.11", - "@smithy/middleware-content-length": "^4.2.11", - "@smithy/middleware-endpoint": "^4.4.22", - "@smithy/middleware-retry": "^4.4.39", - "@smithy/middleware-serde": "^4.2.12", - "@smithy/middleware-stack": "^4.2.11", - "@smithy/node-config-provider": "^4.3.11", - "@smithy/node-http-handler": "^4.4.14", - "@smithy/protocol-http": "^5.3.11", - "@smithy/smithy-client": "^4.12.2", - "@smithy/types": "^4.13.0", - "@smithy/url-parser": "^4.2.11", - "@smithy/util-base64": "^4.3.2", - "@smithy/util-body-length-browser": "^4.2.2", - "@smithy/util-body-length-node": "^4.2.3", - "@smithy/util-defaults-mode-browser": "^4.3.38", - "@smithy/util-defaults-mode-node": "^4.2.41", - "@smithy/util-endpoints": "^3.3.2", - "@smithy/util-middleware": "^4.2.11", - "@smithy/util-retry": "^4.2.11", - "@smithy/util-utf8": "^4.2.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/client-s3": { - "version": "3.1003.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.1003.0.tgz", - "integrity": "sha512-on8GvIWeH1pD0l53NuKbPO84bEC1mk/9zskgU+dVKcVoGxOZI94fVddCJb+IwIUN6rfBHCfXPCVbgVyzsHTAVg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/sha1-browser": "5.2.0", - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "^3.973.18", - "@aws-sdk/credential-provider-node": "^3.972.17", - "@aws-sdk/middleware-bucket-endpoint": "^3.972.7", - "@aws-sdk/middleware-expect-continue": "^3.972.7", - "@aws-sdk/middleware-flexible-checksums": "^3.973.4", - "@aws-sdk/middleware-host-header": "^3.972.7", - "@aws-sdk/middleware-location-constraint": "^3.972.7", - "@aws-sdk/middleware-logger": "^3.972.7", - "@aws-sdk/middleware-recursion-detection": "^3.972.7", - "@aws-sdk/middleware-sdk-s3": "^3.972.18", - "@aws-sdk/middleware-ssec": "^3.972.7", - "@aws-sdk/middleware-user-agent": "^3.972.18", - "@aws-sdk/region-config-resolver": "^3.972.7", - "@aws-sdk/signature-v4-multi-region": "^3.996.6", - "@aws-sdk/types": "^3.973.5", - "@aws-sdk/util-endpoints": "^3.996.4", - "@aws-sdk/util-user-agent-browser": "^3.972.7", - "@aws-sdk/util-user-agent-node": "^3.973.3", - "@smithy/config-resolver": "^4.4.10", - "@smithy/core": "^3.23.8", - "@smithy/eventstream-serde-browser": "^4.2.11", - "@smithy/eventstream-serde-config-resolver": "^4.3.11", - "@smithy/eventstream-serde-node": "^4.2.11", - "@smithy/fetch-http-handler": "^5.3.13", - "@smithy/hash-blob-browser": "^4.2.12", - "@smithy/hash-node": "^4.2.11", - "@smithy/hash-stream-node": "^4.2.11", - "@smithy/invalid-dependency": "^4.2.11", - "@smithy/md5-js": "^4.2.11", - "@smithy/middleware-content-length": "^4.2.11", - "@smithy/middleware-endpoint": "^4.4.22", - "@smithy/middleware-retry": "^4.4.39", - "@smithy/middleware-serde": "^4.2.12", - "@smithy/middleware-stack": "^4.2.11", - "@smithy/node-config-provider": "^4.3.11", - "@smithy/node-http-handler": "^4.4.14", - "@smithy/protocol-http": "^5.3.11", - "@smithy/smithy-client": "^4.12.2", - "@smithy/types": "^4.13.0", - "@smithy/url-parser": "^4.2.11", - "@smithy/util-base64": "^4.3.2", - "@smithy/util-body-length-browser": "^4.2.2", - "@smithy/util-body-length-node": "^4.2.3", - "@smithy/util-defaults-mode-browser": "^4.3.38", - "@smithy/util-defaults-mode-node": "^4.2.41", - "@smithy/util-endpoints": "^3.3.2", - "@smithy/util-middleware": "^4.2.11", - "@smithy/util-retry": "^4.2.11", - "@smithy/util-stream": "^4.5.17", - "@smithy/util-utf8": "^4.2.2", - "@smithy/util-waiter": "^4.2.11", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/core": { - "version": "3.974.12", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.974.12.tgz", - "integrity": "sha512-qrqgioqYFjwR6LatVNS1L2Vk++EwRIxqSQXPKNv5Ofux2D8UNgqMQ1znnMyEImXquVPTtbf71fc128pvmU6y9A==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "^3.973.8", - "@aws-sdk/xml-builder": "^3.972.24", - "@aws/lambda-invoke-store": "^0.2.2", - "@smithy/core": "^3.24.2", - "@smithy/signature-v4": "^5.4.2", - "@smithy/types": "^4.14.1", - "bowser": "^2.11.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/crc64-nvme": { - "version": "3.972.8", - "resolved": "https://registry.npmjs.org/@aws-sdk/crc64-nvme/-/crc64-nvme-3.972.8.tgz", - "integrity": "sha512-fVfUCL/Xh2zINYMPZvj+iBn6XWouQf0DAnjaWCI9MkmqXzL2Iy5FoQB8O7syFe6gN6AH1ecDDU58T51Ou0kFkA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-env": { - "version": "3.972.38", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.38.tgz", - "integrity": "sha512-m3WjZEgPtioMhPmwqUt+DhlTJ2i9ufR6DhfkyXojb9puEvfR+ur2U5shavu5/Cc9WHHsDCvALi6UFHgcqjhQ5w==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-http": { - "version": "3.972.40", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.40.tgz", - "integrity": "sha512-D78L/m2Dr6cJnnSvWoAudPhQmCwmJ7j6APXsPYmFpPaKfQTfCSu0rdm8j14Np+VmXF9z8Aj8HE3xFpsrwtfgeg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/fetch-http-handler": "^5.4.2", - "@smithy/node-http-handler": "^4.7.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-ini": { - "version": "3.972.42", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.972.42.tgz", - "integrity": "sha512-Mu5ESvFXeinafVM8jTIvRqcvK2Ehj4kz3auT39yUcHwu1Vfxo6xRlmUafdKLW4tusjAJukQwK09sCSMgOm7OKg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "@aws-sdk/credential-provider-env": "^3.972.38", - "@aws-sdk/credential-provider-http": "^3.972.40", - "@aws-sdk/credential-provider-login": "^3.972.42", - "@aws-sdk/credential-provider-process": "^3.972.38", - "@aws-sdk/credential-provider-sso": "^3.972.42", - "@aws-sdk/credential-provider-web-identity": "^3.972.42", - "@aws-sdk/nested-clients": "^3.997.10", - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/credential-provider-imds": "^4.3.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-login": { - "version": "3.972.42", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.42.tgz", - "integrity": "sha512-O6WkZga3kf0yqyJYd1dbeJqVhEgJx/x1UaLgtbR+XuL/YP+K5y6QTxQKL7ka9z3jnQASESKGAPnRyt4D5hQrxA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "@aws-sdk/nested-clients": "^3.997.10", - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-node": { - "version": "3.972.43", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.43.tgz", - "integrity": "sha512-D/DJmbrWRP5BXEO3FH+ar4el+2n6OlGofiud7dQun2jES+AQEJjczenp1jBb4MBN7CpGpS8nsWGQLtuzc9tQbA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/credential-provider-env": "^3.972.38", - "@aws-sdk/credential-provider-http": "^3.972.40", - "@aws-sdk/credential-provider-ini": "^3.972.42", - "@aws-sdk/credential-provider-process": "^3.972.38", - "@aws-sdk/credential-provider-sso": "^3.972.42", - "@aws-sdk/credential-provider-web-identity": "^3.972.42", - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/credential-provider-imds": "^4.3.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-process": { - "version": "3.972.38", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.38.tgz", - "integrity": "sha512-EnbYVajGgbkb24s0K1eo4VNAPV5mHIET7LSvirTaFCwkfrfaOJxtSE+wY/tJdKDS21cEYkZs2ruCaAm+W4iblg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-sso": { - "version": "3.972.42", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.972.42.tgz", - "integrity": "sha512-RVV/9NbFwI8ZHEH5dn39lGyFmSbSVj1+orZdr6QsOe1mW9DCglmlen0cFaNZmCcqkqc7erNRHNBduxbeZuHAnw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "@aws-sdk/nested-clients": "^3.997.10", - "@aws-sdk/token-providers": "3.1049.0", - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/credential-provider-web-identity": { - "version": "3.972.42", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.42.tgz", - "integrity": "sha512-/67fXX0ddllD4u2Nujc5PvT4byHgpMUfz6+RxIKi/0nFIckeorm7JvXgzBuDyVKw0s58EbofmETDWUf9vTEuHQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "@aws-sdk/nested-clients": "^3.997.10", - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/dynamodb-codec": { - "version": "3.973.12", - "resolved": "https://registry.npmjs.org/@aws-sdk/dynamodb-codec/-/dynamodb-codec-3.973.12.tgz", - "integrity": "sha512-E+qpJPN1QLzfeVDQe1gVmMiHu9PTJWwXqSQjIt8mH5OQXmds2J/IN+Ar6Oa9ZhhuPZb4fPkcgZg4UEpwJM90NA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "@smithy/core": "^3.24.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/endpoint-cache": { - "version": "3.972.5", - "resolved": "https://registry.npmjs.org/@aws-sdk/endpoint-cache/-/endpoint-cache-3.972.5.tgz", - "integrity": "sha512-itVdge0NozgtgmtbZ25FVwWU3vGlE7x7feE/aOEJNkQfEpbkrF8Rj1QmnK+2blFfYE1xWt/iU+6/jUp/pv1+MA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "mnemonist": "0.38.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/middleware-bucket-endpoint": { - "version": "3.972.14", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-bucket-endpoint/-/middleware-bucket-endpoint-3.972.14.tgz", - "integrity": "sha512-Aaj0d+xbo1jJquBWJP0/9V/XZRYukO3LWIRp3dOLHmoFrYKb4YZ0aLefgVHfGcNOVBS2ZTq7L/n5JcrE7DaC+Q==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/middleware-endpoint-discovery": { - "version": "3.972.13", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-endpoint-discovery/-/middleware-endpoint-discovery-3.972.13.tgz", - "integrity": "sha512-1r6EkFdSQ4quTP3pW8yWIcYuyDwdwdBxGr+kfuPFYE3DqR+1gBc6NyJneAyoIs+wc/cUfnyJ4ZYC0T2SQTxP9A==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/endpoint-cache": "^3.972.5", - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/middleware-expect-continue": { - "version": "3.972.12", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-expect-continue/-/middleware-expect-continue-3.972.12.tgz", - "integrity": "sha512-dA5pKTom/Ls9mgeyeaRBNQrRIVOLVjv4AmKOB0/e4yaiXEUy0gSz2d3liP8JHtYoCAEWySU1jWnyzwLOREN+4g==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/middleware-flexible-checksums": { - "version": "3.974.20", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-flexible-checksums/-/middleware-flexible-checksums-3.974.20.tgz", - "integrity": "sha512-NdnMVQCR1YjIcqFAiNLdBiOwr2DyQDB2IiXQrBhzolKOv32ae4d4Ll7IzLMi04eMHiq/o/Y/GjFuVjF9HuG0QA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/crc32": "5.2.0", - "@aws-crypto/crc32c": "5.2.0", - "@aws-crypto/util": "5.2.0", - "@aws-sdk/core": "^3.974.12", - "@aws-sdk/crc64-nvme": "^3.972.8", - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/middleware-host-header": { - "version": "3.972.13", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-host-header/-/middleware-host-header-3.972.13.tgz", - "integrity": "sha512-EA3+u2LD3kGcfRNmCSjyJuzX4XvG4zYv57i4ZksH+1IEciuSyHQGvzivEz7vZ+jbRPdAAe7WWKy/4M8InCKDcw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/middleware-location-constraint": { - "version": "3.972.10", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-location-constraint/-/middleware-location-constraint-3.972.10.tgz", - "integrity": "sha512-rI3NZvJcEvjoD0+0PI0iUAwlPw2IlSlhyvgBK/3WkKJQE/YiKFedd9dMN2lVacdNxPNhxL/jzQaKQdrGtQagjQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "^3.973.8", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/middleware-logger": { - "version": "3.972.12", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-logger/-/middleware-logger-3.972.12.tgz", - "integrity": "sha512-NxB2dS4/mV3380hNkC72TkhMaLLjWGGBeTAEucqlJptVVovTbNmQWZLwaMC74ICo9NZHmFiBVVTHzDfAh/3y6Q==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/middleware-recursion-detection": { - "version": "3.972.14", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-recursion-detection/-/middleware-recursion-detection-3.972.14.tgz", - "integrity": "sha512-bqL+upATpOJ/7px4IVfMVxcM6Lyt9uRizmEx3mNg4N6+IQlnOaYXXOJ4TNX6P0mKPPW0lwn9ZW8QEhXwQuCH9A==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/middleware-sdk-s3": { - "version": "3.972.41", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.972.41.tgz", - "integrity": "sha512-M4T2I2WPuH5WQpU8Tsp+u2bcO29zGRkU14ATzuqb9I4xh8tzsLqtp4hzaJM5aO2dhMZnHDzyQwSFVgc3XbnoGg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "@aws-sdk/signature-v4-multi-region": "^3.996.27", - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/signature-v4": "^5.4.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/middleware-ssec": { - "version": "3.972.10", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-ssec/-/middleware-ssec-3.972.10.tgz", - "integrity": "sha512-Gli9A0u8EVVb+5bFDGS/QbSVg28w/wpEidg1ggVcSj65BDTdGR6punsOcVjqdiu1i42WHWo51MCvARPIIz9juw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "^3.973.8", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/middleware-user-agent": { - "version": "3.972.42", - "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-user-agent/-/middleware-user-agent-3.972.42.tgz", - "integrity": "sha512-U7jjlJKQnuUlI2swC2umFLFzLAxMLudSRFv+Bqk2F8ORmr5bG25qsFxGm4GEFwoZeGaFFnAFmTY0xReVRfyl2A==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/nested-clients": { - "version": "3.997.10", - "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.10.tgz", - "integrity": "sha512-FtQ/Bt327peZJuyo4WZSOLVUTw9ujRxntepiC7L65FxA2P82Xlq0g14T22BuqBUeMjDoxa9nvwiMHjLIfP3eUg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "^3.974.12", - "@aws-sdk/signature-v4-multi-region": "^3.996.27", - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/fetch-http-handler": "^5.4.2", - "@smithy/node-http-handler": "^4.7.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/region-config-resolver": { - "version": "3.972.16", - "resolved": "https://registry.npmjs.org/@aws-sdk/region-config-resolver/-/region-config-resolver-3.972.16.tgz", - "integrity": "sha512-/YaivCvKUkEeMN9VTKBSvBn5w/4osAM1YboM58DKaLF/vqFGf/FdJCLmppqiPPJWZaXcASqByVjc3evE7KHKdA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/signature-v4-multi-region": { - "version": "3.996.27", - "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.27.tgz", - "integrity": "sha512-0Phbz4t6HI3D3skxvG2uI+VWU034/nSIw1T8d+FPzzQG9EQTrw94o9mOKO2Gv3n3Oc8P7JD7RAUxkoneLWv5Eg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/signature-v4": "^5.4.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/token-providers": { - "version": "3.1049.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1049.0.tgz", - "integrity": "sha512-r7+d0lQMTHKypkmaF5jRTBYLYHCUHzt3gaVoN9SidLhQeWhCmHk3AKrboDTpPF5b7Pt7vKu3+oeMjznM2Eu1ow==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "@aws-sdk/nested-clients": "^3.997.10", - "@aws-sdk/types": "^3.973.8", - "@smithy/core": "^3.24.2", - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/types": { - "version": "3.973.8", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.973.8.tgz", - "integrity": "sha512-gjlAdtHMbtR9X5iIhVUvbVcy55KnznpC6bkDUWW9z915bi0ckdUr5cjf16Kp6xq0bP5HBD2xzgbL9F9Quv5vUw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/types": "^4.14.1", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/util-endpoints": { - "version": "3.996.11", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-endpoints/-/util-endpoints-3.996.11.tgz", - "integrity": "sha512-BUMJ6VoL54r6Udj/wKy8uKRIndL04rGbaS/wTIV0dM1ewxSrR8yARBHdvZKQsK55ZSW2JrmAPk3KP15kBDxJMw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "@smithy/core": "^3.24.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/util-locate-window": { - "version": "3.965.5", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-locate-window/-/util-locate-window-3.965.5.tgz", - "integrity": "sha512-WhlJNNINQB+9qtLtZJcpQdgZw3SCDCpXdUJP7cToGwHbCWCnRckGlc6Bx/OhWwIYFNAn+FIydY8SZ0QmVu3xTQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/util-user-agent-browser": { - "version": "3.972.13", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-browser/-/util-user-agent-browser-3.972.13.tgz", - "integrity": "sha512-wfk9ZdVwh187gdGXB1EyAoprwjSMt/bSfVtva+OaZx+LyNdKD7smlZf611yMd42UpfQ9vaS8NOftjSajgpdd+w==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "tslib": "^2.6.2" - } - }, - "node_modules/@aws-sdk/util-user-agent-node": { - "version": "3.973.28", - "resolved": "https://registry.npmjs.org/@aws-sdk/util-user-agent-node/-/util-user-agent-node-3.973.28.tgz", - "integrity": "sha512-A2l/PTRzsOS9L8dmZbXtDyJQgeeX+qjqLJ+fr0UU5Dz0AUQMuxgZCPSLKZgUDlHAmLFuk34owdMEvJxmDTBgRg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-sdk/core": "^3.974.12", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws-sdk/xml-builder": { - "version": "3.972.24", - "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.24.tgz", - "integrity": "sha512-V8z5YcDPfsvzrBlj0xR1vhRtocblhYbqdreCJB/voGd4Sr5zjNAeWxexbnqVtskTJe0vFb5KMqbSL++ePl+zRw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@nodable/entities": "2.1.0", - "@smithy/types": "^4.14.1", - "fast-xml-parser": "5.7.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@aws/lambda-invoke-store": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.2.4.tgz", - "integrity": "sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@babel/code-frame": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", - "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-validator-identifier": "^7.28.5", - "js-tokens": "^4.0.0", - "picocolors": "^1.1.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/compat-data": { - "version": "7.29.3", - "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.3.tgz", - "integrity": "sha512-LIVqM46zQWZhj17qA8wb4nW/ixr2y1Nw+r1etiAWgRM6U1IqP+LNhL1yg440jYZR72jCWcWbLWzIosH+uP1fqg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/core": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz", - "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.0", - "@babel/generator": "^7.29.0", - "@babel/helper-compilation-targets": "^7.28.6", - "@babel/helper-module-transforms": "^7.28.6", - "@babel/helpers": "^7.28.6", - "@babel/parser": "^7.29.0", - "@babel/template": "^7.28.6", - "@babel/traverse": "^7.29.0", - "@babel/types": "^7.29.0", - "@jridgewell/remapping": "^2.3.5", - "convert-source-map": "^2.0.0", - "debug": "^4.1.0", - "gensync": "^1.0.0-beta.2", - "json5": "^2.2.3", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/babel" - } - }, - "node_modules/@babel/core/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/@babel/generator": { - "version": "7.29.1", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", - "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.29.0", - "@babel/types": "^7.29.0", - "@jridgewell/gen-mapping": "^0.3.12", - "@jridgewell/trace-mapping": "^0.3.28", - "jsesc": "^3.0.2" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-compilation-targets": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz", - "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/compat-data": "^7.28.6", - "@babel/helper-validator-option": "^7.27.1", - "browserslist": "^4.24.0", - "lru-cache": "^5.1.1", - "semver": "^6.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-compilation-targets/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/@babel/helper-globals": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz", - "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-imports": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz", - "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/traverse": "^7.28.6", - "@babel/types": "^7.28.6" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-module-transforms": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz", - "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-module-imports": "^7.28.6", - "@babel/helper-validator-identifier": "^7.28.5", - "@babel/traverse": "^7.28.6" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/@babel/helper-plugin-utils": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz", - "integrity": "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-string-parser": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", - "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", - "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-option": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz", - "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helpers": { - "version": "7.29.2", - "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz", - "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/template": "^7.28.6", - "@babel/types": "^7.29.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/parser": { - "version": "7.29.3", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.3.tgz", - "integrity": "sha512-b3ctpQwp+PROvU/cttc4OYl4MzfJUWy6FZg+PMXfzmt/+39iHVF0sDfqay8TQM3JA2EUOyKcFZt75jWriQijsA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.29.0" - }, - "bin": { - "parser": "bin/babel-parser.js" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@babel/plugin-syntax-async-generators": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", - "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-bigint": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", - "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-class-properties": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", - "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.12.13" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-class-static-block": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", - "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-import-attributes": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.28.6.tgz", - "integrity": "sha512-jiLC0ma9XkQT3TKJ9uYvlakm66Pamywo+qwL+oL8HJOvc6TWdZXVfhqJr8CCzbSGUAbDOzlGHJC1U+vRfLQDvw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.28.6" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-import-meta": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", - "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-json-strings": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", - "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-jsx": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.28.6.tgz", - "integrity": "sha512-wgEmr06G6sIpqr8YDwA2dSRTE3bJ+V0IfpzfSY3Lfgd7YWOaAdlykvJi13ZKBt8cZHfgH1IXN+CL656W3uUa4w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.28.6" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-logical-assignment-operators": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", - "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", - "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-numeric-separator": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", - "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-object-rest-spread": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", - "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-optional-catch-binding": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", - "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-optional-chaining": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", - "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-private-property-in-object": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", - "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-top-level-await": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", - "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-typescript": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.28.6.tgz", - "integrity": "sha512-+nDNmQye7nlnuuHDboPbGm00Vqg3oO8niRRL27/4LYHUsHYh0zJ1xWOz0uRwNFmM1Avzk8wZbc6rdiYhomzv/A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.28.6" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/template": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz", - "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.28.6", - "@babel/parser": "^7.28.6", - "@babel/types": "^7.28.6" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/traverse": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz", - "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.29.0", - "@babel/generator": "^7.29.0", - "@babel/helper-globals": "^7.28.0", - "@babel/parser": "^7.29.0", - "@babel/template": "^7.28.6", - "@babel/types": "^7.29.0", - "debug": "^4.3.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/types": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", - "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-string-parser": "^7.27.1", - "@babel/helper-validator-identifier": "^7.28.5" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@bcoe/v8-coverage": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", - "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@biomejs/biome": { - "version": "1.9.4", - "resolved": "https://registry.npmjs.org/@biomejs/biome/-/biome-1.9.4.tgz", - "integrity": "sha512-1rkd7G70+o9KkTn5KLmDYXihGoTaIGO9PIIN2ZB7UJxFrWw04CZHPYiMRjYsaDvVV7hP1dYNRLxSANLaBFGpog==", - "dev": true, - "hasInstallScript": true, - "license": "MIT OR Apache-2.0", - "bin": { - "biome": "bin/biome" - }, - "engines": { - "node": ">=14.21.3" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/biome" - }, - "optionalDependencies": { - "@biomejs/cli-darwin-arm64": "1.9.4", - "@biomejs/cli-darwin-x64": "1.9.4", - "@biomejs/cli-linux-arm64": "1.9.4", - "@biomejs/cli-linux-arm64-musl": "1.9.4", - "@biomejs/cli-linux-x64": "1.9.4", - "@biomejs/cli-linux-x64-musl": "1.9.4", - "@biomejs/cli-win32-arm64": "1.9.4", - "@biomejs/cli-win32-x64": "1.9.4" - } - }, - "node_modules/@biomejs/cli-darwin-arm64": { - "version": "1.9.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-arm64/-/cli-darwin-arm64-1.9.4.tgz", - "integrity": "sha512-bFBsPWrNvkdKrNCYeAp+xo2HecOGPAy9WyNyB/jKnnedgzl4W4Hb9ZMzYNbf8dMCGmUdSavlYHiR01QaYR58cw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-darwin-x64": { - "version": "1.9.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-darwin-x64/-/cli-darwin-x64-1.9.4.tgz", - "integrity": "sha512-ngYBh/+bEedqkSevPVhLP4QfVPCpb+4BBe2p7Xs32dBgs7rh9nY2AIYUL6BgLw1JVXV8GlpKmb/hNiuIxfPfZg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-arm64": { - "version": "1.9.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64/-/cli-linux-arm64-1.9.4.tgz", - "integrity": "sha512-fJIW0+LYujdjUgJJuwesP4EjIBl/N/TcOX3IvIHJQNsAqvV2CHIogsmA94BPG6jZATS4Hi+xv4SkBBQSt1N4/g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-arm64-musl": { - "version": "1.9.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-arm64-musl/-/cli-linux-arm64-musl-1.9.4.tgz", - "integrity": "sha512-v665Ct9WCRjGa8+kTr0CzApU0+XXtRgwmzIf1SeKSGAv+2scAlW6JR5PMFo6FzqqZ64Po79cKODKf3/AAmECqA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-x64": { - "version": "1.9.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64/-/cli-linux-x64-1.9.4.tgz", - "integrity": "sha512-lRCJv/Vi3Vlwmbd6K+oQ0KhLHMAysN8lXoCI7XeHlxaajk06u7G+UsFSO01NAs5iYuWKmVZjmiOzJ0OJmGsMwg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-linux-x64-musl": { - "version": "1.9.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-linux-x64-musl/-/cli-linux-x64-musl-1.9.4.tgz", - "integrity": "sha512-gEhi/jSBhZ2m6wjV530Yy8+fNqG8PAinM3oV7CyO+6c3CEh16Eizm21uHVsyVBEB6RIM8JHIl6AGYCv6Q6Q9Tg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-win32-arm64": { - "version": "1.9.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-arm64/-/cli-win32-arm64-1.9.4.tgz", - "integrity": "sha512-tlbhLk+WXZmgwoIKwHIHEBZUwxml7bRJgk0X2sPyNR3S93cdRq6XulAZRQJ17FYGGzWne0fgrXBKpl7l4M87Hg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@biomejs/cli-win32-x64": { - "version": "1.9.4", - "resolved": "https://registry.npmjs.org/@biomejs/cli-win32-x64/-/cli-win32-x64-1.9.4.tgz", - "integrity": "sha512-8Y5wMhVIPaWe6jw2H+KlEm4wP/f7EW3810ZLmDlrEEy5KvBsb9ECEfu/kMWD484ijfQ8+nIi0giMgu9g1UAuuA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT OR Apache-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=14.21.3" - } - }, - "node_modules/@emnapi/core": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", - "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.1", - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/runtime": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz", - "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/wasi-threads": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", - "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@eslint-community/eslint-utils": { - "version": "4.9.1", - "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", - "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "eslint-visitor-keys": "^3.4.3" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - }, - "peerDependencies": { - "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" - } - }, - "node_modules/@eslint-community/regexpp": { - "version": "4.12.2", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", - "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.0.0 || ^14.0.0 || >=16.0.0" - } - }, - "node_modules/@eslint/eslintrc": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", - "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ajv": "^6.12.4", - "debug": "^4.3.2", - "espree": "^9.6.0", - "globals": "^13.19.0", - "ignore": "^5.2.0", - "import-fresh": "^3.2.1", - "js-yaml": "^4.1.0", - "minimatch": "^3.1.2", - "strip-json-comments": "^3.1.1" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/@eslint/js": { - "version": "8.57.1", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.57.1.tgz", - "integrity": "sha512-d9zaMRSTIKDLhctzH12MtXvJKSSUhaHcjV+2Z+GK+EEY7XKpP5yR4x+N3TAcHTcu963nIr+TMcCb4DBCYX1z6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - } - }, - "node_modules/@huggingface/jinja": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.3.4.tgz", - "integrity": "sha512-kFFQWJiWwvxezKQnvH1X7GjsECcMljFx+UZK9hx6P26aVHwwidJVTB0ptLfRVZQvVkOGHoMmTGvo4nT0X9hHOA==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/@huggingface/transformers": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/@huggingface/transformers/-/transformers-3.0.2.tgz", - "integrity": "sha512-lTyS81eQazMea5UCehDGFMfdcNRZyei7XQLH5X6j4AhA/18Ka0+5qPgMxUxuZLU4xkv60aY2KNz9Yzthv6WVJg==", - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "@huggingface/jinja": "^0.3.0", - "onnxruntime-node": "1.19.2", - "onnxruntime-web": "1.21.0-dev.20241024-d9ca84ef96", - "sharp": "^0.33.5" - } - }, - "node_modules/@humanwhocodes/config-array": { - "version": "0.13.0", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", - "integrity": "sha512-DZLEEqFWQFiyK6h5YIeynKx7JlvCYWL0cImfSRXZ9l4Sg2efkFGTuFf6vzXjK1cq6IYkU+Eg/JizXw+TD2vRNw==", - "deprecated": "Use @eslint/config-array instead", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@humanwhocodes/object-schema": "^2.0.3", - "debug": "^4.3.1", - "minimatch": "^3.0.5" - }, - "engines": { - "node": ">=10.10.0" - } - }, - "node_modules/@humanwhocodes/module-importer": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", - "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=12.22" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/nzakas" - } - }, - "node_modules/@humanwhocodes/object-schema": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.3.tgz", - "integrity": "sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==", - "deprecated": "Use @eslint/object-schema instead", - "dev": true, - "license": "BSD-3-Clause" - }, - "node_modules/@img/sharp-darwin-arm64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.33.5.tgz", - "integrity": "sha512-UT4p+iz/2H4twwAoLCqfA9UH5pI6DggwKEGuaPy7nCVQ8ZsiY5PIcrRvD1DzuY3qYL07NtIQcWnBSY/heikIFQ==", - "cpu": [ - "arm64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-darwin-arm64": "1.0.4" - } - }, - "node_modules/@img/sharp-darwin-x64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.33.5.tgz", - "integrity": "sha512-fyHac4jIc1ANYGRDxtiqelIbdWkIuQaI84Mv45KvGRRxSAa7o7d1ZKAOBaYbnepLC1WqxfpimdeWfvqqSGwR2Q==", - "cpu": [ - "x64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-darwin-x64": "1.0.4" - } - }, - "node_modules/@img/sharp-libvips-darwin-arm64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.0.4.tgz", - "integrity": "sha512-XblONe153h0O2zuFfTAbQYAX2JhYmDHeWikp1LM9Hul9gVPjFY427k6dFEcOL72O01QxQsWi761svJ/ev9xEDg==", - "cpu": [ - "arm64" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "darwin" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-darwin-x64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.0.4.tgz", - "integrity": "sha512-xnGR8YuZYfJGmWPvmlunFaWJsb9T/AO2ykoP3Fz/0X5XV2aoYBPkX6xqCQvUTKKiLddarLaxpzNe+b1hjeWHAQ==", - "cpu": [ - "x64" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "darwin" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linux-arm": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.0.5.tgz", - "integrity": "sha512-gvcC4ACAOPRNATg/ov8/MnbxFDJqf/pDePbBnuBDcjsI8PssmjoKMAz4LtLaVi+OnSb5FK/yIOamqDwGmXW32g==", - "cpu": [ - "arm" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linux-arm64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.0.4.tgz", - "integrity": "sha512-9B+taZ8DlyyqzZQnoeIvDVR/2F4EbMepXMc/NdVbkzsJbzkUjhXv/70GQJ7tdLA4YJgNP25zukcxpX2/SueNrA==", - "cpu": [ - "arm64" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linux-s390x": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.0.4.tgz", - "integrity": "sha512-u7Wz6ntiSSgGSGcjZ55im6uvTrOxSIS8/dgoVMoiGE9I6JAfU50yH5BoDlYA1tcuGS7g/QNtetJnxA6QEsCVTA==", - "cpu": [ - "s390x" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linux-x64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.0.4.tgz", - "integrity": "sha512-MmWmQ3iPFZr0Iev+BAgVMb3ZyC4KeFc3jFxnNbEPas60e1cIfevbtuyf9nDGIzOaW9PdnDciJm+wFFaTlj5xYw==", - "cpu": [ - "x64" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linuxmusl-arm64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.0.4.tgz", - "integrity": "sha512-9Ti+BbTYDcsbp4wfYib8Ctm1ilkugkA/uscUn6UXK1ldpC1JjiXbLfFZtRlBhjPZ5o1NCLiDbg8fhUPKStHoTA==", - "cpu": [ - "arm64" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-libvips-linuxmusl-x64": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.0.4.tgz", - "integrity": "sha512-viYN1KX9m+/hGkJtvYYp+CCLgnJXwiQB39damAO7WMdKWlIhmYTfHjwSbQeUK/20vY154mwezd9HflVFM1wVSw==", - "cpu": [ - "x64" - ], - "license": "LGPL-3.0-or-later", - "optional": true, - "os": [ - "linux" - ], - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-linux-arm": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.33.5.tgz", - "integrity": "sha512-JTS1eldqZbJxjvKaAkxhZmBqPRGmxgu+qFKSInv8moZ2AmT5Yib3EQ1c6gp493HvrvV8QgdOXdyaIBrhvFhBMQ==", - "cpu": [ - "arm" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-arm": "1.0.5" - } - }, - "node_modules/@img/sharp-linux-arm64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.33.5.tgz", - "integrity": "sha512-JMVv+AMRyGOHtO1RFBiJy/MBsgz0x4AWrT6QoEVVTyh1E39TrCUpTRI7mx9VksGX4awWASxqCYLCV4wBZHAYxA==", - "cpu": [ - "arm64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-arm64": "1.0.4" - } - }, - "node_modules/@img/sharp-linux-s390x": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.33.5.tgz", - "integrity": "sha512-y/5PCd+mP4CA/sPDKl2961b+C9d+vPAveS33s6Z3zfASk2j5upL6fXVPZi7ztePZ5CuH+1kW8JtvxgbuXHRa4Q==", - "cpu": [ - "s390x" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-s390x": "1.0.4" - } - }, - "node_modules/@img/sharp-linux-x64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.33.5.tgz", - "integrity": "sha512-opC+Ok5pRNAzuvq1AG0ar+1owsu842/Ab+4qvU879ippJBHvyY5n2mxF1izXqkPYlGuP/M556uh53jRLJmzTWA==", - "cpu": [ - "x64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linux-x64": "1.0.4" - } - }, - "node_modules/@img/sharp-linuxmusl-arm64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.33.5.tgz", - "integrity": "sha512-XrHMZwGQGvJg2V/oRSUfSAfjfPxO+4DkiRh6p2AFjLQztWUuY/o8Mq0eMQVIY7HJ1CDQUJlxGGZRw1a5bqmd1g==", - "cpu": [ - "arm64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-arm64": "1.0.4" - } - }, - "node_modules/@img/sharp-linuxmusl-x64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.33.5.tgz", - "integrity": "sha512-WT+d/cgqKkkKySYmqoZ8y3pxx7lx9vVejxW/W4DOFMYVSkErR+w7mf2u8m/y4+xHe7yY9DAXQMWQhpnMuFfScw==", - "cpu": [ - "x64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-x64": "1.0.4" - } - }, - "node_modules/@img/sharp-wasm32": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.33.5.tgz", - "integrity": "sha512-ykUW4LVGaMcU9lu9thv85CbRMAwfeadCJHRsg2GmeRa/cJxsVY9Rbd57JcMxBkKHag5U/x7TSBpScF4U8ElVzg==", - "cpu": [ - "wasm32" - ], - "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", - "optional": true, - "dependencies": { - "@emnapi/runtime": "^1.2.0" - }, - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-win32-ia32": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.33.5.tgz", - "integrity": "sha512-T36PblLaTwuVJ/zw/LaH0PdZkRz5rd3SmMHX8GSmR7vtNSP5Z6bQkExdSK7xGWyxLw4sUknBuugTelgw2faBbQ==", - "cpu": [ - "ia32" - ], - "license": "Apache-2.0 AND LGPL-3.0-or-later", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@img/sharp-win32-x64": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.33.5.tgz", - "integrity": "sha512-MpY/o8/8kj+EcnxwvrP4aTJSWw/aZ7JIGR4aBeZkZw5B7/Jn+tY9/VNwtcoGmdT7GfggGIU4kygOMSbYnOrAbg==", - "cpu": [ - "x64" - ], - "license": "Apache-2.0 AND LGPL-3.0-or-later", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/@inquirer/ansi": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.5.tgz", - "integrity": "sha512-doc2sWgJpbFQ64UflSVd17ibMGDuxO1yKgOgLMwavzESnXjFWJqUeG8saYosqKpHp4kWiM5x1nXvEjbpx90gzw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - } - }, - "node_modules/@inquirer/checkbox": { - "version": "5.1.5", - "resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-5.1.5.tgz", - "integrity": "sha512-Jmf9tgBHIEK5SAOB7swYfStqmtkZb00xOTpSQmkoGEpdxOTpJi9RS0A8bkfDPHTTItZRJrRdZrEMu25wyj0VfQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/ansi": "^2.0.5", - "@inquirer/core": "^11.1.10", - "@inquirer/figures": "^2.0.5", - "@inquirer/type": "^4.0.5" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/confirm": { - "version": "6.0.13", - "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-6.0.13.tgz", - "integrity": "sha512-wkGPC7yJ5WJk1DJ5SX7fzk+gfj4BM8cf5dDDi71B/551xHrdsZVRJOC0WyikXd0pEsb/9cLniuE4atbsMqmFkw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^11.1.10", - "@inquirer/type": "^4.0.5" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/core": { - "version": "11.1.10", - "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-11.1.10.tgz", - "integrity": "sha512-a4Q5BXHQAHa9eO202sTaFCHFYVB3x5fauDuThEAdZ9gfn76pSxiKU7wWcEH0N1O0XmQvNfQNU6QXpiRxmYQx+A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/ansi": "^2.0.5", - "@inquirer/figures": "^2.0.5", - "@inquirer/type": "^4.0.5", - "cli-width": "^4.1.0", - "fast-wrap-ansi": "^0.2.0", - "mute-stream": "^3.0.0", - "signal-exit": "^4.1.0" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/editor": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-5.1.2.tgz", - "integrity": "sha512-Y3Nor7S/DhIPo+8Ym/dSY4efwKI4BsflKDwXh0jNeXJsSF3dteS/3Yf+z4wkibVZDvYMyCgknSTQlNahfunGHg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^11.1.10", - "@inquirer/external-editor": "^3.0.0", - "@inquirer/type": "^4.0.5" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/expand": { - "version": "5.0.14", - "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-5.0.14.tgz", - "integrity": "sha512-qyY9zcIX2eKYwaAUiQo9zORd61Lc3sXeM72fVbeHkYnDkqfr8/armcRbmVAIrExeJhI2puk+uomeKtWrpUVUmQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^11.1.10", - "@inquirer/type": "^4.0.5" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/external-editor": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-3.0.0.tgz", - "integrity": "sha512-lDSwMgg+M5rq6JKBYaJwSX6T9e/HK2qqZ1oxmOwn4AQoJE5D+7TumsxLGC02PWS//rkIVqbZv3XA3ejsc9FYvg==", - "dev": true, - "license": "MIT", - "dependencies": { - "chardet": "^2.1.1", - "iconv-lite": "^0.7.2" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/figures": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.0.5.tgz", - "integrity": "sha512-NsSs4kzfm12lNetHwAn3GEuH317IzpwrMCbOuMIVytpjnJ90YYHNwdRgYGuKmVxwuIqSgqk3M5qqQt1cDk0tGQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - } - }, - "node_modules/@inquirer/input": { - "version": "5.0.13", - "resolved": "https://registry.npmjs.org/@inquirer/input/-/input-5.0.13.tgz", - "integrity": "sha512-0l0jCHlJnXIV8CTxwQC0C+5Ziq8WP22edWgmciW2xYvoeoSck4v5FvCS1ctKdqLLR0dUo93uAHgWHywgBSoRyw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^11.1.10", - "@inquirer/type": "^4.0.5" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/number": { - "version": "4.0.13", - "resolved": "https://registry.npmjs.org/@inquirer/number/-/number-4.0.13.tgz", - "integrity": "sha512-WHmkYnnJAou5gx7RgcvAfUggnHNM1zWfoh0dFPl3dxVssuqt+dK5rIbaOYQXNyOegvFnopbKupjnhw2O8gANNg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^11.1.10", - "@inquirer/type": "^4.0.5" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/password": { - "version": "5.0.13", - "resolved": "https://registry.npmjs.org/@inquirer/password/-/password-5.0.13.tgz", - "integrity": "sha512-XDGu64ROHZjOOXLAANvJN7iIxWKhOSCG5VakrZ5kaScVR+snVJCFglD/hL3/677awtWcu4pXoWa280CDIYcBeg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/ansi": "^2.0.5", - "@inquirer/core": "^11.1.10", - "@inquirer/type": "^4.0.5" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/prompts": { - "version": "8.4.3", - "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-8.4.3.tgz", - "integrity": "sha512-ai5LseTw9HhegupIgmo4cn7RpnCGznjjXu4OI+7jMR8vu7T1ZCCNMzFFAovUCjL1fl0cceksIN1++yQE59SmZw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/checkbox": "^5.1.5", - "@inquirer/confirm": "^6.0.13", - "@inquirer/editor": "^5.1.2", - "@inquirer/expand": "^5.0.14", - "@inquirer/input": "^5.0.13", - "@inquirer/number": "^4.0.13", - "@inquirer/password": "^5.0.13", - "@inquirer/rawlist": "^5.2.9", - "@inquirer/search": "^4.1.9", - "@inquirer/select": "^5.1.5" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/rawlist": { - "version": "5.2.9", - "resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-5.2.9.tgz", - "integrity": "sha512-a1ErXEfgjfPYpyQ89dp+7n2IISjH9oQg3ygvF5adz8B7aHn4n2PjEgu1wpVTp69K3bj3lVLxP0qJ2b1clk1Whw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^11.1.10", - "@inquirer/type": "^4.0.5" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/search": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/@inquirer/search/-/search-4.1.9.tgz", - "integrity": "sha512-ZlbM28Q9lmLkFPNAIv+ZuY530n5Km8U1WW48oYEvDhe9yc2uL3m3t+JSdRUkQlk5fuIuskgiIVjcb7czFzQpuA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/core": "^11.1.10", - "@inquirer/figures": "^2.0.5", - "@inquirer/type": "^4.0.5" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/select": { - "version": "5.1.5", - "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-5.1.5.tgz", - "integrity": "sha512-6SRg6kHfK/sjLXOsuqNebuir+sjwrf/iWuRUnXgB2slzEewppI1WfzeS16XxDcOQmXBruMmmB9Cgrz7wsAxqMg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/ansi": "^2.0.5", - "@inquirer/core": "^11.1.10", - "@inquirer/figures": "^2.0.5", - "@inquirer/type": "^4.0.5" - }, - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "node_modules/@inquirer/type": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.0.5.tgz", - "integrity": "sha512-aetVUNeKNc/VriqXlw1NRSW0zhMBB0W4bNbWRJgzRl/3d0QNDQFfk0GO5SDdtjMZVg6o8ZKEiadd7SCCzoOn5Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" - }, - "peerDependencies": { - "@types/node": ">=18" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - } - } - }, - "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/@istanbuljs/load-nyc-config": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", - "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "camelcase": "^5.3.1", - "find-up": "^4.1.0", - "get-package-type": "^0.1.0", - "js-yaml": "^3.13.1", - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "license": "MIT", - "dependencies": { - "sprintf-js": "~1.0.2" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/js-yaml": { - "version": "3.14.2", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", - "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", - "dev": true, - "license": "MIT", - "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-locate": "^4.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-try": "^2.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-limit": "^2.2.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/load-nyc-config/node_modules/resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/schema": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz", - "integrity": "sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/@jest/console": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/console/-/console-29.7.0.tgz", - "integrity": "sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/core": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/core/-/core-29.7.0.tgz", - "integrity": "sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/console": "^29.7.0", - "@jest/reporters": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-changed-files": "^29.7.0", - "jest-config": "^29.7.0", - "jest-haste-map": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-resolve-dependencies": "^29.7.0", - "jest-runner": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "jest-watcher": "^29.7.0", - "micromatch": "^4.0.4", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/@jest/environment": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-29.7.0.tgz", - "integrity": "sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/fake-timers": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-mock": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/expect": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-29.7.0.tgz", - "integrity": "sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "expect": "^29.7.0", - "jest-snapshot": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/expect-utils": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-29.7.0.tgz", - "integrity": "sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==", - "dev": true, - "license": "MIT", - "dependencies": { - "jest-get-type": "^29.6.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/fake-timers": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-29.7.0.tgz", - "integrity": "sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "@sinonjs/fake-timers": "^10.0.2", - "@types/node": "*", - "jest-message-util": "^29.7.0", - "jest-mock": "^29.7.0", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/globals": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-29.7.0.tgz", - "integrity": "sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/expect": "^29.7.0", - "@jest/types": "^29.6.3", - "jest-mock": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/reporters": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-29.7.0.tgz", - "integrity": "sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@bcoe/v8-coverage": "^0.2.3", - "@jest/console": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@jridgewell/trace-mapping": "^0.3.18", - "@types/node": "*", - "chalk": "^4.0.0", - "collect-v8-coverage": "^1.0.0", - "exit": "^0.1.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "istanbul-lib-coverage": "^3.0.0", - "istanbul-lib-instrument": "^6.0.0", - "istanbul-lib-report": "^3.0.0", - "istanbul-lib-source-maps": "^4.0.0", - "istanbul-reports": "^3.1.3", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "jest-worker": "^29.7.0", - "slash": "^3.0.0", - "string-length": "^4.0.1", - "strip-ansi": "^6.0.0", - "v8-to-istanbul": "^9.0.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/@jest/schemas": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz", - "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@sinclair/typebox": "^0.27.8" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/source-map": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-29.6.3.tgz", - "integrity": "sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.18", - "callsites": "^3.0.0", - "graceful-fs": "^4.2.9" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/test-result": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-29.7.0.tgz", - "integrity": "sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/console": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "collect-v8-coverage": "^1.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/test-sequencer": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz", - "integrity": "sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/test-result": "^29.7.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/transform": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-29.7.0.tgz", - "integrity": "sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.11.6", - "@jest/types": "^29.6.3", - "@jridgewell/trace-mapping": "^0.3.18", - "babel-plugin-istanbul": "^6.1.1", - "chalk": "^4.0.0", - "convert-source-map": "^2.0.0", - "fast-json-stable-stringify": "^2.1.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-util": "^29.7.0", - "micromatch": "^4.0.4", - "pirates": "^4.0.4", - "slash": "^3.0.0", - "write-file-atomic": "^4.0.2" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jest/types": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz", - "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/schemas": "^29.6.3", - "@types/istanbul-lib-coverage": "^2.0.0", - "@types/istanbul-reports": "^3.0.0", - "@types/node": "*", - "@types/yargs": "^17.0.8", - "chalk": "^4.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.13", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", - "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/sourcemap-codec": "^1.5.0", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/remapping": { - "version": "2.3.5", - "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", - "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/gen-mapping": "^0.3.5", - "@jridgewell/trace-mapping": "^0.3.24" - } - }, - "node_modules/@jridgewell/resolve-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", - "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.31", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", - "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/resolve-uri": "^3.1.0", - "@jridgewell/sourcemap-codec": "^1.4.14" - } - }, - "node_modules/@napi-rs/cli": { - "version": "3.7.0", - "resolved": "https://registry.npmjs.org/@napi-rs/cli/-/cli-3.7.0.tgz", - "integrity": "sha512-3d3+rmxlOIV/G1zPWeX4PCxuYnhcCQM2BvY9rtimC8RO0dFR9gtYP+Grov+WoduZtfWRj5N1XvytWeRxxCk5zw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@inquirer/prompts": "^8.0.0", - "@napi-rs/cross-toolchain": "^1.0.3", - "@napi-rs/wasm-tools": "^1.0.1", - "@octokit/rest": "^22.0.1", - "clipanion": "^4.0.0-rc.4", - "colorette": "^2.0.20", - "emnapi": "^1.10.0", - "es-toolkit": "^1.41.0", - "js-yaml": "^4.1.0", - "obug": "^2.0.0", - "semver": "^7.7.3", - "typanion": "^3.14.0" - }, - "bin": { - "napi": "dist/cli.js", - "napi-raw": "cli.mjs" - }, - "engines": { - "node": ">= 16" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" - }, - "peerDependencies": { - "@emnapi/runtime": "^1.7.1" - }, - "peerDependenciesMeta": { - "@emnapi/runtime": { - "optional": true - } - } - }, - "node_modules/@napi-rs/cross-toolchain": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@napi-rs/cross-toolchain/-/cross-toolchain-1.0.3.tgz", - "integrity": "sha512-ENPfLe4937bsKVTDA6zdABx4pq9w0tHqRrJHyaGxgaPq03a2Bd1unD5XSKjXJjebsABJ+MjAv1A2OvCgK9yehg==", - "dev": true, - "license": "MIT", - "workspaces": [ - ".", - "arm64/*", - "x64/*" - ], - "dependencies": { - "@napi-rs/lzma": "^1.4.5", - "@napi-rs/tar": "^1.1.0", - "debug": "^4.4.1" - }, - "peerDependencies": { - "@napi-rs/cross-toolchain-arm64-target-aarch64": "^1.0.3", - "@napi-rs/cross-toolchain-arm64-target-armv7": "^1.0.3", - "@napi-rs/cross-toolchain-arm64-target-ppc64le": "^1.0.3", - "@napi-rs/cross-toolchain-arm64-target-s390x": "^1.0.3", - "@napi-rs/cross-toolchain-arm64-target-x86_64": "^1.0.3", - "@napi-rs/cross-toolchain-x64-target-aarch64": "^1.0.3", - "@napi-rs/cross-toolchain-x64-target-armv7": "^1.0.3", - "@napi-rs/cross-toolchain-x64-target-ppc64le": "^1.0.3", - "@napi-rs/cross-toolchain-x64-target-s390x": "^1.0.3", - "@napi-rs/cross-toolchain-x64-target-x86_64": "^1.0.3" - }, - "peerDependenciesMeta": { - "@napi-rs/cross-toolchain-arm64-target-aarch64": { - "optional": true - }, - "@napi-rs/cross-toolchain-arm64-target-armv7": { - "optional": true - }, - "@napi-rs/cross-toolchain-arm64-target-ppc64le": { - "optional": true - }, - "@napi-rs/cross-toolchain-arm64-target-s390x": { - "optional": true - }, - "@napi-rs/cross-toolchain-arm64-target-x86_64": { - "optional": true - }, - "@napi-rs/cross-toolchain-x64-target-aarch64": { - "optional": true - }, - "@napi-rs/cross-toolchain-x64-target-armv7": { - "optional": true - }, - "@napi-rs/cross-toolchain-x64-target-ppc64le": { - "optional": true - }, - "@napi-rs/cross-toolchain-x64-target-s390x": { - "optional": true - }, - "@napi-rs/cross-toolchain-x64-target-x86_64": { - "optional": true - } - } - }, - "node_modules/@napi-rs/lzma": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma/-/lzma-1.4.5.tgz", - "integrity": "sha512-zS5LuN1OBPAyZpda2ZZgYOEDC+xecUdAGnrvbYzjnLXkrq/OBC3B9qcRvlxbDR3k5H/gVfvef1/jyUqPknqjbg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 10" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" - }, - "optionalDependencies": { - "@napi-rs/lzma-android-arm-eabi": "1.4.5", - "@napi-rs/lzma-android-arm64": "1.4.5", - "@napi-rs/lzma-darwin-arm64": "1.4.5", - "@napi-rs/lzma-darwin-x64": "1.4.5", - "@napi-rs/lzma-freebsd-x64": "1.4.5", - "@napi-rs/lzma-linux-arm-gnueabihf": "1.4.5", - "@napi-rs/lzma-linux-arm64-gnu": "1.4.5", - "@napi-rs/lzma-linux-arm64-musl": "1.4.5", - "@napi-rs/lzma-linux-ppc64-gnu": "1.4.5", - "@napi-rs/lzma-linux-riscv64-gnu": "1.4.5", - "@napi-rs/lzma-linux-s390x-gnu": "1.4.5", - "@napi-rs/lzma-linux-x64-gnu": "1.4.5", - "@napi-rs/lzma-linux-x64-musl": "1.4.5", - "@napi-rs/lzma-wasm32-wasi": "1.4.5", - "@napi-rs/lzma-win32-arm64-msvc": "1.4.5", - "@napi-rs/lzma-win32-ia32-msvc": "1.4.5", - "@napi-rs/lzma-win32-x64-msvc": "1.4.5" - } - }, - "node_modules/@napi-rs/lzma-android-arm-eabi": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-android-arm-eabi/-/lzma-android-arm-eabi-1.4.5.tgz", - "integrity": "sha512-Up4gpyw2SacmyKWWEib06GhiDdF+H+CCU0LAV8pnM4aJIDqKKd5LHSlBht83Jut6frkB0vwEPmAkv4NjQ5u//Q==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-android-arm64": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-android-arm64/-/lzma-android-arm64-1.4.5.tgz", - "integrity": "sha512-uwa8sLlWEzkAM0MWyoZJg0JTD3BkPknvejAFG2acUA1raXM8jLrqujWCdOStisXhqQjZ2nDMp3FV6cs//zjfuQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-darwin-arm64": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-darwin-arm64/-/lzma-darwin-arm64-1.4.5.tgz", - "integrity": "sha512-0Y0TQLQ2xAjVabrMDem1NhIssOZzF/y/dqetc6OT8mD3xMTDtF8u5BqZoX3MyPc9FzpsZw4ksol+w7DsxHrpMA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-darwin-x64": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-darwin-x64/-/lzma-darwin-x64-1.4.5.tgz", - "integrity": "sha512-vR2IUyJY3En+V1wJkwmbGWcYiT8pHloTAWdW4pG24+51GIq+intst6Uf6D/r46citObGZrlX0QvMarOkQeHWpw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-freebsd-x64": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-freebsd-x64/-/lzma-freebsd-x64-1.4.5.tgz", - "integrity": "sha512-XpnYQC5SVovO35tF0xGkbHYjsS6kqyNCjuaLQ2dbEblFRr5cAZVvsJ/9h7zj/5FluJPJRDojVNxGyRhTp4z2lw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-linux-arm-gnueabihf": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-arm-gnueabihf/-/lzma-linux-arm-gnueabihf-1.4.5.tgz", - "integrity": "sha512-ic1ZZMoRfRMwtSwxkyw4zIlbDZGC6davC9r+2oX6x9QiF247BRqqT94qGeL5ZP4Vtz0Hyy7TEViWhx5j6Bpzvw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-linux-arm64-gnu": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-arm64-gnu/-/lzma-linux-arm64-gnu-1.4.5.tgz", - "integrity": "sha512-asEp7FPd7C1Yi6DQb45a3KPHKOFBSfGuJWXcAd4/bL2Fjetb2n/KK2z14yfW8YC/Fv6x3rBM0VAZKmJuz4tysg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-linux-arm64-musl": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-arm64-musl/-/lzma-linux-arm64-musl-1.4.5.tgz", - "integrity": "sha512-yWjcPDgJ2nIL3KNvi4536dlT/CcCWO0DUyEOlBs/SacG7BeD6IjGh6yYzd3/X1Y3JItCbZoDoLUH8iB1lTXo3w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-linux-ppc64-gnu": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-ppc64-gnu/-/lzma-linux-ppc64-gnu-1.4.5.tgz", - "integrity": "sha512-0XRhKuIU/9ZjT4WDIG/qnX7Xz7mSQHYZo9Gb3MP2gcvBgr6BA4zywQ9k3gmQaPn9ECE+CZg2V7DV7kT+x2pUMQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-linux-riscv64-gnu": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-riscv64-gnu/-/lzma-linux-riscv64-gnu-1.4.5.tgz", - "integrity": "sha512-QrqDIPEUUB23GCpyQj/QFyMlr8SGxxyExeZz9OWFnHfb70kXdTLWrHS/hEI1Ru+lSbQ/6xRqeoGyQ4Aqdg+/RA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-linux-s390x-gnu": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-s390x-gnu/-/lzma-linux-s390x-gnu-1.4.5.tgz", - "integrity": "sha512-k8RVM5aMhW86E9H0QXdquwojew4H3SwPxbRVbl49/COJQWCUjGi79X6mYruMnMPEznZinUiT1jgKbFo2A00NdA==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-linux-x64-gnu": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.4.5.tgz", - "integrity": "sha512-6rMtBgnIq2Wcl1rQdZsnM+rtCcVCbws1nF8S2NzaUsVaZv8bjrPiAa0lwg4Eqnn1d9lgwqT+cZgm5m+//K08Kw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-linux-x64-musl": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-musl/-/lzma-linux-x64-musl-1.4.5.tgz", - "integrity": "sha512-eiadGBKi7Vd0bCArBUOO/qqRYPHt/VQVvGyYvDFt6C2ZSIjlD+HuOl+2oS1sjf4CFjK4eDIog6EdXnL0NE6iyQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-wasm32-wasi": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-wasm32-wasi/-/lzma-wasm32-wasi-1.4.5.tgz", - "integrity": "sha512-+VyHHlr68dvey6fXc2hehw9gHVFIW3TtGF1XkcbAu65qVXsA9D/T+uuoRVqhE+JCyFHFrO0ixRbZDRK1XJt1sA==", - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@napi-rs/wasm-runtime": "^1.0.3" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@napi-rs/lzma-win32-arm64-msvc": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-win32-arm64-msvc/-/lzma-win32-arm64-msvc-1.4.5.tgz", - "integrity": "sha512-eewnqvIyyhHi3KaZtBOJXohLvwwN27gfS2G/YDWdfHlbz1jrmfeHAmzMsP5qv8vGB+T80TMHNkro4kYjeh6Deg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-win32-ia32-msvc": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-win32-ia32-msvc/-/lzma-win32-ia32-msvc-1.4.5.tgz", - "integrity": "sha512-OeacFVRCJOKNU/a0ephUfYZ2Yt+NvaHze/4TgOwJ0J0P4P7X1mHzN+ig9Iyd74aQDXYqc7kaCXA2dpAOcH87Cg==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/lzma-win32-x64-msvc": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/@napi-rs/lzma-win32-x64-msvc/-/lzma-win32-x64-msvc-1.4.5.tgz", - "integrity": "sha512-T4I1SamdSmtyZgDXGAGP+y5LEK5vxHUFwe8mz6D4R7Sa5/WCxTcCIgPJ9BD7RkpO17lzhlaM2vmVvMy96Lvk9Q==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar/-/tar-1.1.0.tgz", - "integrity": "sha512-7cmzIu+Vbupriudo7UudoMRH2OA3cTw67vva8MxeoAe5S7vPFI7z0vp0pMXiA25S8IUJefImQ90FeJjl8fjEaQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 10" - }, - "optionalDependencies": { - "@napi-rs/tar-android-arm-eabi": "1.1.0", - "@napi-rs/tar-android-arm64": "1.1.0", - "@napi-rs/tar-darwin-arm64": "1.1.0", - "@napi-rs/tar-darwin-x64": "1.1.0", - "@napi-rs/tar-freebsd-x64": "1.1.0", - "@napi-rs/tar-linux-arm-gnueabihf": "1.1.0", - "@napi-rs/tar-linux-arm64-gnu": "1.1.0", - "@napi-rs/tar-linux-arm64-musl": "1.1.0", - "@napi-rs/tar-linux-ppc64-gnu": "1.1.0", - "@napi-rs/tar-linux-s390x-gnu": "1.1.0", - "@napi-rs/tar-linux-x64-gnu": "1.1.0", - "@napi-rs/tar-linux-x64-musl": "1.1.0", - "@napi-rs/tar-wasm32-wasi": "1.1.0", - "@napi-rs/tar-win32-arm64-msvc": "1.1.0", - "@napi-rs/tar-win32-ia32-msvc": "1.1.0", - "@napi-rs/tar-win32-x64-msvc": "1.1.0" - } - }, - "node_modules/@napi-rs/tar-android-arm-eabi": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-android-arm-eabi/-/tar-android-arm-eabi-1.1.0.tgz", - "integrity": "sha512-h2Ryndraj/YiKgMV/r5by1cDusluYIRT0CaE0/PekQ4u+Wpy2iUVqvzVU98ZPnhXaNeYxEvVJHNGafpOfaD0TA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar-android-arm64": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-android-arm64/-/tar-android-arm64-1.1.0.tgz", - "integrity": "sha512-DJFyQHr1ZxNZorm/gzc1qBNLF/FcKzcH0V0Vwan5P+o0aE2keQIGEjJ09FudkF9v6uOuJjHCVDdK6S6uHtShAw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar-darwin-arm64": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-darwin-arm64/-/tar-darwin-arm64-1.1.0.tgz", - "integrity": "sha512-Zz2sXRzjIX4e532zD6xm2SjXEym6MkvfCvL2RMpG2+UwNVDVscHNcz3d47Pf3sysP2e2af7fBB3TIoK2f6trPw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar-darwin-x64": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-darwin-x64/-/tar-darwin-x64-1.1.0.tgz", - "integrity": "sha512-EI+CptIMNweT0ms9S3mkP/q+J6FNZ1Q6pvpJOEcWglRfyfQpLqjlC0O+dptruTPE8VamKYuqdjxfqD8hifZDOA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar-freebsd-x64": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-freebsd-x64/-/tar-freebsd-x64-1.1.0.tgz", - "integrity": "sha512-J0PIqX+pl6lBIAckL/c87gpodLbjZB1OtIK+RDscKC9NLdpVv6VGOxzUV/fYev/hctcE8EfkLbgFOfpmVQPg2g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar-linux-arm-gnueabihf": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-linux-arm-gnueabihf/-/tar-linux-arm-gnueabihf-1.1.0.tgz", - "integrity": "sha512-SLgIQo3f3EjkZ82ZwvrEgFvMdDAhsxCYjyoSuWfHCz0U16qx3SuGCp8+FYOPYCECHN3ZlGjXnoAIt9ERd0dEUg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar-linux-arm64-gnu": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-linux-arm64-gnu/-/tar-linux-arm64-gnu-1.1.0.tgz", - "integrity": "sha512-d014cdle52EGaH6GpYTQOP9Py7glMO1zz/+ynJPjjzYFSxvdYx0byrjumZk2UQdIyGZiJO2MEFpCkEEKFSgPYA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar-linux-arm64-musl": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-linux-arm64-musl/-/tar-linux-arm64-musl-1.1.0.tgz", - "integrity": "sha512-L/y1/26q9L/uBqiW/JdOb/Dc94egFvNALUZV2WCGKQXc6UByPBMgdiEyW2dtoYxYYYYc+AKD+jr+wQPcvX2vrQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar-linux-ppc64-gnu": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-linux-ppc64-gnu/-/tar-linux-ppc64-gnu-1.1.0.tgz", - "integrity": "sha512-EPE1K/80RQvPbLRJDJs1QmCIcH+7WRi0F73+oTe1582y9RtfGRuzAkzeBuAGRXAQEjRQw/RjtNqr6UTJ+8UuWQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar-linux-s390x-gnu": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-linux-s390x-gnu/-/tar-linux-s390x-gnu-1.1.0.tgz", - "integrity": "sha512-B2jhWiB1ffw1nQBqLUP1h4+J1ovAxBOoe5N2IqDMOc63fsPZKNqF1PvO/dIem8z7LL4U4bsfmhy3gBfu547oNQ==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar-linux-x64-gnu": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-linux-x64-gnu/-/tar-linux-x64-gnu-1.1.0.tgz", - "integrity": "sha512-tbZDHnb9617lTnsDMGo/eAMZxnsQFnaRe+MszRqHguKfMwkisc9CCJnks/r1o84u5fECI+J/HOrKXgczq/3Oww==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar-linux-x64-musl": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-linux-x64-musl/-/tar-linux-x64-musl-1.1.0.tgz", - "integrity": "sha512-dV6cODlzbO8u6Anmv2N/ilQHq/AWz0xyltuXoLU3yUyXbZcnWYZuB2rL8OBGPmqNcD+x9NdScBNXh7vWN0naSQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar-wasm32-wasi": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-wasm32-wasi/-/tar-wasm32-wasi-1.1.0.tgz", - "integrity": "sha512-jIa9nb2HzOrfH0F8QQ9g3WE4aMH5vSI5/1NYVNm9ysCmNjCCtMXCAhlI3WKCdm/DwHf0zLqdrrtDFXODcNaqMw==", - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@napi-rs/wasm-runtime": "^1.0.3" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@napi-rs/tar-win32-arm64-msvc": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-win32-arm64-msvc/-/tar-win32-arm64-msvc-1.1.0.tgz", - "integrity": "sha512-vfpG71OB0ijtjemp3WTdmBKJm9R70KM8vsSExMsIQtV0lVzP07oM1CW6JbNRPXNLhRoue9ofYLiUDk8bE0Hckg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar-win32-ia32-msvc": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-win32-ia32-msvc/-/tar-win32-ia32-msvc-1.1.0.tgz", - "integrity": "sha512-hGPyPW60YSpOSgzfy68DLBHgi6HxkAM+L59ZZZPMQ0TOXjQg+p2EW87+TjZfJOkSpbYiEkULwa/f4a2hcVjsqQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/tar-win32-x64-msvc": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@napi-rs/tar-win32-x64-msvc/-/tar-win32-x64-msvc-1.1.0.tgz", - "integrity": "sha512-L6Ed1DxXK9YSCMyvpR8MiNAyKNkQLjsHsHK9E0qnHa8NzLFqzDKhvs5LfnWxM2kJ+F7m/e5n9zPm24kHb3LsVw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz", - "integrity": "sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@tybys/wasm-util": "^0.10.1" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" - }, - "peerDependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1" - } - }, - "node_modules/@napi-rs/wasm-tools": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools/-/wasm-tools-1.0.1.tgz", - "integrity": "sha512-enkZYyuCdo+9jneCPE/0fjIta4wWnvVN9hBo2HuiMpRF0q3lzv1J6b/cl7i0mxZUKhBrV3aCKDBQnCOhwKbPmQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 10" - }, - "optionalDependencies": { - "@napi-rs/wasm-tools-android-arm-eabi": "1.0.1", - "@napi-rs/wasm-tools-android-arm64": "1.0.1", - "@napi-rs/wasm-tools-darwin-arm64": "1.0.1", - "@napi-rs/wasm-tools-darwin-x64": "1.0.1", - "@napi-rs/wasm-tools-freebsd-x64": "1.0.1", - "@napi-rs/wasm-tools-linux-arm64-gnu": "1.0.1", - "@napi-rs/wasm-tools-linux-arm64-musl": "1.0.1", - "@napi-rs/wasm-tools-linux-x64-gnu": "1.0.1", - "@napi-rs/wasm-tools-linux-x64-musl": "1.0.1", - "@napi-rs/wasm-tools-wasm32-wasi": "1.0.1", - "@napi-rs/wasm-tools-win32-arm64-msvc": "1.0.1", - "@napi-rs/wasm-tools-win32-ia32-msvc": "1.0.1", - "@napi-rs/wasm-tools-win32-x64-msvc": "1.0.1" - } - }, - "node_modules/@napi-rs/wasm-tools-android-arm-eabi": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-android-arm-eabi/-/wasm-tools-android-arm-eabi-1.0.1.tgz", - "integrity": "sha512-lr07E/l571Gft5v4aA1dI8koJEmF1F0UigBbsqg9OWNzg80H3lDPO+auv85y3T/NHE3GirDk7x/D3sLO57vayw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/wasm-tools-android-arm64": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-android-arm64/-/wasm-tools-android-arm64-1.0.1.tgz", - "integrity": "sha512-WDR7S+aRLV6LtBJAg5fmjKkTZIdrEnnQxgdsb7Cf8pYiMWBHLU+LC49OUVppQ2YSPY0+GeYm9yuZWW3kLjJ7Bg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/wasm-tools-darwin-arm64": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-darwin-arm64/-/wasm-tools-darwin-arm64-1.0.1.tgz", - "integrity": "sha512-qWTI+EEkiN0oIn/N2gQo7+TVYil+AJ20jjuzD2vATS6uIjVz+Updeqmszi7zq7rdFTLp6Ea3/z4kDKIfZwmR9g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/wasm-tools-darwin-x64": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-darwin-x64/-/wasm-tools-darwin-x64-1.0.1.tgz", - "integrity": "sha512-bA6hubqtHROR5UI3tToAF/c6TDmaAgF0SWgo4rADHtQ4wdn0JeogvOk50gs2TYVhKPE2ZD2+qqt7oBKB+sxW3A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/wasm-tools-freebsd-x64": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-freebsd-x64/-/wasm-tools-freebsd-x64-1.0.1.tgz", - "integrity": "sha512-90+KLBkD9hZEjPQW1MDfwSt5J1L46EUKacpCZWyRuL6iIEO5CgWU0V/JnEgFsDOGyyYtiTvHc5bUdUTWd4I9Vg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/wasm-tools-linux-arm64-gnu": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-linux-arm64-gnu/-/wasm-tools-linux-arm64-gnu-1.0.1.tgz", - "integrity": "sha512-rG0QlS65x9K/u3HrKafDf8cFKj5wV2JHGfl8abWgKew0GVPyp6vfsDweOwHbWAjcHtp2LHi6JHoW80/MTHm52Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/wasm-tools-linux-arm64-musl": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-linux-arm64-musl/-/wasm-tools-linux-arm64-musl-1.0.1.tgz", - "integrity": "sha512-jAasbIvjZXCgX0TCuEFQr+4D6Lla/3AAVx2LmDuMjgG4xoIXzjKWl7c4chuaD+TI+prWT0X6LJcdzFT+ROKGHQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/wasm-tools-linux-x64-gnu": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-linux-x64-gnu/-/wasm-tools-linux-x64-gnu-1.0.1.tgz", - "integrity": "sha512-Plgk5rPqqK2nocBGajkMVbGm010Z7dnUgq0wtnYRZbzWWxwWcXfZMPa8EYxrK4eE8SzpI7VlZP1tdVsdjgGwMw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/wasm-tools-linux-x64-musl": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-linux-x64-musl/-/wasm-tools-linux-x64-musl-1.0.1.tgz", - "integrity": "sha512-GW7AzGuWxtQkyHknHWYFdR0CHmW6is8rG2Rf4V6GNmMpmwtXt/ItWYWtBe4zqJWycMNazpfZKSw/BpT7/MVCXQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/wasm-tools-wasm32-wasi": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-wasm32-wasi/-/wasm-tools-wasm32-wasi-1.0.1.tgz", - "integrity": "sha512-/nQVSTrqSsn7YdAc2R7Ips/tnw5SPUcl3D7QrXCNGPqjbatIspnaexvaOYNyKMU6xPu+pc0BTnKVmqhlJJCPLA==", - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@napi-rs/wasm-runtime": "^1.0.3" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@napi-rs/wasm-tools-win32-arm64-msvc": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-win32-arm64-msvc/-/wasm-tools-win32-arm64-msvc-1.0.1.tgz", - "integrity": "sha512-PFi7oJIBu5w7Qzh3dwFea3sHRO3pojMsaEnUIy22QvsW+UJfNQwJCryVrpoUt8m4QyZXI+saEq/0r4GwdoHYFQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/wasm-tools-win32-ia32-msvc": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-win32-ia32-msvc/-/wasm-tools-win32-ia32-msvc-1.0.1.tgz", - "integrity": "sha512-gXkuYzxQsgkj05Zaq+KQTkHIN83dFAwMcTKa2aQcpYPRImFm2AQzEyLtpXmyCWzJ0F9ZYAOmbSyrNew8/us6bw==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@napi-rs/wasm-tools-win32-x64-msvc": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-tools-win32-x64-msvc/-/wasm-tools-win32-x64-msvc-1.0.1.tgz", - "integrity": "sha512-rEAf05nol3e3eei2sRButmgXP+6ATgm0/38MKhz9Isne82T4rPIMYsCIFj0kOisaGeVwoi2fnm7O9oWp5YVnYQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10" - } - }, - "node_modules/@nodable/entities": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-2.1.0.tgz", - "integrity": "sha512-nyT7T3nbMyBI/lvr6L5TyWbFJAI9FTgVRakNoBqCD+PmID8DzFrrNdLLtHMwMszOtqZa8PAOV24ZqDnQrhQINA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/nodable" - } - ], - "license": "MIT" - }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@octokit/auth-token": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-6.0.0.tgz", - "integrity": "sha512-P4YJBPdPSpWTQ1NU4XYdvHvXJJDxM6YwpS0FZHRgP7YFkdVxsWcpWGy/NVqlAA7PcPCnMacXlRm1y2PFZRWL/w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 20" - } - }, - "node_modules/@octokit/core": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/@octokit/core/-/core-7.0.6.tgz", - "integrity": "sha512-DhGl4xMVFGVIyMwswXeyzdL4uXD5OGILGX5N8Y+f6W7LhC1Ze2poSNrkF/fedpVDHEEZ+PHFW0vL14I+mm8K3Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@octokit/auth-token": "^6.0.0", - "@octokit/graphql": "^9.0.3", - "@octokit/request": "^10.0.6", - "@octokit/request-error": "^7.0.2", - "@octokit/types": "^16.0.0", - "before-after-hook": "^4.0.0", - "universal-user-agent": "^7.0.0" - }, - "engines": { - "node": ">= 20" - } - }, - "node_modules/@octokit/endpoint": { - "version": "11.0.3", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-11.0.3.tgz", - "integrity": "sha512-FWFlNxghg4HrXkD3ifYbS/IdL/mDHjh9QcsNyhQjN8dplUoZbejsdpmuqdA76nxj2xoWPs7p8uX2SNr9rYu0Ag==", - "dev": true, - "license": "MIT", - "dependencies": { - "@octokit/types": "^16.0.0", - "universal-user-agent": "^7.0.2" - }, - "engines": { - "node": ">= 20" - } - }, - "node_modules/@octokit/graphql": { - "version": "9.0.3", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-9.0.3.tgz", - "integrity": "sha512-grAEuupr/C1rALFnXTv6ZQhFuL1D8G5y8CN04RgrO4FIPMrtm+mcZzFG7dcBm+nq+1ppNixu+Jd78aeJOYxlGA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@octokit/request": "^10.0.6", - "@octokit/types": "^16.0.0", - "universal-user-agent": "^7.0.0" - }, - "engines": { - "node": ">= 20" - } - }, - "node_modules/@octokit/openapi-types": { - "version": "27.0.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-27.0.0.tgz", - "integrity": "sha512-whrdktVs1h6gtR+09+QsNk2+FO+49j6ga1c55YZudfEG+oKJVvJLQi3zkOm5JjiUXAagWK2tI2kTGKJ2Ys7MGA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@octokit/plugin-paginate-rest": { - "version": "14.0.0", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-14.0.0.tgz", - "integrity": "sha512-fNVRE7ufJiAA3XUrha2omTA39M6IXIc6GIZLvlbsm8QOQCYvpq/LkMNGyFlB1d8hTDzsAXa3OKtybdMAYsV/fw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@octokit/types": "^16.0.0" - }, - "engines": { - "node": ">= 20" - }, - "peerDependencies": { - "@octokit/core": ">=6" - } - }, - "node_modules/@octokit/plugin-request-log": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/@octokit/plugin-request-log/-/plugin-request-log-6.0.0.tgz", - "integrity": "sha512-UkOzeEN3W91/eBq9sPZNQ7sUBvYCqYbrrD8gTbBuGtHEuycE4/awMXcYvx6sVYo7LypPhmQwwpUe4Yyu4QZN5Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 20" - }, - "peerDependencies": { - "@octokit/core": ">=6" - } - }, - "node_modules/@octokit/plugin-rest-endpoint-methods": { - "version": "17.0.0", - "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-17.0.0.tgz", - "integrity": "sha512-B5yCyIlOJFPqUUeiD0cnBJwWJO8lkJs5d8+ze9QDP6SvfiXSz1BF+91+0MeI1d2yxgOhU/O+CvtiZ9jSkHhFAw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@octokit/types": "^16.0.0" - }, - "engines": { - "node": ">= 20" - }, - "peerDependencies": { - "@octokit/core": ">=6" - } - }, - "node_modules/@octokit/request": { - "version": "10.0.9", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-10.0.9.tgz", - "integrity": "sha512-o8Bi3f608eyM+7BmBiUWxFsdjLb3/ym1cQek5LZOv9KkZcxRrHCPhhRzm6xjO6HVZ85ItD6+sTsjxo821SVa/A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@octokit/endpoint": "^11.0.3", - "@octokit/request-error": "^7.0.2", - "@octokit/types": "^16.0.0", - "content-type": "^2.0.0", - "fast-content-type-parse": "^3.0.0", - "json-with-bigint": "^3.5.3", - "universal-user-agent": "^7.0.2" - }, - "engines": { - "node": ">= 20" - } - }, - "node_modules/@octokit/request-error": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-7.1.0.tgz", - "integrity": "sha512-KMQIfq5sOPpkQYajXHwnhjCC0slzCNScLHs9JafXc4RAJI+9f+jNDlBNaIMTvazOPLgb4BnlhGJOTbnN0wIjPw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@octokit/types": "^16.0.0" - }, - "engines": { - "node": ">= 20" - } - }, - "node_modules/@octokit/rest": { - "version": "22.0.1", - "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-22.0.1.tgz", - "integrity": "sha512-Jzbhzl3CEexhnivb1iQ0KJ7s5vvjMWcmRtq5aUsKmKDrRW6z3r84ngmiFKFvpZjpiU/9/S6ITPFRpn5s/3uQJw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@octokit/core": "^7.0.6", - "@octokit/plugin-paginate-rest": "^14.0.0", - "@octokit/plugin-request-log": "^6.0.0", - "@octokit/plugin-rest-endpoint-methods": "^17.0.0" - }, - "engines": { - "node": ">= 20" - } - }, - "node_modules/@octokit/types": { - "version": "16.0.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-16.0.0.tgz", - "integrity": "sha512-sKq+9r1Mm4efXW1FCk7hFSeJo4QKreL/tTbR0rz/qx/r1Oa2VV83LTA/H/MuCOX7uCIJmQVRKBcbmWoySjAnSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@octokit/openapi-types": "^27.0.0" - } - }, - "node_modules/@opentelemetry/api": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz", - "integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==", - "license": "Apache-2.0", - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/@opentelemetry/core": { - "version": "1.30.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.30.1.tgz", - "integrity": "sha512-OOCM2C/QIURhJMuKaekP3TRBxBKxG/TWWA0TL2J6nXUtDnuCtccy49LUJF8xPFXMX+0LMcxFpCo8M9cGY1W6rQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/semantic-conventions": "1.28.0" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.10.0" - } - }, - "node_modules/@opentelemetry/resources": { - "version": "1.30.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.30.1.tgz", - "integrity": "sha512-5UxZqiAgLYGFjS4s9qm5mBVo433u+dSPUFWVWXmLAD4wB65oMCoXaJP1KJa9DIYYMeHu3z4BZcStG3LC593cWA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "1.30.1", - "@opentelemetry/semantic-conventions": "1.28.0" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.10.0" - } - }, - "node_modules/@opentelemetry/sdk-metrics": { - "version": "1.30.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-1.30.1.tgz", - "integrity": "sha512-q9zcZ0Okl8jRgmy7eNW3Ku1XSgg3sDLa5evHZpCwjspw7E8Is4K/haRPDJrBcX3YSn/Y7gUvFnByNYEKQNbNog==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "1.30.1", - "@opentelemetry/resources": "1.30.1" - }, - "engines": { - "node": ">=14" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.3.0 <1.10.0" - } - }, - "node_modules/@opentelemetry/semantic-conventions": { - "version": "1.28.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz", - "integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=14" - } - }, - "node_modules/@protobufjs/aspromise": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", - "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", - "license": "BSD-3-Clause", - "optional": true - }, - "node_modules/@protobufjs/base64": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", - "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", - "license": "BSD-3-Clause", - "optional": true - }, - "node_modules/@protobufjs/codegen": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", - "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", - "license": "BSD-3-Clause", - "optional": true - }, - "node_modules/@protobufjs/eventemitter": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz", - "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==", - "license": "BSD-3-Clause", - "optional": true - }, - "node_modules/@protobufjs/fetch": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", - "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", - "license": "BSD-3-Clause", - "optional": true, - "dependencies": { - "@protobufjs/aspromise": "^1.1.1" - } - }, - "node_modules/@protobufjs/float": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", - "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", - "license": "BSD-3-Clause", - "optional": true - }, - "node_modules/@protobufjs/inquire": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.2.tgz", - "integrity": "sha512-pa0vFRuws4wkvaXKK1uXZMAwAX4/t8ANaJo45iw/oQHNQ9q5xUzwgFmVJGXiga2BeN+zpX7Vf9vmsiIa2J+MUw==", - "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.1", - "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.1.tgz", - "integrity": "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg==", - "license": "BSD-3-Clause", - "optional": true - }, - "node_modules/@shikijs/core": { - "version": "1.29.2", - "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-1.29.2.tgz", - "integrity": "sha512-vju0lY9r27jJfOY4Z7+Rt/nIOjzJpZ3y+nYpqtUZInVoXQ/TJZcfGnNOGnKjFdVZb8qexiCuSlZRKcGfhhTTZQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/engine-javascript": "1.29.2", - "@shikijs/engine-oniguruma": "1.29.2", - "@shikijs/types": "1.29.2", - "@shikijs/vscode-textmate": "^10.0.1", - "@types/hast": "^3.0.4", - "hast-util-to-html": "^9.0.4" - } - }, - "node_modules/@shikijs/engine-javascript": { - "version": "1.29.2", - "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-1.29.2.tgz", - "integrity": "sha512-iNEZv4IrLYPv64Q6k7EPpOCE/nuvGiKl7zxdq0WFuRPF5PAE9PRo2JGq/d8crLusM59BRemJ4eOqrFrC4wiQ+A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "1.29.2", - "@shikijs/vscode-textmate": "^10.0.1", - "oniguruma-to-es": "^2.2.0" - } - }, - "node_modules/@shikijs/engine-oniguruma": { - "version": "1.29.2", - "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-1.29.2.tgz", - "integrity": "sha512-7iiOx3SG8+g1MnlzZVDYiaeHe7Ez2Kf2HrJzdmGwkRisT7r4rak0e655AcM/tF9JG/kg5fMNYlLLKglbN7gBqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "1.29.2", - "@shikijs/vscode-textmate": "^10.0.1" - } - }, - "node_modules/@shikijs/langs": { - "version": "1.29.2", - "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-1.29.2.tgz", - "integrity": "sha512-FIBA7N3LZ+223U7cJDUYd5shmciFQlYkFXlkKVaHsCPgfVLiO+e12FmQE6Tf9vuyEsFe3dIl8qGWKXgEHL9wmQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "1.29.2" - } - }, - "node_modules/@shikijs/themes": { - "version": "1.29.2", - "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-1.29.2.tgz", - "integrity": "sha512-i9TNZlsq4uoyqSbluIcZkmPL9Bfi3djVxRnofUHwvx/h6SRW3cwgBC5SML7vsDcWyukY0eCzVN980rqP6qNl9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/types": "1.29.2" - } - }, - "node_modules/@shikijs/types": { - "version": "1.29.2", - "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-1.29.2.tgz", - "integrity": "sha512-VJjK0eIijTZf0QSTODEXCqinjBn0joAHQ+aPSBzrv4O2d/QSbsMw+ZeSRx03kV34Hy7NzUvV/7NqfYGRLrASmw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/vscode-textmate": "^10.0.1", - "@types/hast": "^3.0.4" - } - }, - "node_modules/@shikijs/vscode-textmate": { - "version": "10.0.2", - "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz", - "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@sinclair/typebox": { - "version": "0.27.10", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.10.tgz", - "integrity": "sha512-MTBk/3jGLNB2tVxv6uLlFh1iu64iYOQ2PbdOSK3NW8JZsmlaOh2q6sdtKowBhfw8QFLmYNzTW4/oK4uATIi6ZA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@sinonjs/commons": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz", - "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "type-detect": "4.0.8" - } - }, - "node_modules/@sinonjs/fake-timers": { - "version": "10.3.0", - "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz", - "integrity": "sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@sinonjs/commons": "^3.0.0" - } - }, - "node_modules/@smithy/config-resolver": { - "version": "4.5.3", - "resolved": "https://registry.npmjs.org/@smithy/config-resolver/-/config-resolver-4.5.3.tgz", - "integrity": "sha512-TpS6Am5zSEtx3ow7VynThEL7UwRM06zZZcmFaP6Ij9hqKPfsFhTYCLcgU7gjFjw9QAI2kzwXrfS7InH8BivJTA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/core": { - "version": "3.24.3", - "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.24.3.tgz", - "integrity": "sha512-Ep/7tPamGY8mgESE3LyLKtxJyy6U52WWAqr/3wial47Sj4u3PiIF73AOGI27UyLy9duTkhZbgzodOfLV4TduZg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@aws-crypto/crc32": "5.2.0", - "@smithy/types": "^4.14.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/credential-provider-imds": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.3.3.tgz", - "integrity": "sha512-I2Bti0DKFo2IJyN28ijCsx51BAumEYR4/1yZ1FXyBygy9MqbnMqCev4JPth/MbpRfBSRAX35hITSnAdJRo1u5w==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "@smithy/types": "^4.14.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/eventstream-serde-browser": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-browser/-/eventstream-serde-browser-4.3.3.tgz", - "integrity": "sha512-LXg5yYJPYnVSrpa6LOZ+/wqpI2OlIccy7j5F16EFNYDbXWmnhry/PFRRPyM30H+hJeqfVgckFuvNGnAGCt56cA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/eventstream-serde-config-resolver": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-config-resolver/-/eventstream-serde-config-resolver-4.4.3.tgz", - "integrity": "sha512-MdQxEX5SFNc3QmpiLXtcZXsWk4imCfGVN7Ikz9I/XvavypvHT4mqxwo5JHdr/LBKCfAv89+8193ZWlUwDp8YXQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/eventstream-serde-node": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/eventstream-serde-node/-/eventstream-serde-node-4.3.3.tgz", - "integrity": "sha512-54RbRsw9eVaVnqYUXi3F6nMAPgUyKsBvAKBY2lf+81mIgM7N+yS9V5LYk7yUGbrM789b2e1qBuyDSjX1/Axxcw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/fetch-http-handler": { - "version": "5.4.3", - "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.4.3.tgz", - "integrity": "sha512-F+DRf8IJazRJgYog2A/yJK7eYVc0rqTlRzO+5ZxjJd4WkZoKz0IJRncf7G6t1pdVT3kryJcwuTFhN1c5m6N47A==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "@smithy/types": "^4.14.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/hash-blob-browser": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/hash-blob-browser/-/hash-blob-browser-4.3.3.tgz", - "integrity": "sha512-TkGfDlYeWOGwYvAunHHHmKgvFtD7DFAl6gWxATI4pv4B6w0Wnx6RK5zCMoXTTqMVd+zPcWm7w8RPTgHytoCDJA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/hash-node": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/hash-node/-/hash-node-4.3.3.tgz", - "integrity": "sha512-tSUA38sM7kzMoLhqQ2aCGTwLXovjurz3jjG+a0sxqD4qT/4FhQr/wxMdhCumT70giM+axC1pPjimAHLlEQCfzw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/hash-stream-node": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/hash-stream-node/-/hash-stream-node-4.3.3.tgz", - "integrity": "sha512-ZyDAlpKKc7BKHUp+kDBiTwNhiHrOf3syQdvQadvnwWs0QJhYMHMg6QSarlhpzN6qr+KBFM/oF/xP/bvzR6KI9w==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/invalid-dependency": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/invalid-dependency/-/invalid-dependency-4.3.3.tgz", - "integrity": "sha512-wUWowbCm7DGczl6bfLI6wGGtoxwN5Pon8DhF0Q8AA4NvgLwYfLo3h2DWI7sHr33lLcEsyTLQKeUeTHydqSfQ5Q==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/is-array-buffer": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@smithy/is-array-buffer/-/is-array-buffer-2.2.0.tgz", - "integrity": "sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@smithy/md5-js": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/md5-js/-/md5-js-4.3.3.tgz", - "integrity": "sha512-pFw8gEMrHw9BbRwNm//UU4WgnVO7+dhfFRaSAkFPfwslWU2LXt0mM+oap3iFwGbdD8kuAWIeOAxqSiamOcM3Dw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/middleware-content-length": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/middleware-content-length/-/middleware-content-length-4.3.3.tgz", - "integrity": "sha512-Up1XAYnj6oxFBypWpkhNpgX+yReQxkKAV/iLaeP0KVLb2oTkmA9X+UJuGBVvEA9uZIN06y0irDi7sBMuTZMVJg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/middleware-endpoint": { - "version": "4.5.3", - "resolved": "https://registry.npmjs.org/@smithy/middleware-endpoint/-/middleware-endpoint-4.5.3.tgz", - "integrity": "sha512-p60HGFflWsJC6V9GAYeFgbfORn+9ILx8FqgMa/8PzA0rhIUxF57EKoOR4Irs6oe1oy8RLzhjhcGS8CBtPv/t+Q==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/middleware-retry": { - "version": "4.6.3", - "resolved": "https://registry.npmjs.org/@smithy/middleware-retry/-/middleware-retry-4.6.3.tgz", - "integrity": "sha512-MnfYnJs3cBXK3ZBqbPzXRPHIp+QtgpkX5NogcUOWHPU5GbgTAQSIfPLi91lTcEbkFDcH2YbgjLPQjWeyQ689rA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/middleware-serde": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/middleware-serde/-/middleware-serde-4.3.3.tgz", - "integrity": "sha512-RUVCZgn92izDAARs5OJSM2+KWSfTRvQWwN9t0MmiybT3pquRgDx9vD9t/YZjd/5lwcFbsNuPojJSddYQEZGeWw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/middleware-stack": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/middleware-stack/-/middleware-stack-4.3.3.tgz", - "integrity": "sha512-+BPabWluqxo3EfMMvOgnAmPtWnCSzj+gf5mJ27wTZUbvS0hpdUIU1g80R01bEGKZx4JCi8P58jAXD9FUGMjhwA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/node-config-provider": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@smithy/node-config-provider/-/node-config-provider-4.4.3.tgz", - "integrity": "sha512-vDtz5OuytrjP4o9GtAOz1JloN003p94utJIQeO0WAjorhpafFFjpbDOrP6btPoCN3UxaU/U84OIEt5dM7ZRRLA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/node-http-handler": { - "version": "4.7.3", - "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.7.3.tgz", - "integrity": "sha512-/jPhevcTFPMVl6KNjbaI47iOg1zxC7IsnX4PQDGVZKMFceOXtB8IEYaB7a9VvkP/3oC60WzTeKocvSI7vLT0vA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "@smithy/types": "^4.14.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/protocol-http": { - "version": "5.4.3", - "resolved": "https://registry.npmjs.org/@smithy/protocol-http/-/protocol-http-5.4.3.tgz", - "integrity": "sha512-P16TBD/d8ZcD9MHQ0ubQ9BbOYSd5HZKbHOLsyFWxKk2oBEoghbRFPfGOoqToZX1yrfLITXRylL16EyPP4IzLPg==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/signature-v4": { - "version": "5.4.3", - "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.4.3.tgz", - "integrity": "sha512-53+75QuPl6DL+ct6vVEB51FDO5oulXr20TPV46VvJZg76lIlXNWfxi8j+G2V/t0I2qxCBOa3vX/8bmjrpFVo9g==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "@smithy/types": "^4.14.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/smithy-client": { - "version": "4.13.3", - "resolved": "https://registry.npmjs.org/@smithy/smithy-client/-/smithy-client-4.13.3.tgz", - "integrity": "sha512-Z8mQ+YryjP5krDadV6unnp5035L4S1brafXpTiRmjPweKSaQ6X9CYDYWvmEggXjDIa1oufX/2a/bdwu8EIz/lw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "@smithy/types": "^4.14.2", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/types": { - "version": "4.14.2", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.14.2.tgz", - "integrity": "sha512-P+otAxbV4CqBybp7EkcJCrig63yE2E7PuNVOmilVMRcx/O+QDzGULTrKsq4DV13gSfak9ObPrWaHl/9bL5YcWw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/url-parser": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/url-parser/-/url-parser-4.3.3.tgz", - "integrity": "sha512-TsMTAOnjuMOv1zJBw8cfYGWhopyc3og8tZX/KuyCPjg7V3ji3f4YjFOVu843UjBmrfS/+X6kwFv5ZKg7sSm1bQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/util-base64": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@smithy/util-base64/-/util-base64-4.4.3.tgz", - "integrity": "sha512-91lxjhFpAktA9yPBxniqVR/NSH9zyjMjLmoa+jbQHQFR9WiJA+n61T7HBrfh5APdEoAledJwGq8l4cS+ZJFUnQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/util-body-length-browser": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/util-body-length-browser/-/util-body-length-browser-4.3.3.tgz", - "integrity": "sha512-/M6Ya1Fjq8hg3rYjiwwqTen6s1bAa3U3g/2eicBaBQfaoa4ymLUke/x4T8mwb9dSq/L8TQ4YgndS0MaB9ShgmA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/util-body-length-node": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/util-body-length-node/-/util-body-length-node-4.3.3.tgz", - "integrity": "sha512-M+zdSrevWj0grtZx2RBULPUyjTq1aB+n+13Hrm9owiGpow6DqY/WqiSj6sHVQy/rKp0j7NzV3TNf2LrwDel8JQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/util-buffer-from": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@smithy/util-buffer-from/-/util-buffer-from-2.2.0.tgz", - "integrity": "sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/is-array-buffer": "^2.2.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@smithy/util-defaults-mode-browser": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-browser/-/util-defaults-mode-browser-4.4.3.tgz", - "integrity": "sha512-Q60hxKkMEkmBsOEzxlMWEymBWov0dtWGgoJhOUs6mE8k2FDPjK8NlsRdMkmO80n2pwzreHtrYcX5jiRP7ZkP3w==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/util-defaults-mode-node": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/util-defaults-mode-node/-/util-defaults-mode-node-4.3.3.tgz", - "integrity": "sha512-RYj+8gr95WiiBqvVghoRvL12NS9ryvLyufp7FOs7EzKwGX0W5gOVlXdCrFkJScSf8gxdjQMRyIZ3Y82/MvXQ3Q==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/util-endpoints": { - "version": "3.5.3", - "resolved": "https://registry.npmjs.org/@smithy/util-endpoints/-/util-endpoints-3.5.3.tgz", - "integrity": "sha512-2JqSmzQtKDKqBckLl/9NXTL1fY+zQBU5fNGMpud7AT65vql0tVFhb2UEZNZmLSHayLeD+X/Qzn84oXw5KS+KSQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/util-middleware": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/util-middleware/-/util-middleware-4.3.3.tgz", - "integrity": "sha512-8NZwlQ+nyAIWn9YZxH14FC8ca0i6ZGW1aJyPjD+zMZz3k9jOhXXKhdCSRvjmcSYLW42uhbrxavXqMkrTKHyY3A==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/util-retry": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@smithy/util-retry/-/util-retry-4.4.3.tgz", - "integrity": "sha512-8RJXeU5lEhdNfXm4XAuHlf6VtNzd279Z2FJZSR7VaELYCR46ffgjJBSjc+3UAy7V1YqBOLV0G9gWhLB/nA44nA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/util-stream": { - "version": "4.6.3", - "resolved": "https://registry.npmjs.org/@smithy/util-stream/-/util-stream-4.6.3.tgz", - "integrity": "sha512-DSpJpPg0rQwjZk9/CSlOTplD6xSUu+bz8eDJQkq/Fmy9JlSD4ZGhXG/qFl0aRHmouDbBF75tnZ00lPxiL/sgRQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/util-utf8": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@smithy/util-utf8/-/util-utf8-4.3.3.tgz", - "integrity": "sha512-c1QpRBn3aMsoqE64dd4Imgjy8Pynfw+eR7GkjElquxUFSnezwYVaOFm8JcYa+Bo/5ssbEyPKcT3+4bmrWYh6eQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@smithy/util-waiter": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/@smithy/util-waiter/-/util-waiter-4.4.3.tgz", - "integrity": "sha512-WSHSF865zDGFGtJdMmYPI2Blq/MbUrn5CB4bLDg4ARbQ9z7oA87ZZ/FSiwNZbQrU/EiVyl9lpINswALgI4lZXA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@smithy/core": "^3.24.3", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@swc/helpers": { - "version": "0.5.21", - "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.21.tgz", - "integrity": "sha512-jI/VAmtdjB/RnI8GTnokyX7Ug8c+g+ffD6QRLa6XQewtnGyukKkKSk3wLTM3b5cjt1jNh9x0jfVlagdN2gDKQg==", - "license": "Apache-2.0", - "dependencies": { - "tslib": "^2.8.0" - } - }, - "node_modules/@tybys/wasm-util": { - "version": "0.10.2", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz", - "integrity": "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@types/axios": { - "version": "0.14.4", - "resolved": "https://registry.npmjs.org/@types/axios/-/axios-0.14.4.tgz", - "integrity": "sha512-9JgOaunvQdsQ/qW2OPmE5+hCeUB52lQSolecrFrthct55QekhmXEwT203s20RL+UHtCQc15y3VXpby9E7Kkh/g==", - "deprecated": "This is a stub types definition. axios provides its own type definitions, so you do not need this installed.", - "dev": true, - "license": "MIT", - "dependencies": { - "axios": "*" - } - }, - "node_modules/@types/babel__core": { - "version": "7.20.5", - "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", - "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.20.7", - "@babel/types": "^7.20.7", - "@types/babel__generator": "*", - "@types/babel__template": "*", - "@types/babel__traverse": "*" - } - }, - "node_modules/@types/babel__generator": { - "version": "7.27.0", - "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", - "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__template": { - "version": "7.4.4", - "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", - "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/parser": "^7.1.0", - "@babel/types": "^7.0.0" - } - }, - "node_modules/@types/babel__traverse": { - "version": "7.28.0", - "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", - "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/types": "^7.28.2" - } - }, - "node_modules/@types/command-line-args": { - "version": "5.2.3", - "resolved": "https://registry.npmjs.org/@types/command-line-args/-/command-line-args-5.2.3.tgz", - "integrity": "sha512-uv0aG6R0Y8WHZLTamZwtfsDLVRnOa+n+n5rEvFWL5Na5gZ8V2Teab/duDPFzIIIhs9qizDpcavCusCLJZu62Kw==", - "license": "MIT" - }, - "node_modules/@types/command-line-usage": { - "version": "5.0.4", - "resolved": "https://registry.npmjs.org/@types/command-line-usage/-/command-line-usage-5.0.4.tgz", - "integrity": "sha512-BwR5KP3Es/CSht0xqBcUXS3qCAUVXwpRKsV2+arxeb65atasuXG9LykC9Ab10Cw3s2raH92ZqOeILaQbsB2ACg==", - "license": "MIT" - }, - "node_modules/@types/graceful-fs": { - "version": "4.1.9", - "resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz", - "integrity": "sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, - "node_modules/@types/hast": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz", - "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "*" - } - }, - "node_modules/@types/istanbul-lib-coverage": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", - "integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/istanbul-lib-report": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz", - "integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/istanbul-lib-coverage": "*" - } - }, - "node_modules/@types/istanbul-reports": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz", - "integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/istanbul-lib-report": "*" - } - }, - "node_modules/@types/jest": { - "version": "29.5.14", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.14.tgz", - "integrity": "sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "expect": "^29.0.0", - "pretty-format": "^29.0.0" - } - }, - "node_modules/@types/mdast": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", - "integrity": "sha512-kGaNbPh1k7AFzgpud/gMdvIm5xuECykRR+JnWKQno9TAXVa6WIVCGTPvYGekIDL4uwCZQSYbUxNBSb1aUo79oA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "*" - } - }, - "node_modules/@types/node": { - "version": "22.7.4", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.7.4.tgz", - "integrity": "sha512-y+NPi1rFzDs1NdQHHToqeiX2TIS79SWEAw9GYhkkx8bD0ChpfqC+n2j5OXOCpzfojBEBt6DnEnnG9MY0zk1XLg==", - "devOptional": true, - "license": "MIT", - "dependencies": { - "undici-types": "~6.19.2" - } - }, - "node_modules/@types/node-fetch": { - "version": "2.6.13", - "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz", - "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==", - "license": "MIT", - "optional": true, - "dependencies": { - "@types/node": "*", - "form-data": "^4.0.4" - } - }, - "node_modules/@types/stack-utils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", - "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/tmp": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/@types/tmp/-/tmp-0.2.6.tgz", - "integrity": "sha512-chhaNf2oKHlRkDGt+tiKE2Z5aJ6qalm7Z9rlLdBwmOiAAf09YQvvoLXjWK4HWPF1xU/fqvMgfNfpVoBscA/tKA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/unist": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz", - "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/yargs": { - "version": "17.0.35", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", - "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/yargs-parser": "*" - } - }, - "node_modules/@types/yargs-parser": { - "version": "21.0.3", - "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", - "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@typescript-eslint/eslint-plugin": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.18.0.tgz", - "integrity": "sha512-94EQTWZ40mzBc42ATNIBimBEDltSJ9RQHCC8vc/PDbxi4k8dVwUAv4o98dk50M1zB+JGFxp43FP7f8+FP8R6Sw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/regexpp": "^4.10.0", - "@typescript-eslint/scope-manager": "7.18.0", - "@typescript-eslint/type-utils": "7.18.0", - "@typescript-eslint/utils": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0", - "graphemer": "^1.4.0", - "ignore": "^5.3.1", - "natural-compare": "^1.4.0", - "ts-api-utils": "^1.3.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "@typescript-eslint/parser": "^7.0.0", - "eslint": "^8.56.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/parser": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-7.18.0.tgz", - "integrity": "sha512-4Z+L8I2OqhZV8qA132M4wNL30ypZGYOQVBfMgxDH/K5UX0PNqTu1c6za9ST5r9+tavvHiTWmBnKzpCJ/GlVFtg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "@typescript-eslint/scope-manager": "7.18.0", - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/typescript-estree": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0", - "debug": "^4.3.4" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.56.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/scope-manager": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-7.18.0.tgz", - "integrity": "sha512-jjhdIE/FPF2B7Z1uzc6i3oWKbGcHb87Qw7AWj6jmEqNOfDFbJWtjt/XfwCpvNkpGWlcJaog5vTR+VV8+w9JflA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/type-utils": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-7.18.0.tgz", - "integrity": "sha512-XL0FJXuCLaDuX2sYqZUUSOJ2sG5/i1AAze+axqmLnSkNEVMVYLF+cbwlB2w8D1tinFuSikHmFta+P+HOofrLeA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/typescript-estree": "7.18.0", - "@typescript-eslint/utils": "7.18.0", - "debug": "^4.3.4", - "ts-api-utils": "^1.3.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.56.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/types": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-7.18.0.tgz", - "integrity": "sha512-iZqi+Ds1y4EDYUtlOOC+aUmxnE9xS/yCigkjA7XpTKV6nCBd3Hp/PRGGmdwnfkV2ThMyYldP1wRpm/id99spTQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@typescript-eslint/typescript-estree": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-7.18.0.tgz", - "integrity": "sha512-aP1v/BSPnnyhMHts8cf1qQ6Q1IFwwRvAQGRvBFkWlo3/lH29OXA3Pts+c10nxRxIBrDnoMqzhgdwVe5f2D6OzA==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/visitor-keys": "7.18.0", - "debug": "^4.3.4", - "globby": "^11.1.0", - "is-glob": "^4.0.3", - "minimatch": "^9.0.4", - "semver": "^7.6.0", - "ts-api-utils": "^1.3.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.0.tgz", - "integrity": "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { - "version": "9.0.9", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", - "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.2" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@typescript-eslint/utils": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-7.18.0.tgz", - "integrity": "sha512-kK0/rNa2j74XuHVcoCZxdFBMF+aq/vH83CXAOHieC+2Gis4mF8jJXT5eAfyD3K0sAxtPuwxaIOIOvhwzVDt/kw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.4.0", - "@typescript-eslint/scope-manager": "7.18.0", - "@typescript-eslint/types": "7.18.0", - "@typescript-eslint/typescript-estree": "7.18.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.56.0" - } - }, - "node_modules/@typescript-eslint/visitor-keys": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-7.18.0.tgz", - "integrity": "sha512-cDF0/Gf81QpY3xYyJKDV14Zwdmid5+uuENhjH2EqFaF0ni+yAyq/LzMaIJdhNJXZI7uLzwIlA+V7oWoyn6Curg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/types": "7.18.0", - "eslint-visitor-keys": "^3.4.3" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - } - }, - "node_modules/@ungap/structured-clone": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.1.tgz", - "integrity": "sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/abort-controller": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", - "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", - "license": "MIT", - "optional": true, - "dependencies": { - "event-target-shim": "^5.0.0" - }, - "engines": { - "node": ">=6.5" - } - }, - "node_modules/acorn": { - "version": "8.16.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz", - "integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==", - "dev": true, - "license": "MIT", - "bin": { - "acorn": "bin/acorn" - }, - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/acorn-jsx": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", - "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" - } - }, - "node_modules/agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "4" - }, - "engines": { - "node": ">= 6.0.0" - } - }, - "node_modules/agentkeepalive": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.6.0.tgz", - "integrity": "sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "humanize-ms": "^1.2.1" - }, - "engines": { - "node": ">= 8.0.0" - } - }, - "node_modules/ajv": { - "version": "6.15.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", - "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.1", - "fast-json-stable-stringify": "^2.0.0", - "json-schema-traverse": "^0.4.1", - "uri-js": "^4.2.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/ansi-escapes": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", - "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "type-fest": "^0.21.3" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ansi-escapes/node_modules/type-fest": { - "version": "0.21.3", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", - "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", - "dev": true, - "license": "(MIT OR CC0-1.0)", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/anymatch": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "dev": true, - "license": "ISC", - "dependencies": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/apache-arrow": { - "version": "18.1.0", - "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-18.1.0.tgz", - "integrity": "sha512-v/ShMp57iBnBp4lDgV8Jx3d3Q5/Hac25FWmQ98eMahUiHPXcvwIMKJD0hBIgclm/FCG+LwPkAKtkRO1O/W0YGg==", - "license": "Apache-2.0", - "peer": true, - "dependencies": { - "@swc/helpers": "^0.5.11", - "@types/command-line-args": "^5.2.3", - "@types/command-line-usage": "^5.0.4", - "@types/node": "^20.13.0", - "command-line-args": "^5.2.1", - "command-line-usage": "^7.0.1", - "flatbuffers": "^24.3.25", - "json-bignum": "^0.0.3", - "tslib": "^2.6.2" - }, - "bin": { - "arrow2csv": "bin/arrow2csv.js" - } - }, - "node_modules/apache-arrow-15": { - "name": "apache-arrow", - "version": "15.0.0", - "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-15.0.0.tgz", - "integrity": "sha512-e6aunxNKM+woQf137ny3tp/xbLjFJS2oGQxQhYGqW6dGeIwNV1jOeEAeR6sS2jwAI2qLO83gYIP2MBz02Gw5Xw==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@swc/helpers": "^0.5.2", - "@types/command-line-args": "^5.2.1", - "@types/command-line-usage": "^5.0.2", - "@types/node": "^20.6.0", - "command-line-args": "^5.2.1", - "command-line-usage": "^7.0.1", - "flatbuffers": "^23.5.26", - "json-bignum": "^0.0.3", - "tslib": "^2.6.2" - }, - "bin": { - "arrow2csv": "bin/arrow2csv.cjs" - } - }, - "node_modules/apache-arrow-15/node_modules/@types/node": { - "version": "20.19.41", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.41.tgz", - "integrity": "sha512-ECymXOukMnOoVkC2bb1Vc/w/836DXncOg5m8Xj1RH7xSHZJWNYY6Zh7EH477vcnD5egKNNfy2RpNOmuChhFPgQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~6.21.0" - } - }, - "node_modules/apache-arrow-15/node_modules/flatbuffers": { - "version": "23.5.26", - "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-23.5.26.tgz", - "integrity": "sha512-vE+SI9vrJDwi1oETtTIFldC/o9GsVKRM+s6EL0nQgxXlYV1Vc4Tk30hj4xGICftInKQKj1F3up2n8UbIVobISQ==", - "dev": true, - "license": "SEE LICENSE IN LICENSE" - }, - "node_modules/apache-arrow-15/node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/apache-arrow-16": { - "name": "apache-arrow", - "version": "16.0.0", - "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-16.0.0.tgz", - "integrity": "sha512-bVyJeV4ahJW4XYjXefSBco0/mSSSElOzzh3Qx7tsKH+94sZaHrRotKKj1xVjON1hMUm7TODi6DnbFE73Q2h2MA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@swc/helpers": "^0.5.2", - "@types/command-line-args": "^5.2.1", - "@types/command-line-usage": "^5.0.2", - "@types/node": "^20.6.0", - "command-line-args": "^5.2.1", - "command-line-usage": "^7.0.1", - "flatbuffers": "^23.5.26", - "json-bignum": "^0.0.3", - "tslib": "^2.6.2" - }, - "bin": { - "arrow2csv": "bin/arrow2csv.cjs" - } - }, - "node_modules/apache-arrow-16/node_modules/@types/node": { - "version": "20.19.41", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.41.tgz", - "integrity": "sha512-ECymXOukMnOoVkC2bb1Vc/w/836DXncOg5m8Xj1RH7xSHZJWNYY6Zh7EH477vcnD5egKNNfy2RpNOmuChhFPgQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~6.21.0" - } - }, - "node_modules/apache-arrow-16/node_modules/flatbuffers": { - "version": "23.5.26", - "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-23.5.26.tgz", - "integrity": "sha512-vE+SI9vrJDwi1oETtTIFldC/o9GsVKRM+s6EL0nQgxXlYV1Vc4Tk30hj4xGICftInKQKj1F3up2n8UbIVobISQ==", - "dev": true, - "license": "SEE LICENSE IN LICENSE" - }, - "node_modules/apache-arrow-16/node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/apache-arrow-17": { - "name": "apache-arrow", - "version": "17.0.0", - "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-17.0.0.tgz", - "integrity": "sha512-X0p7auzdnGuhYMVKYINdQssS4EcKec9TCXyez/qtJt32DrIMGbzqiaMiQ0X6fQlQpw8Fl0Qygcv4dfRAr5Gu9Q==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@swc/helpers": "^0.5.11", - "@types/command-line-args": "^5.2.3", - "@types/command-line-usage": "^5.0.4", - "@types/node": "^20.13.0", - "command-line-args": "^5.2.1", - "command-line-usage": "^7.0.1", - "flatbuffers": "^24.3.25", - "json-bignum": "^0.0.3", - "tslib": "^2.6.2" - }, - "bin": { - "arrow2csv": "bin/arrow2csv.cjs" - } - }, - "node_modules/apache-arrow-17/node_modules/@types/node": { - "version": "20.19.41", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.41.tgz", - "integrity": "sha512-ECymXOukMnOoVkC2bb1Vc/w/836DXncOg5m8Xj1RH7xSHZJWNYY6Zh7EH477vcnD5egKNNfy2RpNOmuChhFPgQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~6.21.0" - } - }, - "node_modules/apache-arrow-17/node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/apache-arrow-18": { - "name": "apache-arrow", - "version": "18.0.0", - "resolved": "https://registry.npmjs.org/apache-arrow/-/apache-arrow-18.0.0.tgz", - "integrity": "sha512-gFlPaqN9osetbB83zC29AbbZqGiCuFH1vyyPseJ+B7SIbfBtESV62mMT/CkiIt77W6ykC/nTWFzTXFs0Uldg4g==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "@swc/helpers": "^0.5.11", - "@types/command-line-args": "^5.2.3", - "@types/command-line-usage": "^5.0.4", - "@types/node": "^20.13.0", - "command-line-args": "^5.2.1", - "command-line-usage": "^7.0.1", - "flatbuffers": "^24.3.25", - "json-bignum": "^0.0.3", - "tslib": "^2.6.2" - }, - "bin": { - "arrow2csv": "bin/arrow2csv.js" - } - }, - "node_modules/apache-arrow-18/node_modules/@types/node": { - "version": "20.19.41", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.41.tgz", - "integrity": "sha512-ECymXOukMnOoVkC2bb1Vc/w/836DXncOg5m8Xj1RH7xSHZJWNYY6Zh7EH477vcnD5egKNNfy2RpNOmuChhFPgQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~6.21.0" - } - }, - "node_modules/apache-arrow-18/node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/apache-arrow/node_modules/@types/node": { - "version": "20.19.41", - "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.41.tgz", - "integrity": "sha512-ECymXOukMnOoVkC2bb1Vc/w/836DXncOg5m8Xj1RH7xSHZJWNYY6Zh7EH477vcnD5egKNNfy2RpNOmuChhFPgQ==", - "license": "MIT", - "peer": true, - "dependencies": { - "undici-types": "~6.21.0" - } - }, - "node_modules/apache-arrow/node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "license": "MIT", - "peer": true - }, - "node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true, - "license": "Python-2.0" - }, - "node_modules/array-back": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/array-back/-/array-back-3.1.0.tgz", - "integrity": "sha512-TkuxA4UCOvxuDK6NZYXCalszEzj+TLszyASooky+i742l9TqsOdYCMJJupxRic61hwquNtppB3hgcuq9SVSH1Q==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/array-union": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", - "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "devOptional": true, - "license": "MIT" - }, - "node_modules/axios": { - "version": "1.16.1", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.16.1.tgz", - "integrity": "sha512-caYkukvroVPO8KrzuJEb50Hm07KwfBZPEC3VeFHTsqWHvKTsy54hjJz9BS/cdaypROE2rH6xvm9mHX4fgWkr3A==", - "dev": true, - "license": "MIT", - "dependencies": { - "follow-redirects": "^1.16.0", - "form-data": "^4.0.5", - "https-proxy-agent": "^5.0.1", - "proxy-from-env": "^2.1.0" - } - }, - "node_modules/babel-jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-29.7.0.tgz", - "integrity": "sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/transform": "^29.7.0", - "@types/babel__core": "^7.1.14", - "babel-plugin-istanbul": "^6.1.1", - "babel-preset-jest": "^29.6.3", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@babel/core": "^7.8.0" - } - }, - "node_modules/babel-plugin-istanbul": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz", - "integrity": "sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@babel/helper-plugin-utils": "^7.0.0", - "@istanbuljs/load-nyc-config": "^1.0.0", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-instrument": "^5.0.4", - "test-exclude": "^6.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/babel-plugin-istanbul/node_modules/istanbul-lib-instrument": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", - "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@babel/core": "^7.12.3", - "@babel/parser": "^7.14.7", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^6.3.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/babel-plugin-istanbul/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/babel-plugin-jest-hoist": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz", - "integrity": "sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/template": "^7.3.3", - "@babel/types": "^7.3.3", - "@types/babel__core": "^7.1.14", - "@types/babel__traverse": "^7.0.6" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/babel-preset-current-node-syntax": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.2.0.tgz", - "integrity": "sha512-E/VlAEzRrsLEb2+dv8yp3bo4scof3l9nR4lrld+Iy5NyVqgVYUJnDAmunkhPMisRI32Qc4iRiz425d8vM++2fg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/plugin-syntax-async-generators": "^7.8.4", - "@babel/plugin-syntax-bigint": "^7.8.3", - "@babel/plugin-syntax-class-properties": "^7.12.13", - "@babel/plugin-syntax-class-static-block": "^7.14.5", - "@babel/plugin-syntax-import-attributes": "^7.24.7", - "@babel/plugin-syntax-import-meta": "^7.10.4", - "@babel/plugin-syntax-json-strings": "^7.8.3", - "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-numeric-separator": "^7.10.4", - "@babel/plugin-syntax-object-rest-spread": "^7.8.3", - "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", - "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-syntax-private-property-in-object": "^7.14.5", - "@babel/plugin-syntax-top-level-await": "^7.14.5" - }, - "peerDependencies": { - "@babel/core": "^7.0.0 || ^8.0.0-0" - } - }, - "node_modules/babel-preset-jest": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz", - "integrity": "sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA==", - "dev": true, - "license": "MIT", - "dependencies": { - "babel-plugin-jest-hoist": "^29.6.3", - "babel-preset-current-node-syntax": "^1.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0" - } - }, - "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "dev": true, - "license": "MIT" - }, - "node_modules/base-64": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/base-64/-/base-64-0.1.0.tgz", - "integrity": "sha512-Y5gU45svrR5tI2Vt/X9GPd3L0HNIKzGu202EjxrXMpuc2V2CiKgemAbUUsqYmZJvPtCXoUKjNZwBJzsNScUbXA==", - "optional": true - }, - "node_modules/baseline-browser-mapping": { - "version": "2.10.31", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.31.tgz", - "integrity": "sha512-MujYO3eP72uvmSE0i4wltsodRfIpZATP3jvzRNRGGxgzId7aVocVJJV3nf01qnzzKFGxQVC9bpWxl5cjxTr/7Q==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "baseline-browser-mapping": "dist/cli.cjs" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/before-after-hook": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-4.0.0.tgz", - "integrity": "sha512-q6tR3RPqIB1pMiTRMFcZwuG5T8vwp+vUvEG0vuI6B+Rikh5BfPp2fQ82c925FOs+b0lcFQ8CFrL+KbilfZFhOQ==", - "dev": true, - "license": "Apache-2.0" - }, - "node_modules/bowser": { - "version": "2.14.1", - "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz", - "integrity": "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==", - "dev": true, - "license": "MIT" - }, - "node_modules/brace-expansion": { - "version": "1.1.14", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.14.tgz", - "integrity": "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/braces": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", - "dev": true, - "license": "MIT", - "dependencies": { - "fill-range": "^7.1.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/browserslist": { - "version": "4.28.2", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz", - "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "baseline-browser-mapping": "^2.10.12", - "caniuse-lite": "^1.0.30001782", - "electron-to-chromium": "^1.5.328", - "node-releases": "^2.0.36", - "update-browserslist-db": "^1.2.3" - }, - "bin": { - "browserslist": "cli.js" - }, - "engines": { - "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" - } - }, - "node_modules/bs-logger": { - "version": "0.2.6", - "resolved": "https://registry.npmjs.org/bs-logger/-/bs-logger-0.2.6.tgz", - "integrity": "sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-json-stable-stringify": "2.x" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/bser": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", - "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "node-int64": "^0.4.0" - } - }, - "node_modules/buffer-from": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", - "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", - "devOptional": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/camelcase": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", - "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/caniuse-lite": { - "version": "1.0.30001793", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001793.tgz", - "integrity": "sha512-iwSsYWaCOoh26cV8NwNRViHlrfUvYsHDfRVcbtmw0Kg6PJIZZXwMkj1442FYLBGkeUf1juAsU3DTfxW579mrPA==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/caniuse-lite" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "CC-BY-4.0" - }, - "node_modules/ccount": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/ccount/-/ccount-2.0.1.tgz", - "integrity": "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/chalk-template": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/chalk-template/-/chalk-template-0.4.0.tgz", - "integrity": "sha512-/ghrgmhfY8RaSdeo43hNXxpoHAtxdbskUHjPpfqUWGttFgycUhYPGx3YZBCnUCvOa7Doivn1IZec3DEGFoMgLg==", - "license": "MIT", - "dependencies": { - "chalk": "^4.1.2" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/chalk-template?sponsor=1" - } - }, - "node_modules/char-regex": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", - "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/character-entities-html4": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/character-entities-html4/-/character-entities-html4-2.1.0.tgz", - "integrity": "sha512-1v7fgQRj6hnSwFpq1Eu0ynr/CDEw0rXo2B61qXrLNdHZmPKgb7fqS1a2JwF0rISo9q77jDI8VMEHoApn8qDoZA==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/character-entities-legacy": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz", - "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/chardet": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.1.1.tgz", - "integrity": "sha512-PsezH1rqdV9VvyNhxxOW32/d75r01NY7TQCmOqomRo15ZSOKbpTFVsfjghxo6JloQUCGnH4k1LGu0R4yCLlWQQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/charenc": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz", - "integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==", - "license": "BSD-3-Clause", - "optional": true, - "engines": { - "node": "*" - } - }, - "node_modules/chownr": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", - "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", - "license": "BlueOak-1.0.0", - "optional": true, - "engines": { - "node": ">=18" - } - }, - "node_modules/ci-info": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", - "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/cjs-module-lexer": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz", - "integrity": "sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/cli-width": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz", - "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">= 12" - } - }, - "node_modules/clipanion": { - "version": "4.0.0-rc.4", - "resolved": "https://registry.npmjs.org/clipanion/-/clipanion-4.0.0-rc.4.tgz", - "integrity": "sha512-CXkMQxU6s9GklO/1f714dkKBMu1lopS1WFF0B8o4AxPykR1hpozxSiUZ5ZUeBjfPgCWqbcNOtZVFhB8Lkfp1+Q==", - "dev": true, - "license": "MIT", - "workspaces": [ - "website" - ], - "dependencies": { - "typanion": "^3.8.0" - }, - "peerDependencies": { - "typanion": "*" - } - }, - "node_modules/cliui": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", - "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "string-width": "^4.2.0", - "strip-ansi": "^6.0.1", - "wrap-ansi": "^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/co": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", - "dev": true, - "license": "MIT", - "engines": { - "iojs": ">= 1.0.0", - "node": ">= 0.12.0" - } - }, - "node_modules/collect-v8-coverage": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.3.tgz", - "integrity": "sha512-1L5aqIkwPfiodaMgQunkF1zRhNqifHBmtbbbxcr6yVxxBnliw4TDOW6NxpO8DJLgJ16OT+Y4ztZqP6p/FtXnAw==", - "dev": true, - "license": "MIT" - }, - "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", - "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" - }, - "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/colorette": { - "version": "2.0.20", - "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", - "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", - "dev": true, - "license": "MIT" - }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "devOptional": true, - "license": "MIT", - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/comma-separated-tokens": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", - "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/command-line-args": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/command-line-args/-/command-line-args-5.2.1.tgz", - "integrity": "sha512-H4UfQhZyakIjC74I9d34fGYDwk3XpSr17QhEd0Q3I9Xq1CETHo4Hcuo87WyWHpAF1aSLjLRf5lD9ZGX2qStUvg==", - "license": "MIT", - "dependencies": { - "array-back": "^3.1.0", - "find-replace": "^3.0.0", - "lodash.camelcase": "^4.3.0", - "typical": "^4.0.0" - }, - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/command-line-usage": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/command-line-usage/-/command-line-usage-7.0.4.tgz", - "integrity": "sha512-85UdvzTNx/+s5CkSgBm/0hzP80RFHAa7PsfeADE5ezZF3uHz3/Tqj9gIKGT9PTtpycc3Ua64T0oVulGfKxzfqg==", - "license": "MIT", - "dependencies": { - "array-back": "^6.2.2", - "chalk-template": "^0.4.0", - "table-layout": "^4.1.1", - "typical": "^7.3.0" - }, - "engines": { - "node": ">=12.20.0" - } - }, - "node_modules/command-line-usage/node_modules/array-back": { - "version": "6.2.3", - "resolved": "https://registry.npmjs.org/array-back/-/array-back-6.2.3.tgz", - "integrity": "sha512-SGDvmg6QTYiTxCBkYVmThcoa67uLl35pyzRHdpCGBOcqFy6BtwnphoFPk7LhJshD+Yk1Kt35WGWeZPTgwR4Fhw==", - "license": "MIT", - "engines": { - "node": ">=12.17" - } - }, - "node_modules/command-line-usage/node_modules/typical": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/typical/-/typical-7.3.0.tgz", - "integrity": "sha512-ya4mg/30vm+DOWfBg4YK3j2WD6TWtRkCbasOJr40CseYENzCUby/7rIvXA99JGsQHeNxLbnXdyLLxKSv3tauFw==", - "license": "MIT", - "engines": { - "node": ">=12.17" - } - }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true, - "license": "MIT" - }, - "node_modules/content-type": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", - "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/convert-source-map": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", - "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", - "dev": true, - "license": "MIT" - }, - "node_modules/create-jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/create-jest/-/create-jest-29.7.0.tgz", - "integrity": "sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "exit": "^0.1.2", - "graceful-fs": "^4.2.9", - "jest-config": "^29.7.0", - "jest-util": "^29.7.0", - "prompts": "^2.0.1" - }, - "bin": { - "create-jest": "bin/create-jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/crypt": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz", - "integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==", - "license": "BSD-3-Clause", - "optional": true, - "engines": { - "node": "*" - } - }, - "node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/dedent": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz", - "integrity": "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "babel-plugin-macros": "^3.1.0" - }, - "peerDependenciesMeta": { - "babel-plugin-macros": { - "optional": true - } - } - }, - "node_modules/deep-is": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", - "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/deepmerge": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", - "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "devOptional": true, - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/dequal": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", - "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "license": "Apache-2.0", - "optional": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/detect-newline": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", - "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/devlop": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", - "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", - "dev": true, - "license": "MIT", - "dependencies": { - "dequal": "^2.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/diff-sequences": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/diff-sequences/-/diff-sequences-29.6.3.tgz", - "integrity": "sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/digest-fetch": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/digest-fetch/-/digest-fetch-1.3.0.tgz", - "integrity": "sha512-CGJuv6iKNM7QyZlM2T3sPAdZWd/p9zQiRNS9G+9COUCwzWFTs0Xp8NF5iePx7wtvhDykReiRRrSeNb4oMmB8lA==", - "license": "ISC", - "optional": true, - "dependencies": { - "base-64": "^0.1.0", - "md5": "^2.3.0" - } - }, - "node_modules/dir-glob": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", - "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-type": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/doctrine": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz", - "integrity": "sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "esutils": "^2.0.2" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/dunder-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", - "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "devOptional": true, - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/electron-to-chromium": { - "version": "1.5.357", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.357.tgz", - "integrity": "sha512-NHlTIQDK8fmVwHwuIzmXYEJ1Ewq3D9wDNc0cWXxDGysP6Pb21giwGNkxiTifyKy/4SoPuN5l6GLP1W9Sv7zB2g==", - "dev": true, - "license": "ISC" - }, - "node_modules/emittery": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", - "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sindresorhus/emittery?sponsor=1" - } - }, - "node_modules/emnapi": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/emnapi/-/emnapi-1.10.0.tgz", - "integrity": "sha512-swoyZjupDvLoe/KC3HZ4SY1JUN+tviT6eOZ3Px28TZAYdBHtRIiMWWrIUUH+2/9CYY4fNTID1YhYZ+kdFHszHg==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "node-addon-api": ">= 6.1.0" - }, - "peerDependenciesMeta": { - "node-addon-api": { - "optional": true - } - } - }, - "node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, - "license": "MIT" - }, - "node_modules/emoji-regex-xs": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex-xs/-/emoji-regex-xs-1.0.0.tgz", - "integrity": "sha512-LRlerrMYoIDrT6jgpeZ2YYl/L8EulRTt5hQcYjy5AInh7HWXKimpqx68aknBFpGL2+/IcogTcaydJEgaTmOpDg==", - "dev": true, - "license": "MIT" - }, - "node_modules/entities": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", - "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/error-ex": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz", - "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-arrayish": "^0.2.1" - } - }, - "node_modules/es-define-property": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", - "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "devOptional": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "devOptional": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-object-atoms": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", - "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", - "devOptional": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-set-tostringtag": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", - "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", - "devOptional": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-toolkit": { - "version": "1.46.1", - "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.46.1.tgz", - "integrity": "sha512-5eNtXOs3tbfxXOj04tjjseeWkRWaoCjdEI+96DgwzZoe6c9juL49pXlzAFTI72aWC9Y8p7168g6XIKjh7k6pyQ==", - "dev": true, - "license": "MIT", - "workspaces": [ - "docs", - "benchmarks" - ] - }, - "node_modules/escalade": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", - "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "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==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/eslint": { - "version": "8.57.1", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.57.1.tgz", - "integrity": "sha512-ypowyDxpVSYpkXr9WPv2PAZCtNip1Mv5KTW0SCurXv/9iOpcrH9PaqUElksqEB6pChqHGDRCFTyrZlGhnLNGiA==", - "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", - "dev": true, - "license": "MIT", - "dependencies": { - "@eslint-community/eslint-utils": "^4.2.0", - "@eslint-community/regexpp": "^4.6.1", - "@eslint/eslintrc": "^2.1.4", - "@eslint/js": "8.57.1", - "@humanwhocodes/config-array": "^0.13.0", - "@humanwhocodes/module-importer": "^1.0.1", - "@nodelib/fs.walk": "^1.2.8", - "@ungap/structured-clone": "^1.2.0", - "ajv": "^6.12.4", - "chalk": "^4.0.0", - "cross-spawn": "^7.0.2", - "debug": "^4.3.2", - "doctrine": "^3.0.0", - "escape-string-regexp": "^4.0.0", - "eslint-scope": "^7.2.2", - "eslint-visitor-keys": "^3.4.3", - "espree": "^9.6.1", - "esquery": "^1.4.2", - "esutils": "^2.0.2", - "fast-deep-equal": "^3.1.3", - "file-entry-cache": "^6.0.1", - "find-up": "^5.0.0", - "glob-parent": "^6.0.2", - "globals": "^13.19.0", - "graphemer": "^1.4.0", - "ignore": "^5.2.0", - "imurmurhash": "^0.1.4", - "is-glob": "^4.0.0", - "is-path-inside": "^3.0.3", - "js-yaml": "^4.1.0", - "json-stable-stringify-without-jsonify": "^1.0.1", - "levn": "^0.4.1", - "lodash.merge": "^4.6.2", - "minimatch": "^3.1.2", - "natural-compare": "^1.4.0", - "optionator": "^0.9.3", - "strip-ansi": "^6.0.1", - "text-table": "^0.2.0" - }, - "bin": { - "eslint": "bin/eslint.js" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint-scope": { - "version": "7.2.2", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-7.2.2.tgz", - "integrity": "sha512-dOt21O7lTMhDM+X9mB4GX+DZrZtCUJPL/wlcTqxyrx5IvO0IYtILdtrQGQp+8n5S0gwSVmOf9NQrjMOgfQZlIg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^5.2.0" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/eslint-visitor-keys": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", - "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/espree": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.6.1.tgz", - "integrity": "sha512-oruZaFkjorTpF32kDSI5/75ViwGeZginGGy2NoOSg3Q9bnwlnmDm4HLnkl0RE3n+njDXR037aY1+x58Z/zFdwQ==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "acorn": "^8.9.0", - "acorn-jsx": "^5.3.2", - "eslint-visitor-keys": "^3.4.1" - }, - "engines": { - "node": "^12.22.0 || ^14.17.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/eslint" - } - }, - "node_modules/esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, - "license": "BSD-2-Clause", - "bin": { - "esparse": "bin/esparse.js", - "esvalidate": "bin/esvalidate.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/esquery": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", - "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "estraverse": "^5.1.0" - }, - "engines": { - "node": ">=0.10" - } - }, - "node_modules/esrecurse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "estraverse": "^5.2.0" - }, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/event-target-shim": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", - "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/execa": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", - "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", - "dev": true, - "license": "MIT", - "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" - } - }, - "node_modules/execa/node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/exit": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/exit/-/exit-0.1.2.tgz", - "integrity": "sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ==", - "dev": true, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/expect": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/expect/-/expect-29.7.0.tgz", - "integrity": "sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/expect-utils": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/fast-content-type-parse": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/fast-content-type-parse/-/fast-content-type-parse-3.0.0.tgz", - "integrity": "sha512-ZvLdcY8P+N8mGQJahJV5G4U88CSvT1rP8ApL6uETe88MBXrBHAkZlSEySdUlyztF7ccb+Znos3TFqaepHxdhBg==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT" - }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-glob": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", - "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.8" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/fast-glob/node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/fast-json-stable-stringify": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", - "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-levenshtein": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", - "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-string-truncated-width": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz", - "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-string-width": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz", - "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-string-truncated-width": "^3.0.2" - } - }, - "node_modules/fast-wrap-ansi": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.0.tgz", - "integrity": "sha512-rLV8JHxTyhVmFYhBJuMujcrHqOT2cnO5Zxj37qROj23CP39GXubJRBUFF0z8KFK77Uc0SukZUf7JZhsVEQ6n8w==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-string-width": "^3.0.2" - } - }, - "node_modules/fast-xml-builder": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.2.0.tgz", - "integrity": "sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "dependencies": { - "path-expression-matcher": "^1.5.0", - "xml-naming": "^0.1.0" - } - }, - "node_modules/fast-xml-parser": { - "version": "5.7.3", - "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.7.3.tgz", - "integrity": "sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "dependencies": { - "@nodable/entities": "^2.1.0", - "fast-xml-builder": "^1.1.7", - "path-expression-matcher": "^1.5.0", - "strnum": "^2.2.3" - }, - "bin": { - "fxparser": "src/cli/cli.js" - } - }, - "node_modules/fastq": { - "version": "1.20.1", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", - "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", - "dev": true, - "license": "ISC", - "dependencies": { - "reusify": "^1.0.4" - } - }, - "node_modules/fb-watchman": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", - "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "bser": "2.1.1" - } - }, - "node_modules/file-entry-cache": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", - "integrity": "sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==", - "dev": true, - "license": "MIT", - "dependencies": { - "flat-cache": "^3.0.4" - }, - "engines": { - "node": "^10.12.0 || >=12.0.0" - } - }, - "node_modules/fill-range": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", - "dev": true, - "license": "MIT", - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/find-replace": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-replace/-/find-replace-3.0.0.tgz", - "integrity": "sha512-6Tb2myMioCAgv5kfvP5/PkZZ/ntTpVK39fHY7WkWBgvbeE+VHd/tZuZ4mrC+bxh4cfOZeYKVPaJIZtZXV7GNCQ==", - "license": "MIT", - "dependencies": { - "array-back": "^3.0.1" - }, - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/find-up": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", - "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", - "dev": true, - "license": "MIT", - "dependencies": { - "locate-path": "^6.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/flat-cache": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", - "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", - "dev": true, - "license": "MIT", - "dependencies": { - "flatted": "^3.2.9", - "keyv": "^4.5.3", - "rimraf": "^3.0.2" - }, - "engines": { - "node": "^10.12.0 || >=12.0.0" - } - }, - "node_modules/flatbuffers": { - "version": "24.12.23", - "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-24.12.23.tgz", - "integrity": "sha512-dLVCAISd5mhls514keQzmEG6QHmUUsNuWsb4tFafIUwvvgDjXhtfAYSKOzt5SWOy+qByV5pbsDZ+Vb7HUOBEdA==", - "license": "Apache-2.0" - }, - "node_modules/flatted": { - "version": "3.4.2", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz", - "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==", - "dev": true, - "license": "ISC" - }, - "node_modules/follow-redirects": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", - "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/RubenVerborgh" - } - ], - "license": "MIT", - "engines": { - "node": ">=4.0" - }, - "peerDependenciesMeta": { - "debug": { - "optional": true - } - } - }, - "node_modules/form-data": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", - "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", - "devOptional": true, - "license": "MIT", - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/form-data-encoder": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz", - "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==", - "license": "MIT", - "optional": true - }, - "node_modules/formdata-node": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz", - "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "node-domexception": "1.0.0", - "web-streams-polyfill": "4.0.0-beta.3" - }, - "engines": { - "node": ">= 12.20" - } - }, - "node_modules/formdata-node/node_modules/web-streams-polyfill": { - "version": "4.0.0-beta.3", - "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", - "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 14" - } - }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true, - "license": "ISC" - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "devOptional": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/gensync": { - "version": "1.0.0-beta.2", - "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", - "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/get-caller-file": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", - "dev": true, - "license": "ISC", - "engines": { - "node": "6.* || 8.* || >= 10.*" - } - }, - "node_modules/get-intrinsic": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", - "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "devOptional": true, - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "function-bind": "^1.1.2", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-package-type": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", - "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/get-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", - "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "devOptional": true, - "license": "MIT", - "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "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", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/glob-parent": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", - "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.3" - }, - "engines": { - "node": ">=10.13.0" - } - }, - "node_modules/globals": { - "version": "13.24.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", - "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "type-fest": "^0.20.2" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/globby": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.1.0.tgz", - "integrity": "sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==", - "dev": true, - "license": "MIT", - "dependencies": { - "array-union": "^2.1.0", - "dir-glob": "^3.0.1", - "fast-glob": "^3.2.9", - "ignore": "^5.2.0", - "merge2": "^1.4.1", - "slash": "^3.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "devOptional": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/graphemer": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz", - "integrity": "sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==", - "dev": true, - "license": "MIT" - }, - "node_modules/guid-typescript": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", - "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==", - "license": "ISC", - "optional": true - }, - "node_modules/handlebars": { - "version": "4.7.9", - "resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.9.tgz", - "integrity": "sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "minimist": "^1.2.5", - "neo-async": "^2.6.2", - "source-map": "^0.6.1", - "wordwrap": "^1.0.0" - }, - "bin": { - "handlebars": "bin/handlebars" - }, - "engines": { - "node": ">=0.4.7" - }, - "optionalDependencies": { - "uglify-js": "^3.1.4" - } - }, - "node_modules/has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/has-symbols": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", - "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "devOptional": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-tostringtag": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", - "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", - "devOptional": true, - "license": "MIT", - "dependencies": { - "has-symbols": "^1.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.3.tgz", - "integrity": "sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==", - "devOptional": true, - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/hast-util-to-html": { - "version": "9.0.5", - "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz", - "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0", - "@types/unist": "^3.0.0", - "ccount": "^2.0.0", - "comma-separated-tokens": "^2.0.0", - "hast-util-whitespace": "^3.0.0", - "html-void-elements": "^3.0.0", - "mdast-util-to-hast": "^13.0.0", - "property-information": "^7.0.0", - "space-separated-tokens": "^2.0.0", - "stringify-entities": "^4.0.0", - "zwitch": "^2.0.4" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/hast-util-whitespace": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/hast-util-whitespace/-/hast-util-whitespace-3.0.0.tgz", - "integrity": "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/html-escaper": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", - "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", - "dev": true, - "license": "MIT" - }, - "node_modules/html-void-elements": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz", - "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/https-proxy-agent": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", - "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "6", - "debug": "4" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/human-signals": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", - "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=10.17.0" - } - }, - "node_modules/humanize-ms": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", - "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "ms": "^2.0.0" - } - }, - "node_modules/iconv-lite": { - "version": "0.7.2", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", - "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", - "dev": true, - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/ignore": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", - "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "node_modules/import-fresh": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", - "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "parent-module": "^1.0.0", - "resolve-from": "^4.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/import-local": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", - "integrity": "sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==", - "dev": true, - "license": "MIT", - "dependencies": { - "pkg-dir": "^4.2.0", - "resolve-cwd": "^3.0.0" - }, - "bin": { - "import-local-fixture": "fixtures/cli.js" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8.19" - } - }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", - "dev": true, - "license": "ISC", - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/interpret": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/interpret/-/interpret-1.4.0.tgz", - "integrity": "sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/is-arrayish": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", - "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", - "dev": true, - "license": "MIT" - }, - "node_modules/is-buffer": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", - "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==", - "license": "MIT", - "optional": true - }, - "node_modules/is-core-module": { - "version": "2.16.2", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.2.tgz", - "integrity": "sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "hasown": "^2.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/is-generator-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", - "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/is-path-inside": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/is-path-inside/-/is-path-inside-3.0.3.tgz", - "integrity": "sha512-Fd4gABb+ycGAmKou8eMftCupSir5lRxqf4aD/vd0cD2qc4HL07OjCeuHMr8Ro4CoMaeCKDB0/ECBOVWjTwUvPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/is-stream": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", - "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, - "license": "ISC" - }, - "node_modules/istanbul-lib-coverage": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", - "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=8" - } - }, - "node_modules/istanbul-lib-instrument": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.3.tgz", - "integrity": "sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@babel/core": "^7.23.9", - "@babel/parser": "^7.23.9", - "@istanbuljs/schema": "^0.1.3", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^7.5.4" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-report": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", - "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "istanbul-lib-coverage": "^3.0.0", - "make-dir": "^4.0.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-source-maps": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", - "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "debug": "^4.1.1", - "istanbul-lib-coverage": "^3.0.0", - "source-map": "^0.6.1" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-reports": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", - "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "html-escaper": "^2.0.0", - "istanbul-lib-report": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/jest": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest/-/jest-29.7.0.tgz", - "integrity": "sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/core": "^29.7.0", - "@jest/types": "^29.6.3", - "import-local": "^3.0.2", - "jest-cli": "^29.7.0" - }, - "bin": { - "jest": "bin/jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/jest-changed-files": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-29.7.0.tgz", - "integrity": "sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w==", - "dev": true, - "license": "MIT", - "dependencies": { - "execa": "^5.0.0", - "jest-util": "^29.7.0", - "p-limit": "^3.1.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-circus": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-29.7.0.tgz", - "integrity": "sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/expect": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "co": "^4.6.0", - "dedent": "^1.0.0", - "is-generator-fn": "^2.0.0", - "jest-each": "^29.7.0", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "p-limit": "^3.1.0", - "pretty-format": "^29.7.0", - "pure-rand": "^6.0.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-cli": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-29.7.0.tgz", - "integrity": "sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/core": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "create-jest": "^29.7.0", - "exit": "^0.1.2", - "import-local": "^3.0.2", - "jest-config": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "yargs": "^17.3.1" - }, - "bin": { - "jest": "bin/jest.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/jest-config": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-29.7.0.tgz", - "integrity": "sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.11.6", - "@jest/test-sequencer": "^29.7.0", - "@jest/types": "^29.6.3", - "babel-jest": "^29.7.0", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "deepmerge": "^4.2.2", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-circus": "^29.7.0", - "jest-environment-node": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-runner": "^29.7.0", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "micromatch": "^4.0.4", - "parse-json": "^5.2.0", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "strip-json-comments": "^3.1.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "peerDependencies": { - "@types/node": "*", - "ts-node": ">=9.0.0" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "ts-node": { - "optional": true - } - } - }, - "node_modules/jest-diff": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-29.7.0.tgz", - "integrity": "sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==", - "dev": true, - "license": "MIT", - "dependencies": { - "chalk": "^4.0.0", - "diff-sequences": "^29.6.3", - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-docblock": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-29.7.0.tgz", - "integrity": "sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g==", - "dev": true, - "license": "MIT", - "dependencies": { - "detect-newline": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-each": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-29.7.0.tgz", - "integrity": "sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "chalk": "^4.0.0", - "jest-get-type": "^29.6.3", - "jest-util": "^29.7.0", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-environment-node": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-29.7.0.tgz", - "integrity": "sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/fake-timers": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-mock": "^29.7.0", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-get-type": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/jest-get-type/-/jest-get-type-29.6.3.tgz", - "integrity": "sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-haste-map": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-29.7.0.tgz", - "integrity": "sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "@types/graceful-fs": "^4.1.3", - "@types/node": "*", - "anymatch": "^3.0.3", - "fb-watchman": "^2.0.0", - "graceful-fs": "^4.2.9", - "jest-regex-util": "^29.6.3", - "jest-util": "^29.7.0", - "jest-worker": "^29.7.0", - "micromatch": "^4.0.4", - "walker": "^1.0.8" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - }, - "optionalDependencies": { - "fsevents": "^2.3.2" - } - }, - "node_modules/jest-leak-detector": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz", - "integrity": "sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw==", - "dev": true, - "license": "MIT", - "dependencies": { - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-matcher-utils": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz", - "integrity": "sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "chalk": "^4.0.0", - "jest-diff": "^29.7.0", - "jest-get-type": "^29.6.3", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-message-util": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-29.7.0.tgz", - "integrity": "sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.12.13", - "@jest/types": "^29.6.3", - "@types/stack-utils": "^2.0.0", - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "micromatch": "^4.0.4", - "pretty-format": "^29.7.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-mock": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-29.7.0.tgz", - "integrity": "sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "jest-util": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-pnp-resolver": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", - "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - }, - "peerDependencies": { - "jest-resolve": "*" - }, - "peerDependenciesMeta": { - "jest-resolve": { - "optional": true - } - } - }, - "node_modules/jest-regex-util": { - "version": "29.6.3", - "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-29.6.3.tgz", - "integrity": "sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-resolve": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-29.7.0.tgz", - "integrity": "sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA==", - "dev": true, - "license": "MIT", - "dependencies": { - "chalk": "^4.0.0", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-pnp-resolver": "^1.2.2", - "jest-util": "^29.7.0", - "jest-validate": "^29.7.0", - "resolve": "^1.20.0", - "resolve.exports": "^2.0.0", - "slash": "^3.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-resolve-dependencies": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz", - "integrity": "sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA==", - "dev": true, - "license": "MIT", - "dependencies": { - "jest-regex-util": "^29.6.3", - "jest-snapshot": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-runner": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-29.7.0.tgz", - "integrity": "sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/console": "^29.7.0", - "@jest/environment": "^29.7.0", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "emittery": "^0.13.1", - "graceful-fs": "^4.2.9", - "jest-docblock": "^29.7.0", - "jest-environment-node": "^29.7.0", - "jest-haste-map": "^29.7.0", - "jest-leak-detector": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-resolve": "^29.7.0", - "jest-runtime": "^29.7.0", - "jest-util": "^29.7.0", - "jest-watcher": "^29.7.0", - "jest-worker": "^29.7.0", - "p-limit": "^3.1.0", - "source-map-support": "0.5.13" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-runtime": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-29.7.0.tgz", - "integrity": "sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/environment": "^29.7.0", - "@jest/fake-timers": "^29.7.0", - "@jest/globals": "^29.7.0", - "@jest/source-map": "^29.6.3", - "@jest/test-result": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "cjs-module-lexer": "^1.0.0", - "collect-v8-coverage": "^1.0.0", - "glob": "^7.1.3", - "graceful-fs": "^4.2.9", - "jest-haste-map": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-mock": "^29.7.0", - "jest-regex-util": "^29.6.3", - "jest-resolve": "^29.7.0", - "jest-snapshot": "^29.7.0", - "jest-util": "^29.7.0", - "slash": "^3.0.0", - "strip-bom": "^4.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-snapshot": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-29.7.0.tgz", - "integrity": "sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.11.6", - "@babel/generator": "^7.7.2", - "@babel/plugin-syntax-jsx": "^7.7.2", - "@babel/plugin-syntax-typescript": "^7.7.2", - "@babel/types": "^7.3.3", - "@jest/expect-utils": "^29.7.0", - "@jest/transform": "^29.7.0", - "@jest/types": "^29.6.3", - "babel-preset-current-node-syntax": "^1.0.0", - "chalk": "^4.0.0", - "expect": "^29.7.0", - "graceful-fs": "^4.2.9", - "jest-diff": "^29.7.0", - "jest-get-type": "^29.6.3", - "jest-matcher-utils": "^29.7.0", - "jest-message-util": "^29.7.0", - "jest-util": "^29.7.0", - "natural-compare": "^1.4.0", - "pretty-format": "^29.7.0", - "semver": "^7.5.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-util": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz", - "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "@types/node": "*", - "chalk": "^4.0.0", - "ci-info": "^3.2.0", - "graceful-fs": "^4.2.9", - "picomatch": "^2.2.3" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-validate": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-29.7.0.tgz", - "integrity": "sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "^29.6.3", - "camelcase": "^6.2.0", - "chalk": "^4.0.0", - "jest-get-type": "^29.6.3", - "leven": "^3.1.0", - "pretty-format": "^29.7.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-validate/node_modules/camelcase": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", - "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/jest-watcher": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-29.7.0.tgz", - "integrity": "sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/test-result": "^29.7.0", - "@jest/types": "^29.6.3", - "@types/node": "*", - "ansi-escapes": "^4.2.1", - "chalk": "^4.0.0", - "emittery": "^0.13.1", - "jest-util": "^29.7.0", - "string-length": "^4.0.1" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-worker": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz", - "integrity": "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "jest-util": "^29.7.0", - "merge-stream": "^2.0.0", - "supports-color": "^8.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/jest-worker/node_modules/supports-color": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/supports-color?sponsor=1" - } - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/js-yaml": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", - "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", - "dev": true, - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, - "node_modules/jsesc": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", - "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", - "dev": true, - "license": "MIT", - "bin": { - "jsesc": "bin/jsesc" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/json-bignum": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/json-bignum/-/json-bignum-0.0.3.tgz", - "integrity": "sha512-2WHyXj3OfHSgNyuzDbSxI1w2jgw5gkWSWhS7Qg4bWXx1nLk3jnbwfUeS0PSba3IzpTUWdHxBieELUzXRjQB2zg==", - "engines": { - "node": ">=0.8" - } - }, - "node_modules/json-buffer": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", - "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-parse-even-better-errors": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-schema-traverse": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", - "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-stable-stringify-without-jsonify": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", - "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", - "dev": true, - "license": "MIT" - }, - "node_modules/json-with-bigint": { - "version": "3.5.8", - "resolved": "https://registry.npmjs.org/json-with-bigint/-/json-with-bigint-3.5.8.tgz", - "integrity": "sha512-eq/4KP6K34kwa7TcFdtvnftvHCD9KvHOGGICWwMFc4dOOKF5t4iYqnfLK8otCRCRv06FXOzGGyqE8h8ElMvvdw==", - "dev": true, - "license": "MIT" - }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "dev": true, - "license": "MIT", - "bin": { - "json5": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/keyv": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", - "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", - "dev": true, - "license": "MIT", - "dependencies": { - "json-buffer": "3.0.1" - } - }, - "node_modules/kleur": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", - "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/leven": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", - "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/levn": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", - "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1", - "type-check": "~0.4.0" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/lines-and-columns": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", - "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", - "dev": true, - "license": "MIT" - }, - "node_modules/linkify-it": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.0.tgz", - "integrity": "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "uc.micro": "^2.0.0" - } - }, - "node_modules/locate-path": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", - "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-locate": "^5.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/lodash.camelcase": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", - "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", - "license": "MIT" - }, - "node_modules/lodash.memoize": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/lodash.memoize/-/lodash.memoize-4.1.2.tgz", - "integrity": "sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.merge": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/long": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", - "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", - "license": "Apache-2.0", - "optional": true - }, - "node_modules/lru-cache": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", - "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^3.0.2" - } - }, - "node_modules/lunr": { - "version": "2.3.9", - "resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.9.tgz", - "integrity": "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==", - "dev": true, - "license": "MIT" - }, - "node_modules/make-dir": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", - "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", - "dev": true, - "license": "MIT", - "dependencies": { - "semver": "^7.5.3" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/make-error": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", - "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", - "dev": true, - "license": "ISC" - }, - "node_modules/makeerror": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", - "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "tmpl": "1.0.5" - } - }, - "node_modules/markdown-it": { - "version": "14.1.1", - "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.1.tgz", - "integrity": "sha512-BuU2qnTti9YKgK5N+IeMubp14ZUKUUw7yeJbkjtosvHiP0AZ5c8IAgEMk79D0eC8F23r4Ac/q8cAIFdm2FtyoA==", - "dev": true, - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1", - "entities": "^4.4.0", - "linkify-it": "^5.0.0", - "mdurl": "^2.0.0", - "punycode.js": "^2.3.1", - "uc.micro": "^2.1.0" - }, - "bin": { - "markdown-it": "bin/markdown-it.mjs" - } - }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "devOptional": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/md5": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz", - "integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==", - "license": "BSD-3-Clause", - "optional": true, - "dependencies": { - "charenc": "0.0.2", - "crypt": "0.0.2", - "is-buffer": "~1.1.6" - } - }, - "node_modules/mdast-util-to-hast": { - "version": "13.2.1", - "resolved": "https://registry.npmjs.org/mdast-util-to-hast/-/mdast-util-to-hast-13.2.1.tgz", - "integrity": "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/hast": "^3.0.0", - "@types/mdast": "^4.0.0", - "@ungap/structured-clone": "^1.0.0", - "devlop": "^1.0.0", - "micromark-util-sanitize-uri": "^2.0.0", - "trim-lines": "^3.0.0", - "unist-util-position": "^5.0.0", - "unist-util-visit": "^5.0.0", - "vfile": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/mdurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz", - "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==", - "dev": true, - "license": "MIT" - }, - "node_modules/merge-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", - "dev": true, - "license": "MIT" - }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/micromark-util-character": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", - "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-symbol": "^2.0.0", - "micromark-util-types": "^2.0.0" - } - }, - "node_modules/micromark-util-encode": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", - "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT" - }, - "node_modules/micromark-util-sanitize-uri": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", - "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT", - "dependencies": { - "micromark-util-character": "^2.0.0", - "micromark-util-encode": "^2.0.0", - "micromark-util-symbol": "^2.0.0" - } - }, - "node_modules/micromark-util-symbol": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", - "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT" - }, - "node_modules/micromark-util-types": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.2.tgz", - "integrity": "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA==", - "dev": true, - "funding": [ - { - "type": "GitHub Sponsors", - "url": "https://github.com/sponsors/unifiedjs" - }, - { - "type": "OpenCollective", - "url": "https://opencollective.com/unified" - } - ], - "license": "MIT" - }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "devOptional": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "devOptional": true, - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mimic-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/minimist": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", - "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "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/mnemonist": { - "version": "0.38.3", - "resolved": "https://registry.npmjs.org/mnemonist/-/mnemonist-0.38.3.tgz", - "integrity": "sha512-2K9QYubXx/NAjv4VLq1d1Ly8pWNC5L3BrixtdkyTegXWJIqY+zLNDhhX/A+ZwWt70tB1S8H4BE8FLYEFyNoOBw==", - "dev": true, - "license": "MIT", - "dependencies": { - "obliterator": "^1.6.1" - } - }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "devOptional": true, - "license": "MIT" - }, - "node_modules/mute-stream": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-3.0.0.tgz", - "integrity": "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==", - "dev": true, - "license": "ISC", - "engines": { - "node": "^20.17.0 || >=22.9.0" - } - }, - "node_modules/natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true, - "license": "MIT" - }, - "node_modules/neo-async": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", - "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", - "dev": true, - "license": "MIT" - }, - "node_modules/node-domexception": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", - "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", - "deprecated": "Use your platform's native DOMException instead", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/jimmywarting" - }, - { - "type": "github", - "url": "https://paypal.me/jimmywarting" - } - ], - "license": "MIT", - "optional": true, - "engines": { - "node": ">=10.5.0" - } - }, - "node_modules/node-fetch": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", - "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", - "license": "MIT", - "optional": true, - "dependencies": { - "whatwg-url": "^5.0.0" - }, - "engines": { - "node": "4.x || >=6.0.0" - }, - "peerDependencies": { - "encoding": "^0.1.0" - }, - "peerDependenciesMeta": { - "encoding": { - "optional": true - } - } - }, - "node_modules/node-int64": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", - "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", - "dev": true, - "license": "MIT" - }, - "node_modules/node-releases": { - "version": "2.0.44", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.44.tgz", - "integrity": "sha512-5WUyunoPMsvvEhS8AxHtRzP+oA8UCkJ7YRxatWKjngndhDGLiqEVAQKWjFAiAiuL8zMRGzGSJxFnLetoa43qGQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/npm-run-path": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", - "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/obliterator": { - "version": "1.6.1", - "resolved": "https://registry.npmjs.org/obliterator/-/obliterator-1.6.1.tgz", - "integrity": "sha512-9WXswnqINnnhOG/5SLimUlzuU1hFJUc8zkwyD59Sd+dPOMf05PmnYG/d6Q7HZ+KmgkZJa1PxRso6QdM3sTNHig==", - "dev": true, - "license": "MIT" - }, - "node_modules/obug": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz", - "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==", - "dev": true, - "funding": [ - "https://github.com/sponsors/sxzz", - "https://opencollective.com/debug" - ], - "license": "MIT" - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/onetime": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", - "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "mimic-fn": "^2.1.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/oniguruma-to-es": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-2.3.0.tgz", - "integrity": "sha512-bwALDxriqfKGfUufKGGepCzu9x7nJQuoRoAFp4AnwehhC2crqrDIAP/uN2qdlsAvSMpeRC3+Yzhqc7hLmle5+g==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex-xs": "^1.0.0", - "regex": "^5.1.1", - "regex-recursion": "^5.1.1" - } - }, - "node_modules/onnxruntime-common": { - "version": "1.19.2", - "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.19.2.tgz", - "integrity": "sha512-a4R7wYEVFbZBlp0BfhpbFWqe4opCor3KM+5Wm22Az3NGDcQMiU2hfG/0MfnBs+1ZrlSGmlgWeMcXQkDk1UFb8Q==", - "license": "MIT", - "optional": true - }, - "node_modules/onnxruntime-node": { - "version": "1.19.2", - "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.19.2.tgz", - "integrity": "sha512-9eHMP/HKbbeUcqte1JYzaaRC8JPn7ojWeCeoyShO86TOR97OCyIyAIOGX3V95ErjslVhJRXY8Em/caIUc0hm1Q==", - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "win32", - "darwin", - "linux" - ], - "dependencies": { - "onnxruntime-common": "1.19.2", - "tar": "^7.0.1" - } - }, - "node_modules/onnxruntime-web": { - "version": "1.21.0-dev.20241024-d9ca84ef96", - "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.21.0-dev.20241024-d9ca84ef96.tgz", - "integrity": "sha512-ANSQfMALvCviN3Y4tvTViKofKToV1WUb2r2VjZVCi3uUBPaK15oNJyIxhsNyEckBr/Num3JmSXlkHOD8HfVzSQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "flatbuffers": "^1.12.0", - "guid-typescript": "^1.0.9", - "long": "^5.2.3", - "onnxruntime-common": "1.20.0-dev.20241016-2b8fc5529b", - "platform": "^1.3.6", - "protobufjs": "^7.2.4" - } - }, - "node_modules/onnxruntime-web/node_modules/flatbuffers": { - "version": "1.12.0", - "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-1.12.0.tgz", - "integrity": "sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==", - "license": "SEE LICENSE IN LICENSE.txt", - "optional": true - }, - "node_modules/onnxruntime-web/node_modules/onnxruntime-common": { - "version": "1.20.0-dev.20241016-2b8fc5529b", - "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.20.0-dev.20241016-2b8fc5529b.tgz", - "integrity": "sha512-KZK8b6zCYGZFjd4ANze0pqBnqnFTS3GIVeclQpa2qseDpXrCQJfkWBixRcrZShNhm3LpFOZ8qJYFC5/qsJK9WQ==", - "license": "MIT", - "optional": true - }, - "node_modules/openai": { - "version": "4.29.2", - "resolved": "https://registry.npmjs.org/openai/-/openai-4.29.2.tgz", - "integrity": "sha512-cPkT6zjEcE4qU5OW/SoDDuXEsdOLrXlAORhzmaguj5xZSPlgKvLhi27sFWhLKj07Y6WKNWxcwIbzm512FzTBNQ==", - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "@types/node": "^18.11.18", - "@types/node-fetch": "^2.6.4", - "abort-controller": "^3.0.0", - "agentkeepalive": "^4.2.1", - "digest-fetch": "^1.3.0", - "form-data-encoder": "1.7.2", - "formdata-node": "^4.3.2", - "node-fetch": "^2.6.7", - "web-streams-polyfill": "^3.2.1" - }, - "bin": { - "openai": "bin/cli" - } - }, - "node_modules/openai/node_modules/@types/node": { - "version": "18.19.130", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.130.tgz", - "integrity": "sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==", - "license": "MIT", - "optional": true, - "dependencies": { - "undici-types": "~5.26.4" - } - }, - "node_modules/openai/node_modules/undici-types": { - "version": "5.26.5", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", - "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", - "license": "MIT", - "optional": true - }, - "node_modules/optionator": { - "version": "0.9.4", - "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", - "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "deep-is": "^0.1.3", - "fast-levenshtein": "^2.0.6", - "levn": "^0.4.1", - "prelude-ls": "^1.2.1", - "type-check": "^0.4.0", - "word-wrap": "^1.2.5" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/p-limit": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", - "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "yocto-queue": "^0.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-locate": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", - "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-limit": "^3.0.2" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/parent-module": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", - "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", - "dev": true, - "license": "MIT", - "dependencies": { - "callsites": "^3.0.0" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/parse-json": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", - "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.0.0", - "error-ex": "^1.3.1", - "json-parse-even-better-errors": "^2.3.0", - "lines-and-columns": "^1.1.6" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-expression-matcher": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.5.0.tgz", - "integrity": "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true, - "license": "MIT" - }, - "node_modules/path-type": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", - "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", - "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/pirates": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", - "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/pkg-dir": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", - "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "find-up": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/pkg-dir/node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/pkg-dir/node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-locate": "^4.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/pkg-dir/node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-try": "^2.0.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/pkg-dir/node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-limit": "^2.2.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/platform": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", - "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", - "license": "MIT", - "optional": true - }, - "node_modules/prelude-ls": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", - "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/pretty-format": { - "version": "29.7.0", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-29.7.0.tgz", - "integrity": "sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/schemas": "^29.6.3", - "ansi-styles": "^5.0.0", - "react-is": "^18.0.0" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || >=18.0.0" - } - }, - "node_modules/pretty-format/node_modules/ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/prompts": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz", - "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "kleur": "^3.0.3", - "sisteransi": "^1.0.5" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/property-information": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz", - "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/protobufjs": { - "version": "7.6.0", - "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.0.tgz", - "integrity": "sha512-LtESOsMPTZgyYtwxhvdgdjGL0HmXEaRA/hVD6sol4zA60hVXXXP/SGmxnqDbgGE8gy7pYex7cym+5vYPcmaXBQ==", - "hasInstallScript": true, - "license": "BSD-3-Clause", - "optional": true, - "dependencies": { - "@protobufjs/aspromise": "^1.1.2", - "@protobufjs/base64": "^1.1.2", - "@protobufjs/codegen": "^2.0.5", - "@protobufjs/eventemitter": "^1.1.0", - "@protobufjs/fetch": "^1.1.1", - "@protobufjs/float": "^1.0.2", - "@protobufjs/inquire": "^1.1.2", - "@protobufjs/path": "^1.1.2", - "@protobufjs/pool": "^1.1.0", - "@protobufjs/utf8": "^1.1.1", - "@types/node": ">=13.7.0", - "long": "^5.3.2" - }, - "engines": { - "node": ">=12.0.0" - } - }, - "node_modules/proxy-from-env": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", - "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/punycode": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", - "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/punycode.js": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", - "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/pure-rand": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-6.1.0.tgz", - "integrity": "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA==", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/dubzzz" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fast-check" - } - ], - "license": "MIT" - }, - "node_modules/queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/react-is": { - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", - "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", - "dev": true, - "license": "MIT" - }, - "node_modules/rechoir": { - "version": "0.6.2", - "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.6.2.tgz", - "integrity": "sha512-HFM8rkZ+i3zrV+4LQjwQ0W+ez98pApMGM3HUrN04j3CqzPOzl9nmP15Y8YXNm8QHGv/eacOVEjqhmWpkRV0NAw==", - "dev": true, - "dependencies": { - "resolve": "^1.1.6" - }, - "engines": { - "node": ">= 0.10" - } - }, - "node_modules/reflect-metadata": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", - "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", - "license": "Apache-2.0" - }, - "node_modules/regex": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/regex/-/regex-5.1.1.tgz", - "integrity": "sha512-dN5I359AVGPnwzJm2jN1k0W9LPZ+ePvoOeVMMfqIMFz53sSwXkxaJoxr50ptnsC771lK95BnTrVSZxq0b9yCGw==", - "dev": true, - "license": "MIT", - "dependencies": { - "regex-utilities": "^2.3.0" - } - }, - "node_modules/regex-recursion": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-5.1.1.tgz", - "integrity": "sha512-ae7SBCbzVNrIjgSbh7wMznPcQel1DNlDtzensnFxpiNpXt1U2ju/bHugH422r+4LAVS1FpW1YCwilmnNsjum9w==", - "dev": true, - "license": "MIT", - "dependencies": { - "regex": "^5.1.1", - "regex-utilities": "^2.3.0" - } - }, - "node_modules/regex-utilities": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz", - "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==", - "dev": true, - "license": "MIT" - }, - "node_modules/require-directory": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", - "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/resolve": { - "version": "1.22.12", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.12.tgz", - "integrity": "sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "is-core-module": "^2.16.1", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/resolve-cwd": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", - "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", - "dev": true, - "license": "MIT", - "dependencies": { - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/resolve-cwd/node_modules/resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/resolve-from": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", - "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/resolve.exports": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/resolve.exports/-/resolve.exports-2.0.3.tgz", - "integrity": "sha512-OcXjMsGdhL4XnbShKpAcSqPMzQoYkYyhbEaeSko47MjRP9NfEQMhZkXL1DoFlt9LWQn4YttrdnV6X2OiyzBi+A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/reusify": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", - "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", - "dev": true, - "license": "MIT", - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" - } - }, - "node_modules/rimraf": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "deprecated": "Rimraf versions prior to v4 are no longer supported", - "dev": true, - "license": "ISC", - "dependencies": { - "glob": "^7.1.3" - }, - "bin": { - "rimraf": "bin.js" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/run-parallel": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "queue-microtask": "^1.2.2" - } - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true, - "license": "MIT" - }, - "node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", - "devOptional": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/sharp": { - "version": "0.33.5", - "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.33.5.tgz", - "integrity": "sha512-haPVm1EkS9pgvHrQ/F3Xy+hgcuMV0Wm9vfIBSiwZ05k+xgb0PkBQpGsAA/oWdDobNaZTH5ppvHtzCFbnSEwHVw==", - "hasInstallScript": true, - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "color": "^4.2.3", - "detect-libc": "^2.0.3", - "semver": "^7.6.3" - }, - "engines": { - "node": "^18.17.0 || ^20.3.0 || >=21.0.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - }, - "optionalDependencies": { - "@img/sharp-darwin-arm64": "0.33.5", - "@img/sharp-darwin-x64": "0.33.5", - "@img/sharp-libvips-darwin-arm64": "1.0.4", - "@img/sharp-libvips-darwin-x64": "1.0.4", - "@img/sharp-libvips-linux-arm": "1.0.5", - "@img/sharp-libvips-linux-arm64": "1.0.4", - "@img/sharp-libvips-linux-s390x": "1.0.4", - "@img/sharp-libvips-linux-x64": "1.0.4", - "@img/sharp-libvips-linuxmusl-arm64": "1.0.4", - "@img/sharp-libvips-linuxmusl-x64": "1.0.4", - "@img/sharp-linux-arm": "0.33.5", - "@img/sharp-linux-arm64": "0.33.5", - "@img/sharp-linux-s390x": "0.33.5", - "@img/sharp-linux-x64": "0.33.5", - "@img/sharp-linuxmusl-arm64": "0.33.5", - "@img/sharp-linuxmusl-x64": "0.33.5", - "@img/sharp-wasm32": "0.33.5", - "@img/sharp-win32-ia32": "0.33.5", - "@img/sharp-win32-x64": "0.33.5" - } - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/shelljs": { - "version": "0.8.5", - "resolved": "https://registry.npmjs.org/shelljs/-/shelljs-0.8.5.tgz", - "integrity": "sha512-TiwcRcrkhHvbrZbnRcFYMLl30Dfov3HKqzp5tO5b4pt6G/SezKcYhmDg15zXVBswHmctSAQKznqNW2LO5tTDow==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "glob": "^7.0.0", - "interpret": "^1.0.0", - "rechoir": "^0.6.2" - }, - "bin": { - "shjs": "bin/shjs" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/shiki": { - "version": "1.29.2", - "resolved": "https://registry.npmjs.org/shiki/-/shiki-1.29.2.tgz", - "integrity": "sha512-njXuliz/cP+67jU2hukkxCNuH1yUi4QfdZZY+sMr5PPrIyXSu5iTb/qYC4BiWWB0vZ+7TbdvYUCeL23zpwCfbg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@shikijs/core": "1.29.2", - "@shikijs/engine-javascript": "1.29.2", - "@shikijs/engine-oniguruma": "1.29.2", - "@shikijs/langs": "1.29.2", - "@shikijs/themes": "1.29.2", - "@shikijs/types": "1.29.2", - "@shikijs/vscode-textmate": "^10.0.1", - "@types/hast": "^3.0.4" - } - }, - "node_modules/shx": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/shx/-/shx-0.3.4.tgz", - "integrity": "sha512-N6A9MLVqjxZYcVn8hLmtneQWIJtp8IKzMP4eMnx+nqkvXoqinUPCbUFLp2UcWTEIUONhlk0ewxr/jaVGlc+J+g==", - "dev": true, - "license": "MIT", - "dependencies": { - "minimist": "^1.2.3", - "shelljs": "^0.8.5" - }, - "bin": { - "shx": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "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/simple-swizzle/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/sisteransi": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", - "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", - "dev": true, - "license": "MIT" - }, - "node_modules/slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/source-map-support": { - "version": "0.5.13", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", - "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", - "dev": true, - "license": "MIT", - "dependencies": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, - "node_modules/space-separated-tokens": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz", - "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", - "dev": true, - "license": "BSD-3-Clause" - }, - "node_modules/stack-utils": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", - "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "escape-string-regexp": "^2.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/stack-utils/node_modules/escape-string-regexp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/string-length": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", - "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "char-regex": "^1.0.2", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/stringify-entities": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", - "integrity": "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg==", - "dev": true, - "license": "MIT", - "dependencies": { - "character-entities-html4": "^2.0.0", - "character-entities-legacy": "^3.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-bom": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", - "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-final-newline": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/strnum": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.3.0.tgz", - "integrity": "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT" - }, - "node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/table-layout": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/table-layout/-/table-layout-4.1.1.tgz", - "integrity": "sha512-iK5/YhZxq5GO5z8wb0bY1317uDF3Zjpha0QFFLA8/trAoiLbQD0HUbMesEaxyzUgDxi2QlcbM8IvqOlEjgoXBA==", - "license": "MIT", - "dependencies": { - "array-back": "^6.2.2", - "wordwrapjs": "^5.1.0" - }, - "engines": { - "node": ">=12.17" - } - }, - "node_modules/table-layout/node_modules/array-back": { - "version": "6.2.3", - "resolved": "https://registry.npmjs.org/array-back/-/array-back-6.2.3.tgz", - "integrity": "sha512-SGDvmg6QTYiTxCBkYVmThcoa67uLl35pyzRHdpCGBOcqFy6BtwnphoFPk7LhJshD+Yk1Kt35WGWeZPTgwR4Fhw==", - "license": "MIT", - "engines": { - "node": ">=12.17" - } - }, - "node_modules/tar": { - "version": "7.5.15", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.15.tgz", - "integrity": "sha512-dzGK0boVlC4W5QFuQN1EFSl3bIDYsk7Tj40U6eIBnK2k/8ml7TZ5agbI5j5+qnoVcAA+rNtBml8SEiLxZpNqRQ==", - "license": "BlueOak-1.0.0", - "optional": true, - "dependencies": { - "@isaacs/fs-minipass": "^4.0.0", - "chownr": "^3.0.0", - "minipass": "^7.1.2", - "minizlib": "^3.1.0", - "yallist": "^5.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/tar/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" - } - }, - "node_modules/test-exclude": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", - "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", - "dev": true, - "license": "ISC", - "dependencies": { - "@istanbuljs/schema": "^0.1.2", - "glob": "^7.1.4", - "minimatch": "^3.0.4" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", - "dev": true, - "license": "MIT" - }, - "node_modules/tmp": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz", - "integrity": "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14.14" - } - }, - "node_modules/tmpl": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", - "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", - "dev": true, - "license": "BSD-3-Clause" - }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "license": "MIT", - "optional": true - }, - "node_modules/trim-lines": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz", - "integrity": "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - }, - "node_modules/ts-api-utils": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.4.3.tgz", - "integrity": "sha512-i3eMG77UTMD0hZhgRS562pv83RC6ukSAC2GMNWc+9dieh/+jDM5u5YG+NHX6VNDRHQcHwmsTHctP9LhbC3WxVw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=16" - }, - "peerDependencies": { - "typescript": ">=4.2.0" - } - }, - "node_modules/ts-jest": { - "version": "29.4.9", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.4.9.tgz", - "integrity": "sha512-LTb9496gYPMCqjeDLdPrKuXtncudeV1yRZnF4Wo5l3SFi0RYEnYRNgMrFIdg+FHvfzjCyQk1cLncWVqiSX+EvQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "bs-logger": "^0.2.6", - "fast-json-stable-stringify": "^2.1.0", - "handlebars": "^4.7.9", - "json5": "^2.2.3", - "lodash.memoize": "^4.1.2", - "make-error": "^1.3.6", - "semver": "^7.7.4", - "type-fest": "^4.41.0", - "yargs-parser": "^21.1.1" - }, - "bin": { - "ts-jest": "cli.js" - }, - "engines": { - "node": "^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0" - }, - "peerDependencies": { - "@babel/core": ">=7.0.0-beta.0 <8", - "@jest/transform": "^29.0.0 || ^30.0.0", - "@jest/types": "^29.0.0 || ^30.0.0", - "babel-jest": "^29.0.0 || ^30.0.0", - "jest": "^29.0.0 || ^30.0.0", - "jest-util": "^29.0.0 || ^30.0.0", - "typescript": ">=4.3 <7" - }, - "peerDependenciesMeta": { - "@babel/core": { - "optional": true - }, - "@jest/transform": { - "optional": true - }, - "@jest/types": { - "optional": true - }, - "babel-jest": { - "optional": true - }, - "esbuild": { - "optional": true - }, - "jest-util": { - "optional": true - } - } - }, - "node_modules/ts-jest/node_modules/type-fest": { - "version": "4.41.0", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", - "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", - "dev": true, - "license": "(MIT OR CC0-1.0)", - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "license": "0BSD" - }, - "node_modules/typanion": { - "version": "3.14.0", - "resolved": "https://registry.npmjs.org/typanion/-/typanion-3.14.0.tgz", - "integrity": "sha512-ZW/lVMRabETuYCd9O9ZvMhAh8GslSqaUjxmK/JLPCh6l73CvLBiuXswj/+7LdnWOgYsQ130FqLzFz5aGT4I3Ug==", - "dev": true, - "license": "MIT", - "workspaces": [ - "website" - ] - }, - "node_modules/type-check": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", - "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", - "dev": true, - "license": "MIT", - "dependencies": { - "prelude-ls": "^1.2.1" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/type-detect": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "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==", - "dev": true, - "license": "(MIT OR CC0-1.0)", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/typedoc": { - "version": "0.26.4", - "resolved": "https://registry.npmjs.org/typedoc/-/typedoc-0.26.4.tgz", - "integrity": "sha512-FlW6HpvULDKgc3rK04V+nbFyXogPV88hurarDPOjuuB5HAwuAlrCMQ5NeH7Zt68a/ikOKu6Z/0hFXAeC9xPccQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "lunr": "^2.3.9", - "markdown-it": "^14.1.0", - "minimatch": "^9.0.5", - "shiki": "^1.9.1", - "yaml": "^2.4.5" - }, - "bin": { - "typedoc": "bin/typedoc" - }, - "engines": { - "node": ">= 18" - }, - "peerDependencies": { - "typescript": "4.6.x || 4.7.x || 4.8.x || 4.9.x || 5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x" - } - }, - "node_modules/typedoc-plugin-markdown": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/typedoc-plugin-markdown/-/typedoc-plugin-markdown-4.2.1.tgz", - "integrity": "sha512-7hQt/1WaW/VI4+x3sxwcCGsEylP1E1GvF6OTTELK5sfTEp6AeK+83jkCOgZGp1pI2DiOammMYQMnxxOny9TKsQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 18" - }, - "peerDependencies": { - "typedoc": "0.26.x" - } - }, - "node_modules/typedoc/node_modules/brace-expansion": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.0.tgz", - "integrity": "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/typedoc/node_modules/minimatch": { - "version": "9.0.9", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", - "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.2" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/typescript": { - "version": "5.5.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz", - "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/typescript-eslint": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-7.18.0.tgz", - "integrity": "sha512-PonBkP603E3tt05lDkbOMyaxJjvKqQrXsnow72sVeOFINDE/qNmnnd+f9b4N+U7W6MXnnYyrhtmF2t08QWwUbA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typescript-eslint/eslint-plugin": "7.18.0", - "@typescript-eslint/parser": "7.18.0", - "@typescript-eslint/utils": "7.18.0" - }, - "engines": { - "node": "^18.18.0 || >=20.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/typescript-eslint" - }, - "peerDependencies": { - "eslint": "^8.56.0" - }, - "peerDependenciesMeta": { - "typescript": { - "optional": true - } - } - }, - "node_modules/typical": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/typical/-/typical-4.0.0.tgz", - "integrity": "sha512-VAH4IvQ7BDFYglMd7BPRDfLgxZZX4O4TFcRDA6EN5X7erNJJq+McIEp8np9aVtxrCJ6qx4GTYVfOWNjcqwZgRw==", - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/uc.micro": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", - "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==", - "dev": true, - "license": "MIT" - }, - "node_modules/uglify-js": { - "version": "3.19.3", - "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz", - "integrity": "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==", - "dev": true, - "license": "BSD-2-Clause", - "optional": true, - "bin": { - "uglifyjs": "bin/uglifyjs" - }, - "engines": { - "node": ">=0.8.0" - } - }, - "node_modules/undici-types": { - "version": "6.19.8", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", - "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", - "devOptional": true, - "license": "MIT" - }, - "node_modules/unist-util-is": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/unist-util-is/-/unist-util-is-6.0.1.tgz", - "integrity": "sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-position": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/unist-util-position/-/unist-util-position-5.0.0.tgz", - "integrity": "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-stringify-position": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz", - "integrity": "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-visit": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/unist-util-visit/-/unist-util-visit-5.1.0.tgz", - "integrity": "sha512-m+vIdyeCOpdr/QeQCu2EzxX/ohgS8KbnPDgFni4dQsfSCtpz8UqDyY5GjRru8PDKuYn7Fq19j1CQ+nJSsGKOzg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "unist-util-is": "^6.0.0", - "unist-util-visit-parents": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/unist-util-visit-parents": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.0.2.tgz", - "integrity": "sha512-goh1s1TBrqSqukSc8wrjwWhL0hiJxgA8m4kFxGlQ+8FYQ3C/m11FcTs4YYem7V664AhHVvgoQLk890Ssdsr2IQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "unist-util-is": "^6.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/universal-user-agent": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-7.0.3.tgz", - "integrity": "sha512-TmnEAEAsBJVZM/AADELsK76llnwcf9vMKuPz8JflO1frO8Lchitr0fNaN9d+Ap0BjKtqWqd/J17qeDnXh8CL2A==", - "dev": true, - "license": "ISC" - }, - "node_modules/update-browserslist-db": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", - "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", - "dev": true, - "funding": [ - { - "type": "opencollective", - "url": "https://opencollective.com/browserslist" - }, - { - "type": "tidelift", - "url": "https://tidelift.com/funding/github/npm/browserslist" - }, - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "license": "MIT", - "dependencies": { - "escalade": "^3.2.0", - "picocolors": "^1.1.1" - }, - "bin": { - "update-browserslist-db": "cli.js" - }, - "peerDependencies": { - "browserslist": ">= 4.21.0" - } - }, - "node_modules/uri-js": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", - "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "punycode": "^2.1.0" - } - }, - "node_modules/v8-to-istanbul": { - "version": "9.3.0", - "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz", - "integrity": "sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==", - "dev": true, - "license": "ISC", - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.12", - "@types/istanbul-lib-coverage": "^2.0.1", - "convert-source-map": "^2.0.0" - }, - "engines": { - "node": ">=10.12.0" - } - }, - "node_modules/vfile": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz", - "integrity": "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "vfile-message": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/vfile-message": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/vfile-message/-/vfile-message-4.0.3.tgz", - "integrity": "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/unist": "^3.0.0", - "unist-util-stringify-position": "^4.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/unified" - } - }, - "node_modules/walker": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", - "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "makeerror": "1.0.12" - } - }, - "node_modules/web-streams-polyfill": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", - "integrity": "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">= 8" - } - }, - "node_modules/webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "license": "BSD-2-Clause", - "optional": true - }, - "node_modules/whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "license": "MIT", - "optional": true, - "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/word-wrap": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", - "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/wordwrap": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", - "integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/wordwrapjs": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/wordwrapjs/-/wordwrapjs-5.1.1.tgz", - "integrity": "sha512-0yweIbkINJodk27gX9LBGMzyQdBDan3s/dEAiwBOj+Mf0PPyWL6/rikalkv8EeD0E8jm4o5RXEOrFTP3NXbhJg==", - "license": "MIT", - "engines": { - "node": ">=12.17" - } - }, - "node_modules/wrap-ansi": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/write-file-atomic": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-4.0.2.tgz", - "integrity": "sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg==", - "dev": true, - "license": "ISC", - "dependencies": { - "imurmurhash": "^0.1.4", - "signal-exit": "^3.0.7" - }, - "engines": { - "node": "^12.13.0 || ^14.15.0 || >=16.0.0" - } - }, - "node_modules/write-file-atomic/node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/xml-naming": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.1.0.tgz", - "integrity": "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/NaturalIntelligence" - } - ], - "license": "MIT", - "engines": { - "node": ">=16.0.0" - } - }, - "node_modules/y18n": { - "version": "5.0.8", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", - "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=10" - } - }, - "node_modules/yallist": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", - "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", - "dev": true, - "license": "ISC" - }, - "node_modules/yaml": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", - "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", - "dev": true, - "license": "ISC", - "bin": { - "yaml": "bin.mjs" - }, - "engines": { - "node": ">= 14.6" - }, - "funding": { - "url": "https://github.com/sponsors/eemeli" - } - }, - "node_modules/yargs": { - "version": "17.7.2", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", - "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "cliui": "^8.0.1", - "escalade": "^3.1.1", - "get-caller-file": "^2.0.5", - "require-directory": "^2.1.1", - "string-width": "^4.2.3", - "y18n": "^5.0.5", - "yargs-parser": "^21.1.1" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/yargs-parser": { - "version": "21.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", - "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=12" - } - }, - "node_modules/yocto-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/zwitch": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", - "integrity": "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==", - "dev": true, - "license": "MIT", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wooorm" - } - } - } -} diff --git a/nodejs/package.json b/nodejs/package.json index 19c7f4d32..a4a2286b7 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -67,7 +67,7 @@ "timeout": "3m" }, "engines": { - "node": ">= 18" + "node": ">= 22" }, "packageManager": "pnpm@11.1.1", "cpu": ["x64", "arm64"], @@ -101,7 +101,7 @@ "openai": "4.29.2" }, "peerDependencies": { - "@types/node": ">=18", + "@types/node": ">=22", "apache-arrow": ">=15.0.0 <=18.1.0" }, "peerDependenciesMeta": { From 36c142fa2e82c329513bcba478e0bbc41f32ed08 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Sat, 29 Aug 2026 14:51:41 -0700 Subject: [PATCH 146/206] chore: update lance dependency to v12.0.0-beta.5 (#4089) Updates the Rust workspace and Java lance-core dependency to Lance v12.0.0-beta.5. Includes minimal Rust 1.97 Clippy compatibility fixes required by validation. Lance tag: https://github.com/lance-format/lance/releases/tag/v12.0.0-beta.5 --------- Co-authored-by: Jack Ye --- Cargo.lock | 84 +++++++++++----------- Cargo.toml | 28 ++++---- java/pom.xml | 2 +- rust/lancedb/src/remote/table.rs | 5 +- rust/lancedb/src/table.rs | 7 ++ rust/lancedb/src/table/computed_columns.rs | 4 +- 6 files changed, 67 insertions(+), 63 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cff38a304..6d973b073 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow", "arrow-array", @@ -5013,8 +5013,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow", "arrow-array", @@ -5031,8 +5031,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "proc-macro2", "quote", @@ -5041,8 +5041,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-arith", "arrow-array", @@ -5075,8 +5075,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-arith", "arrow-array", @@ -5107,8 +5107,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arc-swap", "arrow", @@ -5172,8 +5172,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-schema", @@ -5195,8 +5195,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow", "arrow-array", @@ -5236,8 +5236,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-schema", @@ -5251,8 +5251,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow", "async-trait", @@ -5264,8 +5264,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow", "arrow-ipc", @@ -5318,8 +5318,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-buffer", @@ -5333,8 +5333,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow", "arrow-array", @@ -5374,8 +5374,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-schema", @@ -5388,8 +5388,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "12.0.0-beta.2" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.2#dafa4642658d996b3e31dde91e02f72db7860d7e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index a16f0412c..033da5907 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=12.0.0-beta.2", default-features = false, "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=12.0.0-beta.2", default-features = false, "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=12.0.0-beta.2", default-features = false, "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=12.0.0-beta.2", "tag" = "v12.0.0-beta.2", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=12.0.0-beta.5", default-features = false, "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=12.0.0-beta.5", default-features = false, "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=12.0.0-beta.5", default-features = false, "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index b3521f9c6..87e6a2bae 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 12.0.0-beta.2 + 12.0.0-beta.5 false 2.30.0 1.7 diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 57d2dc47d..5ce886369 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -5734,9 +5734,8 @@ mod tests { )) .execute() .await; - let err = match result { - Ok(_) => panic!("legacy remote query unexpectedly succeeded"), - Err(err) => err, + let Err(err) = result else { + panic!("legacy remote query unexpectedly succeeded") }; assert!( diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 70b86f3cf..efc705e3c 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -5763,6 +5763,13 @@ mod tests { assert!(index_bytes > 0); assert_eq!(with_index, data_only + index_bytes); + // Release builds reject unstable overlay datasets unless explicitly opted in. + if !lance_table::feature_flags::can_read_dataset( + lance_table::feature_flags::FLAG_UNSTABLE_DATA_OVERLAY_FILES, + ) { + return; + } + // Commit an overlay file supplying new `foo` values for the first three // rows of fragment 0. There is no high-level API that writes overlays // yet, so write the overlay's data file and commit the `DataOverlay` diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 4e8d8211e..b62db3fbb 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -1462,9 +1462,7 @@ fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result< for (name, expression) in columns { if schema.field_with_name(name).is_ok() { - return Err(Error::ColumnAlreadyExists { - name: name.to_string(), - }); + return Err(Error::ColumnAlreadyExists { name: name.clone() }); } let bound = bind(schema.clone(), name, expression)?; From 101f524e4786582e5e8a08020df4bd6f5d5ae08f Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sat, 29 Aug 2026 23:07:59 -0700 Subject: [PATCH 147/206] feat(python): support nested Function Arrow types (#4088) Teach Python Function authoring to retain the compact V1 grammar for existing types and emit canonical exact JSON for nested struct signatures. Adds coverage for recursive struct/list schemas and exact field properties. --- python/python/lancedb/functions.py | 110 ++++++++- .../tests/test_first_class_function_slice2.py | 219 +++++++++++++++++- 2 files changed, 312 insertions(+), 17 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 8a19a9d37..3e1b4f2d6 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -502,31 +502,107 @@ _GRAMMAR_PRIMITIVES = ( def _canonical_arrow_type(data_type: pa.DataType) -> str: - """The server's V1 Function type grammar. Anything outside it is rejected - here rather than at registration.""" + """The compact Function grammar, or canonical exact JSON for nested types.""" + grammar = _grammar_arrow_type(data_type) + if grammar is not None: + return grammar + exact = _exact_arrow_type(data_type) + return json.dumps(exact, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + + +def _grammar_arrow_type(data_type: pa.DataType) -> Optional[str]: for candidate, name in _GRAMMAR_PRIMITIVES: if data_type == candidate: return name if pa.types.is_list(data_type) or pa.types.is_large_list(data_type): + item = _grammar_list_item(data_type) + if item is None: + return None prefix = "list" if pa.types.is_list(data_type) else "large_list" - return f"{prefix}<{_canonical_list_item(data_type)}>" + return f"{prefix}<{item}>" if pa.types.is_fixed_size_list(data_type) and data_type.list_size > 0: - return ( - f"fixed_size_list<{_canonical_list_item(data_type)}, {data_type.list_size}>" - ) - raise TypeError(f"unsupported Arrow type for Function signature: {data_type}") + item = _grammar_list_item(data_type) + if item is not None: + return f"fixed_size_list<{item}, {data_type.list_size}>" + return None -def _canonical_list_item(data_type: pa.DataType) -> str: +def _grammar_list_item(data_type: pa.DataType) -> Optional[str]: """The grammar names only the item type; it always means a non-nullable - child called `item`, so any other child metadata cannot be represented.""" + child called `item`, so other child properties require exact JSON.""" child = data_type.value_field if child.name != "item" or child.nullable or child.metadata: + return None + return _grammar_arrow_type(child.type) + + +def _validate_exact_arrow_field(field: pa.Field) -> None: + if not field.name: raise TypeError( - "unsupported Arrow type for Function signature: list items must be a " - f"non-nullable field named 'item', got {child}" + "unsupported Arrow type for Function signature: field names " + "must not be empty" ) - return _canonical_arrow_type(child.type) + if field.metadata: + raise TypeError( + "unsupported Arrow type for Function signature: field metadata " + f"is not supported, got {field}" + ) + + +def _exact_arrow_field(field: pa.Field) -> dict[str, Any]: + _validate_exact_arrow_field(field) + return { + "name": field.name, + "nullable": field.nullable, + "type": _exact_arrow_type(field.type), + } + + +def _exact_arrow_type(data_type: pa.DataType) -> dict[str, Any]: + for candidate, name in _GRAMMAR_PRIMITIVES: + if data_type == candidate: + return {"type": name} + if pa.types.is_struct(data_type): + fields = list(data_type) + names = [field.name for field in fields] + if not fields or len(set(names)) != len(names): + raise TypeError( + "unsupported Arrow type for Function signature: structs must have " + "non-empty, uniquely named fields" + ) + return { + "type": "struct", + "fields": [_exact_arrow_field(field) for field in fields], + } + if ( + pa.types.is_list(data_type) + or pa.types.is_large_list(data_type) + or pa.types.is_fixed_size_list(data_type) + ): + if pa.types.is_fixed_size_list(data_type): + if data_type.value_field.name != "item": + raise TypeError( + "unsupported Arrow type for Function signature: fixed-size list " + "items must be named 'item'" + ) + if data_type.list_size <= 0: + raise TypeError( + f"unsupported Arrow type for Function signature: {data_type}" + ) + value: dict[str, Any] = { + "type": ( + "list" + if pa.types.is_list(data_type) + else "large_list" + if pa.types.is_large_list(data_type) + else "fixed_size_list" + ), + "fields": [_exact_arrow_field(data_type.value_field)], + } + if pa.types.is_fixed_size_list(data_type): + value["length"] = data_type.list_size + return value + raise TypeError(f"unsupported Arrow type for Function signature: {data_type}") def _list_of(item: pa.DataType) -> pa.DataType: @@ -600,8 +676,11 @@ def _callable_parameters(function: Callable[..., Any]) -> tuple[inspect.Paramete def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutput: if isinstance(output, pa.Schema): + if output.metadata: + raise TypeError("Function output schema metadata is not supported") fields = tuple(output) elif isinstance(output, pa.Field) and pa.types.is_struct(output.type): + _validate_exact_arrow_field(output) if output.nullable: raise ValueError("Function output must be non-nullable") fields = tuple(output.type) @@ -617,6 +696,7 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp raise TypeError( "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") return FunctionOutput( @@ -629,6 +709,8 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp raise ValueError("named-struct Function output must contain at least one field") if any(field.nullable for field in fields): raise ValueError("Function output fields must be non-nullable") + for field in fields: + _validate_exact_arrow_field(field) names = [field.name for field in fields] if len(set(names)) != len(names): raise ValueError("Function output field names must be unique") @@ -657,6 +739,10 @@ def _infer_signature( if input_schema is not None: if not isinstance(input_schema, pa.Schema): raise TypeError("input_schema must be a PyArrow Schema") + if input_schema.metadata: + raise TypeError("Function input schema metadata is not supported") + for field in input_schema: + _validate_exact_arrow_field(field) expected = tuple(parameter.name for parameter in parameters) actual = tuple(input_schema.names) if actual != expected: diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 7ce6b6b91..ee14043e4 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -168,7 +168,7 @@ def test_udf_resolves_module_globals_before_builtins(tmp_path): udf(module.uses_callable_shadow) -def test_canonical_arrow_type_is_exactly_the_grammar(): +def test_canonical_arrow_type_prefers_the_compact_grammar(): from lancedb.functions import _GRAMMAR_PRIMITIVES, _canonical_arrow_type golden = json.loads( @@ -181,6 +181,13 @@ def test_canonical_arrow_type_is_exactly_the_grammar(): case["arrow_type"] for case in golden["valid"] if "<" not in case["arrow_type"] ] assert [name for _, name in _GRAMMAR_PRIMITIVES] == primitives + assert _canonical_arrow_type(pa.list_(pa.field("item", pa.float32(), False))) == ( + "list" + ) + assert ( + _canonical_arrow_type(pa.large_list(pa.field("item", pa.float32(), False))) + == "large_list" + ) for outside in [ pa.timestamp("us"), pa.decimal128(10, 2), @@ -188,7 +195,6 @@ def test_canonical_arrow_type_is_exactly_the_grammar(): pa.large_binary(), pa.binary(4), pa.duration("s"), - pa.struct([pa.field("a", pa.int32())]), pa.list_(pa.float32(), 0), pa.list_(pa.timestamp("us")), ]: @@ -378,14 +384,29 @@ def test_udf_recursion_versus_a_rebound_module_name(tmp_path): udf(raw_fact) -def test_canonical_arrow_type_rejects_unrepresentable_list_children(): +def test_canonical_arrow_type_uses_exact_json_for_list_child_properties(): from lancedb.functions import _canonical_arrow_type + nullable = pa.list_(pa.float32()) + assert json.loads(_canonical_arrow_type(nullable)) == { + "type": "list", + "fields": [ + { + "name": "item", + "nullable": True, + "type": {"type": "float32"}, + } + ], + } + named = pa.list_(pa.field("custom", pa.float32(), nullable=False)) + assert json.loads(_canonical_arrow_type(named))["fields"][0]["name"] == "custom" for outside in [ - pa.list_(pa.float32()), # pyarrow default: nullable child - pa.list_(pa.field("custom", pa.float32(), nullable=False)), pa.list_(pa.field("item", pa.float32(), nullable=False, metadata={"k": "v"})), pa.list_(pa.field("item", pa.float32(), nullable=False), 0), + pa.list_( + pa.field("item", pa.float32(), nullable=False, metadata={"k": "v"}), 3 + ), + pa.list_(pa.field("custom", pa.float32(), nullable=False), 3), ]: with pytest.raises(TypeError, match="unsupported Arrow type"): _canonical_arrow_type(outside) @@ -395,6 +416,29 @@ def test_canonical_arrow_type_rejects_unrepresentable_list_children(): ) == "fixed_size_list" ) + fixed = json.loads(_canonical_arrow_type(pa.list_(pa.float32(), 3))) + assert fixed == { + "type": "fixed_size_list", + "fields": [ + { + "name": "item", + "nullable": True, + "type": {"type": "float32"}, + } + ], + "length": 3, + } + large = json.loads(_canonical_arrow_type(pa.large_list(pa.float32()))) + assert large["type"] == "large_list" + assert large["fields"][0]["nullable"] is True + + for invalid_struct in [ + pa.struct([]), + pa.struct([pa.field("a", pa.int32()), pa.field("a", pa.int64())]), + pa.struct([pa.field("", pa.int32())]), + ]: + with pytest.raises(TypeError, match="unsupported Arrow type"): + _canonical_arrow_type(invalid_struct) def _calls_missing(value: int) -> int: @@ -482,6 +526,105 @@ def test_explicit_arrow_schema_is_deterministic(): assert signature.output.nullable is False +def test_nested_struct_output_uses_canonical_exact_json(): + token = pa.struct( + [ + pa.field("position", pa.int32(), nullable=False), + pa.field("value", pa.string(), nullable=False), + pa.field("length", pa.int32(), nullable=False), + ] + ) + analysis = pa.struct( + [ + pa.field("normalized_text", pa.string(), nullable=False), + pa.field("has_content", pa.bool_(), nullable=False), + pa.field( + "metrics", + pa.struct( + [ + pa.field("character_count", pa.int64(), nullable=False), + pa.field("word_count", pa.int32(), nullable=False), + pa.field("average_word_length", pa.float64(), nullable=False), + ] + ), + nullable=False, + ), + pa.field( + "diagnostics", + pa.struct( + [ + pa.field("status", pa.string(), nullable=False), + pa.field( + "normalization", + pa.struct( + [ + pa.field("changed", pa.bool_(), nullable=False), + pa.field( + "original_length", pa.int64(), nullable=False + ), + ] + ), + nullable=False, + ), + ] + ), + nullable=False, + ), + pa.field( + "token_preview", + pa.list_(pa.field("item", token, nullable=False)), + nullable=False, + ), + ] + ) + + @udf( + input_schema=pa.schema([pa.field("text", pa.string(), nullable=False)]), + output_schema=pa.field("analysis", analysis, nullable=False), + ) + def analyze(text): + return {"normalized_text": text} + + output = analyze.registration_request.signature.output + assert output.kind == "named_struct" + assert [field.name for field in output.fields] == [ + "normalized_text", + "has_content", + "metrics", + "diagnostics", + "token_preview", + ] + metrics = json.loads(output.fields[2].arrow_type) + assert metrics == { + "type": "struct", + "fields": [ + { + "name": "character_count", + "nullable": False, + "type": {"type": "int64"}, + }, + { + "name": "word_count", + "nullable": False, + "type": {"type": "int32"}, + }, + { + "name": "average_word_length", + "nullable": False, + "type": {"type": "float64"}, + }, + ], + } + preview = json.loads(output.fields[4].arrow_type) + assert preview["type"] == "list" + assert preview["fields"][0]["type"]["type"] == "struct" + assert [field["name"] for field in preview["fields"][0]["type"]["fields"]] == [ + "position", + "value", + "length", + ] + + def test_annotation_and_explicit_schema_validation_fail_closed(): with pytest.raises(TypeError, match="missing Function annotations"): @@ -525,6 +668,72 @@ def test_annotation_and_explicit_schema_validation_fail_closed(): def nullable_explicit(value): return value + for invalid_field in [ + pa.field("", pa.int32(), nullable=False), + pa.field("result", pa.int32(), nullable=False, metadata={"k": "v"}), + ]: + with pytest.raises(TypeError, match="unsupported Arrow type"): + + @udf( + input_schema=pa.schema([pa.field("value", pa.int64())]), + output_schema=pa.schema([invalid_field]), + ) + def invalid_explicit_field(value): + return value + + with pytest.raises(TypeError, match="unsupported Arrow type"): + + @udf( + input_schema=pa.schema( + [pa.field("value", pa.int64(), metadata={"k": "v"})] + ), + output_schema=pa.int64(), + ) + def input_field_metadata(value): + return value + + with pytest.raises(TypeError, match="unsupported Arrow type"): + + @udf( + input_schema=pa.schema([pa.field("value", pa.int64())]), + output_schema=pa.field( + "result", pa.int64(), nullable=False, metadata={"k": "v"} + ), + ) + def scalar_output_field_metadata(value): + return value + + struct_type = pa.struct([pa.field("value", pa.int64(), nullable=False)]) + with pytest.raises(TypeError, match="unsupported Arrow type"): + + @udf( + input_schema=pa.schema([pa.field("value", pa.int64())]), + output_schema=pa.field( + "result", struct_type, nullable=False, metadata={"k": "v"} + ), + ) + def struct_output_field_metadata(value): + return {"value": value} + + for input_schema, output_schema in [ + ( + pa.schema([pa.field("value", pa.int64())], metadata={"k": "v"}), + pa.int64(), + ), + ( + pa.schema([pa.field("value", pa.int64())]), + pa.schema( + [pa.field("result", pa.int64(), nullable=False)], + metadata={"k": "v"}, + ), + ), + ]: + with pytest.raises(TypeError, match="schema metadata"): + + @udf(input_schema=input_schema, output_schema=output_schema) + def schema_metadata(value): + return value + def test_local_function_catalog_operations_are_not_supported(tmp_path): db = lancedb.connect(tmp_path) From 0c4e0667bca14f00307dc21c31cec9bcf24c2ebe Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 30 Aug 2026 06:08:51 +0000 Subject: [PATCH 148/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.12=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.13?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 3d57dc0fe..0afd176a0 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.12" +current_version = "0.38.0-beta.13" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 6d973b073..a3aaf566d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.12" +version = "0.38.0-beta.13" dependencies = [ "ahash", "anyhow", @@ -5490,7 +5490,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.12" +version = "0.38.0-beta.13" dependencies = [ "arrow-array", "arrow-buffer", @@ -5515,7 +5515,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.12" +version = "0.38.0-beta.13" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index e19880e29..e0d7485af 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.38.0-beta.12 + 0.38.0-beta.13 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 3864ed127..7f36371f6 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.12 + 0.38.0-beta.13 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 87e6a2bae..0efb48110 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.12 + 0.38.0-beta.13 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index c3b69424f..0cfcb4f49 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.12" +version = "0.38.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 2b8d43c3d..1863059de 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.38.0-beta.12", + "version": "0.38.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 6656fdd5c..c4c1bc504 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.38.0-beta.12", + "version": "0.38.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 f8f3e151f..7a491258f 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.38.0-beta.12", + "version": "0.38.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 20efa860a..37f6eb3f0 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.38.0-beta.12", + "version": "0.38.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 4b735a687..fde8388cf 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.38.0-beta.12", + "version": "0.38.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 35fee5ee0..7bf23c75d 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.38.0-beta.12", + "version": "0.38.0-beta.13", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 925211fbe..2cabfcc20 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.38.0-beta.12", + "version": "0.38.0-beta.13", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index a4a2286b7..2071f4633 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.12", + "version": "0.38.0-beta.13", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 0ee561977..09ff1cc50 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.12" +version = "0.38.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 881a5017e..688123006 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.12" +version = "0.38.0-beta.13" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From fcdc3f949ee59a791b5facb91bb32eb4c26b2311 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sun, 30 Aug 2026 01:16:57 -0700 Subject: [PATCH 149/206] fix: allow multiple function bindings per table (#4090) Allow a remote Function declaration when the table already contains valid, supported Function binding metadata. Existing bindings remain fully validated, including fail-closed handling for newer or inconsistent contracts, while other schema mutations retain their existing no-binding guard. Add planner and remote request-path regression coverage for a second binding and reject dependent Function inputs, including nested paths. --- rust/lancedb/src/remote/table.rs | 87 ++++++++ rust/lancedb/src/table/computed_columns.rs | 229 +++++++++++++++++++-- 2 files changed, 302 insertions(+), 14 deletions(-) diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 5ce886369..d372a6f56 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -7464,6 +7464,93 @@ mod tests { assert_eq!(result.version, 8); } + #[tokio::test] + async fn test_add_function_column_allows_an_existing_binding() { + let binding = crate::function::FunctionBinding::from_json(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + let binding_metadata = crate::table::computed_columns::function_bindings_metadata( + std::slice::from_ref(&binding), + ) + .unwrap(); + let mut fields = vec![ + Field::new("title", DataType::Utf8, true), + Field::new("body", DataType::Utf8, true), + ]; + fields.extend(binding.outputs().iter().map(|output| { + let data_type = match output.arrow_type.as_str() { + "utf8" => DataType::Utf8, + "int64" => DataType::Int64, + other => panic!("unexpected fixture output type {other}"), + }; + Field::new(&output.output_name, data_type, true).with_metadata( + crate::table::computed_columns::function_computed_column_metadata( + binding.binding_id(), + output.output_ordinal, + &["title".into(), "body".into()], + ), + ) + })); + let schema = Schema::new_with_metadata( + fields, + HashMap::from([( + crate::table::computed_columns::FUNCTION_BINDINGS_META_KEY.to_string(), + binding_metadata, + )]), + ); + 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(), + "/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":"secondary_text","all_null":true}, + {"name":"secondary_token_count","all_null":true} + ]) + ); + http::Response::builder() + .status(200) + .body(r#"{"version":10}"#.to_string()) + .unwrap() + } + path => panic!("Unexpected path: {path}"), + }); + let application = crate::function::FunctionApplication::from_json( + r#"{ + "function":{"name":"text_features","version":"fv_01K3TEXT"}, + "inputs":[ + {"parameter":"title","kind":"column","value":{"path":"title"}}, + {"parameter":"body","kind":"column","value":{"path":"body"}} + ], + "output":{"kind":"named_struct","fields":[ + {"name":"normalized_text","arrow_type":"utf8","nullable":false}, + {"name":"token_count","arrow_type":"int64","nullable":false} + ]}, + "columns":{ + "normalized_text":"secondary_text", + "token_count":"secondary_token_count" + } + }"#, + ) + .unwrap(); + + let result = table + .add_columns() + .function(application) + .execute() + .await + .unwrap(); + assert_eq!(result.version, 10); + } + #[tokio::test] async fn test_add_fixed_size_list_function_column_declares_the_vector_type() { let table = Table::new_with_handler("my_table", |request| { diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index b62db3fbb..6dc3ffad5 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -547,7 +547,12 @@ fn ensure_known_binding_shape(value: &Value) -> Result<()> { Ok(()) } -fn resolve_field_path<'a>(schema: &'a ArrowSchema, path: &str) -> Result<&'a ArrowField> { +struct ResolvedFieldPath<'a> { + root: &'a ArrowField, + leaf: &'a ArrowField, +} + +fn resolve_field_path<'a>(schema: &'a ArrowSchema, path: &str) -> Result> { let parts = lance_core::datatypes::parse_field_path(path).map_err(|e| { invalid_function(format!("invalid Function input field path '{path}': {e}")) })?; @@ -556,22 +561,23 @@ fn resolve_field_path<'a>(schema: &'a ArrowSchema, path: &str) -> Result<&'a Arr "Function input field path cannot be empty", )); }; - let mut field = schema + let root = schema .field_with_name(root) .map_err(|_| invalid_function(format!("unknown Function input column '{path}'")))?; + let mut leaf = root; for child in children { - let DataType::Struct(fields) = field.data_type() else { + let DataType::Struct(fields) = leaf.data_type() else { return Err(invalid_function(format!( "Function input field path '{path}' traverses a non-struct field" ))); }; - field = fields + leaf = fields .iter() .find(|field| field.name() == child) .map(AsRef::as_ref) .ok_or_else(|| invalid_function(format!("unknown Function input column '{path}'")))?; } - Ok(field) + Ok(ResolvedFieldPath { root, leaf }) } fn canonical_input_arrow_type(field: &JsonArrowField) -> Result { @@ -666,7 +672,8 @@ fn parse_output_arrow_type(raw: &str) -> Result { 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() { - let field = resolve_field_path(schema, &input.field_path)?; + let resolved = resolve_field_path(schema, &input.field_path)?; + let field = resolved.leaf; if field .metadata() .get(COMPUTED_COLUMN_META_KEY) @@ -721,6 +728,11 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding ))); } + let expected_inputs = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); let mut output_fields = Vec::with_capacity(binding.outputs().len()); for output in binding.outputs() { let field = schema.field_with_name(&output.output_name).map_err(|_| { @@ -747,6 +759,28 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding binding.binding_id() ))); } + let metadata = field.metadata(); + let declared_inputs = metadata + .get(INPUTS_META_KEY) + .and_then(|raw| serde_json::from_str::>(raw).ok()); + if metadata.get(COMPUTED_COLUMN_META_KEY).map(String::as_str) != Some("true") + || metadata.get(KIND_META_KEY).map(String::as_str) != Some(FUNCTION_KIND) + || metadata + .get(FUNCTION_BINDING_ID_META_KEY) + .map(String::as_str) + != Some(binding.binding_id()) + || metadata + .get(FUNCTION_OUTPUT_ORDINAL_META_KEY) + .and_then(|value| value.parse::().ok()) + != Some(output.output_ordinal) + || declared_inputs.as_deref() != Some(expected_inputs.as_slice()) + { + return Err(invalid_function(format!( + "Function output '{}' declaration metadata does not match binding '{}'", + output.output_name, + binding.binding_id() + ))); + } output_fields.push(ArrowField::new( field.name().clone(), field.data_type().clone(), @@ -778,7 +812,7 @@ pub(crate) fn plan_function_application( application: &FunctionApplication, output_name: Option<&str>, ) -> Result { - ensure_no_function_bindings_for_mutation(schema, "Function binding declaration")?; + ensure_supported_function_metadata(schema)?; if application.has_unknown_fields() { return Err(Error::NotSupported { message: "Function application contains fields from a newer contract".into(), @@ -828,8 +862,9 @@ pub(crate) fn plan_function_application( input.parameter )) })?; - let field = resolve_field_path(schema, path)?; - if field + let resolved = resolve_field_path(schema, path)?; + if resolved + .root .metadata() .get(COMPUTED_COLUMN_META_KEY) .map(String::as_str) @@ -839,6 +874,7 @@ pub(crate) fn plan_function_application( "Function input '{path}' is computed; computed-on-computed bindings are not supported" ))); } + let field = resolved.leaf; let parameter_field = ArrowField::new( input.parameter.clone(), field.data_type().clone(), @@ -2579,6 +2615,37 @@ mod tests { ]) } + fn valid_function_binding_schema( + title_nullable: bool, + body_nullable: bool, + binding: &FunctionBinding, + ) -> ArrowSchema { + let mut fields = function_binding_schema(title_nullable, body_nullable) + .fields() + .iter() + .map(|field| field.as_ref().clone()) + .collect::>(); + let inputs = binding + .inputs() + .iter() + .map(|input| input.field_path.clone()) + .collect::>(); + for output in binding.outputs() { + let index = fields + .iter() + .position(|field| field.name() == &output.output_name) + .unwrap(); + fields[index] = fields[index] + .clone() + .with_metadata(function_computed_column_metadata( + binding.binding_id(), + output.output_ordinal, + &inputs, + )); + } + ArrowSchema::new(fields) + } + #[test] fn test_non_nullable_function_inputs_can_bind_to_nullable_parameters() { let binding = FunctionBinding::from_json(include_str!( @@ -2586,7 +2653,11 @@ mod tests { )) .unwrap(); - ensure_binding_matches_schema(&function_binding_schema(false, false), &binding).unwrap(); + ensure_binding_matches_schema( + &valid_function_binding_schema(false, false, &binding), + &binding, + ) + .unwrap(); } #[test] @@ -2599,8 +2670,11 @@ mod tests { raw_binding["input_schema"]["fields"][0]["nullable"] = Value::Bool(false); let binding: FunctionBinding = serde_json::from_value(raw_binding).unwrap(); - let err = ensure_binding_matches_schema(&function_binding_schema(true, false), &binding) - .unwrap_err(); + let err = ensure_binding_matches_schema( + &valid_function_binding_schema(true, false, &binding), + &binding, + ) + .unwrap_err(); assert!( matches!(&err, Error::InvalidInput { message } if message.contains("input column 'title' is nullable") @@ -2611,6 +2685,73 @@ mod tests { ); } + #[test] + fn test_second_binding_rejects_outputs_without_reciprocal_metadata() { + let binding = FunctionBinding::from_json(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + let schema = ArrowSchema::new_with_metadata( + function_binding_schema(true, true).fields().to_vec(), + HashMap::from([( + FUNCTION_BINDINGS_META_KEY.to_string(), + function_bindings_metadata(std::slice::from_ref(&binding)).unwrap(), + )]), + ); + + let err = plan_function_application( + &schema, + &named_struct_application( + r#"{"normalized_text":"secondary_text","token_count":"secondary_token_count"}"#, + ), + None, + ) + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } + if message.contains("declaration metadata") + && message.contains("fb_01K3TEXT")), + "{err:?}" + ); + } + + #[test] + fn test_persisted_nested_input_keeps_leaf_level_validation() { + let mut raw_binding: Value = serde_json::from_str(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + raw_binding["inputs"][0]["field_path"] = Value::String("title.value".to_string()); + let binding: FunctionBinding = serde_json::from_value(raw_binding).unwrap(); + let title = ArrowField::new( + "title", + DataType::Struct(vec![ArrowField::new("value", DataType::Utf8, true)].into()), + true, + ) + .with_metadata(HashMap::from([ + (COMPUTED_COLUMN_META_KEY.to_string(), "true".to_string()), + (KIND_META_KEY.to_string(), SQL_KIND.to_string()), + (EXPRESSION_META_KEY.to_string(), "title".to_string()), + ])); + let mut fields = vec![title, ArrowField::new("body", DataType::Utf8, true)]; + fields.extend(binding.outputs().iter().map(|output| { + let data_type = match output.arrow_type.as_str() { + "utf8" => DataType::Utf8, + "int64" => DataType::Int64, + other => panic!("unexpected fixture output type {other}"), + }; + ArrowField::new(&output.output_name, data_type, true).with_metadata( + function_computed_column_metadata( + binding.binding_id(), + output.output_ordinal, + &["title.value".into(), "body".into()], + ), + ) + })); + + ensure_binding_matches_schema(&ArrowSchema::new(fields), &binding).unwrap(); + } + #[test] fn test_function_binding_metadata_survives_schema_round_trip() { let binding = FunctionBinding::from_json(include_str!( @@ -2659,9 +2800,36 @@ mod tests { output_ordinal: 1, } if binding_id == "fb_01K3TEXT" )); - let err = plan_function_application(&reopened, &named_struct_application("{}"), None) + let dependent_application = FunctionApplication::from_json( + r#"{ + "function":{"name":"dependent","version":"fv_dependent"}, + "inputs":[ + {"parameter":"text","kind":"column","value":{"path":"search_text"}} + ], + "output":{"kind":"scalar","arrow_type":"int64","nullable":false} + }"#, + ) + .unwrap(); + let err = plan_function_application(&reopened, &dependent_application, Some("dependent")) .unwrap_err(); - assert!(matches!(err, Error::NotSupported { .. })); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("computed-on-computed")) + ); + let plan = plan_function_application( + &reopened, + &named_struct_application( + r#"{"normalized_text":"secondary_text","token_count":"secondary_token_count"}"#, + ), + None, + ) + .unwrap(); + assert_eq!( + plan.outputs + .iter() + .map(|output| output.output_name.as_str()) + .collect::>(), + ["secondary_text", "secondary_token_count"] + ); } #[test] @@ -2817,5 +2985,38 @@ mod tests { assert!( matches!(&err, Error::InvalidInput { message } if message.contains("computed-on-computed")) ); + + let nested_title = ArrowField::new( + "title", + DataType::Struct(vec![ArrowField::new("value", DataType::Utf8, true)].into()), + true, + ) + .with_metadata(HashMap::from([ + (COMPUTED_COLUMN_META_KEY.to_string(), "true".to_string()), + (KIND_META_KEY.to_string(), SQL_KIND.to_string()), + ( + EXPRESSION_META_KEY.to_string(), + "struct('value')".to_string(), + ), + ])); + let nested_schema = ArrowSchema::new(vec![nested_title, schema.field(1).as_ref().clone()]); + let nested_application = FunctionApplication::from_json( + r#"{ + "function":{"name":"text_features","version":"fv_exact"}, + "inputs":[ + {"parameter":"title","kind":"column","value":{"path":"title.value"}}, + {"parameter":"body","kind":"column","value":{"path":"body"}} + ], + "output":{"kind":"named_struct","fields":[ + {"name":"normalized_text","arrow_type":"utf8","nullable":false}, + {"name":"token_count","arrow_type":"int64","nullable":false} + ]} + }"#, + ) + .unwrap(); + let err = plan_function_application(&nested_schema, &nested_application, None).unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("computed-on-computed")) + ); } } From a417e46bface04b813f54458b76f7181f4b7bdb7 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Sun, 30 Aug 2026 23:10:08 +0800 Subject: [PATCH 150/206] feat(functions): support GPU resource requirements (#4085) Functions can describe their Python environment today, but cannot declare accelerator requirements. That prevents Sophon from scheduling computed-column UDF refreshes onto GPU workers from the immutable Function definition. Add `num_gpus` to Python `@udf` through a typed `FunctionResourceRequirements` value and represent resource-aware definitions with the `python_v2` runtime discriminator. CPU Functions retain their existing `python` encoding and canonical identity. The new discriminator is intentional for mixed-version safety: deployments that do not understand execution resources reject the runtime instead of accepting a new field and silently running the Function on CPU. Required resources are part of Function version identity; priority, concurrency, and retry policy remain Job concerns. The actual resource scheduling remains owned by Sophon. --- python/python/lancedb/functions.py | 60 +++++- .../tests/test_first_class_function_slice2.py | 54 +++++- rust/lancedb/src/function.rs | 177 +++++++++++++++--- 3 files changed, 260 insertions(+), 31 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 3e1b4f2d6..9be63a558 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -54,6 +54,18 @@ _UInt32 = conint(strict=True, ge=0, le=2**32 - 1) _UInt64 = conint(strict=True, ge=0, le=2**64 - 1) +def _validate_gpu_wire_marker(value: Any) -> bool: + if value is not True: + raise ValueError("runtime.gpu must be true") + return True + + +def _normalize_gpu_marker(value: bool) -> Optional[bool]: + if not isinstance(value, bool): + raise ValueError("gpu must be a boolean") + return True if value else None + + class _FrozenDict(dict): def _immutable(self, *args, **kwargs): raise TypeError("remote canonical values are immutable") @@ -239,6 +251,23 @@ class PythonRuntimeSpec(_RemoteValue): python_version: Optional[str] = None environment: Optional[PythonEnvironmentSpec] = None env: Optional[Mapping[str, str]] = None + gpu: Optional[bool] = None + + @model_validator(mode="before") + @classmethod + def _discard_unknown_runtime_payload(cls, value): + if isinstance(value, Mapping): + kind = value.get("kind") + if isinstance(kind, str) and kind not in {"python", "python_v2"}: + return {"kind": kind} + return value + + @field_validator("gpu", mode="before") + @classmethod + def _validate_gpu_marker(cls, value): + if value is None: + return None + return _validate_gpu_wire_marker(value) @model_validator(mode="after") def _validate_runtime_kind(self): @@ -247,18 +276,28 @@ class PythonRuntimeSpec(_RemoteValue): raise ValueError("python runtime requires python_version") if self.environment is None: raise ValueError("python runtime requires environment") + if self.gpu is not None: + raise ValueError("python runtime with gpu requires kind='python_v2'") + elif self.kind == "python_v2": + if self.python_version is None: + raise ValueError("python_v2 runtime requires python_version") + if self.environment is None: + raise ValueError("python_v2 runtime requires environment") + if self.gpu is None: + raise ValueError("python_v2 runtime requires gpu") else: object.__setattr__(self, "python_version", None) object.__setattr__(self, "environment", None) object.__setattr__(self, "env", None) + object.__setattr__(self, "gpu", None) return self class FunctionVersion(_RemoteValue): """An exact immutable Function version returned by Enterprise. - Scheduling resources, priority, concurrency, and retry policy belong to - the submitting Job and are not part of this identity. + The GPU execution requirement is part of this identity. CPU and memory sizing, + priority, concurrency, and retry policy belong to the execution platform. """ name: str @@ -996,6 +1035,7 @@ class UdfDefinition: pip: tuple[str, ...], env: Mapping[str, str], python_version: Optional[str], + gpu: bool = False, conda: tuple[str, ...] = (), conda_channels: tuple[str, ...] = (), ): @@ -1024,12 +1064,14 @@ class UdfDefinition: signature = _infer_signature(function, input_schema, output_schema) source = _package_source(function) digest = f"sha256:{hashlib.sha256(source).hexdigest()}" + gpu_marker = _normalize_gpu_marker(gpu) runtime = PythonRuntimeSpec( - kind="python", + kind="python_v2" if gpu_marker is not None else "python", python_version=python_version or f"{sys.version_info.major}.{sys.version_info.minor}", environment=environment_spec, env=environment, + gpu=gpu_marker, ) self._function = function self._request = FunctionRegistrationRequest( @@ -1075,6 +1117,7 @@ def udf( pip: tuple[str, ...] | list[str] = (), env: Optional[Mapping[str, str]] = None, python_version: Optional[str] = None, + gpu: bool = False, conda: tuple[str, ...] | list[str] = (), conda_channels: tuple[str, ...] | list[str] = (), ) -> Callable[[Callable[..., Any]], UdfDefinition]: ... @@ -1089,6 +1132,7 @@ def udf( pip: tuple[str, ...] | list[str] = (), env: Optional[Mapping[str, str]] = None, python_version: Optional[str] = None, + gpu: bool = False, conda: tuple[str, ...] | list[str] = (), conda_channels: tuple[str, ...] | list[str] = (), ): @@ -1121,6 +1165,10 @@ def udf( Environment variables included in the Function definition. python_version : str, optional Remote Python major/minor version. Defaults to the client version. + 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 + the immutable Function version. The packaged artifact is a snapshot: the function source plus exactly the module-level names it references (modules as imports, importable @@ -1145,6 +1193,11 @@ def udf( ... return value * 2 >>> score(1.5) 3.0 + >>> @udf(pip=["cupy-cuda12x"], gpu=True) + ... def gpu_score(value: int) -> int: + ... return value * 2 + >>> gpu_score.registration_request.runtime.gpu + True """ def decorate(target: Callable[..., Any]) -> UdfDefinition: @@ -1156,6 +1209,7 @@ def udf( pip=tuple(pip), env={} if env is None else env, python_version=python_version, + gpu=gpu, conda=tuple(conda), conda_channels=tuple(conda_channels), ) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index ee14043e4..cf1542b55 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -19,7 +19,7 @@ import pyarrow as pa import pytest import lancedb -from lancedb.functions import UdfDefinition, udf +from lancedb.functions import PythonRuntimeSpec, UdfDefinition, udf THRESHOLD = 20 _CACHE = None @@ -89,6 +89,58 @@ def test_udf_conda_environment(): udf(name="channels", conda_channels=["conda-forge"])(lambda value: value) +def test_udf_gpu_marker_uses_gpu_runtime(): + @udf(pip=["cupy-cuda12x"], gpu=True) + 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" + assert request["runtime"]["gpu"] is True + + @udf(pip=["pyarrow"]) + def cpu_function(value: int) -> int: + return value + + cpu_runtime = json.loads(cpu_function.registration_request.to_canonical_json())[ + "runtime" + ] + assert cpu_runtime["kind"] == "python" + assert "gpu" not in cpu_runtime + + def identity(value: int) -> int: + return value + + 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) + + base_runtime = { + "kind": "python_v2", + "python_version": "3.12", + "environment": {"kind": "pip"}, + } + runtime = PythonRuntimeSpec.model_validate({**base_runtime, "gpu": True}) + assert runtime.gpu is True + for invalid in [False, 1, 0, "", "true", "1", "H100"]: + with pytest.raises(ValueError, match="runtime.gpu must be true"): + PythonRuntimeSpec.model_validate({**base_runtime, "gpu": invalid}) + + +def test_unknown_runtime_discards_payload_before_known_field_validation(): + for payload in [ + {"kind": "python_v3", "gpu": {"model": "H100"}}, + {"kind": "python_v3", "resources": []}, + { + "kind": "python_v3", + "environment": {"kind": []}, + "python_version": 3.15, + }, + ]: + runtime = PythonRuntimeSpec.model_validate(payload) + assert runtime.to_canonical_json() == '{"kind":"python_v3"}' + + def test_udf_packages_attribute_access_and_body_imports(): @udf def word_norm(body: str) -> float: diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 5366d984e..4b31a4376 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -207,6 +207,33 @@ pub enum PythonRuntimeSpec { environment: PythonEnvironmentSpec, env: BTreeMap, }, + /// The GPU-enabled Sophon-managed Python runtime. + /// + /// # Examples + /// + /// ``` + /// use std::collections::BTreeMap; + /// use lancedb::function::{PythonEnvironmentSpec, PythonRuntimeSpec}; + /// + /// let runtime = PythonRuntimeSpec::PythonV2 { + /// python_version: "3.12".to_string(), + /// environment: PythonEnvironmentSpec { + /// kind: "pip".to_string(), + /// packages: vec!["cupy-cuda12x".to_string()], + /// channels: Vec::new(), + /// path: None, + /// modules: Vec::new(), + /// image: None, + /// }, + /// env: BTreeMap::new(), + /// }; + /// assert!(runtime.requires_gpu()); + /// ``` + PythonV2 { + python_version: String, + environment: PythonEnvironmentSpec, + env: BTreeMap, + }, /// A runtime kind introduced by a newer server. /// /// Unknown payload fields are intentionally not retained because the @@ -219,22 +246,27 @@ impl PythonRuntimeSpec { pub fn kind(&self) -> &str { match self { Self::Python { .. } => "python", + Self::PythonV2 { .. } => "python_v2", Self::Unrecognized { kind } => kind, } } - /// The Python version for the V1 runtime, or `None` for an unknown kind. + /// The Python version for a known Python runtime, or `None` for an unknown kind. pub fn python_version(&self) -> Option<&str> { match self { - Self::Python { python_version, .. } => Some(python_version), + Self::Python { python_version, .. } | Self::PythonV2 { python_version, .. } => { + Some(python_version) + } Self::Unrecognized { .. } => None, } } - /// The Python environment for the V1 runtime, or `None` for an unknown kind. + /// The Python environment for a known Python runtime, or `None` for an unknown kind. pub fn environment(&self) -> Option<&PythonEnvironmentSpec> { match self { - Self::Python { environment, .. } => Some(environment), + Self::Python { environment, .. } | Self::PythonV2 { environment, .. } => { + Some(environment) + } Self::Unrecognized { .. } => None, } } @@ -242,38 +274,73 @@ impl PythonRuntimeSpec { /// Environment variables, or `None` for an unknown kind. pub fn env(&self) -> Option<&BTreeMap> { match self { - Self::Python { env, .. } => Some(env), + Self::Python { env, .. } | Self::PythonV2 { env, .. } => Some(env), Self::Unrecognized { .. } => None, } } + + /// Whether the runtime requires a GPU selected by the execution platform. + pub fn requires_gpu(&self) -> bool { + matches!(self, Self::PythonV2 { .. }) + } } #[derive(Deserialize)] -struct PythonRuntimeWire { - kind: String, - #[serde(default)] - python_version: Option, - #[serde(default)] - environment: Option, +struct PythonRuntimeV1Wire { + python_version: String, + environment: PythonEnvironmentSpec, #[serde(default)] env: BTreeMap, + #[serde(default)] + gpu: Option, +} + +#[derive(Deserialize)] +struct PythonRuntimeV2Wire { + python_version: String, + environment: PythonEnvironmentSpec, + #[serde(default)] + env: BTreeMap, + gpu: bool, } impl<'de> Deserialize<'de> for PythonRuntimeSpec { fn deserialize>(deserializer: D) -> std::result::Result { - let wire = PythonRuntimeWire::deserialize(deserializer)?; - if wire.kind == "python" { - Ok(Self::Python { - python_version: wire - .python_version - .ok_or_else(|| de::Error::missing_field("python_version"))?, - environment: wire - .environment - .ok_or_else(|| de::Error::missing_field("environment"))?, - env: wire.env, - }) - } else { - Ok(Self::Unrecognized { kind: wire.kind }) + let value = Value::deserialize(deserializer)?; + let kind = value + .get("kind") + .ok_or_else(|| de::Error::missing_field("kind"))? + .as_str() + .ok_or_else(|| de::Error::custom("runtime.kind must be a string"))? + .to_string(); + match kind.as_str() { + "python" => { + let wire: PythonRuntimeV1Wire = + serde_json::from_value(value).map_err(de::Error::custom)?; + if wire.gpu.is_some() { + return Err(de::Error::custom( + "python runtime with gpu requires kind='python_v2'", + )); + } + Ok(Self::Python { + python_version: wire.python_version, + environment: wire.environment, + env: wire.env, + }) + } + "python_v2" => { + let wire: PythonRuntimeV2Wire = + serde_json::from_value(value).map_err(de::Error::custom)?; + if !wire.gpu { + return Err(de::Error::custom("runtime.gpu must be true")); + } + Ok(Self::PythonV2 { + python_version: wire.python_version, + environment: wire.environment, + env: wire.env, + }) + } + _ => Ok(Self::Unrecognized { kind }), } } } @@ -287,6 +354,8 @@ impl Serialize for PythonRuntimeSpec { environment: &'a PythonEnvironmentSpec, #[serde(skip_serializing_if = "BTreeMap::is_empty")] env: &'a BTreeMap, + #[serde(skip_serializing_if = "Option::is_none")] + gpu: Option, } #[derive(Serialize)] @@ -304,6 +373,19 @@ impl Serialize for PythonRuntimeSpec { python_version, environment, env, + gpu: None, + } + .serialize(serializer), + Self::PythonV2 { + python_version, + environment, + env, + } => PythonRuntimeRef { + kind: "python_v2", + python_version, + environment, + env, + gpu: Some(true), } .serialize(serializer), Self::Unrecognized { kind } => UnrecognizedRuntimeRef { kind }.serialize(serializer), @@ -313,8 +395,8 @@ impl Serialize for PythonRuntimeSpec { /// Immutable Function version returned by the Enterprise catalog. /// -/// Scheduling resources, priority, concurrency, and retry policy belong to -/// the submitting Job and are not part of this identity. +/// The GPU execution requirement is part of this identity. CPU and memory sizing, +/// priority, concurrency, and retry policy belong to the execution platform. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionVersion { name: String, @@ -589,7 +671,7 @@ impl_json!(RefreshColumnResult); #[cfg(test)] mod conda_environment_tests { - use super::PythonEnvironmentSpec; + use super::{PythonEnvironmentSpec, PythonRuntimeSpec}; #[test] fn conda_channels_round_trip_and_pip_stays_bare() { @@ -608,4 +690,45 @@ mod conda_environment_tests { serde_json::from_str(r#"{"kind":"pip","packages":["numpy"]}"#).unwrap(); assert!(!serde_json::to_string(&pip).unwrap().contains("channels")); } + + #[test] + fn gpu_python_runtime_marker_round_trips_and_validates() { + let runtime: PythonRuntimeSpec = serde_json::from_str( + r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"},"gpu":true}"#, + ) + .unwrap(); + assert_eq!(runtime.kind(), "python_v2"); + assert!(runtime.requires_gpu()); + assert_eq!( + super::canonical_json(&runtime).unwrap(), + r#"{"environment":{"kind":"pip"},"gpu":true,"kind":"python_v2","python_version":"3.12"}"# + ); + + for invalid in [ + r#"{"kind":"python","python_version":"3.12","environment":{"kind":"pip"},"gpu":true}"#, + r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"}}"#, + r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"},"gpu":1}"#, + r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"},"gpu":false}"#, + r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"},"gpu":"true"}"#, + r#"{"kind":"python_v2","python_version":"3.12","environment":{"kind":"pip"},"gpu":"H100"}"#, + ] { + assert!(serde_json::from_str::(invalid).is_err()); + } + } + + #[test] + fn unknown_runtime_discards_payload_before_known_field_validation() { + for encoded in [ + r#"{"kind":"python_v3","gpu":{"model":"H100"}}"#, + r#"{"kind":"python_v3","resources":[]}"#, + r#"{"kind":"python_v3","python_version":3.15,"environment":{"kind":[]}}"#, + ] { + let runtime: PythonRuntimeSpec = serde_json::from_str(encoded).unwrap(); + assert_eq!(runtime.kind(), "python_v3"); + assert_eq!( + super::canonical_json(&runtime).unwrap(), + r#"{"kind":"python_v3"}"# + ); + } + } } From 1b0fc2c465ea94ca97d322c76acb43e8319d0f2f Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 30 Aug 2026 15:16:00 +0000 Subject: [PATCH 151/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.13=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.14?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 0afd176a0..763df001b 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.13" +current_version = "0.38.0-beta.14" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index a3aaf566d..69c33c587 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.13" +version = "0.38.0-beta.14" dependencies = [ "ahash", "anyhow", @@ -5490,7 +5490,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.13" +version = "0.38.0-beta.14" dependencies = [ "arrow-array", "arrow-buffer", @@ -5515,7 +5515,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.13" +version = "0.38.0-beta.14" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index e0d7485af..b66a8db2f 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.38.0-beta.13 + 0.38.0-beta.14 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 7f36371f6..6b4f2ea82 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.13 + 0.38.0-beta.14 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 0efb48110..9a752b3ef 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.13 + 0.38.0-beta.14 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 0cfcb4f49..accd9e3bf 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.13" +version = "0.38.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 1863059de..8ae5be4ef 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.38.0-beta.13", + "version": "0.38.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 c4c1bc504..b923bf224 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.38.0-beta.13", + "version": "0.38.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 7a491258f..2e2bd92c5 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.38.0-beta.13", + "version": "0.38.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 37f6eb3f0..e0b918b2f 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.38.0-beta.13", + "version": "0.38.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 fde8388cf..da6de64d1 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.38.0-beta.13", + "version": "0.38.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 7bf23c75d..5f7c7d6c2 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.38.0-beta.13", + "version": "0.38.0-beta.14", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 2cabfcc20..d2a808411 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.38.0-beta.13", + "version": "0.38.0-beta.14", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 2071f4633..38536d7f5 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.13", + "version": "0.38.0-beta.14", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 09ff1cc50..972c86ede 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.13" +version = "0.38.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 688123006..21babc252 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.13" +version = "0.38.0-beta.14" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From d5dac65a21e4fb28ea909388bf49021ac1e4f265 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sun, 30 Aug 2026 23:33:30 -0700 Subject: [PATCH 152/206] feat: support Blob v2 UDF signatures (#4091) Make Function authoring and declaration planning treat Blob v2 as a scalar semantic type while preserving exact Blob metadata in binding schemas. Covers scalar Blob outputs, expanded named-struct outputs, and whole-result structs with Blob children. --- python/python/lancedb/functions.py | 93 ++++- .../tests/test_first_class_function_slice2.py | 118 ++++++ rust/lancedb/src/function.rs | 3 + rust/lancedb/src/table/computed_columns.rs | 378 ++++++++++++++++-- 4 files changed, 552 insertions(+), 40 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 9be63a558..bac6a762f 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -49,6 +49,8 @@ from pydantic import ( model_validator, ) +from .schema import is_blob_v2_field as _is_blob_v2_field + _Int32 = conint(strict=True, ge=-(2**31), le=2**31 - 1) _UInt32 = conint(strict=True, ge=0, le=2**32 - 1) _UInt64 = conint(strict=True, ge=0, le=2**64 - 1) @@ -518,6 +520,7 @@ class RefreshColumnResult(_RemoteValue): _FUNCTION_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]*$") +_FUNCTION_BLOB_V2_TYPE = "blob_v2" _GRAMMAR_PRIMITIVES = ( @@ -581,20 +584,90 @@ def _validate_exact_arrow_field(field: pa.Field) -> None: "unsupported Arrow type for Function signature: field names " "must not be empty" ) - if field.metadata: + if _is_blob_v2_field(field): + if not _has_supported_blob_v2_layout(field): + raise TypeError( + "unsupported Arrow type for Function signature: lance.blob.v2 " + f"requires a supported Blob storage layout, got {field}" + ) + elif field.metadata: raise TypeError( "unsupported Arrow type for Function signature: field metadata " f"is not supported, got {field}" ) +def _has_supported_blob_v2_layout(field: pa.Field) -> bool: + data_type = field.type + if isinstance(data_type, pa.ExtensionType): + data_type = data_type.storage_type + if not pa.types.is_struct(data_type): + return False + + fields = tuple(data_type) + + def matches(spec, compare_nullable) -> bool: + return len(fields) == len(spec) and all( + actual.name == name + and actual.type == expected_type + and (not check_nullable or actual.nullable == nullable) + for actual, (name, expected_type, nullable), check_nullable in zip( + fields, spec, compare_nullable + ) + ) + + logical_minimal = ( + ("data", pa.large_binary(), True), + ("uri", pa.utf8(), True), + ) + logical_full = logical_minimal + ( + ("position", pa.uint64(), True), + ("size", pa.uint64(), True), + ) + prepared = ( + ("kind", pa.uint8(), True), + ("data", pa.large_binary(), True), + ("uri", pa.utf8(), True), + ("blob_id", pa.uint32(), True), + ("blob_size", pa.uint64(), True), + ("position", pa.uint64(), True), + ) + descriptor = ( + ("kind", pa.uint8(), False), + ("position", pa.uint64(), False), + ("size", pa.uint64(), False), + ("blob_id", pa.uint32(), False), + ("blob_uri", pa.utf8(), False), + ) + return ( + matches(logical_minimal, (True, True)) + or matches(logical_full, (True, True, False, False)) + or matches(prepared, (True,) * len(prepared)) + or matches(descriptor, (False,) * len(descriptor)) + ) + + +def _canonical_arrow_field(field: pa.Field) -> str: + _validate_exact_arrow_field(field) + if _is_blob_v2_field(field): + return _FUNCTION_BLOB_V2_TYPE + return _canonical_arrow_type(field.type) + + def _exact_arrow_field(field: pa.Field) -> dict[str, Any]: _validate_exact_arrow_field(field) - return { + if _is_blob_v2_field(field): + raise TypeError( + "unsupported Arrow type for Function signature: nested Blob v2 " + "fields are not supported; declare Blob parameters or named result " + "fields directly" + ) + value = { "name": field.name, "nullable": field.nullable, "type": _exact_arrow_type(field.type), } + return value def _exact_arrow_type(data_type: pa.DataType) -> dict[str, Any]: @@ -718,7 +791,11 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp if output.metadata: raise TypeError("Function output schema metadata is not supported") fields = tuple(output) - elif isinstance(output, pa.Field) and pa.types.is_struct(output.type): + elif ( + isinstance(output, pa.Field) + and not _is_blob_v2_field(output) + and pa.types.is_struct(output.type) + ): _validate_exact_arrow_field(output) if output.nullable: raise ValueError("Function output must be non-nullable") @@ -740,7 +817,7 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp raise ValueError("Function output must be non-nullable") return FunctionOutput( kind="scalar", - arrow_type=_canonical_arrow_type(field.type), + arrow_type=_canonical_arrow_field(field), nullable=False, ) @@ -758,7 +835,7 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp fields=tuple( FunctionResultField( name=field.name, - arrow_type=_canonical_arrow_type(field.type), + arrow_type=_canonical_arrow_field(field), nullable=False, ) for field in fields @@ -792,7 +869,7 @@ def _infer_signature( inputs = tuple( FunctionParameter( name=field.name, - arrow_type=_canonical_arrow_type(field.type), + arrow_type=_canonical_arrow_field(field), nullable=field.nullable, ) for field in input_schema @@ -815,7 +892,9 @@ def _infer_signature( inputs.append( FunctionParameter( name=parameter.name, - arrow_type=_canonical_arrow_type(data_type), + arrow_type=_canonical_arrow_field( + pa.field(parameter.name, data_type, nullable=nullable) + ), nullable=nullable, ) ) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index cf1542b55..518a62bae 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -578,6 +578,124 @@ def test_explicit_arrow_schema_is_deterministic(): assert signature.output.nullable is False +def test_blob_fields_use_the_scalar_function_semantic_type(): + @udf( + input_schema=pa.schema([lancedb.blob("image", nullable=False)]), + output_schema=lancedb.blob("result", nullable=False), + ) + def copy_blob(image): + return image + + signature = copy_blob.registration_request.signature + assert signature.inputs[0].arrow_type == "blob_v2" + assert signature.output.kind == "scalar" + assert signature.output.arrow_type == "blob_v2" + + +def test_named_struct_function_can_include_a_blob_result_field(): + @udf( + input_schema=pa.schema([lancedb.blob("image", nullable=False)]), + output_schema=pa.schema( + [ + lancedb.blob("thumbnail", nullable=False), + pa.field("width", pa.int32(), nullable=False), + ] + ), + ) + def inspect_blob(image): + return {"thumbnail": image, "width": 1} + + output = inspect_blob.registration_request.signature.output + assert output.kind == "named_struct" + assert [(field.name, field.arrow_type) for field in output.fields] == [ + ("thumbnail", "blob_v2"), + ("width", "int32"), + ] + + +def test_metadata_marked_blob_field_uses_the_semantic_type(): + extension = lancedb.blob("image", nullable=False).type + storage = ( + extension.storage_type if isinstance(extension, pa.ExtensionType) else extension + ) + metadata_blob = pa.field( + "image", + storage, + nullable=False, + metadata={"ARROW:extension:name": "lance.blob.v2"}, + ) + + @udf( + input_schema=pa.schema([metadata_blob]), + output_schema=pa.field("size", pa.int64(), nullable=False), + ) + def blob_size(image): + return len(image) + + assert blob_size.registration_request.signature.inputs[0].arrow_type == "blob_v2" + + +def test_blob_marker_rejects_invalid_storage_layout(): + malformed = pa.field( + "image", + pa.int64(), + nullable=False, + metadata={"ARROW:extension:name": "lance.blob.v2"}, + ) + + with pytest.raises(TypeError, match="requires a supported Blob storage layout"): + + @udf( + input_schema=pa.schema([malformed]), + output_schema=pa.field("size", pa.int64(), nullable=False), + ) + def blob_size(image): + return len(image) + + +def test_nested_blob_signature_field_has_a_clear_error(): + nested = pa.field( + "value", + pa.struct([lancedb.blob("image", nullable=False)]), + nullable=False, + ) + with pytest.raises(TypeError, match="nested Blob v2 fields are not supported"): + + @udf( + input_schema=pa.schema([nested]), + output_schema=pa.field("size", pa.int64(), nullable=False), + ) + def blob_size(value): + return len(value["image"]) + + +def test_nested_non_blob_extension_is_not_silently_unwrapped(): + class TestExtension(pa.ExtensionType): + def __init__(self): + super().__init__(pa.int64(), "test.function.extension") + + def __arrow_ext_serialize__(self): + return b"" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type, serialized): + return cls() + + nested = pa.field( + "value", + pa.struct([pa.field("extended", TestExtension(), nullable=False)]), + nullable=False, + ) + with pytest.raises(TypeError, match="unsupported Arrow type"): + + @udf( + input_schema=pa.schema([nested]), + output_schema=pa.field("result", pa.int64(), nullable=False), + ) + def extension_value(value): + return value["extended"] + + def test_nested_struct_output_uses_canonical_exact_json(): token = pa.struct( [ diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 4b31a4376..79693c031 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -15,6 +15,9 @@ use serde_json::Value; use crate::{Error, Result}; +/// Semantic Function type for a Blob v2 value. +pub const FUNCTION_BLOB_V2_TYPE: &str = "blob_v2"; + fn invalid_json(error: impl std::fmt::Display) -> Error { Error::InvalidInput { message: format!("invalid remote Function JSON: {error}"), diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 6dc3ffad5..77e3d0a4d 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -29,14 +29,16 @@ use datafusion_common::{ScalarValue, tree_node::TreeNode}; use datafusion_expr::Expr; use datafusion_physical_plan::PhysicalExpr; use lance::dataset::NewColumnTransform; -use lance_arrow::FieldExt; -use lance_core::datatypes::{BLOB_V2_DESC_FIELD, format_field_path_minimal, parse_field_path}; +use lance_arrow::{ARROW_EXT_NAME_KEY, BLOB_V2_EXT_NAME, FieldExt}; +use lance_core::datatypes::{ + BLOB_V2_DESC_FIELD, BlobV2Layout, format_field_path_minimal, parse_field_path, +}; use lance_datafusion::planner::Planner; use lance_namespace::models::{JsonArrowDataType, JsonArrowField, JsonArrowSchema}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use crate::function::{FunctionApplication, FunctionBinding}; +use crate::function::{FUNCTION_BLOB_V2_TYPE, FunctionApplication, FunctionBinding}; use crate::utils::resolve_arrow_field_path; use crate::{Error, Result}; @@ -581,6 +583,23 @@ fn resolve_field_path<'a>(schema: &'a ArrowSchema, path: &str) -> Result Result { + let is_blob_v2 = field + .metadata + .as_ref() + .and_then(|metadata| metadata.get(ARROW_EXT_NAME_KEY)) + .map(String::as_str) + == Some(BLOB_V2_EXT_NAME); + if is_blob_v2 { + let arrow_field = lance_namespace::schema::convert_json_arrow_field(field) + .map_err(|e| invalid_function(format!("invalid Function input field: {e}")))?; + if !has_supported_blob_v2_layout(&arrow_field) { + return Err(invalid_function(format!( + "Function input '{}' has an invalid Blob v2 storage layout", + arrow_field.name() + ))); + } + return Ok(FUNCTION_BLOB_V2_TYPE.to_string()); + } if field.r#type.fields.is_none() && field.r#type.length.is_none() { Ok(field.r#type.r#type.clone()) } else { @@ -590,6 +609,14 @@ fn canonical_input_arrow_type(field: &JsonArrowField) -> Result { } } +fn has_supported_blob_v2_layout(field: &ArrowField) -> bool { + field.is_blob_v2() + && matches!( + field.data_type(), + DataType::Struct(fields) if BlobV2Layout::classify(fields).is_some() + ) +} + /// `fixed_size_list` -> (`item`, `size`); the comma must sit outside /// any nested `<...>`. fn split_fixed_size_list(raw: &str) -> Option<(&str, i32)> { @@ -669,6 +696,76 @@ fn parse_output_arrow_type(raw: &str) -> Result { Ok(data_type) } +fn function_output_field(name: &str, nullable: bool, raw: &str) -> Result { + if raw == FUNCTION_BLOB_V2_TYPE { + return lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ + crate::blob(name, nullable), + ])) + .map_err(|e| invalid_function(format!("could not encode Blob v2 output field: {e}")))? + .fields + .into_iter() + .next() + .ok_or_else(|| invalid_function("Blob v2 output field is missing")); + } + Ok(JsonArrowField::new( + name.to_string(), + nullable, + parse_output_arrow_type(raw)?, + )) +} + +fn function_output_field_matches(expected: &ArrowField, actual: &ArrowField) -> bool { + expected.name() == actual.name() + && expected.is_nullable() == actual.is_nullable() + && if expected.is_blob_v2() { + has_supported_blob_v2_layout(expected) && has_supported_blob_v2_layout(actual) + } else { + function_output_type_matches(expected.data_type(), actual.data_type()) + } +} + +fn function_output_type_matches(expected: &DataType, actual: &DataType) -> bool { + if expected == actual { + return true; + } + match (expected, actual) { + (DataType::Struct(expected), DataType::Struct(actual)) => { + expected.len() == actual.len() + && expected + .iter() + .zip(actual) + .all(|(expected, actual)| function_output_field_matches(expected, actual)) + } + (DataType::List(expected), DataType::List(actual)) + | (DataType::LargeList(expected), DataType::LargeList(actual)) => { + function_output_field_matches(expected, actual) + } + ( + DataType::FixedSizeList(expected, expected_size), + DataType::FixedSizeList(actual, actual_size), + ) => expected_size == actual_size && function_output_field_matches(expected, actual), + (DataType::Map(expected, expected_sorted), DataType::Map(actual, actual_sorted)) => { + expected_sorted == actual_sorted && function_output_field_matches(expected, actual) + } + _ => false, + } +} + +fn function_output_type_has_blob(data_type: &DataType) -> bool { + match data_type { + DataType::Struct(fields) => fields + .iter() + .any(|field| field.is_blob_v2() || function_output_type_has_blob(field.data_type())), + DataType::List(field) + | DataType::LargeList(field) + | DataType::FixedSizeList(field, _) + | DataType::Map(field, _) => { + field.is_blob_v2() || function_output_type_has_blob(field.data_type()) + } + _ => false, + } +} + 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() { @@ -749,10 +846,18 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding binding.binding_id() ))); } - let expected_type = parse_output_arrow_type(&output.arrow_type)?; - let expected_type = lance_namespace::schema::convert_json_arrow_type(&expected_type) - .map_err(|e| invalid_function(format!("invalid Function output type: {e}")))?; - if field.data_type() != &expected_type { + let (type_matches, has_semantic_blob) = if output.arrow_type == FUNCTION_BLOB_V2_TYPE { + (has_supported_blob_v2_layout(field), true) + } else { + let expected_type = parse_output_arrow_type(&output.arrow_type)?; + let expected_type = lance_namespace::schema::convert_json_arrow_type(&expected_type) + .map_err(|e| invalid_function(format!("invalid Function output type: {e}")))?; + ( + function_output_type_matches(&expected_type, field.data_type()), + function_output_type_has_blob(&expected_type), + ) + }; + if !type_matches { return Err(invalid_function(format!( "Function output '{}' type no longer matches binding '{}'", output.output_name, @@ -781,15 +886,21 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding binding.binding_id() ))); } - output_fields.push(ArrowField::new( - field.name().clone(), - field.data_type().clone(), - true, - )); - } - let output_schema = - lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(output_fields)) + if has_semantic_blob { + output_fields.push(function_output_field( + field.name(), + true, + &output.arrow_type, + )?); + } else { + let json = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ + ArrowField::new(field.name().clone(), field.data_type().clone(), true), + ])) .map_err(|e| invalid_function(format!("invalid Function output schema: {e}")))?; + output_fields.push(json.fields.into_iter().next().unwrap()); + } + } + let output_schema = JsonArrowSchema::new(output_fields); let output_schema = serde_json::to_value(output_schema).map_err(|e| { invalid_function(format!( "could not encode exact Function output schema: {e}" @@ -918,16 +1029,15 @@ pub(crate) fn plan_function_application( "Function logical outputs must be non-nullable during NULL assignment", )); } - let data_type = - parse_output_arrow_type(output.arrow_type.as_deref().ok_or_else(|| { - invalid_function("scalar Function output is missing its Arrow type") - })?)?; + let arrow_type = output.arrow_type.as_deref().ok_or_else(|| { + invalid_function("scalar Function output is missing its Arrow type") + })?; outputs.push(FunctionOutputTarget { result_field: WHOLE_RESULT_FIELD.to_string(), output_name: name.to_string(), output_ordinal: 0, }); - output_fields.push(JsonArrowField::new(name.to_string(), true, data_type)); + output_fields.push(function_output_field(name, true, arrow_type)?); } "named_struct" => { if output.fields.is_empty() { @@ -971,13 +1081,7 @@ pub(crate) fn plan_function_application( let fields = output .fields .iter() - .map(|field| { - Ok(JsonArrowField::new( - field.name.clone(), - false, - parse_output_arrow_type(&field.arrow_type)?, - )) - }) + .map(|field| function_output_field(&field.name, false, &field.arrow_type)) .collect::>>()?; let mut data_type = JsonArrowDataType::new("struct".to_string()); data_type.fields = Some(fields); @@ -1004,11 +1108,7 @@ pub(crate) fn plan_function_application( output_name: name.clone(), output_ordinal: ordinal as u32, }); - output_fields.push(JsonArrowField::new( - name.clone(), - true, - parse_output_arrow_type(&field.arrow_type)?, - )); + output_fields.push(function_output_field(name, true, &field.arrow_type)?); } } } @@ -1645,7 +1745,7 @@ mod tests { } use arrow_array::record_batch; - use arrow_schema::DataType; + use arrow_schema::{DataType, TimeUnit}; use futures::TryStreamExt; use lance::dataset::ColumnAlteration; @@ -2606,6 +2706,73 @@ mod tests { .unwrap() } + fn blob_application(output: &str) -> FunctionApplication { + FunctionApplication::from_json(&format!( + r#"{{ + "function":{{"name":"blob_features","version":"fv_blob"}}, + "inputs":[ + {{"parameter":"image","kind":"column","value":{{"path":"image"}}}} + ], + "output":{output} + }}"# + )) + .unwrap() + } + + fn binding_from_plan(plan: &FunctionDeclarationPlan) -> FunctionBinding { + let inputs = plan + .input_bindings + .iter() + .enumerate() + .map(|(index, input)| { + serde_json::json!({ + "parameter": input.parameter, + "field_id": index, + "field_path": input.field_path, + "arrow_type": input.arrow_type, + "nullable": input.nullable, + }) + }) + .collect::>(); + let outputs = plan + .outputs + .iter() + .zip(&plan.output_schema.fields) + .enumerate() + .map(|(index, (output, field))| { + serde_json::json!({ + "result_field": output.result_field, + "output_name": output.output_name, + "output_field_id": 100 + index, + "output_ordinal": output.output_ordinal, + "arrow_type": canonical_input_arrow_type(field).unwrap(), + "nullable": false, + }) + }) + .collect::>(); + FunctionBinding::from_json( + &serde_json::json!({ + "binding_id": "fb_blob", + "function": plan.application.function(), + "inputs": inputs, + "outputs": outputs, + "input_schema": plan.input_schema, + "output_schema": plan.output_schema, + }) + .to_string(), + ) + .unwrap() + } + + fn full_blob_field(name: &str, nullable: bool) -> ArrowField { + ArrowField::new( + name, + DataType::Struct(lance_core::datatypes::BLOB_V2_LOGICAL_FIELDS.clone()), + nullable, + ) + .with_metadata(crate::blob(name, nullable).metadata().clone()) + } + fn function_binding_schema(title_nullable: bool, body_nullable: bool) -> ArrowSchema { ArrowSchema::new(vec![ ArrowField::new("title", DataType::Utf8, title_nullable), @@ -2879,6 +3046,151 @@ mod tests { ); } + #[test] + fn test_blob_function_plans_semantic_input_and_scalar_output() { + let schema = ArrowSchema::new(vec![crate::blob("image", false)]); + let application = + blob_application(r#"{"kind":"scalar","arrow_type":"blob_v2","nullable":false}"#); + let plan = plan_function_application(&schema, &application, Some("thumbnail")).unwrap(); + + assert_eq!(plan.input_bindings[0].arrow_type, FUNCTION_BLOB_V2_TYPE); + let input_schema = + lance_namespace::schema::convert_json_arrow_schema(&plan.input_schema).unwrap(); + assert!(input_schema.field(0).is_blob_v2()); + let output_schema = + lance_namespace::schema::convert_json_arrow_schema(&plan.output_schema).unwrap(); + assert!(output_schema.field(0).is_blob_v2()); + } + + #[test] + fn test_blob_scalar_binding_accepts_full_logical_layout() { + let input = crate::blob("image", false); + let application = + blob_application(r#"{"kind":"scalar","arrow_type":"blob_v2","nullable":false}"#); + let plan = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &application, + Some("thumbnail"), + ) + .unwrap(); + let binding = binding_from_plan(&plan); + 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); + + ensure_binding_matches_schema(&ArrowSchema::new(vec![input, output]), &binding).unwrap(); + } + + #[test] + fn test_blob_binding_rejects_marker_on_invalid_storage_layout() { + let input = crate::blob("image", false); + let application = + blob_application(r#"{"kind":"scalar","arrow_type":"blob_v2","nullable":false}"#); + let plan = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &application, + Some("thumbnail"), + ) + .unwrap(); + let binding = binding_from_plan(&plan); + let malformed = ArrowField::new("thumbnail", DataType::Int64, true) + .with_metadata(crate::blob("thumbnail", true).metadata().clone()); + + ensure_binding_matches_schema(&ArrowSchema::new(vec![input, malformed]), &binding) + .unwrap_err(); + } + + #[test] + fn test_blob_input_rejects_marker_on_invalid_storage_layout() { + let malformed = ArrowField::new("image", DataType::Int64, false) + .with_metadata(crate::blob("image", false).metadata().clone()); + let application = + blob_application(r#"{"kind":"scalar","arrow_type":"blob_v2","nullable":false}"#); + + plan_function_application( + &ArrowSchema::new(vec![malformed]), + &application, + Some("thumbnail"), + ) + .unwrap_err(); + } + + #[test] + fn test_non_blob_input_does_not_require_json_round_trip() { + let json = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ + ArrowField::new("event_time", DataType::Time64(TimeUnit::Microsecond), false), + ])) + .unwrap(); + + assert_eq!( + canonical_input_arrow_type(&json.fields[0]).unwrap(), + "time64" + ); + } + + #[test] + fn test_blob_named_struct_plans_expanded_and_whole_outputs() { + let schema = ArrowSchema::new(vec![crate::blob("image", false)]); + let application = blob_application( + r#"{"kind":"named_struct","fields":[ + {"name":"thumbnail","arrow_type":"blob_v2","nullable":false}, + {"name":"width","arrow_type":"int32","nullable":false} + ]}"#, + ); + + let expanded = plan_function_application(&schema, &application, None).unwrap(); + let expanded_schema = + lance_namespace::schema::convert_json_arrow_schema(&expanded.output_schema).unwrap(); + assert!(expanded_schema.field(0).is_blob_v2()); + assert_eq!(expanded_schema.field(1).data_type(), &DataType::Int32); + + let whole = plan_function_application(&schema, &application, Some("analysis")).unwrap(); + let whole_schema = + lance_namespace::schema::convert_json_arrow_schema(&whole.output_schema).unwrap(); + let DataType::Struct(fields) = whole_schema.field(0).data_type() else { + panic!("whole Function output should be a struct"); + }; + assert!(fields[0].is_blob_v2()); + assert_eq!(fields[1].data_type(), &DataType::Int32); + } + + #[test] + fn test_blob_whole_struct_binding_accepts_full_logical_layout() { + let input = crate::blob("image", false); + let application = blob_application( + r#"{"kind":"named_struct","fields":[ + {"name":"thumbnail","arrow_type":"blob_v2","nullable":false}, + {"name":"width","arrow_type":"int32","nullable":false} + ]}"#, + ); + let plan = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &application, + Some("analysis"), + ) + .unwrap(); + let binding = binding_from_plan(&plan); + + let output = ArrowField::new( + "analysis", + DataType::Struct(Fields::from(vec![ + full_blob_field("thumbnail", false), + ArrowField::new("width", DataType::Int32, false), + ])), + true, + ) + .with_metadata(function_computed_column_metadata( + binding.binding_id(), + 0, + &["image".into()], + )); + ensure_binding_matches_schema(&ArrowSchema::new(vec![input, output]), &binding).unwrap(); + } + #[test] fn test_function_mapping_and_sibling_collisions_fail_before_request() { let unknown = named_struct_application(r#"{"missing":"renamed"}"#); From c6dfe830d90857ef930b56aa1d0b3afeffa7772a Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Mon, 31 Aug 2026 00:32:04 -0700 Subject: [PATCH 153/206] feat(python): support large_utf8 function signatures (#4092) Teach the Python Function signature emitter to serialize PyArrow large strings as the canonical Arrow type name `large_utf8`. Extend the shared Function Arrow type fixture and explicit-schema coverage for scalar, nested, list, and large-list compositions. --- python/python/lancedb/functions.py | 1 + .../tests/test_first_class_function_slice2.py | 43 +++++++++++++++---- .../first_class_functions/v1/arrow_types.json | 38 +++++++++++++++- 3 files changed, 73 insertions(+), 9 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index bac6a762f..3bdd117cb 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -537,6 +537,7 @@ _GRAMMAR_PRIMITIVES = ( (pa.float32(), "float32"), (pa.float64(), "float64"), (pa.string(), "utf8"), + (pa.large_string(), "large_utf8"), (pa.binary(), "binary"), (pa.date32(), "date32"), (pa.date64(), "date64"), diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 518a62bae..415ecbe0f 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -19,7 +19,13 @@ import pyarrow as pa import pytest import lancedb -from lancedb.functions import PythonRuntimeSpec, UdfDefinition, udf +from lancedb.functions import ( + PythonRuntimeSpec, + UdfDefinition, + _canonical_arrow_type, + _GRAMMAR_PRIMITIVES, + udf, +) THRESHOLD = 20 _CACHE = None @@ -221,8 +227,6 @@ def test_udf_resolves_module_globals_before_builtins(tmp_path): def test_canonical_arrow_type_prefers_the_compact_grammar(): - from lancedb.functions import _GRAMMAR_PRIMITIVES, _canonical_arrow_type - golden = json.loads( ( Path(__file__).parents[3] @@ -243,7 +247,6 @@ def test_canonical_arrow_type_prefers_the_compact_grammar(): for outside in [ pa.timestamp("us"), pa.decimal128(10, 2), - pa.large_string(), pa.large_binary(), pa.binary(4), pa.duration("s"), @@ -437,8 +440,6 @@ def test_udf_recursion_versus_a_rebound_module_name(tmp_path): def test_canonical_arrow_type_uses_exact_json_for_list_child_properties(): - from lancedb.functions import _canonical_arrow_type - nullable = pa.list_(pa.float32()) assert json.loads(_canonical_arrow_type(nullable)) == { "type": "list", @@ -528,6 +529,7 @@ def _arrow_type_from_golden(spec: dict) -> pa.DataType: "null": pa.null(), "bool": pa.bool_(), "utf8": pa.string(), + "large_utf8": pa.large_string(), "binary": pa.binary(), "float16": pa.float16(), "float32": pa.float32(), @@ -544,8 +546,6 @@ def test_arrow_type_grammar_matches_the_shared_golden(): / "rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json" ).read_text() ) - from lancedb.functions import _canonical_arrow_type - emitted = { case["arrow_type"]: _canonical_arrow_type(_arrow_type_from_golden(case["json"])) for case in golden["valid"] @@ -696,6 +696,33 @@ def test_nested_non_blob_extension_is_not_silently_unwrapped(): return value["extended"] +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) + def preserve(text): + return text + + signature = preserve.registration_request.signature + assert signature.inputs[0].arrow_type == "large_utf8" + assert signature.inputs[0].nullable is True + assert signature.output.arrow_type == "large_utf8" + assert signature.output.nullable is False + + nested = pa.struct([pa.field("text", pa.large_string(), nullable=True)]) + assert json.loads(_canonical_arrow_type(nested)) == { + "type": "struct", + "fields": [ + { + "name": "text", + "nullable": True, + "type": {"type": "large_utf8"}, + } + ], + } + + def test_nested_struct_output_uses_canonical_exact_json(): token = pa.struct( [ diff --git a/rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json b/rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json index ff26e4c08..38d17821b 100644 --- a/rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json +++ b/rust/lancedb/tests/fixtures/first_class_functions/v1/arrow_types.json @@ -78,6 +78,12 @@ "type": "utf8" } }, + { + "arrow_type": "large_utf8", + "json": { + "type": "large_utf8" + } + }, { "arrow_type": "binary", "json": { @@ -171,6 +177,21 @@ ] } }, + { + "arrow_type": "list", + "json": { + "type": "list", + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "large_utf8" + } + } + ] + } + }, { "arrow_type": "large_list", "json": { @@ -186,6 +207,21 @@ ] } }, + { + "arrow_type": "large_list", + "json": { + "type": "large_list", + "fields": [ + { + "name": "item", + "nullable": false, + "type": { + "type": "large_utf8" + } + } + ] + } + }, { "arrow_type": "fixed_size_list", "json": { @@ -330,4 +366,4 @@ "timestamp[us]", "struct" ] -} \ No newline at end of file +} From 57b8d3bf053e839270d81d7af1927655a36f453b Mon Sep 17 00:00:00 2001 From: Lance Release Date: Mon, 31 Aug 2026 07:33:01 +0000 Subject: [PATCH 154/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.14=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.15?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 763df001b..287f49768 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.14" +current_version = "0.38.0-beta.15" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 69c33c587..8172c1b75 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.14" +version = "0.38.0-beta.15" dependencies = [ "ahash", "anyhow", @@ -5490,7 +5490,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.14" +version = "0.38.0-beta.15" dependencies = [ "arrow-array", "arrow-buffer", @@ -5515,7 +5515,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.14" +version = "0.38.0-beta.15" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index b66a8db2f..1ac67b1c1 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.38.0-beta.14 + 0.38.0-beta.15 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 6b4f2ea82..0b39ecc68 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.14 + 0.38.0-beta.15 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 9a752b3ef..c5481e022 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.14 + 0.38.0-beta.15 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index accd9e3bf..cb1281e85 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.14" +version = "0.38.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 8ae5be4ef..defb684c3 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.38.0-beta.14", + "version": "0.38.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 b923bf224..b2cb057d6 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.38.0-beta.14", + "version": "0.38.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 2e2bd92c5..23d9df464 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.38.0-beta.14", + "version": "0.38.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 e0b918b2f..d12ad53fa 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.38.0-beta.14", + "version": "0.38.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 da6de64d1..42ad36ab8 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.38.0-beta.14", + "version": "0.38.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 5f7c7d6c2..6264bb5dc 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.38.0-beta.14", + "version": "0.38.0-beta.15", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index d2a808411..dc21cd79c 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.38.0-beta.14", + "version": "0.38.0-beta.15", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 38536d7f5..496faf410 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.14", + "version": "0.38.0-beta.15", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 972c86ede..92126a178 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.14" +version = "0.38.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 21babc252..e61ebf141 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.14" +version = "0.38.0-beta.15" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From c4ee8ae670807a97258b3dc822cfd43c3c4ae074 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Mon, 31 Aug 2026 00:35:09 -0700 Subject: [PATCH 155/206] feat: update lance dependency to v11.0.0 (#4093) Updates the Rust workspace and Java lance-core dependency to Lance v11.0.0. Includes compatibility adjustments for the Lance 11 object-store, table-listing, and shard-manifest APIs. --- Cargo.lock | 107 +++++++----- Cargo.toml | 28 ++-- java/pom.xml | 2 +- rust/lancedb/src/database/listing.rs | 158 +++++++++++++----- rust/lancedb/src/io/object_store.rs | 10 +- .../src/io/object_store/io_tracking.rs | 10 +- rust/lancedb/src/table.rs | 16 -- rust/lancedb/src/table/query/lsm.rs | 2 +- 8 files changed, 203 insertions(+), 130 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8172c1b75..3a2a4a8a3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,9 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f727719438dfdb74f358a347c91ff81b6e7084a6421f34de3e473ce271f10caa" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4816,9 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be781f40c7a75f9eae2188a2f71174acb7a360dca97163db40b041d0828dea48" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4890,9 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb97fd9875f3036d7c2561aa5b16eb87b80ccabaa4eeb5e6099b19cc662f1cd8" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4914,8 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "771f68b04b47f3addf781116f65061808de94b05e1e9411c23c18f32d14ebe79" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,17 +4929,20 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd47ec33c90bf29f688fd02118e37d3a5ad5c339caa3163f89e417dc0867001f" dependencies = [ "arrow-array", "arrow-schema", + "half", "lance-arrow-scalar", ] [[package]] name = "lance-bitpacking" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f45658c5b2dc9aada41b66ee44b83af3fa888b7385ae414bae951b12a9f1cd3" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4952,9 @@ dependencies = [ [[package]] name = "lance-core" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27af3df3a7d08897efccd04461df31cedf0880c4b86a055ddce48e423d27f967" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4991,9 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c377f837df5296e92f9fad724c83c1bef4e74d5af6e5a9312e9307e1dead8614" dependencies = [ "arrow", "arrow-array", @@ -5013,8 +5022,9 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "778e1a5065fa4bc184e36e32681f10f8f4680ad8cedc9377b4c088dce8c5b8da" dependencies = [ "arrow", "arrow-array", @@ -5031,8 +5041,9 @@ dependencies = [ [[package]] name = "lance-derive" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13e5e95e0fd3d74f7938f4bee623041421b323b5c61f242c8622a1f48a202527" dependencies = [ "proc-macro2", "quote", @@ -5041,8 +5052,9 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1625653c55c65f3426e281f6e29b54c603f38a40bd4cebd707bd4f3ea48be6c5" dependencies = [ "arrow-arith", "arrow-array", @@ -5075,8 +5087,9 @@ dependencies = [ [[package]] name = "lance-file" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7e13c9266b478fc98f36ee19347c4658f7a6613fed77778b1a455fe1b88552e" dependencies = [ "arrow-arith", "arrow-array", @@ -5107,8 +5120,9 @@ dependencies = [ [[package]] name = "lance-index" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0e0cb95f2c4f341c4dd04ac60f6a89ea26a6f75e09570225cbda4854c8b088e" dependencies = [ "arc-swap", "arrow", @@ -5172,8 +5186,9 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79ccd371977c1f7168da259d66ad37154f23146f093d46136bc7f79559f00f2c" dependencies = [ "arrow-array", "arrow-schema", @@ -5195,8 +5210,9 @@ dependencies = [ [[package]] name = "lance-io" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "414d50997391b1ac83dc183c1612fdff88f58b959806078dc4c5e465154566de" dependencies = [ "arrow", "arrow-array", @@ -5236,8 +5252,9 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ff55b152ef23a56d7ba7e4d1b2c9cf0cc79aef6ee607c115597557ea4059f41" dependencies = [ "arrow-array", "arrow-schema", @@ -5251,8 +5268,9 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09991c13ab282b731e323619613914e08da9cc82b312f904e58c128b23f2f0e3" dependencies = [ "arrow", "async-trait", @@ -5264,8 +5282,9 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec0bc005f6bb8f120774eb4a9ba02e10463d8338167a46cbb1391d46680a174" dependencies = [ "arrow", "arrow-ipc", @@ -5318,8 +5337,9 @@ dependencies = [ [[package]] name = "lance-select" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8f676a2a1837cc85b77feb5326d3296827da964e40d67144f646563302a6ce9" dependencies = [ "arrow-array", "arrow-buffer", @@ -5333,8 +5353,9 @@ dependencies = [ [[package]] name = "lance-table" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd33054347395048b1d842dfb85a13f7801392c2da5f39425db62f00a481744b" dependencies = [ "arrow", "arrow-array", @@ -5374,8 +5395,9 @@ dependencies = [ [[package]] name = "lance-testing" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc9ad9ae24f045dfddd538a39e55a28fa7e1ca6ad9f23e20d4087eaf2bb66f7" dependencies = [ "arrow-array", "arrow-schema", @@ -5388,8 +5410,9 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "11.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bfa6f0164c8b7056150f5682ce4d415a335b59b04c479873fda04b200117d27" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 033da5907..276658157 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=12.0.0-beta.5", default-features = false, "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=12.0.0-beta.5", default-features = false, "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=12.0.0-beta.5", default-features = false, "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=11.0.0", default-features = false } +lance-core = "=11.0.0" +lance-datagen = "=11.0.0" +lance-file = "=11.0.0" +lance-io = { "version" = "=11.0.0", default-features = false } +lance-index = "=11.0.0" +lance-linalg = "=11.0.0" +lance-namespace = "=11.0.0" +lance-namespace-impls = { "version" = "=11.0.0", default-features = false } +lance-table = "=11.0.0" +lance-testing = "=11.0.0" +lance-datafusion = "=11.0.0" +lance-encoding = "=11.0.0" +lance-arrow = "=11.0.0" lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index c5481e022..3b0b84667 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 12.0.0-beta.5 + 11.0.0 false 2.30.0 1.7 diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index c22b73dd7..71e4016dd 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -13,7 +13,7 @@ use lance::dataset::{ReadParams, WriteMode, builder::DatasetBuilder}; use lance::io::{ObjectStore, ObjectStoreParams, WrappingObjectStore}; use lance_datafusion::utils::StreamingWriteSource; use lance_file::version::LanceFileVersion; -use lance_io::object_store::{ReadDirOptions, StorageOptionsAccessor, StorageOptionsProvider}; +use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider}; use lance_table::io::commit::commit_handler_from_url; use object_store::local::LocalFileSystem; use snafu::ResultExt; @@ -282,14 +282,11 @@ impl std::fmt::Display for ListingDatabase { const LANCE_EXTENSION: &str = "lance"; -/// The table a listed child of the database names, or `None` if the child is not a table. +/// The table a listed child directory holds, or `None` if it is not a table at all. /// /// A table is the directory `.lance`; a loose file or any other directory under the /// database prefix belongs to something else. `dir_suffix` is `.lance`, built once by the /// caller rather than per child. -/// The table a listed child directory holds, or `None` if it is not a table at all. -/// -/// Only directories are considered, so a loose object named like a table is not one. fn table_name(location: &object_store::path::Path, dir_suffix: &str) -> Option { location .filename()? @@ -297,6 +294,75 @@ fn table_name(location: &object_store::path::Path, dir_suffix: &str) -> Option, + /// Resumes after this page, or `None` when the page reached the end of the level. + page_token: Option, +} + +/// Where a listed location sits inside the database directory — the space page tokens live +/// in — or `None` if it is not a child of that directory at all. Matching both halves of the +/// prefix drops a location that merely starts with the directory's name (`dbx/y` against +/// `db/`) as well as the marker object some stores keep for the directory itself. +fn relative_key<'a>(prefix: Option<&str>, location: &'a str) -> Option<&'a str> { + let relative = match prefix { + Some(prefix) => location.strip_prefix(prefix)?, + None => location, + }; + (!relative.is_empty()).then_some(relative) +} + +/// One page of the table directories under `base_path`, one directory level deep. +/// +/// Lance 11 exposes no paginated directory listing, so the level is listed in full and paged +/// locally: table directories go into key order (a directory's key keeps its trailing `/`, +/// so a token is never a table name), the page is the smallest `limit` of them past +/// `page_token`, and the token handed back is the key of the last directory the page took — +/// so a page that took nothing ends the listing rather than resuming from a position no page +/// ever reached. Only `.lance/` directories enter the page: loose objects, other +/// directories, and a bare `.lance/` never take a page slot or name a token, which keeps a +/// page to exactly one listing of the level. Correct on every store, at the cost of that one +/// full-level listing per page. +async fn read_dir_page( + object_store: &ObjectStore, + base_path: &object_store::path::Path, + page_token: Option, + limit: Option, +) -> Result { + let listed = object_store.list_with_delimiter(Some(base_path)).await?; + let prefix = { + let base = base_path.as_ref(); + (!base.is_empty()).then(|| format!("{base}/")) + }; + let table_dir_suffix = format!(".{LANCE_EXTENSION}/"); + let mut children: Vec<(String, object_store::path::Path)> = listed + .common_prefixes + .into_iter() + .filter_map(|location| { + let key = format!("{}/", relative_key(prefix.as_deref(), location.as_ref())?); + (key.len() > table_dir_suffix.len() && key.ends_with(&table_dir_suffix)) + .then_some((key, location)) + }) + .collect(); + children.sort_unstable_by(|(left, _), (right, _)| left.cmp(right)); + if let Some(resume) = &page_token { + children.retain(|(key, _)| key > resume); + } + let total = children.len(); + children.truncate(limit.unwrap_or(total).min(total)); + let page_token = match children.last() { + Some((last, _)) if children.len() < total => Some(last.clone()), + _ => None, + }; + Ok(DirPage { + common_prefixes: children.into_iter().map(|(_, location)| location).collect(), + page_token, + }) +} + const ENGINE: &str = "engine"; const MIRRORED_STORE: &str = "mirroredStore"; @@ -982,8 +1048,7 @@ impl Database for ListingDatabase { let mut tables = Vec::new(); let mut page_token = request.page_token.filter(|token| !token.is_empty()); - // A page of nothing: the store rejects a limit of zero, and no table was handed over - // for a token to resume after. + // A page of nothing: no table was handed over for a token to resume after. if limit == Some(0) { return Ok(ListTablesResponse { context: None, @@ -992,35 +1057,21 @@ impl Database for ListingDatabase { }); } - loop { - // Ask only for what the page still has room for, so a database holding more - // than one page costs one request per page rather than one per table. - let listing = self - .object_store - .read_dir_page( - self.base_path.clone(), - ReadDirOptions { - page_token: page_token.take(), - limit: limit.map(|limit| limit - tables.len()), - }, - ) - .await?; - page_token = listing.page_token; - // Only child directories can be tables, and the store already separates them - // out, so the objects in the page are not looked at. - tables.extend( - listing - .result - .common_prefixes - .iter() - .filter_map(|location| table_name(location, &dir_suffix)), - ); - // Children that are not tables leave the page short of the limit, so keep - // going until the page is full or the database runs out. - if page_token.is_none() || limit.is_none_or(|limit| tables.len() >= limit) { - break; - } - } + // The page holds only table directories, so one call — and the one full-level + // listing behind it — fills it. + let page = read_dir_page( + &self.object_store, + &self.base_path, + page_token.take(), + limit, + ) + .await?; + page_token = page.page_token; + tables.extend( + page.common_prefixes + .iter() + .filter_map(|location| table_name(location, &dir_suffix)), + ); Ok(ListTablesResponse { context: None, @@ -1666,8 +1717,8 @@ mod tests { } /// Only directories named `.lance` are tables; loose files and other directories - /// under the database prefix are not. A page spent on them is filled from the next one, - /// so a page holding only non-tables does not read as an empty database. + /// under the database prefix are not. They never take a page slot, so even a `limit` + /// smaller than the clutter ahead of the first table returns that table. #[tokio::test] async fn test_listing_ignores_non_table_children() { let (tempdir, db) = setup_database().await; @@ -1686,6 +1737,37 @@ mod tests { assert_eq!(page.tables, vec!["real"]); } + /// The Lance 11 fallback pages locally over one full-level listing, so a bounded page + /// costs exactly one listing call — clutter ahead of the first table must not buy extra + /// round trips. + #[tokio::test] + async fn test_one_full_listing_per_public_page() { + use crate::io::object_store::io_tracking::IoStatsHolder; + use lance_io::object_store::WrappingObjectStore; + + let (tempdir, mut db) = setup_database().await; + create_tables(&db, &["real"]).await; + std::fs::write(tempdir.path().join("aaa-loose.lance"), b"not a table").unwrap(); + create_dir_all(tempdir.path().join("aaa-scratch")).unwrap(); + + let io_stats = IoStatsHolder::default(); + let mut tracked_store = (*db.object_store).clone(); + tracked_store.inner = + io_stats.wrap(&tracked_store.store_prefix, tracked_store.inner.clone()); + db.object_store = Arc::new(tracked_store); + + let page = db + .list_tables(ListTablesRequest { + limit: Some(1), + ..Default::default() + }) + .await + .unwrap(); + + assert_eq!(page.tables, vec!["real"]); + assert_eq!(io_stats.incremental_stats().read_iops, 1); + } + #[tokio::test] async fn listing_ignores_empty_table_name() { let (tempdir, db) = setup_database().await; diff --git a/rust/lancedb/src/io/object_store.rs b/rust/lancedb/src/io/object_store.rs index c4a9a4f7e..d594bd857 100644 --- a/rust/lancedb/src/io/object_store.rs +++ b/rust/lancedb/src/io/object_store.rs @@ -10,7 +10,7 @@ use lance::io::WrappingObjectStore; use object_store::{ CopyOptions, Error, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, ObjectStoreExt, PutMultipartOptions, PutOptions, PutPayload, PutResult, Result, - UploadPart, list::PaginatedListStore, path::Path, + UploadPart, path::Path, }; use async_trait::async_trait; @@ -187,14 +187,6 @@ impl WrappingObjectStore for MirroringObjectStoreWrapper { secondary: self.secondary.clone(), }) } - - fn wrap_paginated( - &self, - _store_prefix: &str, - original: Arc, - ) -> Option> { - Some(original) - } } // windows pathing can't be simply concatenated diff --git a/rust/lancedb/src/io/object_store/io_tracking.rs b/rust/lancedb/src/io/object_store/io_tracking.rs index 7f9750216..bd4f8f54a 100644 --- a/rust/lancedb/src/io/object_store/io_tracking.rs +++ b/rust/lancedb/src/io/object_store/io_tracking.rs @@ -12,7 +12,7 @@ use lance::io::WrappingObjectStore; use object_store::{ CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, PutMultipartOptions, PutOptions, PutPayload, PutResult, RenameOptions, Result as OSResult, - UploadPart, list::PaginatedListStore, path::Path, + UploadPart, path::Path, }; #[derive(Debug, Default)] @@ -57,14 +57,6 @@ impl WrappingObjectStore for IoStatsHolder { stats: self.0.clone(), }) } - - fn wrap_paginated( - &self, - _store_prefix: &str, - original: Arc, - ) -> Option> { - Some(original) - } } impl IoTrackingStore { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index efc705e3c..d152f3616 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -4183,14 +4183,6 @@ mod tests { parent_list_calls: self.parent_list_calls.clone(), }) } - - fn wrap_paginated( - &self, - _store_prefix: &str, - _original: Arc, - ) -> Option> { - None - } } #[tokio::test] @@ -4294,14 +4286,6 @@ mod tests { self.called.store(true, Ordering::Relaxed); original } - - fn wrap_paginated( - &self, - _store_prefix: &str, - original: Arc, - ) -> Option> { - Some(original) - } } #[tokio::test] diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index 86c1fe5f2..07ea7fb81 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -300,7 +300,7 @@ async fn build_read_context( for shard_id in shard_ids { let manifest_store = ShardManifestStore::new(store.clone(), &base_path, shard_id, scan_batch_size); - if let Some(manifest) = manifest_store.latest().await? { + if let Some(manifest) = manifest_store.read_latest().await? { snapshots.push(snapshot_from_manifest(shard_id, &manifest, &exclude)); } } From 1a9414c47c9c4e18ef00c89401d871b3363214da Mon Sep 17 00:00:00 2001 From: Lance Release Date: Mon, 31 Aug 2026 07:38:25 +0000 Subject: [PATCH 156/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.15=20?= =?UTF-8?q?=E2=86=92=200.38.0-beta.16?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- 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 +- 15 files changed, 15 insertions(+), 15 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 287f49768..ee9f48658 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.15" +current_version = "0.38.0-beta.16" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 1ac67b1c1..aba19ac03 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.38.0-beta.15 + 0.38.0-beta.16 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 0b39ecc68..113ff633e 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.15 + 0.38.0-beta.16 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 3b0b84667..0974df14a 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.15 + 0.38.0-beta.16 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index cb1281e85..0f83189bc 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.15" +version = "0.38.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 defb684c3..95578fad5 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.38.0-beta.15", + "version": "0.38.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 b2cb057d6..be34180bb 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.38.0-beta.15", + "version": "0.38.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 23d9df464..5a2871e25 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.38.0-beta.15", + "version": "0.38.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 d12ad53fa..01680fe3b 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.38.0-beta.15", + "version": "0.38.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 42ad36ab8..9631a2b94 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.38.0-beta.15", + "version": "0.38.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 6264bb5dc..8ba1a0038 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.38.0-beta.15", + "version": "0.38.0-beta.16", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index dc21cd79c..ef410b875 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.38.0-beta.15", + "version": "0.38.0-beta.16", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 496faf410..3c6506d57 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.15", + "version": "0.38.0-beta.16", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 92126a178..47645b9f0 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.15" +version = "0.38.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 e61ebf141..d4a97c195 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.15" +version = "0.38.0-beta.16" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 840e1d7313df25473556e5f29404c58fa51b3a7d Mon Sep 17 00:00:00 2001 From: Lance Release Date: Mon, 31 Aug 2026 07:38:30 +0000 Subject: [PATCH 157/206] =?UTF-8?q?Bump=20version:=200.38.0-beta.16=20?= =?UTF-8?q?=E2=86=92=200.38.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index ee9f48658..b88c14615 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0-beta.16" +current_version = "0.38.0" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 3a2a4a8a3..7eec5a8e5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5425,7 +5425,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0-beta.15" +version = "0.38.0" dependencies = [ "ahash", "anyhow", @@ -5513,7 +5513,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0-beta.15" +version = "0.38.0" dependencies = [ "arrow-array", "arrow-buffer", @@ -5538,7 +5538,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0-beta.15" +version = "0.38.0" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index aba19ac03..f3e7952f4 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.38.0-beta.16 + 0.38.0 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 113ff633e..6a9059119 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.16 + 0.38.0-final.0 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 0974df14a..80cef9716 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-beta.16 + 0.38.0-final.0 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 0f83189bc..b6f006327 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0-beta.16" +version = "0.38.0" 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 95578fad5..68ce67487 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.38.0-beta.16", + "version": "0.38.0", "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 be34180bb..4cb228b9e 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.38.0-beta.16", + "version": "0.38.0", "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 5a2871e25..ad22eecb7 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.38.0-beta.16", + "version": "0.38.0", "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 01680fe3b..e6a8c566b 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.38.0-beta.16", + "version": "0.38.0", "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 9631a2b94..8c33306d3 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.38.0-beta.16", + "version": "0.38.0", "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 8ba1a0038..97977353e 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.38.0-beta.16", + "version": "0.38.0", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index ef410b875..6a1cb0f41 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.38.0-beta.16", + "version": "0.38.0", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 3c6506d57..857952b5c 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0-beta.16", + "version": "0.38.0", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 47645b9f0..7cbe5d418 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0-beta.16" +version = "0.38.0" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index d4a97c195..faababd08 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0-beta.16" +version = "0.38.0" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 16753b805ae6dd9bd3055b7d61509e59120a46a7 Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Mon, 31 Aug 2026 20:40:46 +0800 Subject: [PATCH 158/206] revert: restore the lance v12.0.0-beta.5 pin on main (#4095) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reverts #4093 (`c4ee8ae`), restoring main's lance dependency to v12.0.0-beta.5 and the v12 integration surface it carried — the `read_dir_page` paginated-listing pushdown from #3979, the v12 object-store wrapper APIs, and the shard-manifest call sites. Pinning lance v11.0.0 stable belonged on a dedicated release branch for cutting v0.38.0, not on main: main was already on the v12 beta train, so #4093 was a downgrade of the development line. The released **v0.38.0 stands as published** — this only moves main forward again. Verified on this branch: `cargo check --features remote --tests --examples` clean, all 48 `database::listing` tests pass (the restored store-pushdown pagination versions), `cargo fmt --check` and `cargo clippy --features remote --tests --examples` clean. The root `Cargo.lock` is restored by the revert and resolves as-is. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01BX7w9fUMQbPAXuxe9YgQKc --- _Generated by [Claude Code](https://claude.ai/code/session_01BX7w9fUMQbPAXuxe9YgQKc)_ Co-authored-by: Claude --- Cargo.lock | 107 +++++------- Cargo.toml | 28 ++-- java/pom.xml | 2 +- rust/lancedb/src/database/listing.rs | 158 +++++------------- rust/lancedb/src/io/object_store.rs | 10 +- .../src/io/object_store/io_tracking.rs | 10 +- rust/lancedb/src/table.rs | 16 ++ rust/lancedb/src/table/query/lsm.rs | 2 +- 8 files changed, 130 insertions(+), 203 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7eec5a8e5..adf15c218 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,9 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f727719438dfdb74f358a347c91ff81b6e7084a6421f34de3e473ce271f10caa" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4816,9 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be781f40c7a75f9eae2188a2f71174acb7a360dca97163db40b041d0828dea48" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arc-swap", "arrow", @@ -4890,9 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb97fd9875f3036d7c2561aa5b16eb87b80ccabaa4eeb5e6099b19cc662f1cd8" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-buffer", @@ -4914,8 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "771f68b04b47f3addf781116f65061808de94b05e1e9411c23c18f32d14ebe79" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-buffer", @@ -4929,20 +4925,17 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd47ec33c90bf29f688fd02118e37d3a5ad5c339caa3163f89e417dc0867001f" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-schema", - "half", "lance-arrow-scalar", ] [[package]] name = "lance-bitpacking" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f45658c5b2dc9aada41b66ee44b83af3fa888b7385ae414bae951b12a9f1cd3" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrayref", "crunchy", @@ -4952,9 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27af3df3a7d08897efccd04461df31cedf0880c4b86a055ddce48e423d27f967" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-buffer", @@ -4991,9 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c377f837df5296e92f9fad724c83c1bef4e74d5af6e5a9312e9307e1dead8614" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow", "arrow-array", @@ -5022,9 +5013,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "778e1a5065fa4bc184e36e32681f10f8f4680ad8cedc9377b4c088dce8c5b8da" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow", "arrow-array", @@ -5041,9 +5031,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13e5e95e0fd3d74f7938f4bee623041421b323b5c61f242c8622a1f48a202527" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "proc-macro2", "quote", @@ -5052,9 +5041,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1625653c55c65f3426e281f6e29b54c603f38a40bd4cebd707bd4f3ea48be6c5" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-arith", "arrow-array", @@ -5087,9 +5075,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7e13c9266b478fc98f36ee19347c4658f7a6613fed77778b1a455fe1b88552e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-arith", "arrow-array", @@ -5120,9 +5107,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0e0cb95f2c4f341c4dd04ac60f6a89ea26a6f75e09570225cbda4854c8b088e" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arc-swap", "arrow", @@ -5186,9 +5172,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79ccd371977c1f7168da259d66ad37154f23146f093d46136bc7f79559f00f2c" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-schema", @@ -5210,9 +5195,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "414d50997391b1ac83dc183c1612fdff88f58b959806078dc4c5e465154566de" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow", "arrow-array", @@ -5252,9 +5236,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ff55b152ef23a56d7ba7e4d1b2c9cf0cc79aef6ee607c115597557ea4059f41" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-schema", @@ -5268,9 +5251,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09991c13ab282b731e323619613914e08da9cc82b312f904e58c128b23f2f0e3" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow", "async-trait", @@ -5282,9 +5264,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec0bc005f6bb8f120774eb4a9ba02e10463d8338167a46cbb1391d46680a174" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow", "arrow-ipc", @@ -5337,9 +5318,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8f676a2a1837cc85b77feb5326d3296827da964e40d67144f646563302a6ce9" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-buffer", @@ -5353,9 +5333,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd33054347395048b1d842dfb85a13f7801392c2da5f39425db62f00a481744b" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow", "arrow-array", @@ -5395,9 +5374,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ecc9ad9ae24f045dfddd538a39e55a28fa7e1ca6ad9f23e20d4087eaf2bb66f7" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "arrow-array", "arrow-schema", @@ -5410,9 +5388,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "11.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bfa6f0164c8b7056150f5682ce4d415a335b59b04c479873fda04b200117d27" +version = "12.0.0-beta.5" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 276658157..033da5907 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=11.0.0", default-features = false } -lance-core = "=11.0.0" -lance-datagen = "=11.0.0" -lance-file = "=11.0.0" -lance-io = { "version" = "=11.0.0", default-features = false } -lance-index = "=11.0.0" -lance-linalg = "=11.0.0" -lance-namespace = "=11.0.0" -lance-namespace-impls = { "version" = "=11.0.0", default-features = false } -lance-table = "=11.0.0" -lance-testing = "=11.0.0" -lance-datafusion = "=11.0.0" -lance-encoding = "=11.0.0" -lance-arrow = "=11.0.0" +lance = { "version" = "=12.0.0-beta.5", default-features = false, "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=12.0.0-beta.5", default-features = false, "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=12.0.0-beta.5", default-features = false, "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index 80cef9716..91ece16a1 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 11.0.0 + 12.0.0-beta.5 false 2.30.0 1.7 diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index 71e4016dd..c22b73dd7 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -13,7 +13,7 @@ use lance::dataset::{ReadParams, WriteMode, builder::DatasetBuilder}; use lance::io::{ObjectStore, ObjectStoreParams, WrappingObjectStore}; use lance_datafusion::utils::StreamingWriteSource; use lance_file::version::LanceFileVersion; -use lance_io::object_store::{StorageOptionsAccessor, StorageOptionsProvider}; +use lance_io::object_store::{ReadDirOptions, StorageOptionsAccessor, StorageOptionsProvider}; use lance_table::io::commit::commit_handler_from_url; use object_store::local::LocalFileSystem; use snafu::ResultExt; @@ -282,11 +282,14 @@ impl std::fmt::Display for ListingDatabase { const LANCE_EXTENSION: &str = "lance"; -/// The table a listed child directory holds, or `None` if it is not a table at all. +/// The table a listed child of the database names, or `None` if the child is not a table. /// /// A table is the directory `.lance`; a loose file or any other directory under the /// database prefix belongs to something else. `dir_suffix` is `.lance`, built once by the /// caller rather than per child. +/// The table a listed child directory holds, or `None` if it is not a table at all. +/// +/// Only directories are considered, so a loose object named like a table is not one. fn table_name(location: &object_store::path::Path, dir_suffix: &str) -> Option { location .filename()? @@ -294,75 +297,6 @@ fn table_name(location: &object_store::path::Path, dir_suffix: &str) -> Option, - /// Resumes after this page, or `None` when the page reached the end of the level. - page_token: Option, -} - -/// Where a listed location sits inside the database directory — the space page tokens live -/// in — or `None` if it is not a child of that directory at all. Matching both halves of the -/// prefix drops a location that merely starts with the directory's name (`dbx/y` against -/// `db/`) as well as the marker object some stores keep for the directory itself. -fn relative_key<'a>(prefix: Option<&str>, location: &'a str) -> Option<&'a str> { - let relative = match prefix { - Some(prefix) => location.strip_prefix(prefix)?, - None => location, - }; - (!relative.is_empty()).then_some(relative) -} - -/// One page of the table directories under `base_path`, one directory level deep. -/// -/// Lance 11 exposes no paginated directory listing, so the level is listed in full and paged -/// locally: table directories go into key order (a directory's key keeps its trailing `/`, -/// so a token is never a table name), the page is the smallest `limit` of them past -/// `page_token`, and the token handed back is the key of the last directory the page took — -/// so a page that took nothing ends the listing rather than resuming from a position no page -/// ever reached. Only `.lance/` directories enter the page: loose objects, other -/// directories, and a bare `.lance/` never take a page slot or name a token, which keeps a -/// page to exactly one listing of the level. Correct on every store, at the cost of that one -/// full-level listing per page. -async fn read_dir_page( - object_store: &ObjectStore, - base_path: &object_store::path::Path, - page_token: Option, - limit: Option, -) -> Result { - let listed = object_store.list_with_delimiter(Some(base_path)).await?; - let prefix = { - let base = base_path.as_ref(); - (!base.is_empty()).then(|| format!("{base}/")) - }; - let table_dir_suffix = format!(".{LANCE_EXTENSION}/"); - let mut children: Vec<(String, object_store::path::Path)> = listed - .common_prefixes - .into_iter() - .filter_map(|location| { - let key = format!("{}/", relative_key(prefix.as_deref(), location.as_ref())?); - (key.len() > table_dir_suffix.len() && key.ends_with(&table_dir_suffix)) - .then_some((key, location)) - }) - .collect(); - children.sort_unstable_by(|(left, _), (right, _)| left.cmp(right)); - if let Some(resume) = &page_token { - children.retain(|(key, _)| key > resume); - } - let total = children.len(); - children.truncate(limit.unwrap_or(total).min(total)); - let page_token = match children.last() { - Some((last, _)) if children.len() < total => Some(last.clone()), - _ => None, - }; - Ok(DirPage { - common_prefixes: children.into_iter().map(|(_, location)| location).collect(), - page_token, - }) -} - const ENGINE: &str = "engine"; const MIRRORED_STORE: &str = "mirroredStore"; @@ -1048,7 +982,8 @@ impl Database for ListingDatabase { let mut tables = Vec::new(); let mut page_token = request.page_token.filter(|token| !token.is_empty()); - // A page of nothing: no table was handed over for a token to resume after. + // A page of nothing: the store rejects a limit of zero, and no table was handed over + // for a token to resume after. if limit == Some(0) { return Ok(ListTablesResponse { context: None, @@ -1057,21 +992,35 @@ impl Database for ListingDatabase { }); } - // The page holds only table directories, so one call — and the one full-level - // listing behind it — fills it. - let page = read_dir_page( - &self.object_store, - &self.base_path, - page_token.take(), - limit, - ) - .await?; - page_token = page.page_token; - tables.extend( - page.common_prefixes - .iter() - .filter_map(|location| table_name(location, &dir_suffix)), - ); + loop { + // Ask only for what the page still has room for, so a database holding more + // than one page costs one request per page rather than one per table. + let listing = self + .object_store + .read_dir_page( + self.base_path.clone(), + ReadDirOptions { + page_token: page_token.take(), + limit: limit.map(|limit| limit - tables.len()), + }, + ) + .await?; + page_token = listing.page_token; + // Only child directories can be tables, and the store already separates them + // out, so the objects in the page are not looked at. + tables.extend( + listing + .result + .common_prefixes + .iter() + .filter_map(|location| table_name(location, &dir_suffix)), + ); + // Children that are not tables leave the page short of the limit, so keep + // going until the page is full or the database runs out. + if page_token.is_none() || limit.is_none_or(|limit| tables.len() >= limit) { + break; + } + } Ok(ListTablesResponse { context: None, @@ -1717,8 +1666,8 @@ mod tests { } /// Only directories named `.lance` are tables; loose files and other directories - /// under the database prefix are not. They never take a page slot, so even a `limit` - /// smaller than the clutter ahead of the first table returns that table. + /// under the database prefix are not. A page spent on them is filled from the next one, + /// so a page holding only non-tables does not read as an empty database. #[tokio::test] async fn test_listing_ignores_non_table_children() { let (tempdir, db) = setup_database().await; @@ -1737,37 +1686,6 @@ mod tests { assert_eq!(page.tables, vec!["real"]); } - /// The Lance 11 fallback pages locally over one full-level listing, so a bounded page - /// costs exactly one listing call — clutter ahead of the first table must not buy extra - /// round trips. - #[tokio::test] - async fn test_one_full_listing_per_public_page() { - use crate::io::object_store::io_tracking::IoStatsHolder; - use lance_io::object_store::WrappingObjectStore; - - let (tempdir, mut db) = setup_database().await; - create_tables(&db, &["real"]).await; - std::fs::write(tempdir.path().join("aaa-loose.lance"), b"not a table").unwrap(); - create_dir_all(tempdir.path().join("aaa-scratch")).unwrap(); - - let io_stats = IoStatsHolder::default(); - let mut tracked_store = (*db.object_store).clone(); - tracked_store.inner = - io_stats.wrap(&tracked_store.store_prefix, tracked_store.inner.clone()); - db.object_store = Arc::new(tracked_store); - - let page = db - .list_tables(ListTablesRequest { - limit: Some(1), - ..Default::default() - }) - .await - .unwrap(); - - assert_eq!(page.tables, vec!["real"]); - assert_eq!(io_stats.incremental_stats().read_iops, 1); - } - #[tokio::test] async fn listing_ignores_empty_table_name() { let (tempdir, db) = setup_database().await; diff --git a/rust/lancedb/src/io/object_store.rs b/rust/lancedb/src/io/object_store.rs index d594bd857..c4a9a4f7e 100644 --- a/rust/lancedb/src/io/object_store.rs +++ b/rust/lancedb/src/io/object_store.rs @@ -10,7 +10,7 @@ use lance::io::WrappingObjectStore; use object_store::{ CopyOptions, Error, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, ObjectStoreExt, PutMultipartOptions, PutOptions, PutPayload, PutResult, Result, - UploadPart, path::Path, + UploadPart, list::PaginatedListStore, path::Path, }; use async_trait::async_trait; @@ -187,6 +187,14 @@ impl WrappingObjectStore for MirroringObjectStoreWrapper { secondary: self.secondary.clone(), }) } + + fn wrap_paginated( + &self, + _store_prefix: &str, + original: Arc, + ) -> Option> { + Some(original) + } } // windows pathing can't be simply concatenated diff --git a/rust/lancedb/src/io/object_store/io_tracking.rs b/rust/lancedb/src/io/object_store/io_tracking.rs index bd4f8f54a..7f9750216 100644 --- a/rust/lancedb/src/io/object_store/io_tracking.rs +++ b/rust/lancedb/src/io/object_store/io_tracking.rs @@ -12,7 +12,7 @@ use lance::io::WrappingObjectStore; use object_store::{ CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, ObjectStore, PutMultipartOptions, PutOptions, PutPayload, PutResult, RenameOptions, Result as OSResult, - UploadPart, path::Path, + UploadPart, list::PaginatedListStore, path::Path, }; #[derive(Debug, Default)] @@ -57,6 +57,14 @@ impl WrappingObjectStore for IoStatsHolder { stats: self.0.clone(), }) } + + fn wrap_paginated( + &self, + _store_prefix: &str, + original: Arc, + ) -> Option> { + Some(original) + } } impl IoTrackingStore { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index d152f3616..efc705e3c 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -4183,6 +4183,14 @@ mod tests { parent_list_calls: self.parent_list_calls.clone(), }) } + + fn wrap_paginated( + &self, + _store_prefix: &str, + _original: Arc, + ) -> Option> { + None + } } #[tokio::test] @@ -4286,6 +4294,14 @@ mod tests { self.called.store(true, Ordering::Relaxed); original } + + fn wrap_paginated( + &self, + _store_prefix: &str, + original: Arc, + ) -> Option> { + Some(original) + } } #[tokio::test] diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index 07ea7fb81..86c1fe5f2 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -300,7 +300,7 @@ async fn build_read_context( for shard_id in shard_ids { let manifest_store = ShardManifestStore::new(store.clone(), &base_path, shard_id, scan_batch_size); - if let Some(manifest) = manifest_store.read_latest().await? { + if let Some(manifest) = manifest_store.latest().await? { snapshots.push(snapshot_from_manifest(shard_id, &manifest, &exclude)); } } From c196d033e932591bb696772ebb3490cde49011b7 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Mon, 31 Aug 2026 22:17:11 +0800 Subject: [PATCH 159/206] feat: add drop_function client APIs (#4097) --- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/db.py | 18 ++++++++ python/python/lancedb/remote/db.py | 4 ++ .../tests/test_first_class_function_slice2.py | 45 +++++++++++++++++++ python/src/connection.rs | 11 +++++ rust/lancedb/src/connection.rs | 15 +++++++ rust/lancedb/src/database.rs | 4 ++ rust/lancedb/src/remote/db.rs | 38 ++++++++++++++++ .../tests/first_class_function_slice2.rs | 6 ++- 9 files changed, 141 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 7d7ca7f2a..05ece3043 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -150,6 +150,7 @@ class Connection(object): def job(self, job_id: str) -> Job: ... async def create_function_async(self, request_json: str) -> Job: ... async def get_function(self, name: str, version: str) -> str: ... + async def drop_function(self, name: str, version: str) -> bool: ... async def list_jobs(self) -> List[JobInfo]: ... async def get_job(self, job_id: str) -> Optional[JobDescription]: ... async def cancel_job(self, job_id: str) -> bool: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 51b8d9993..ecaae42f8 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -712,6 +712,16 @@ class DBConnection(EnforceOverrides): "Function catalog operations are not supported for this connection type" ) + def drop_function(self, name: str, *, version: str) -> bool: + """Drop one exact immutable Function version from the remote catalog. + + Returns True when the version changed to Dropped and False for an + idempotent replay. Local connections raise NotImplementedError. + """ + raise NotImplementedError( + "Function catalog operations are not supported for this connection type" + ) + def job(self, job_id: str) -> Job: """A [Job][lancedb.job.Job] handle for a server-side job by id. @@ -1413,6 +1423,10 @@ class LanceDBConnection(DBConnection): def get_function(self, name: str, *, version: str) -> FunctionVersion: return LOOP.run(self._conn.get_function(name, version=version)) + @override + def drop_function(self, name: str, *, version: str) -> bool: + return LOOP.run(self._conn.drop_function(name, version=version)) + @override def list_jobs(self) -> List[JobInfo]: """List server-side jobs across the database's tables.""" @@ -2243,6 +2257,10 @@ class AsyncConnection(object): """Open one exact immutable Function version from the remote catalog.""" return FunctionVersion.from_json(await self._inner.get_function(name, version)) + async def drop_function(self, name: str, *, version: str) -> bool: + """Drop one exact immutable Function version from the remote catalog.""" + return await self._inner.drop_function(name, version) + async def list_jobs(self) -> List[JobInfo]: """List server-side jobs across the database's tables.""" return await self._inner.list_jobs() diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index b228cfb5b..27e21d200 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -749,6 +749,10 @@ class RemoteDBConnection(DBConnection): def get_function(self, name: str, *, version: str) -> FunctionVersion: return LOOP.run(self._conn.get_function(name, version=version)) + @override + def drop_function(self, name: str, *, version: str) -> bool: + return LOOP.run(self._conn.drop_function(name, version=version)) + @override def list_jobs(self) -> List["JobInfo"]: """List server-side jobs across the database's tables.""" diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 415ecbe0f..bab78316c 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -941,6 +941,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="fv_exact") + with pytest.raises(NotImplementedError, match=message): + db.drop_function("normalize_score", version="fv_exact") @contextlib.contextmanager @@ -986,6 +988,12 @@ def _mock_remote_function_catalog(): "version": "fv_exact", } response = state["version"] + elif self.path == "/v1/functions/drop": + assert body == { + "name": "normalize_score", + "version": "fv_exact", + } + response = {"dropped": True} else: status = 404 response = {"error": "not found"} @@ -1044,3 +1052,40 @@ def test_blocking_remote_registration_returns_function_version(): "/v1/functions/create", "/v1/jobs/describe", ] + + +def test_remote_drop_function_sends_exact_version(): + with _mock_remote_function_catalog() as (host, state): + db = lancedb.connect( + "db://dev", + api_key="fake", + host_override=host, + client_config={"retry_config": {"retries": 0}}, + ) + assert db.drop_function("normalize_score", version="fv_exact") is True + + assert state["requests"] == [ + ( + "/v1/functions/drop", + {"name": "normalize_score", "version": "fv_exact"}, + ) + ] + + +@pytest.mark.asyncio +async def test_async_remote_drop_function_sends_exact_version(): + with _mock_remote_function_catalog() as (host, state): + db = await lancedb.connect_async( + "db://dev", + api_key="fake", + host_override=host, + client_config={"retry_config": {"retries": 0}}, + ) + assert await db.drop_function("normalize_score", version="fv_exact") is True + + assert state["requests"] == [ + ( + "/v1/functions/drop", + {"name": "normalize_score", "version": "fv_exact"}, + ) + ] diff --git a/python/src/connection.rs b/python/src/connection.rs index 902489f4f..fc835f805 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -629,6 +629,17 @@ impl Connection { }) } + pub fn drop_function( + self_: PyRef<'_, Self>, + name: String, + version: String, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + inner.drop_function(name, version).await.infer_error() + }) + } + pub fn list_jobs(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 5f66d9dee..943ad51b7 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -523,6 +523,21 @@ impl Connection { .await } + /// Drop one exact immutable Function version from the remote catalog. + /// + /// Returns `true` when the server appended a Dropped transition and + /// `false` for an idempotent replay. Local databases return + /// [`Error::NotSupported`]. + pub async fn drop_function( + &self, + name: impl AsRef, + version: impl AsRef, + ) -> Result { + self.internal + .drop_function(name.as_ref(), version.as_ref()) + .await + } + /// Rename a table in the database. /// /// This is only supported in LanceDB Cloud. diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 6c4537972..775b0b579 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -307,6 +307,10 @@ pub trait Database: ) -> Result { function_catalog_not_supported() } + /// Drop one exact immutable Function version from the remote catalog. + async fn drop_function(&self, _name: &str, _version: &str) -> Result { + function_catalog_not_supported() + } /// A [`crate::job::Job`] handle for a server-side job by id, suitable for /// waiting on or cancelling the job. The handle is constructed without a /// server round trip; an unknown id surfaces when the handle is used. diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index da9a4b09b..39b258a63 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -533,6 +533,11 @@ struct RemoteListJobsResponse { page_token: Option, } +#[derive(serde::Deserialize)] +struct RemoteDropFunctionResponse { + dropped: bool, +} + /// Bound on `list_jobs` page walking; a warning is logged when the listing /// is truncated at this many pages. const MAX_LIST_JOBS_PAGES: usize = 100; @@ -583,6 +588,20 @@ impl Database for RemoteDatabase { response.json().await.err_to_http(request_id) } + async fn drop_function(&self, name: &str, version: &str) -> Result { + let req = self + .client + .post("/v1/functions/drop") + .json(&serde_json::json!({ + "name": name, + "version": version, + })); + let (request_id, response) = self.client.send(req).await?; + let response = self.client.check_response(&request_id, response).await?; + let response: RemoteDropFunctionResponse = response.json().await.err_to_http(request_id)?; + Ok(response.dropped) + } + fn job(&self, job_id: &str) -> Result { Ok(crate::job::Job::new(Box::new(super::job::RemoteJob::new( self.client.clone(), @@ -2689,6 +2708,25 @@ mod tests { assert_eq!(version.version(), "fv_01K3EXACT"); } + #[tokio::test] + async fn test_drop_function_sends_exact_version_and_decodes_replay() { + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::POST); + assert_eq!(request.url().path(), "/v1/functions/drop"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!( + body, + serde_json::json!({"name": "embed", "version": "fv_01K3EXACT"}) + ); + http::Response::builder() + .status(200) + .body(r#"{"dropped":false}"#) + .unwrap() + }); + assert!(!conn.drop_function("embed", "fv_01K3EXACT").await.unwrap()); + } + #[tokio::test] async fn test_conn_job_waits_to_done() { let polls = Arc::new(AtomicUsize::new(0)); diff --git a/rust/lancedb/tests/first_class_function_slice2.rs b/rust/lancedb/tests/first_class_function_slice2.rs index 93252dde4..6d046d9d1 100644 --- a/rust/lancedb/tests/first_class_function_slice2.rs +++ b/rust/lancedb/tests/first_class_function_slice2.rs @@ -45,7 +45,11 @@ async fn local_function_catalog_operations_return_stable_not_supported() { .get_function("normalize_score", "fv_exact") .await .unwrap_err(); - for error in [create_error, lookup_error] { + let drop_error = connection + .drop_function("normalize_score", "fv_exact") + .await + .unwrap_err(); + for error in [create_error, lookup_error, drop_error] { assert!(matches!( error, Error::NotSupported { message } From c8fd3e97d1bb35ad704ea442def79bf9188e8cbf Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Mon, 31 Aug 2026 22:34:34 +0800 Subject: [PATCH 160/206] test(python): cover stable main udf registration identity (#4094) ## Other changes ### What changed? - Add a subprocess regression harness for an ordinary `@udf` function defined in `__main__`. - Verify the full registration request, artifact digest, and Function signature stay identical across independent Python processes and renamed/moved script paths. - Verify body, referenced-global, and annotation changes still produce distinct artifact identities, with annotation changes also producing a distinct Function signature. ### Why is the change needed? [ENT-2441](https://linear.app/lancedb/issue/ENT-2441/make-sure-function-defined-in-main-gets-stable-signature) tracks the stability guarantee. Investigation on the exact `840e1d73` main base found that LanceDB already packages canonical source instead of cloudpickle bytes, so the unchanged `__main__` function is stable and no production-code fix is needed. This change closes the missing regression-test coverage. [GEN-950](https://linear.app/lancedb/issue/GEN-950/class-based-udfs-defined-in-main-get-a-new-auto-version-on-every-run) remains a separate Geneva checkpoint-version issue for class-based callables. LanceDB's Function API continues to accept synchronous Python functions only. ## Validation - `cd python && uv run --extra tests pytest python/tests/test_first_class_function_slice2.py -q` (`40 passed`) - `uv run --project python --extra dev ruff format .` - `uv run --project python --extra dev ruff check .` (`All checks passed!`) --- .../tests/test_first_class_function_slice2.py | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index bab78316c..57b08e18d 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -12,6 +12,8 @@ from datetime import date import http.server import json from pathlib import Path +import subprocess +import sys import threading from typing import Optional @@ -67,6 +69,80 @@ def test_scalar_udf_matches_shared_registration_golden_and_remains_callable(): } +def _main_udf_source( + *, threshold: int = 20, input_annotation: str = "int", comparison: str = ">=" +) -> str: + return ( + "from __future__ import annotations\n" + "from lancedb.functions import udf\n" + f"THRESHOLD = {threshold}\n" + "\n" + "@udf\n" + f"def label(value: {input_annotation}) -> str:\n" + f" return 'big' if value {comparison} THRESHOLD else 'small'\n" + "\n" + "assert label.__module__ == '__main__'\n" + "print(label.registration_request.to_canonical_json())\n" + ) + + +def _run_main_udf(path: Path, source: str) -> dict: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(source) + result = subprocess.run( + [sys.executable, str(path)], + check=True, + capture_output=True, + text=True, + ) + return json.loads(result.stdout) + + +def test_main_udf_registration_identity_is_stable_across_processes_and_paths( + tmp_path, +): + source = _main_udf_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) + + assert len({run["artifact"]["digest"] for run in [*original_runs, moved_run]}) == 1 + assert all( + run["signature"] == original_runs[0]["signature"] + for run in [original_runs[1], moved_run] + ) + assert original_runs[0] == original_runs[1] == moved_run + + body_change = _run_main_udf( + tmp_path / "changes" / "body.py", _main_udf_source(comparison=">") + ) + global_change = _run_main_udf( + tmp_path / "changes" / "global.py", _main_udf_source(threshold=21) + ) + annotation_change = _run_main_udf( + tmp_path / "changes" / "annotation.py", + _main_udf_source(input_annotation="float"), + ) + + baseline = original_runs[0] + assert baseline["signature"] == body_change["signature"] + assert baseline["signature"] == global_change["signature"] + assert baseline["signature"] != annotation_change["signature"] + assert ( + len( + { + baseline["artifact"]["digest"], + body_change["artifact"]["digest"], + global_change["artifact"]["digest"], + annotation_change["artifact"]["digest"], + } + ) + == 4 + ) + + 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) From e773d1e093a08b775b9ff3ee5386fe310f378443 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 31 Aug 2026 10:40:11 -0700 Subject: [PATCH 161/206] build(deps): bump the rust-minor-patch group across 1 directory with 9 updates (#4084) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps the rust-minor-patch group with 9 updates in the / directory: | Package | From | To | | --- | --- | --- | | [async-trait](https://github.com/dtolnay/async-trait) | `0.1.91` | `0.1.92` | | [log](https://github.com/rust-lang/log) | `0.4.33` | `0.4.34` | | [moka](https://github.com/moka-rs/moka) | `0.12.15` | `0.12.16` | | [uuid](https://github.com/uuid-rs/uuid) | `1.24.0` | `1.26.0` | | [serde_with](https://github.com/jonasbb/serde_with) | `3.21.0` | `3.22.0` | | [roaring](https://github.com/RoaringBitmap/roaring-rs) | `0.11.4` | `0.11.5` | | [napi](https://github.com/napi-rs/napi-rs) | `3.11.0` | `3.12.0` | | [napi-derive](https://github.com/napi-rs/napi-rs) | `3.6.1` | `3.6.3` | | [napi-build](https://github.com/napi-rs/napi-rs) | `2.4.0` | `2.4.1` | Updates `async-trait` from 0.1.91 to 0.1.92
Release notes

Sourced from async-trait's releases.

0.1.92

  • Resolve double_must_use clippy lint in generated code (#303)
Commits

Updates `log` from 0.4.33 to 0.4.34
Release notes

Sourced from log's releases.

0.4.34

What's Changed

New Contributors

Full Changelog: https://github.com/rust-lang/log/compare/0.4.33...0.4.34

Changelog

Sourced from log's changelog.

[0.4.34] - 2026-08-22

What's Changed

New Contributors

Full Changelog: https://github.com/rust-lang/log/compare/0.4.33...0.4.34

Commits

Updates `moka` from 0.12.15 to 0.12.16
Release notes

Sourced from moka's releases.

v0.12.16

Version 0.12.16

Fixed

  • Fixed a bug where cache eviction could stall permanently when the cache was configured with the non-default LRU eviction policy (EvictionPolicy::lru()) by a race between insert and remove operations on the same key (#592gh-pull-0592 by @​kim-jhyeon, reported in #590gh-issue-0590):
    • This bug was introduced in v0.12.0 and affected sync::Cache, sync::SegmentedCache and future::Cache.
    • A race between applying a write recording for an entry and concurrently removing that entry from the internal concurrent hash table could leave an orphaned node at the front of the LRU queue. Once present, no entry was ever evicted again and the cache grew unboundedly past max_capacity.
    • The same race also affected the default TinyLFU eviction policy, but with a milder symptom: each occurrence permanently leaked one phantom entry slot, causing entry_count and weighted_size to over-report and the usable capacity to shrink by one entry per occurrence. Fixed by the same change.

Changed

  • Worked around a ThreadSanitizer false positive (#602gh-pull-0602):
    • Replaced the standalone fence(Acquire) in the internal MiniArc's drop path with an Acquire load of the reference count, so that downstream projects can now run ThreadSanitizer on code using Moka without hitting this false positive.
    • std::sync::Arc has a similar workaround.
  • Raised the minimum version of the crossbeam-epoch crate from v0.9.18 to v0.9.20 to avoid the following advisory (#603gh-pull-0603):
    • [RUSTSEC-2026-0204] crossbeam-epoch: invalid pointer dereference in fmt::Pointer for Atomic and Shared
    • Moka is not affected by this advisory because it never formats these pointer types. However, raising the minimum version prevents downstream lockfiles from resolving to an affected crossbeam-epoch version via Moka.
Changelog

Sourced from moka's changelog.

Version 0.12.16

Fixed

  • Fixed a bug where cache eviction could stall permanently when the cache was configured with the non-default LRU eviction policy (EvictionPolicy::lru()) by a race between insert and remove operations on the same key (#592[gh-pull-0592] by [@​kim-jhyeon][gh-kim-jhyeon], reported in #590[gh-issue-0590]):
    • This bug was introduced in v0.12.0 and affected sync::Cache, sync::SegmentedCache and future::Cache.
    • A race between applying a write recording for an entry and concurrently removing that entry from the internal concurrent hash table could leave an orphaned node at the front of the LRU queue. Once present, no entry was ever evicted again and the cache grew unboundedly past max_capacity.
    • The same race also affected the default TinyLFU eviction policy, but with a milder symptom: each occurrence permanently leaked one phantom entry slot, causing entry_count and weighted_size to over-report and the usable capacity to shrink by one entry per occurrence. Fixed by the same change.

Changed

  • Worked around a ThreadSanitizer false positive (#602[gh-pull-0602]):
    • Replaced the standalone fence(Acquire) in the internal MiniArc's drop path with an Acquire load of the reference count, so that downstream projects can now run ThreadSanitizer on code using Moka without hitting this false positive.
    • std::sync::Arc has a similar workaround.
  • Raised the minimum version of the crossbeam-epoch crate from v0.9.18 to v0.9.20 to avoid the following advisory (#603[gh-pull-0603]):
    • [RUSTSEC-2026-0204] crossbeam-epoch: invalid pointer dereference in fmt::Pointer for Atomic and Shared
    • Moka is not affected by this advisory because it never formats these pointer types. However, raising the minimum version prevents downstream lockfiles from resolving to an affected crossbeam-epoch version via Moka.
Commits
  • a616ec1 Merge pull request #604 from moka-rs/chore/bump-v0.12.16
  • 3b140a6 Bump the version to v0.12.16
  • 51b802d Merge pull request #603 from moka-rs/bump-crossbeam-epoch-floor
  • 4f90716 Raise the minimum crossbeam-epoch version to 0.9.20
  • 08d0e04 Merge pull request #602 from moka-rs/gh600-tsan-workaround
  • 14447a7 Restructure the v0.12.16 TSan workaround CHANGELOG entry
  • 7b14c37 Avoid a TSan false positive by replacing the fence in MiniArc::drop
  • 05b37c6 Merge pull request #599 from moka-rs/gh590-deterministic-tests
  • fc31858 Replace private doc references in gh590 test comments
  • 5743592 Improve the v0.12.16 CHANGELOG entry
  • Additional commits viewable in compare view

Updates `uuid` from 1.24.0 to 1.26.0
Release notes

Sourced from uuid's releases.

v1.26.0

What's Changed

Full Changelog: https://github.com/uuid-rs/uuid/compare/1.25.0...v1.26.0

1.25.0

What's Changed

New Contributors

Full Changelog: https://github.com/uuid-rs/uuid/compare/v1.24.1...1.25.0

v1.24.1

What's Changed

New Contributors

Full Changelog: https://github.com/uuid-rs/uuid/compare/v1.24.0...v1.24.1

Commits
  • cdc96a8 Merge pull request #905 from uuid-rs/cargo/v1.26.0
  • 34e4f49 don't test macros under miri
  • d9e7242 update nightly used for miri
  • ec16819 prepare for 1.26.0 release
  • 162cd20 Merge pull request #904 from ChrisJr404/v7-additional-precision-bits
  • 97eceff Add ContextV7::with_additional_precision_bits for microsecond clocks
  • 302e0bf Merge pull request #903 from uuid-rs/cargo/1.25.0
  • b7ccde8 prepare for 1.25.0 release
  • c62dffb Merge pull request #902 from ChrisJr404/serde-bytes-module
  • 8c198b2 Add a serde::bytes module that encodes as a byte string
  • Additional commits viewable in compare view

Updates `serde_with` from 3.21.0 to 3.22.0
Release notes

Sourced from serde_with's releases.

serde_with v3.22.0

Added

  • Add support for jiff v0.2 behind the new jiff_0_2 feature flag (#936) jiff::SignedDuration works with DurationSeconds and its variants. jiff::Timestamp, jiff::Zoned, and jiff::civil::DateTime work with TimestampSeconds and its variants. Deserializing a jiff::Zoned uses the system time zone, like chrono::DateTime<Local>.

Fixed

  • Extend the GHSA-7gcf-g7xr-8hxj fix to the duplicate-key-prevention collections. The rust::sets_duplicate_value_is_error, rust::maps_duplicate_key_is_error, rust::sets_last_value_wins, and rust::maps_first_key_wins adapters created their backing sets/maps with with_capacity_and_hasher using the raw deserializer size_hint, bypassing the size_hint_cautious cap added in #966 (the clippy.toml disallowed_methods lint only covers Vec::with_capacity, not with_capacity_and_hasher, so these sites were not flagged). Attacker-controlled input claiming a huge length could panic with Hash table capacity overflow before a single element was read. All such constructions now route through size_hint_cautious.
Commits
  • 88f576a Bump version to 3.22.0 (#991)
  • 931e664 Bump version to 3.22.0
  • e26930e Bump github/codeql-action from 4.37.3 to 4.37.4 in the github-actions group (...
  • 92cd5a0 Bump github/codeql-action in the github-actions group
  • 32be66f Guard with_capacity_and_hasher against untrusted size_hint (DoS) (#971)
  • 33871cd Merge branch 'master' into fix/duplicate-key-impls-capacity-overflow
  • bb1e064 Change function position within impl (#968)
  • 202d3dd Improve the time unit macros to remove unnecessary repetition and make the co...
  • b347efb Move the use_duration_signed_ser/*_de macros utils
  • 6590545 chrono_0_4: Implement the same time unit macro cleanup as jiff_0_2
  • Additional commits viewable in compare view

Updates `roaring` from 0.11.4 to 0.11.5
Release notes

Sourced from roaring's releases.

v0.11.5

What's Changed

New Contributors

Full Changelog: https://github.com/RoaringBitmap/roaring-rs/compare/v0.11.4...v0.11.5

Commits
  • 0ce3fc8 Merge pull request #364 from RoaringBitmap/upgrade-dependencies-bump-version
  • a961a04 Remove the once_cell dependency
  • 5e8445b Merge pull request #363 from youdie006/fix/359-interval-remove-boundary
  • bf2961d Bump version to v0.11.5
  • 048a8b0 Fix off-by-one that corrupts a bitmap in remove_smallest/remove_biggest
  • 27d84f5 Merge pull request #360 from silver-ymz/fix/treemap-iter-advance-across-bitmaps
  • aac2de8 Make clippy happy
  • a3d1d54 Merge pull request #362 from RoaringBitmap/std-error-for-integer-too-small
  • 9a3c33e Implement std Error for IntegerTooSmall
  • f46c0ff fix: invalid treemap iter advance
  • See full diff in compare view

Updates `napi` from 3.11.0 to 3.12.0
Release notes

Sourced from napi's releases.

napi-v3.12.0

Added

  • (cli) support non-threaded WASI targets (#3353)
Commits
  • 58bd87f chore: release (#3414)
  • 9da8723 chore(release): publish
  • 8d22196 chore(deps): update dependency oxc-parser to ^0.142.0 (#3422)
  • abc30fb build(deps): bump postcss from 8.5.17 to 8.5.23 (#3421)
  • 5542139 build(deps): bump fast-xml-parser from 5.9.3 to 5.10.1 (#3418)
  • dc4ee8c build(deps): bump fast-uri from 3.1.3 to 3.1.4 (#3419)
  • 050d985 feat(async-runtime): drain-linger surface + lock-free scheduler internals (#3...
  • e0b8708 chore(deps): update dependency oxc-parser to ^0.141.0 (#3417)
  • fc84940 chore(deps): update actions/setup-node action to v7 (#3413)
  • ee598db build(deps): bump protobufjs from 7.6.4 to 7.6.5 (#3410)
  • Additional commits viewable in compare view

Updates `napi-derive` from 3.6.1 to 3.6.3
Release notes

Sourced from napi-derive's releases.

napi-derive-v3.6.3

Other

  • updated the following local packages: napi-derive-backend

napi-derive-v3.6.2

Other

  • updated the following local packages: napi-derive-backend
Commits
  • 956e452 chore: release (#3448)
  • 73048f5 chore(release): publish
  • 61fae8a fix(napi): stop unloading addons with live native code, preserve non-Error re...
  • 93e86ce chore(release): publish
  • 2c90599 fix(cli): support npm 12 pack output (#3449)
  • 360b1ec fix(wasi): avoid randomness during module registration (#3447)
  • b648c40 build(deps): bump nanoid from 3.3.16 to 3.3.18 (#3446)
  • ffda4ef chore(deps): update dependency js-yaml to v4.3.1 [security] (#3445)
  • 387b0dc feat(cli): size WASI browser worker pools from navigator.hardwareConcurrency ...
  • 61e4346 build(deps): bump fast-uri from 3.1.4 to 3.1.5 (#3440)
  • Additional commits viewable in compare view

Updates `napi-build` from 2.4.0 to 2.4.1
Release notes

Sourced from napi-build's releases.

napi-build-v2.4.1

Fixed

  • (napi) stop unloading addons with live native code, preserve non-Error rejections, and add the wasm teardown barrier (#3423)
Commits
  • 956e452 chore: release (#3448)
  • 73048f5 chore(release): publish
  • 61fae8a fix(napi): stop unloading addons with live native code, preserve non-Error re...
  • 93e86ce chore(release): publish
  • 2c90599 fix(cli): support npm 12 pack output (#3449)
  • 360b1ec fix(wasi): avoid randomness during module registration (#3447)
  • b648c40 build(deps): bump nanoid from 3.3.16 to 3.3.18 (#3446)
  • ffda4ef chore(deps): update dependency js-yaml to v4.3.1 [security] (#3445)
  • 387b0dc feat(cli): size WASI browser worker pools from navigator.hardwareConcurrency ...
  • 61e4346 build(deps): bump fast-uri from 3.1.4 to 3.1.5 (#3440)
  • Additional commits viewable in compare view

--------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Will Jones Co-authored-by: Claude Sonnet 5 --- Cargo.lock | 50 +++++++++++++++++++++++---------------------- nodejs/src/query.rs | 6 +++++- 2 files changed, 31 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index adf15c218..d1f4675a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -535,9 +535,9 @@ dependencies = [ [[package]] name = "async-trait" -version = "0.1.91" +version = "0.1.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae36dc4177970ef04fde5178d3e2429882def40e57a451f919c098f72baa6cec" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", @@ -1443,9 +1443,9 @@ checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" [[package]] name = "bytemuck" -version = "1.25.0" +version = "1.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" dependencies = [ "bytemuck_derive", ] @@ -5748,9 +5748,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.33" +version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" [[package]] name = "loom" @@ -6001,9 +6001,9 @@ dependencies = [ [[package]] name = "moka" -version = "0.12.15" +version = "0.12.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "957228ad12042ee839f93c8f257b62b4c0ab5eaae1d4fa60de53b27c9d7c5046" +checksum = "4293f18e7567a1caf3c584855554377025c65e0aa445344d04171f5ad63d19b9" dependencies = [ "async-lock", "crossbeam-channel", @@ -6097,14 +6097,15 @@ dependencies = [ [[package]] name = "napi" -version = "3.11.0" +version = "3.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de33522036981030a75c231829566bc63414e08101a6f5ff4ac6cef19c8e0941" +checksum = "58c5f4d5375213fdb7be2655e152386e82f026f9a5ba36a75556e11359aafe09" dependencies = [ "bitflags 2.11.1", "chrono", "ctor 1.0.12", "futures", + "libc", "napi-build", "napi-sys", "nohash-hasher", @@ -6116,15 +6117,15 @@ dependencies = [ [[package]] name = "napi-build" -version = "2.4.0" +version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5282704fbe8d49b0cf8b08e3f33233416a528658f205c7e5ace63b582de0b11c" +checksum = "60fdf9b392c50e7c4170fa633bd909490ed7835cea4c046776d1a4dd8d2ae0ab" [[package]] name = "napi-derive" -version = "3.6.1" +version = "3.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d5c9c02556ea6dc99dffd36c1ce60141411657438501a125b675776d011ce92" +checksum = "0fa55ea69990c90b888e9e77044410e304ce7f35de599dc6d0b5c1923d2e59af" dependencies = [ "convert_case", "ctor 1.0.12", @@ -6136,9 +6137,9 @@ dependencies = [ [[package]] name = "napi-derive-backend" -version = "6.1.1" +version = "6.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d60b5d773ad46c698c8cc2cd9fde0b283d39cbb7f71c04bee633c7bdba4423bd" +checksum = "df4056ac7c18e4438ccf0edaed4340ca0d269278c8ec19284f7b23cb039fd0ae" dependencies = [ "convert_case", "proc-macro2", @@ -8601,9 +8602,9 @@ dependencies = [ [[package]] name = "roaring" -version = "0.11.4" +version = "0.11.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dedc5658c6ecb3bdb5ef5f3295bb9253f42dcf3fd1402c03f6b1f7659c3c4a9" +checksum = "18bd8a37d17a58532776dcdf6041ce64929adca78e8489d5cacbafe99229d3e1" dependencies = [ "bytemuck", "byteorder", @@ -9063,9 +9064,9 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.21.0" +version = "3.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76a5c54c7310e7b8b9577c286d7e399ddd876c3e12b3ed917a8aabc4b96e9e8c" +checksum = "ee78f1fbe43ac4a0e47aadb3dbd357b69eb0d3793e948624cd03dd2750ab1c0a" dependencies = [ "base64 0.22.1", "bs58", @@ -9073,6 +9074,7 @@ dependencies = [ "hex", "indexmap 1.9.3", "indexmap 2.14.0", + "jiff", "schemars 0.9.0", "schemars 1.2.1", "serde_core", @@ -9083,9 +9085,9 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.21.0" +version = "3.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84d57bc0c8b9a17920c178daa6bb924850d54a9c97ab45194bb8c17ad66bb660" +checksum = "8705578779c2b6bd90d84d66eb2e206b708b1a4d7b9f17641b293545bf1c7e46" dependencies = [ "darling 0.23.0", "proc-macro2", @@ -10452,9 +10454,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.24.0" +version = "1.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf3923a6f5c4c6382e0b653c4117f48d631ea17f38ed86e2a828e6f7412f5239" +checksum = "b5772d71c9be8a8a6ac2117d949c5b224c1b72241bb611d9a3012edcf8af7812" dependencies = [ "getrandom 0.4.2", "js-sys", diff --git a/nodejs/src/query.rs b/nodejs/src/query.rs index 3828023a9..f9fe91d35 100644 --- a/nodejs/src/query.rs +++ b/nodejs/src/query.rs @@ -664,7 +664,11 @@ impl JsFullTextQuery { } fn parse_fts_query(query: Object) -> napi::Result { - if let Ok(Some(query)) = query.get::<&JsFullTextQuery>("query") { + // `&JsFullTextQuery` recovers a native class reference through napi's borrow-tracked + // path, which is only usable from generated `#[napi]` argument conversion. This is a + // manual lookup on a nested `Object` property instead, so use `ClassInstance`, which + // unwraps the class without requiring a borrow scope. + if let Ok(Some(query)) = query.get::>("query") { Ok(FullTextSearchQuery::new_query(query.inner.clone())) } else if let Ok(Some(query_text)) = query.get::("query") { let mut query_text = query_text; From 5cbd979455d792cf6c6d8ed27e13daaeabc20e2f Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 1 Sep 2026 05:02:40 +0800 Subject: [PATCH 162/206] fix: preserve namespace drop errors (#4099) ## Summary - preserve typed namespace errors returned by `drop_table` - return `TableNotFound` when dropping an absent namespace table - cover repeated drop behavior in the namespace database test ## Validation - `cargo test --quiet --features remote -p lancedb database::namespace::tests::test_namespace_drop_table --lib` - `cargo clippy --quiet --features remote -p lancedb --lib --tests -- -D warnings` ## Context Sophon SQL implements `DROP TABLE IF EXISTS` by matching `lancedb::Error::TableNotFound`. The namespace database previously wrapped this error as `Runtime`, causing cleanup to fail and mask an earlier statement error. --- rust/lancedb/src/database/namespace.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/rust/lancedb/src/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index 250d933f6..5ca720e85 100644 --- a/rust/lancedb/src/database/namespace.rs +++ b/rust/lancedb/src/database/namespace.rs @@ -539,9 +539,7 @@ impl Database for LanceNamespaceDatabase { self.namespace .drop_table(drop_request) .await - .map_err(|e| Error::Runtime { - message: format!("Failed to drop table: {}", e), - })?; + .map_err(|e| map_namespace_lance_error(e, name))?; Ok(()) } @@ -1495,6 +1493,15 @@ mod tests { .expect("Failed to list tables"); assert!(!table_names_after.contains(&"drop_test".to_string())); + let error = conn + .drop_table("drop_test", &["test_ns".into()]) + .await + .expect_err("dropping a missing table should fail"); + assert!( + matches!(error, Error::TableNotFound { ref name, .. } if name == "drop_test"), + "expected TableNotFound, got: {error:?}" + ); + // Verify: Cannot open dropped table let open_result = conn.open_table("drop_test").execute().await; assert!(open_result.is_err()); From 19232f9c50aa988e4c97a147f70f75feca2c097a Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Tue, 1 Sep 2026 20:08:47 +0800 Subject: [PATCH 163/206] fix: preserve duplicate take offsets (#4024) ## Summary - preserve repeated table offsets without adding a public ordering guarantee - retain exact requested ordering in identity and persisted permutations - cover local, projected, multi-batch, and mocked-remote query paths ## Root cause Take queries lowered offsets to a set-like IN predicate and discarded repeated occurrences. Persisted permutation loading also compared the distinct base-table result count with the requested occurrence count, rejecting repeated row IDs before its existing reordering step could expand them. ## Fix The shared take-query path now deduplicates the predicate for efficient lookup, requests row-offset metadata internally, and expands each matching row to the requested multiplicity in backend result order. An internal opt-in keeps exact requested order for identity PermutationReader reads, while persisted permutations continue using their existing ordering map. ## Validation - cargo test --quiet --features remote --tests - cargo check --quiet --features remote --tests --examples - cargo clippy --quiet --features remote --tests --examples - targeted Python local and mocked-remote regression tests - exact issue reproduction Fixes #2820 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/query.py | 6 + python/python/lancedb/table.py | 29 +- python/python/tests/test_query.py | 15 + python/python/tests/test_remote_db.py | 35 +- python/src/query.rs | 3 + .../src/dataloader/permutation/reader.rs | 74 +- rust/lancedb/src/query.rs | 840 +++++++++++++++++- rust/lancedb/src/remote/table.rs | 162 +++- rust/lancedb/src/table.rs | 14 +- rust/lancedb/src/table/query.rs | 9 +- 11 files changed, 1157 insertions(+), 31 deletions(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 05ece3043..2b2691139 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -607,6 +607,7 @@ class FullTextQuery: class PyQueryRequest: limit: Optional[int] offset: Optional[int] + take_offsets: 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 451384ad1..c76e9e7db 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -109,6 +109,7 @@ def _query_is_plain_scan(query: Query) -> bool: return ( query.vector is None and query.full_text_query is None + and query.take_offsets is None and not query.postfilter and not query.order_by ) @@ -804,6 +805,10 @@ class Query(pydantic.BaseModel): # offset to start fetching results from offset: Optional[int] = None + # Dataset offsets whose duplicate occurrences must be restored after lookup. + # This is populated when a take query is converted to this serializable form. + take_offsets: Optional[List[int]] = None + # if true, will only search the indexed data fast_search: Optional[bool] = None @@ -825,6 +830,7 @@ class Query(pydantic.BaseModel): query = cls() query.limit = req.limit query.offset = req.offset + query.take_offsets = req.take_offsets 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 36c5b727d..287dff1f6 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1678,9 +1678,9 @@ 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. If - you desire an output order that matches the order of the given offsets, you will - need to add the row offset column to the output and align it yourself. + 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. Parameters ---------- @@ -4090,6 +4090,7 @@ class LanceTable(Table): ) and not self._route_pushdown_to_rust and self.current_branch() is None + and query.take_offsets is None ): from lancedb.namespace import _execute_server_side_query @@ -5983,7 +5984,23 @@ class AsyncTable: def _sync_query_to_async( self, query: Query - ) -> AsyncHybridQuery | AsyncFTSQuery | AsyncVectorQuery | AsyncQuery: + ) -> ( + AsyncHybridQuery + | AsyncFTSQuery + | AsyncVectorQuery + | 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.use_lsm is not None: + take_query = take_query.use_lsm(query.use_lsm) + if query.with_row_id: + take_query = take_query.with_row_id() + return take_query + async_query = self.query() if query.limit is not None: async_query = async_query.limit(query.limit) @@ -6048,6 +6065,7 @@ class AsyncTable: self._namespace_client, self._pushdown_operations ) and not self._route_pushdown_to_rust + and query.take_offsets is None ): from lancedb.namespace import _execute_server_side_query @@ -6545,6 +6563,9 @@ 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. + Parameters ---------- offsets: list[int] diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index ff62b2b51..6fbe0689b 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -1923,6 +1923,21 @@ def test_take_queries(tmp_path): 17, ] + # Duplicate offsets are occurrences, not set members. Ordering is unspecified. + assert sorted(table.take_offsets([5, 2, 5, 17]).to_pandas()["idx"].to_list()) == [ + 2, + 5, + 5, + 17, + ] + + # Converting a take builder to its serializable query representation must + # retain occurrence metadata and execute with the same multiplicity. + query = table.take_offsets([5, 2, 5, 17]).select(["idx"]).to_query_object() + assert query.take_offsets == [5, 2, 5, 17] + converted = table._execute_query(query).read_all() + 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()) diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index ab0df386d..01e2cc4c5 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -479,24 +479,49 @@ def test_remote_permutation_is_picklable(): match = re.search( r"_rowoffset\s+in\s+\((.*?)\)", body["filter"], re.IGNORECASE ) - offsets = [int(o.strip()) for o in match.group(1).split(",")] + offsets = list( + dict.fromkeys(int(o.strip()) for o in match.group(1).split(",")) + ) else: offsets = list(range(len(rows))) - table = pa.table({"a": [rows[offset] for offset in offsets]}) + columns = body.get("columns") or ["a"] + table = pa.table( + { + column: ( + [rows[offset] for offset in offsets] + if column == "a" + else offsets + ) + for column in columns + } + ) request.send_response(200) request.send_header("Content-Type", "application/vnd.apache.arrow.file") request.end_headers() with pa.ipc.new_file(request.wfile, schema=table.schema) as writer: - writer.write_table(table) + writer.write_table(table, max_chunksize=2) else: request.send_response(404) request.end_headers() with mock_lancedb_connection(handler) as db: - permutation = Permutation.identity(db.open_table("test")) + table = db.open_table("test") + assert table.take_offsets([0, 2, 0, 4]).to_list() == [ + {"a": 0}, + {"a": 0}, + {"a": 2}, + {"a": 4}, + ] + + permutation = Permutation.identity(table) restored = pickle.loads(pickle.dumps(permutation)) - assert restored.__getitems__([0, 2, 4]) == [{"a": 0}, {"a": 2}, {"a": 4}] + assert restored.__getitems__([0, 2, 0, 4]) == [ + {"a": 0}, + {"a": 2}, + {"a": 0}, + {"a": 4}, + ] def test_create_table_exist_ok(): diff --git a/python/src/query.rs b/python/src/query.rs index 38153729f..ef71939f2 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -323,6 +323,7 @@ impl<'py> IntoPyObject<'py> for PyQueryVectors { pub struct PyQueryRequest { pub limit: Option, pub offset: Option, + pub take_offsets: Option>, pub filter: Option, pub full_text_search: Option>, pub select: PySelect, @@ -353,6 +354,7 @@ impl From for PyQueryRequest { AnyQuery::Query(query_request) => Self { limit: query_request.limit, offset: query_request.offset, + take_offsets: query_request.take_offsets, filter: query_request.filter.map(PyQueryFilter), full_text_search: query_request .full_text_search @@ -381,6 +383,7 @@ impl From for PyQueryRequest { AnyQuery::VectorQuery(vector_query) => Self { limit: vector_query.base.limit, offset: vector_query.base.offset, + take_offsets: vector_query.base.take_offsets, 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/dataloader/permutation/reader.rs b/rust/lancedb/src/dataloader/permutation/reader.rs index 9757dc552..015c3a17d 100644 --- a/rust/lancedb/src/dataloader/permutation/reader.rs +++ b/rust/lancedb/src/dataloader/permutation/reader.rs @@ -31,7 +31,7 @@ use lance::io::RecordBatchStream; use lance_arrow::RecordBatchExt; use lance_core::ROW_ID; use lance_core::error::LanceOptionExt; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; /// Reads a permutation of a source table based on row IDs stored in a separate table @@ -234,7 +234,14 @@ impl PermutationReader { .expect_ok()? .values(); - let in_list: Vec = row_ids.iter().map(|id| lit(*id)).collect(); + let mut unique_row_ids = HashSet::with_capacity(num_rows); + let in_list: Vec = row_ids + .iter() + .copied() + .filter(|row_id| unique_row_ids.insert(*row_id)) + .map(lit) + .collect(); + let num_unique_row_ids = unique_row_ids.len(); let base_query = QueryRequest { filter: Some(QueryFilter::Datafusion(col(ROW_ID).in_list(in_list, false))), @@ -247,7 +254,7 @@ impl PermutationReader { .query( &AnyQuery::Query(base_query), QueryExecutionOptions { - max_batch_length: num_rows as u32, + max_batch_length: num_unique_row_ids as u32, ..Default::default() }, ) @@ -262,9 +269,9 @@ impl PermutationReader { }); } - if batches.iter().map(|b| b.num_rows()).sum::() != num_rows { + if batches.iter().map(|b| b.num_rows()).sum::() != num_unique_row_ids { return Err(Error::InvalidInput { - message: "Base table returned different number of rows than the number of row IDs" + message: "Base table returned a different number of rows than the number of unique row IDs" .to_string(), }); } @@ -504,6 +511,7 @@ impl PermutationReader { let table = Table::from(self.base_table.clone()); let batches = table .take_offsets(offsets.to_vec()) + .preserve_order() .select(selection.clone()) .execute() .await? @@ -803,10 +811,10 @@ mod tests { .unwrap(); // Take offsets in reverse order and verify returned rows match that order - let offsets = vec![5, 3, 1, 0]; + let offsets = vec![5, 3, 5, 1, 0]; let batch = reader.take_offsets(&offsets, Select::All).await.unwrap(); - assert_eq!(batch.num_rows(), 4); + assert_eq!(batch.num_rows(), 5); let idx_values = batch .column(0) @@ -820,6 +828,52 @@ mod tests { assert_eq!(idx_values, expected); } + #[tokio::test] + async fn test_take_offsets_preserves_repeated_rows_in_permutation() { + let base_table = lance_datagen::gen_batch() + .col("idx", lance_datagen::array::step::()) + .into_mem_table("tbl", RowCount::from(5), BatchCount::from(1)) + .await; + let base_row_ids = collect_column::(&base_table, "_rowid").await; + let permutation_row_ids = vec![ + base_row_ids[3], + base_row_ids[1], + base_row_ids[3], + base_row_ids[2], + ]; + let permutation_batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("row_id", DataType::UInt64, false), + Field::new(SPLIT_ID_COLUMN, DataType::UInt64, false), + ])), + vec![ + Arc::new(UInt64Array::from(permutation_row_ids)), + Arc::new(UInt64Array::from(vec![0; 4])), + ], + ) + .unwrap(); + let permutation_table = virtual_table("row_ids", &permutation_batch).await; + let reader = PermutationReader::try_from_tables( + base_table.base_table().clone(), + permutation_table.base_table().clone(), + 0, + ) + .await + .unwrap(); + + let batch = reader + .take_offsets(&[0, 1, 2, 3], Select::All) + .await + .unwrap(); + let idx_values = batch + .column(0) + .as_primitive::() + .values() + .to_vec(); + + assert_eq!(idx_values, vec![3, 1, 3, 2]); + } + #[tokio::test] async fn test_take_offsets_with_column_selection() { let (base_table, row_ids_table, row_ids) = setup_permutation_tables(10).await; @@ -883,17 +937,17 @@ mod tests { .unwrap(); // With no permutation table, take_offsets uses the base table directly - let offsets = vec![0, 2, 4, 6]; + let offsets = vec![0, 2, 0, 4, 6]; let batch = reader.take_offsets(&offsets, Select::All).await.unwrap(); - assert_eq!(batch.num_rows(), 4); + assert_eq!(batch.num_rows(), 5); let idx_values = batch .column(0) .as_primitive::() .values() .to_vec(); - assert_eq!(idx_values, vec![0, 2, 4, 6]); + assert_eq!(idx_values, vec![0, 2, 0, 4, 6]); } #[tokio::test] diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index cd346f42e..5b889cada 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -1,21 +1,37 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors +use std::collections::{HashMap, HashSet}; +use std::pin::Pin; use std::sync::Arc; use std::{future::Future, time::Duration}; use arrow::compute::concat_batches; -use arrow_array::{Array, Float16Array, Float32Array, Float64Array, RecordBatch, make_array}; +use arrow_array::{ + Array, Float16Array, Float32Array, Float64Array, RecordBatch, UInt64Array, + cast::AsArray, + make_array, + types::{Int64Type, UInt64Type}, +}; 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_plan::ExecutionPlan; -use futures::{FutureExt, TryFutureExt, TryStreamExt, stream, try_join}; +use datafusion_physical_expr::{EquivalenceProperties, Partitioning}; +use datafusion_physical_plan::{ + DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, + coalesce_partitions::CoalescePartitionsExec, + execution_plan::{Boundedness, EmissionType}, + limit::GlobalLimitExec, + stream::RecordBatchStreamAdapter, +}; +use futures::{FutureExt, StreamExt, TryFutureExt, TryStreamExt, stream, try_join}; use half::f16; /// Re-export Lance ColumnOrdering type for use in query ordering pub use lance::dataset::scanner::ColumnOrdering; use lance::dataset::{ROW_ID, scanner::DatasetRecordBatchStream}; use lance_arrow::RecordBatchExt; -use lance_datafusion::exec::execute_plan; +use lance_datafusion::exec::{execute_plan, format_plan as format_analyzed_plan}; use lance_index::scalar::FullTextSearchQuery; use lance_index::scalar::inverted::SCORE_COL; use lance_index::vector::DIST_COL; @@ -825,6 +841,14 @@ pub struct QueryRequest { /// Offset of the query. pub offset: Option, + /// Dataset offsets whose occurrence multiplicity must be restored after + /// executing the physical lookup represented by this request. + /// + /// This is client-side execution metadata used when a [`TakeQuery`] is + /// converted into a request. It is not sent to remote services. + #[doc(hidden)] + pub take_offsets: Option>, + /// Apply filter to the returned rows. pub filter: Option, @@ -893,6 +917,7 @@ impl Default for QueryRequest { Self { limit: None, offset: None, + take_offsets: None, filter: None, filter_error: None, full_text_search: None, @@ -1529,6 +1554,302 @@ 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; + } + occurrences +} + +fn restore_take_batch_with_occurrences( + batch: RecordBatch, + offsets: &[u64], + occurrences: &HashMap, + ordering_column: &str, + drop_ordering_column: bool, + preserve_order: bool, +) -> Result { + let actual_offsets = 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 + .as_primitive::() + .values() + .to_vec(), + DataType::Int64 => actual_offsets + .as_primitive::() + .values() + .iter() + .map(|offset| { + u64::try_from(*offset).map_err(|_| Error::Schema { + message: format!( + "take query ordering column '{ordering_column}' contained a negative offset" + ), + }) + }) + .collect::>>()?, + data_type => { + return Err(Error::Schema { + message: format!( + "take query ordering column '{ordering_column}' had unsupported type {data_type}" + ), + }); + } + }; + + let mut desired_order = Vec::with_capacity(offsets.len()); + if preserve_order { + let ordering = actual_offsets + .iter() + .copied() + .enumerate() + .map(|(index, offset)| (offset, index as u64)) + .collect::>(); + // Missing offsets retain the filter-based behavior of returning no row. + desired_order.extend( + offsets + .iter() + .filter_map(|offset| ordering.get(offset).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)); + } + } + } + + let mut ordered_batch = if desired_order.len() == batch.num_rows() + && desired_order + .iter() + .enumerate() + .all(|(index, desired)| *desired == index as u64) + { + batch + } else { + arrow_select::take::take_record_batch(&batch, &UInt64Array::from(desired_order))? + }; + + if drop_ordering_column { + ordered_batch = ordered_batch.drop_column(ordering_column)?; + } + + Ok(ordered_batch) +} + +#[cfg(test)] +fn restore_take_batch( + batch: RecordBatch, + offsets: &[u64], + ordering_column: &str, + drop_ordering_column: bool, + preserve_order: bool, +) -> Result { + restore_take_batch_with_occurrences( + batch, + offsets, + &take_occurrences(offsets), + ordering_column, + drop_ordering_column, + preserve_order, + ) +} + +/// Restores the logical offset 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 +/// input before restoring requested order. Pagination must remain above this operator +/// so it applies to occurrences. +#[derive(Debug)] +struct TakeRestoreExec { + input: Arc, + offsets: Vec, + occurrences: Arc>, + ordering_column: String, + drop_ordering_column: bool, + preserve_order: bool, + schema: SchemaRef, + properties: Arc, +} + +impl TakeRestoreExec { + fn try_new( + input: Arc, + offsets: 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() + } else { + input.schema() + }; + let partition_count = if preserve_order { + 1 + } else { + input.output_partitioning().partition_count() + }; + let emission_type = if preserve_order { + EmissionType::Final + } else { + EmissionType::Incremental + }; + let properties = Arc::new(PlanProperties::new( + EquivalenceProperties::new(schema.clone()), + Partitioning::UnknownPartitioning(partition_count), + emission_type, + Boundedness::Bounded, + )); + + Ok(Self { + input, + occurrences: Arc::new(take_occurrences(&offsets)), + offsets, + ordering_column, + drop_ordering_column, + preserve_order, + schema, + properties, + }) + } +} + +impl DisplayAs for TakeRestoreExec { + fn fmt_as( + &self, + _display_type: DisplayFormatType, + formatter: &mut std::fmt::Formatter<'_>, + ) -> std::fmt::Result { + write!( + formatter, + "TakeRestoreExec: occurrences={}", + self.offsets.len() + ) + } +} + +impl ExecutionPlan for TakeRestoreExec { + fn name(&self) -> &str { + "TakeRestoreExec" + } + + fn properties(&self) -> &Arc { + &self.properties + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + + fn maintains_input_order(&self) -> Vec { + vec![!self.preserve_order] + } + + fn benefits_from_input_partitioning(&self) -> Vec { + vec![false] + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> DataFusionResult> { + if children.len() != 1 { + return Err(DataFusionError::Internal(format!( + "TakeRestoreExec expected one child, got {}", + children.len() + ))); + } + let child = children.into_iter().next().unwrap(); + let plan = Self::try_new( + child, + self.offsets.clone(), + self.ordering_column.clone(), + self.drop_ordering_column, + self.preserve_order, + ) + .map_err(|error| DataFusionError::External(Box::new(error)))?; + Ok(Arc::new(plan)) + } + + fn execute( + &self, + partition: usize, + context: Arc, + ) -> DataFusionResult { + let partition_count = self.input.output_partitioning().partition_count(); + if partition >= partition_count || (self.preserve_order && partition != 0) { + return Err(DataFusionError::Internal(format!( + "TakeRestoreExec cannot execute partition {partition}; input has {partition_count} partitions" + ))); + } + + let input = self.input.execute(partition, context)?; + let output_schema = self.schema.clone(); + let offsets = self.offsets.clone(); + let occurrences = self.occurrences.clone(); + let ordering_column = self.ordering_column.clone(); + let drop_ordering_column = self.drop_ordering_column; + let preserve_order = self.preserve_order; + let stream: Pin> + Send>> = + if preserve_order { + let input_schema = input.schema(); + Box::pin(stream::once(async move { + let batches = input.try_collect::>().await?; + let batch = if batches.is_empty() { + RecordBatch::new_empty(input_schema.clone()) + } else { + concat_batches(&input_schema, &batches)? + }; + restore_take_batch_with_occurrences( + batch, + &offsets, + &occurrences, + &ordering_column, + drop_ordering_column, + true, + ) + .map_err(|error| DataFusionError::External(Box::new(error))) + })) + } else { + Box::pin(input.map(move |batch| { + batch.and_then(|batch| { + restore_take_batch_with_occurrences( + batch, + &offsets, + &occurrences, + &ordering_column, + drop_ordering_column, + false, + ) + .map_err(|error| DataFusionError::External(Box::new(error))) + }) + })) + }; + + Ok(Box::pin(RecordBatchStreamAdapter::new( + output_schema, + stream, + ))) + } + + fn supports_limit_pushdown(&self) -> bool { + false + } +} + /// A builder for LanceDB take queries. /// /// See [`crate::Table::query`] for more details on queries @@ -1545,6 +1866,8 @@ impl HasQuery for VectorQuery { pub struct TakeQuery { parent: Arc, request: QueryRequest, + offsets: Option>, + preserve_order: bool, } impl TakeQuery { @@ -1552,15 +1875,24 @@ impl TakeQuery { /// /// See [`crate::Table::take_offsets`] for more details. pub fn from_offsets(parent: Arc, offsets: Vec) -> Self { - let in_list: Vec = offsets.iter().map(|o| lit(*o)).collect(); + let mut seen = HashSet::with_capacity(offsets.len()); + let in_list: Vec = offsets + .iter() + .copied() + .filter(|offset| seen.insert(*offset)) + .map(lit) + .collect(); Self { parent, request: QueryRequest { filter: Some(QueryFilter::Datafusion( col("_rowoffset").in_list(in_list, false), )), + take_offsets: Some(offsets.clone()), ..Default::default() }, + offsets: Some(offsets), + preserve_order: false, } } @@ -1575,9 +1907,181 @@ impl TakeQuery { filter: Some(QueryFilter::Datafusion(col(ROW_ID).in_list(in_list, false))), ..Default::default() }, + offsets: None, + 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 { + debug_assert!(self.offsets.is_some()); + self.preserve_order = true; + self + } + + async fn request_with_row_offset( + parent: &dyn BaseTable, + request: &QueryRequest, + ) -> Result<(QueryRequest, String, bool)> { + const ROW_OFFSET: &str = "_rowoffset"; + const INTERNAL_ROW_OFFSET: &str = "__lancedb_take_row_offset"; + + let mut request = request.clone(); + // The physical lookup must not recursively restore occurrences. The + // wrapper above this request owns that logical operation. + request.take_offsets = None; + let (ordering_column, drop_ordering_column) = match &mut request.select { + Select::All => { + let mut columns = parent + .schema() + .await? + .fields() + .iter() + .map(|field| field.name().clone()) + .collect::>(); + columns.push(ROW_OFFSET.to_string()); + request.select = Select::Columns(columns); + (ROW_OFFSET.to_string(), true) + } + Select::Columns(columns) => { + if columns.iter().any(|column| column == ROW_OFFSET) { + (ROW_OFFSET.to_string(), false) + } else { + columns.push(ROW_OFFSET.to_string()); + (ROW_OFFSET.to_string(), true) + } + } + Select::Dynamic(columns) => { + let mut ordering_column = INTERNAL_ROW_OFFSET.to_string(); + while columns.iter().any(|(name, _)| name == &ordering_column) { + ordering_column.push('_'); + } + columns.push((ordering_column.clone(), ROW_OFFSET.to_string())); + (ordering_column, true) + } + Select::Expr(columns) => { + let mut ordering_column = INTERNAL_ROW_OFFSET.to_string(); + while columns.iter().any(|(name, _)| name == &ordering_column) { + ordering_column.push('_'); + } + columns.push((ordering_column.clone(), col(ROW_OFFSET))); + (ordering_column, true) + } + }; + + Ok((request, ordering_column, drop_ordering_column)) + } + + async fn prepare_offsets_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?; + // 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(( + request, + ordering_column, + drop_ordering_column, + output_offset, + output_limit, + )) + } + + fn wrap_offsets_plan( + lookup: Arc, + offsets: &[u64], + ordering_column: String, + drop_ordering_column: bool, + output_offset: usize, + output_limit: Option, + preserve_order: bool, + ) -> Result> { + let lookup = if preserve_order { + Arc::new(CoalescePartitionsExec::new(lookup)) as Arc + } else { + lookup + }; + let restored: Arc = Arc::new(TakeRestoreExec::try_new( + lookup, + offsets.to_vec(), + ordering_column, + drop_ordering_column, + preserve_order, + )?); + + if output_offset > 0 || output_limit.is_some() { + Ok(Arc::new(GlobalLimitExec::new( + restored, + output_offset, + output_limit, + ))) + } else { + Ok(restored) + } + } + + fn wrap_offsets_explanation( + lookup: &str, + occurrence_count: usize, + output_offset: usize, + output_limit: Option, + preserve_order: bool, + ) -> String { + fn indent(plan: &str, spaces: usize) -> String { + let indentation = " ".repeat(spaces); + plan.lines() + .map(|line| format!("{indentation}{line}")) + .collect::>() + .join("\n") + } + + let restored = if preserve_order { + format!( + "TakeRestoreExec: occurrences={occurrence_count}\n CoalescePartitionsExec\n{}", + indent(lookup, 4) + ) + } else { + format!( + "TakeRestoreExec: occurrences={occurrence_count}\n{}", + indent(lookup, 2) + ) + }; + + if output_offset > 0 || output_limit.is_some() { + let fetch = output_limit + .map(|limit| limit.to_string()) + .unwrap_or_else(|| "None".to_string()); + format!( + "GlobalLimitExec: skip={output_offset}, fetch={fetch}\n{}", + indent(&restored, 2) + ) + } else { + restored + } + } + + 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 @@ -1622,6 +2126,63 @@ impl TakeQuery { } } +pub(crate) async fn create_take_offsets_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 lookup_options = if preserve_order { + options.without_output_batch_length_limit() + } else { + options + }; + let lookup = parent + .create_plan(&AnyQuery::Query(request), lookup_options) + .await?; + + TakeQuery::wrap_offsets_plan( + lookup, + offsets, + ordering_column, + drop_ordering_column, + output_offset, + output_limit, + preserve_order, + ) +} + +pub(crate) async fn explain_take_offsets_plan( + parent: &dyn BaseTable, + request: &QueryRequest, + offsets: &[u64], + verbose: bool, +) -> Result { + let (request, _, _, output_offset, output_limit) = + TakeQuery::prepare_offsets_lookup(parent, request).await?; + let lookup = parent + .explain_plan(&AnyQuery::Query(request), verbose) + .await?; + Ok(TakeQuery::wrap_offsets_explanation( + &lookup, + offsets.len(), + output_offset, + output_limit, + false, + )) +} + +pub(crate) async fn prepare_take_offsets_request( + parent: &dyn BaseTable, + request: &QueryRequest, +) -> Result { + let (request, _, _, _, _) = TakeQuery::prepare_offsets_lookup(parent, request).await?; + Ok(request) +} + impl HasQuery for TakeQuery { fn mut_query(&mut self) -> &mut QueryRequest { &mut self.request @@ -1630,6 +2191,10 @@ 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; + } + let req = AnyQuery::Query(self.request.clone()); self.parent.clone().create_plan(&req, options).await } @@ -1638,6 +2203,18 @@ impl ExecutableQuery for TakeQuery { &self, options: QueryExecutionOptions, ) -> Result { + if self.offsets.is_some() { + 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); + let inner = if let Some(timeout) = options.timeout { + TimeoutStream::new_boxed(inner, timeout) + } else { + inner + }; + return Ok(DatasetRecordBatchStream::new(inner).into()); + } + let query = AnyQuery::Query(self.request.clone()); Ok(SendableRecordBatchStream::from( self.parent.clone().query(&query, options).await?, @@ -1645,11 +2222,51 @@ 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, + self.preserve_order, + )); + } + let query = AnyQuery::Query(self.request.clone()); self.parent.explain_plan(&query, verbose).await } async fn analyze_plan_with_options(&self, options: QueryExecutionOptions) -> Result { + if self.offsets.is_some() { + if self.parent.analyze_plan_is_remote() { + let (request, _, _, _, _) = + Self::prepare_offsets_lookup(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 + // for client-side restoration operators. + return self + .parent + .analyze_plan(&AnyQuery::Query(request), options) + .await; + } + + let plan = self.create_plan(options).await?; + execute_plan(plan.clone(), Default::default())? + .try_collect::>() + .await?; + return Ok(format_analyzed_plan(plan)); + } + let query = AnyQuery::Query(self.request.clone()); self.parent.analyze_plan(&query, options).await } @@ -1670,6 +2287,7 @@ mod tests { StringArray, cast::AsArray, types::Float32Type, }; use arrow_schema::{DataType, Field as ArrowField, Schema as ArrowSchema}; + use datafusion_physical_plan::display::DisplayableExecutionPlan; use futures::{StreamExt, TryStreamExt}; use lance_testing::datagen::{BatchGenerator, IncrementingInt32, RandomVector}; use rand::seq::IndexedRandom; @@ -2924,6 +3542,218 @@ mod tests { assert_eq!(results[0].num_columns(), 1); } + #[tokio::test] + async fn test_take_offsets_preserves_duplicate_multiplicity() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + + let results = table + .take_offsets(vec![5, 1, 5, 17]) + .select(Select::Columns(vec!["id".to_string()])) + .execute_with_options(QueryExecutionOptions { + max_batch_length: 2, + ..Default::default() + }) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + + assert_eq!(results.len(), 2); + assert!(results.iter().all(|batch| batch.num_columns() == 1)); + let mut ids = results + .iter() + .flat_map(|batch| { + batch + .column_by_name("id") + .unwrap() + .as_primitive::() + .values() + .to_vec() + }) + .collect::>(); + ids.sort_unstable(); + assert_eq!(ids, vec![1, 5, 5, 17]); + } + + #[tokio::test] + async fn test_take_offsets_plan_is_incremental() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + + let plan = table + .take_offsets(vec![5, 1, 17]) + .create_plan(QueryExecutionOptions { + max_batch_length: 1, + ..Default::default() + }) + .await + .unwrap(); + + assert_eq!(plan.properties().emission_type, EmissionType::Incremental); + let displayed = DisplayableExecutionPlan::new(plan.as_ref()) + .indent(false) + .to_string(); + assert!(displayed.contains("TakeRestoreExec")); + assert!(!displayed.contains("CoalescePartitionsExec")); + } + + #[tokio::test] + async fn test_take_into_request_preserves_duplicate_multiplicity() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + let request = table.take_offsets(vec![5, 5]).into_request(); + assert_eq!(request.take_offsets, Some(vec![5, 5])); + + let batches = table + .base_table() + .query(&AnyQuery::Query(request), QueryExecutionOptions::default()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 2); + } + + #[test] + fn test_restore_take_batch_only_reorders_when_requested() { + let batch = RecordBatch::try_from_iter([ + ( + "id", + Arc::new(Int32Array::from(vec![17, 5, 1])) as Arc, + ), + ( + "_rowoffset", + Arc::new(UInt64Array::from(vec![17, 5, 1])) as Arc, + ), + ]) + .unwrap(); + + let restored = + restore_take_batch(batch.clone(), &[5, 1, 5, 17], "_rowoffset", true, false).unwrap(); + assert_eq!( + restored + .column_by_name("id") + .unwrap() + .as_primitive::() + .values(), + &[17, 5, 5, 1] + ); + + let ordered = restore_take_batch(batch, &[5, 1, 5, 17], "_rowoffset", true, true).unwrap(); + assert_eq!( + ordered + .column_by_name("id") + .unwrap() + .as_primitive::() + .values(), + &[5, 1, 5, 17] + ); + } + + #[tokio::test] + async fn test_take_offsets_applies_pagination_after_restoration() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + + let limited = table + .take_offsets(vec![0, 1, 0, 2]) + .select(Select::Columns(vec!["id".to_string()])) + .limit(3) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let limited = concat_batches(&limited[0].schema(), &limited).unwrap(); + assert_eq!(limited.num_rows(), 3); + assert!( + limited + .column_by_name("id") + .unwrap() + .as_primitive::() + .values() + .iter() + .all(|id| [0, 1, 2].contains(id)) + ); + + let offset = table + .take_offsets(vec![5, 1, 5, 17]) + .select(Select::Columns(vec!["id".to_string()])) + .offset(1) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + let offset = concat_batches(&offset[0].schema(), &offset).unwrap(); + assert_eq!(offset.num_rows(), 3); + assert!( + offset + .column_by_name("id") + .unwrap() + .as_primitive::() + .values() + .iter() + .all(|id| [1, 5, 17].contains(id)) + ); + } + + #[tokio::test] + async fn test_take_offsets_create_plan_restores_occurrences() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + let take = table + .take_offsets(vec![5, 1, 5, 17]) + .select(Select::Columns(vec!["id".to_string()])); + + let plan = take + .create_plan(QueryExecutionOptions::default()) + .await + .unwrap(); + assert_eq!(plan.schema().fields().len(), 1); + assert_eq!(plan.schema().field(0).name(), "id"); + let planned = execute_plan(plan, Default::default()) + .unwrap() + .try_collect::>() + .await + .unwrap(); + let planned = concat_batches(&planned[0].schema(), &planned).unwrap(); + let mut ids = planned + .column_by_name("id") + .unwrap() + .as_primitive::() + .values() + .to_vec(); + ids.sort_unstable(); + assert_eq!(ids, vec![1, 5, 5, 17]); + } + + #[tokio::test] + async fn test_take_offsets_plan_introspection_shows_restoration() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + let take = table + .take_offsets(vec![0, 1, 0, 2]) + .select(Select::Columns(vec!["id".to_string()])) + .limit(3); + + let explained = take.explain_plan(false).await.unwrap(); + assert!(explained.contains("GlobalLimitExec")); + assert!(explained.contains("TakeRestoreExec")); + assert!(!explained.contains("CoalescePartitionsExec")); + + let analyzed = take.analyze_plan().await.unwrap(); + assert!(analyzed.contains("GlobalLimitExec")); + assert!(analyzed.contains("TakeRestoreExec")); + assert!(!analyzed.contains("CoalescePartitionsExec")); + } + #[tokio::test] async fn test_take_row_ids() { let tmp_dir = tempdir().unwrap(); diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index d372a6f56..daea028e9 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -40,8 +40,8 @@ use crate::table::{ use crate::table::{AnyQuery, Filter, Predicate, PreprocessingOutput, TableStatistics}; use crate::utils::background_cache::BackgroundCache; use crate::utils::{ - resolve_arrow_field_path, resolve_arrow_fts_field_path, supported_btree_data_type, - supported_vector_data_type, + MaxBatchLengthStream, TimeoutStream, resolve_arrow_field_path, resolve_arrow_fts_field_path, + supported_btree_data_type, supported_vector_data_type, }; use crate::{DistanceType, Error}; use crate::{ @@ -2022,6 +2022,9 @@ impl BaseTable for RemoteTable { fn as_any(&self) -> &dyn std::any::Any { self } + fn analyze_plan_is_remote(&self) -> bool { + true + } fn name(&self) -> &str { &self.name } @@ -2594,6 +2597,13 @@ impl BaseTable for RemoteTable { query: &AnyQuery, options: QueryExecutionOptions, ) -> Result> { + if let AnyQuery::Query(request) = query + && let Some(offsets) = &request.take_offsets + { + return crate::query::create_take_offsets_plan(self, request, offsets, options, false) + .await; + } + let streams = self.execute_query(query, &options).await?; if streams.len() == 1 { let stream = streams.into_iter().next().unwrap(); @@ -2612,6 +2622,27 @@ impl BaseTable for RemoteTable { query: &AnyQuery, options: QueryExecutionOptions, ) -> Result { + if let AnyQuery::Query(request) = query + && let Some(offsets) = &request.take_offsets + { + let plan = crate::query::create_take_offsets_plan( + self, + request, + offsets, + 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 { + TimeoutStream::new_boxed(inner, timeout) + } else { + inner + }; + return Ok(DatasetRecordBatchStream::new(inner)); + } + let streams = self.execute_query(query, &options).await?; if streams.len() == 1 { @@ -2649,6 +2680,12 @@ 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 + { + return crate::query::explain_take_offsets_plan(self, request, offsets, verbose).await; + } + let base_request = self .client .post(&format!("/v1/table/{}/explain_plan/", self.identifier)); @@ -2701,6 +2738,17 @@ impl BaseTable for RemoteTable { query: &AnyQuery, options: QueryExecutionOptions, ) -> Result { + let prepared_query = if let AnyQuery::Query(request) = query + && request.take_offsets.is_some() + { + Some(AnyQuery::Query( + crate::query::prepare_take_offsets_request(self, request).await?, + )) + } else { + None + }; + let query = prepared_query.as_ref().unwrap_or(query); + let mut request = self .client .post(&format!("/v1/table/{}/analyze_plan/", self.identifier)); @@ -3690,7 +3738,7 @@ mod tests { }; use arrow_schema::{DataType, Field, Schema}; use chrono::{DateTime, Utc}; - use futures::{StreamExt, TryFutureExt, future::BoxFuture}; + use futures::{StreamExt, TryFutureExt, TryStreamExt, future::BoxFuture}; use lance_index::scalar::inverted::{DocumentGranularity, query::MatchQuery}; use lance_index::scalar::{FullTextSearchQuery, InvertedIndexParams}; use reqwest::Body; @@ -5611,6 +5659,114 @@ mod tests { assert_eq!(result, "analyzed plan"); } + #[tokio::test] + async fn test_take_offsets_explain_plan_does_not_execute_query() { + 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/"); + + http::Response::builder() + .status(200) + .body(r#""RemoteLookupExec""#) + .unwrap() + }); + + let explained = table + .take_offsets(vec![0, 1, 0, 2]) + .select(crate::query::Select::columns(&["id"])) + .limit(3) + .explain_plan(false) + .await + .unwrap(); + + assert!(explained.contains("GlobalLimitExec")); + assert!(explained.contains("TakeRestoreExec")); + assert!(!explained.contains("CoalescePartitionsExec")); + assert!(explained.contains("RemoteLookupExec")); + } + + #[tokio::test] + async fn test_converted_take_request_restores_remote_occurrences() { + let table = Table::new_with_handler("my_table", |request| { + assert_eq!(request.method(), "POST"); + 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", "_rowoffset"])); + + let data = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("_rowoffset", DataType::UInt64, false), + ])), + vec![ + Arc::new(Int32Array::from(vec![5])), + Arc::new(arrow_array::UInt64Array::from(vec![5])), + ], + ) + .unwrap(); + http::Response::builder() + .status(200) + .header(CONTENT_TYPE, ARROW_FILE_CONTENT_TYPE) + .body(write_ipc_file(&data)) + .unwrap() + }); + + let request = table + .take_offsets(vec![5, 5]) + .select(crate::query::Select::columns(&["id"])) + .into_request(); + let batches = table + .base_table() + .query(&AnyQuery::Query(request), QueryExecutionOptions::default()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + + assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::(), 2); + assert!( + batches + .iter() + .all(|batch| batch.schema().fields().len() == 1) + ); + } + + #[tokio::test] + async fn test_take_offsets_analyze_plan_delegates_to_remote() { + 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/"); + assert_eq!( + request + .url() + .query_pairs() + .find(|(key, _)| key == "distributed_metrics"), + Some(("distributed_metrics".into(), "per_worker".into())) + ); + + http::Response::builder() + .status(200) + .body(r#""Remote analyzed plan: worker metrics""#) + .unwrap() + }); + + let analyzed = table + .take_offsets(vec![0, 1, 0, 2]) + .select(crate::query::Select::columns(&["id"])) + .limit(3) + .analyze_plan_with_options(QueryExecutionOptions { + analyze_plan_distributed_metrics: AnalyzePlanDistributedMetrics::PerWorker, + ..Default::default() + }) + .await + .unwrap(); + + assert_eq!(analyzed, "Remote analyzed plan: worker metrics"); + } + #[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 efc705e3c..4602d35ed 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -595,6 +595,14 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { query: &AnyQuery, options: QueryExecutionOptions, ) -> Result; + /// Whether [`BaseTable::analyze_plan`] is provided by a remote service. + /// + /// Client-side query wrappers use this to preserve backend metrics and + /// distributed-analysis options instead of replacing them with a local plan. + #[doc(hidden)] + fn analyze_plan_is_remote(&self) -> bool { + false + } /// Add new records to the table. async fn add(&self, add: AddDataBuilder) -> Result; @@ -1652,9 +1660,9 @@ impl Table { /// Offsets are 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. If you - /// desire an output order that matches the order of the given offsets, you will need - /// to add the row offset column to the output and align it yourself. + /// 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. /// /// Parameters /// ---------- diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 6f6bbf372..d611fe8a5 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -110,7 +110,7 @@ fn requires_local_namespace_execution(query: &AnyQuery) -> bool { // pushing these down would silently ignore the user's setting. For use_lsm that // is worse than a tuning miss: MemWAL read routing lives only in `create_plan`, // so a pushed-down query would return stale base-only data with no error. - if query.base().use_lsm.is_some() { + if query.base().use_lsm.is_some() || query.base().take_offsets.is_some() { return true; } matches!( @@ -154,6 +154,13 @@ pub async fn create_plan( options: QueryExecutionOptions, ) -> Result> { let query = query.canonicalized()?; + if let AnyQuery::Query(request) = &query + && let Some(offsets) = &request.take_offsets + { + return crate::query::create_take_offsets_plan(table, request, offsets, options, false) + .await; + } + let query = match query { AnyQuery::VectorQuery(query) => query, AnyQuery::Query(query) => VectorQueryRequest::from_plain_query(query), From d118ef168bfb1229a5075f5f202ea50a666a66f4 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Tue, 1 Sep 2026 06:05:02 -0700 Subject: [PATCH 164/206] feat: record the source namespace in a materialized view definition (#4098) A view definition recorded its source by bare name and refresh resolved that name at the root, so declaring a view over a namespaced source was refused outright -- materialized views were root-only for every caller. The definition now carries `source_namespace`, and refresh opens the source at that coordinate. `plan` takes the namespace too: refresh re-plans the stored definition and persists the result when it migrates, so defaulting it there would strand the view on its next rebuild. The stored kind is the version boundary. Root definitions keep the `select` form byte-for-byte, so everything written before this change reads exactly as it always did. A namespaced source is stored as `namespaced_select`: released readers drop unknown fields and resolve a `select` source at the root, so keeping the old kind would let a rolled-back worker refresh a view from a same-name root table -- the new kind routes them to their existing unrecognized-kind refusal instead. The Python and Node definition parsers learn the new kind alongside the Rust core. --- .../interfaces/MaterializedViewDefinition.md | 10 + nodejs/__test__/materialized_view.test.ts | 22 ++ nodejs/lancedb/materialized_view.ts | 6 +- python/python/lancedb/materialized_view.py | 6 +- .../python/tests/test_materialized_views.py | 35 +++ rust/lancedb/src/materialized_view.rs | 254 ++++++++++++++---- rust/lancedb/src/materialized_view/refresh.rs | 5 +- 7 files changed, 288 insertions(+), 50 deletions(-) diff --git a/docs/src/js/interfaces/MaterializedViewDefinition.md b/docs/src/js/interfaces/MaterializedViewDefinition.md index 741bbba31..607563de5 100644 --- a/docs/src/js/interfaces/MaterializedViewDefinition.md +++ b/docs/src/js/interfaces/MaterializedViewDefinition.md @@ -50,6 +50,16 @@ projections: [string, string][]; *** +### sourceNamespace + +```ts +sourceNamespace: string[]; +``` + +Namespace holding the source table; empty is the root namespace. + +*** + ### sourceTable ```ts diff --git a/nodejs/__test__/materialized_view.test.ts b/nodejs/__test__/materialized_view.test.ts index 2e7b2ec4d..b9d8ec911 100644 --- a/nodejs/__test__/materialized_view.test.ts +++ b/nodejs/__test__/materialized_view.test.ts @@ -48,6 +48,28 @@ describe("materialized views", () => { expect(definitionFromMetadata(safe, "v").limit).toBe(42); }); + it("reads the namespaced select kind and refuses unknown kinds", () => { + // "namespaced_select" is the namespaced form of "select": same shape, a + // separate kind so readers that predate it refuse instead of resolving + // the source at the root. + const namespaced = new Map([ + [ + DEFINITION_META_KEY, + '{"kind":"namespaced_select","source_table":"people","source_namespace":["ns"]}', + ], + ]); + const definition = definitionFromMetadata(namespaced, "v"); + expect(definition.sourceTable).toBe("people"); + expect(definition.sourceNamespace).toEqual(["ns"]); + + const unknown = new Map([ + [DEFINITION_META_KEY, '{"kind":"select_v3","source_table":"people"}'], + ]); + expect(() => definitionFromMetadata(unknown, "v")).toThrow( + /cannot refresh/, + ); + }); + it("creates, refreshes and queries a view", async () => { const view = await db.createMaterializedView("adults", "people", { select: ["name", ["shout", "upper(name)"]], diff --git a/nodejs/lancedb/materialized_view.ts b/nodejs/lancedb/materialized_view.ts index b26dee59e..1d47b640a 100644 --- a/nodejs/lancedb/materialized_view.ts +++ b/nodejs/lancedb/materialized_view.ts @@ -19,6 +19,8 @@ export interface MaterializedViewDefinition { limit?: number; /** Source columns the projections and filter read. */ inputs: string[]; + /** Namespace holding the source table; empty is the root namespace. */ + sourceNamespace: string[]; } /** @@ -78,7 +80,8 @@ export function definitionFromMetadata( } // biome-ignore lint/suspicious/noExplicitAny: raw JSON const value: any = JSON.parse(raw); - if (value.kind !== "select") { + // "namespaced_select" keeps older readers from resolving the source at root. + if (value.kind !== "select" && value.kind !== "namespaced_select") { throw new Error( `materialized view '${name}' is defined by '${value.kind}', which this ` + "version of lancedb cannot refresh", @@ -103,6 +106,7 @@ export function definitionFromMetadata( filter: value.filter ?? undefined, limit, inputs: value.inputs ?? [], + sourceNamespace: value.source_namespace ?? [], }; } diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py index 5abb44dc0..c52a2d7a9 100644 --- a/python/python/lancedb/materialized_view.py +++ b/python/python/lancedb/materialized_view.py @@ -42,6 +42,8 @@ class MaterializedViewDefinition: """Cap on the number of rows the view holds.""" inputs: List[str] = field(default_factory=list) """Source columns the projections and filter read.""" + source_namespace: List[str] = field(default_factory=list) + """Namespace holding the source table; empty is the root namespace.""" def _definition_from_schema( @@ -53,7 +55,8 @@ def _definition_from_schema( raise ValueError(f"Table '{name}' is not a materialized view") value = json.loads(raw) kind = value.get("kind") - if kind != "select": + # "namespaced_select" keeps older readers from resolving the source at root. + if kind not in ("select", "namespaced_select"): raise NotImplementedError( f"materialized view '{name}' is defined by '{kind}', which this " "version of lancedb cannot refresh" @@ -66,6 +69,7 @@ def _definition_from_schema( filter=value.get("filter"), limit=value.get("limit"), inputs=value.get("inputs", []), + source_namespace=value.get("source_namespace", []), ) diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index 5fa3aa4fb..5cd7b23d6 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -266,3 +266,38 @@ async def test_async_namespace_connection_materialized_views(tmp_path): handle._route_pushdown_to_rust == through_namespace._route_pushdown_to_rust ) assert handle._namespace_path == through_namespace._namespace_path + + +def test_namespaced_select_kind_is_read_and_unknown_kinds_are_refused(): + import json + + import pyarrow as pa + + from lancedb.materialized_view import _definition_from_schema + + def schema_with(definition: dict) -> pa.Schema: + return pa.schema([pa.field("id", pa.int32())]).with_metadata( + {b"mv.definition": json.dumps(definition).encode()} + ) + + # "namespaced_select" is the namespaced form of "select": same shape, + # a separate kind so readers that predate it refuse instead of + # resolving the source at the root. + definition = _definition_from_schema( + schema_with( + { + "kind": "namespaced_select", + "source_table": "people", + "source_namespace": ["ns"], + "projections": [{"output": "name", "expression": "name"}], + } + ), + "v", + ) + assert definition.source_table == "people" + assert definition.source_namespace == ["ns"] + + with pytest.raises(NotImplementedError, match="cannot refresh"): + _definition_from_schema( + schema_with({"kind": "select_v3", "source_table": "people"}), "v" + ) diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 08d6c921e..ec77c1181 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -74,8 +74,15 @@ const EMBEDDING_FUNCTIONS_META_KEY: &str = "embedding_functions"; const COLUMN_DEFINITIONS_META_KEY: &str = "lancedb::column_definitions"; /// Value of the definition's `kind` tag for the projected `select` form. +/// Reserved for root-namespace sources; see [`NAMESPACED_SELECT_KIND`]. pub const SELECT_KIND: &str = "select"; +/// The `select` form over a namespaced source: its own kind, because released +/// readers drop unknown fields and resolve a `select` source at the root, so +/// this routes them to the [`MaterializedViewKind::Unrecognized`] refusal +/// instead of a wrong-table refresh. +pub const NAMESPACED_SELECT_KIND: &str = "namespaced_select"; + /// Which view outputs each source column is projected to directly. A column /// may be projected more than once, so each carries every name the view gives /// it, in projection order. @@ -95,6 +102,10 @@ pub struct ViewProjection { pub struct MaterializedViewDefinition { /// Name of the source table, in the same database as the view. pub source_table: String, + /// Namespace path holding the source table; empty is the root namespace. + /// A definition written before namespaced sources reads as root. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub source_namespace: Vec, /// The projected output columns, in view schema order. pub projections: Vec, /// SQL predicate selecting the source rows the view holds. @@ -129,7 +140,12 @@ pub(crate) fn definition_to_metadata(definition: &MaterializedViewDefinition) -> let mut value = serde_json::to_value(definition).map_err(|e| Error::Runtime { message: format!("failed to serialize view definition: {e}"), })?; - value["kind"] = serde_json::Value::String(SELECT_KIND.to_string()); + let kind = if definition.source_namespace.is_empty() { + SELECT_KIND + } else { + NAMESPACED_SELECT_KIND + }; + value["kind"] = serde_json::Value::String(kind.to_string()); Ok(value.to_string()) } @@ -150,12 +166,21 @@ pub fn materialized_view_kind( .get("kind") .and_then(|k| k.as_str()) .ok_or_else(|| unreadable(&"missing kind tag"))?; - if kind != SELECT_KIND { + if kind != SELECT_KIND && kind != NAMESPACED_SELECT_KIND { return Ok(Some(MaterializedViewKind::Unrecognized { kind: kind.to_string(), })); } - let definition = serde_json::from_value(value).map_err(|e| unreadable(&e))?; + let kind = kind.to_string(); + let definition: MaterializedViewDefinition = + serde_json::from_value(value).map_err(|e| unreadable(&e))?; + // No correct writer produces a kind that disagrees with its namespace. + if (kind == SELECT_KIND) != definition.source_namespace.is_empty() { + return Err(unreadable(&format!( + "kind '{kind}' does not match its source namespace {:?}", + definition.source_namespace + ))); + } Ok(Some(MaterializedViewKind::Select(definition))) } @@ -166,6 +191,7 @@ pub fn materialized_view_kind( pub(crate) fn plan( source_schema: SchemaRef, source_table: &str, + source_namespace: &[String], projections: &[(String, String)], filter: Option<&str>, limit: Option, @@ -319,6 +345,7 @@ pub(crate) fn plan( let definition = MaterializedViewDefinition { source_table: source_table.to_string(), + source_namespace: source_namespace.to_vec(), projections: projections .into_iter() .map(|(output, expression)| ViewProjection { output, expression }) @@ -602,7 +629,7 @@ pub struct PreparedDeclaration { definition: MaterializedViewDefinition, /// The source's own database: the only place /// [`PreparedDeclaration::create`] will put the view, because refresh - /// resolves the recorded source name through the view's database. + /// resolves the recorded source coordinate through the view's database. database: Arc, } @@ -622,10 +649,21 @@ impl PreparedDeclaration { /// Create the view table and verify it, consuming the declaration. /// - /// The view goes in the source's own database, where refresh resolves the - /// recorded source name. Stable row ids are requested at both levels and - /// verified rather than trusted; nothing is rolled back on failure. + /// The view goes at the root of the source's own database, where refresh + /// resolves the recorded source coordinate. Stable row ids are requested + /// at both levels and verified rather than trusted; nothing is rolled + /// back on failure. pub async fn create(self, name: &str) -> Result { + self.create_in(&[], name).await + } + + /// Create the view in `namespace_path`, empty for the root namespace. + /// Otherwise [`PreparedDeclaration::create`]. + pub async fn create_in( + self, + namespace_path: &[String], + name: &str, + ) -> Result { let empty: Vec> = vec![]; // Minted here, not at preparation: a declaration can be cloned and @@ -640,6 +678,7 @@ impl PreparedDeclaration { let reader: Box = Box::new(arrow_array::RecordBatchIterator::new(empty, schema)); let mut request = CreateTableRequest::new(name.to_string(), Box::new(reader)); + request.namespace_path = namespace_path.to_vec(); let write_params = request .write_options .lance_write_params @@ -680,8 +719,8 @@ impl PreparedDeclaration { /// Validate a view declaration against its live source and hold what its /// creation needs. The declaration is canonicalized through the coordinate a -/// refresh will resolve, so a handle that does not resolve back to itself is -/// rejected, as is a namespaced source. Same creation-time checks as +/// refresh will resolve -- name and namespace both -- so a handle that does +/// not resolve back to itself is rejected. Same creation-time checks as /// [`Connection::create_materialized_view`]. /// /// ```no_run @@ -710,17 +749,9 @@ pub async fn prepare_declaration( message: "materialized views are supported only on local databases".into(), }); }; - // The definition records the source by bare name; any other source - // form would be recorded as a name its refresh cannot resolve. - if !source.namespace().is_empty() { - return Err(Error::NotSupported { - message: format!( - "a namespaced source cannot be recorded in a view definition; \ - '{}' must be a root-namespace table", - source.name() - ), - }); - } + // Refresh resolves the source at exactly this coordinate, so the + // definition records the namespace alongside the name. + let source_namespace = source.namespace().to_vec(); let database = source .database_opt() .ok_or_else(|| Error::InvalidInput { @@ -734,7 +765,7 @@ pub async fn prepare_declaration( let resolved = database .open_table(OpenTableRequest { name: source.name().to_string(), - namespace_path: vec![], + namespace_path: source_namespace.clone(), index_cache_size: None, lance_read_params: None, location: None, @@ -780,6 +811,7 @@ pub async fn prepare_declaration( let (definition, mut fields, lineage) = plan( source_schema.clone(), resolved.name(), + &source_namespace, projections, filter, limit, @@ -839,7 +871,9 @@ fn ensure_local(connection: &Connection) -> Result<()> { pub struct CreateMaterializedViewBuilder { connection: Connection, name: String, + namespace: Vec, source: String, + source_namespace: Vec, projections: Vec<(String, String)>, filter: Option, limit: Option, @@ -850,13 +884,28 @@ impl CreateMaterializedViewBuilder { Self { connection, name, + namespace: Vec::new(), source, + source_namespace: Vec::new(), projections: Vec::new(), filter: None, limit: None, } } + /// The namespace to create the view in. Defaults to the root namespace. + pub fn namespace(mut self, namespace_path: Vec) -> Self { + self.namespace = namespace_path; + self + } + + /// The namespace holding the source table; recorded in the definition + /// for refresh to resolve. Defaults to the root namespace. + pub fn source_namespace(mut self, namespace_path: Vec) -> Self { + self.source_namespace = namespace_path; + self + } + /// The view's columns, as `(name, SQL expression)` pairs. Not calling /// this selects every source column, expanded at creation time. pub fn select( @@ -887,7 +936,12 @@ impl CreateMaterializedViewBuilder { /// provenance across compaction, and cannot be enabled later. pub async fn execute(self) -> Result { ensure_local(&self.connection)?; - let source = self.connection.open_table(&self.source).execute().await?; + let source = self + .connection + .open_table(&self.source) + .namespace(self.source_namespace.clone()) + .execute() + .await?; let prepared = prepare_declaration( &source, &self.projections, @@ -895,7 +949,7 @@ impl CreateMaterializedViewBuilder { self.limit, ) .await?; - prepared.create(&self.name).await + prepared.create_in(&self.namespace, &self.name).await } } @@ -1152,6 +1206,7 @@ mod tests { view.definition(), &MaterializedViewDefinition { source_table: "people".into(), + source_namespace: Vec::new(), projections: vec![ ViewProjection { output: "name".into(), @@ -2083,33 +2138,138 @@ mod tests { .await .unwrap_err(); assert!(err.to_string().contains("custom_loc"), "{err}"); + } - // A namespaced source cannot be recorded in the definition: the - // bare name refresh resolves would reach a different table or none. - let namespaced = crate::table::NativeTable::create( - "memory://ns_src", - "ns_src", - vec!["ns".to_string()], - Box::new(arrow_array::RecordBatchIterator::new( - vec![], - std::sync::Arc::new(arrow_schema::Schema::new(vec![arrow_schema::Field::new( - "id", - arrow_schema::DataType::Int32, - true, - )])), - )) as Box, - None, - None, - None, - None, - std::collections::HashSet::new(), - ) + /// A view declared over a namespaced source records that namespace, and + /// refresh resolves the source through it -- the coordinate round-trips. + #[tokio::test] + async fn a_namespaced_source_round_trips_through_refresh() { + use lance_namespace::models::CreateNamespaceRequest; + + let tmp = tempfile::tempdir().unwrap(); + let mut properties = std::collections::HashMap::new(); + properties.insert("root".to_string(), tmp.path().to_str().unwrap().to_string()); + let conn = crate::connect_namespace("dir", properties) + .execute() + .await + .unwrap(); + conn.create_namespace(CreateNamespaceRequest { + id: Some(vec!["ns".into()]), + ..Default::default() + }) .await .unwrap(); - let namespaced = Table::new(std::sync::Arc::new(namespaced), conn.database().clone()); - let err = prepare_declaration(&namespaced, &[], None, None) + + let batch = record_batch!( + ("name", Utf8, ["ada", "grace", "alan"]), + ("age", Int32, [36, 85, 41]) + ) + .unwrap(); + conn.create_table("people", batch) + .namespace(vec!["ns".to_string()]) + .write_options(stable_row_ids()) + .execute() .await - .unwrap_err(); - assert!(err.to_string().contains("namespaced source"), "{err}"); + .unwrap(); + + // A decoy of the same name at the root: resolving the source at the + // wrong namespace materializes one row here instead of three. + let decoy = record_batch!(("name", Utf8, ["mallory"]), ("age", Int32, [42])).unwrap(); + conn.create_table("people", decoy) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap(); + + let view = conn + .create_materialized_view("adults", "people") + .namespace(vec!["ns".to_string()]) + .source_namespace(vec!["ns".to_string()]) + .select([("name", "name")]) + .only_if("age >= 18") + .execute() + .await + .unwrap(); + + assert_eq!(view.definition().source_table, "people"); + assert_eq!(view.definition().source_namespace, vec!["ns".to_string()]); + assert_eq!(view.table().namespace(), &["ns"]); + + // Refresh resolves the source at the recorded namespace, not at root. + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.rows_written, 3); + } + + /// A definition stored before namespaced sources existed carries no + /// namespace key and must read as the root namespace. + #[test] + fn a_definition_without_a_namespace_reads_as_root() { + let stored = + r#"{"source_table":"people","projections":[{"output":"name","expression":"name"}]}"#; + let definition: MaterializedViewDefinition = serde_json::from_str(stored).unwrap(); + assert!(definition.source_namespace.is_empty()); + } + + fn definition(source_namespace: Vec) -> MaterializedViewDefinition { + MaterializedViewDefinition { + source_table: "people".to_string(), + source_namespace, + projections: vec![ViewProjection { + output: "name".to_string(), + expression: "name".to_string(), + }], + filter: None, + limit: None, + inputs: vec!["name".to_string()], + } + } + + /// A root definition keeps the pre-namespace `select` form byte-stably; + /// a namespaced one moves off `select`, which sends pre-namespace readers + /// to the `Unrecognized` refusal instead of a root resolve. + #[test] + fn a_namespaced_definition_is_refused_by_the_pre_namespace_reader() { + let root = definition_to_metadata(&definition(Vec::new())).unwrap(); + let root: serde_json::Value = serde_json::from_str(&root).unwrap(); + assert_eq!(root["kind"], "select"); + assert!( + root.get("source_namespace").is_none(), + "a root definition must not grow new keys: {root}" + ); + + let stored = definition_to_metadata(&definition(vec!["ns".to_string()])).unwrap(); + let value: serde_json::Value = serde_json::from_str(&stored).unwrap(); + // The pre-namespace discriminator is `kind == "select"`; anything + // else lands in its Unrecognized refusal rather than in a root open. + assert_eq!(value["kind"], "namespaced_select"); + + // The current reader round-trips the coordinate. + let metadata = HashMap::from([(DEFINITION_META_KEY.to_string(), stored)]); + match materialized_view_kind(&metadata).unwrap() { + Some(MaterializedViewKind::Select(read)) => { + assert_eq!(read.source_namespace, vec!["ns".to_string()]) + } + other => panic!("expected the namespaced select form, got {other:?}"), + } + } + + /// A kind that disagrees with its namespace is an error, not a view: + /// under `select` it is the shape old readers would resolve at the root. + #[test] + fn a_kind_namespace_mismatch_is_refused() { + for (kind, namespace) in [ + (SELECT_KIND, vec!["ns".to_string()]), + (NAMESPACED_SELECT_KIND, Vec::new()), + ] { + let mut value = serde_json::to_value(definition(namespace)).unwrap(); + value["kind"] = serde_json::Value::String(kind.to_string()); + let metadata = HashMap::from([(DEFINITION_META_KEY.to_string(), value.to_string())]); + let err = materialized_view_kind(&metadata).unwrap_err(); + assert!( + err.to_string() + .contains("does not match its source namespace"), + "kind '{kind}': {err}" + ); + } } } diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index b967e81f8..efddd1c7b 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -170,6 +170,7 @@ pub(crate) async fn execute_refresh( let (replanned, mut planned_fields, _renames) = super::plan( source_schema, &definition.source_table, + &definition.source_namespace, &projections, definition.filter.as_deref(), definition.limit, @@ -590,7 +591,7 @@ async fn open_source(view: &Table, definition: &MaterializedViewDefinition) -> R let source = database .open_table(OpenTableRequest { name: definition.source_table.clone(), - namespace_path: Vec::new(), + namespace_path: definition.source_namespace.clone(), index_cache_size: None, lance_read_params: None, location: None, @@ -2919,6 +2920,7 @@ mod tests { let replacement = crate::materialized_view::MaterializedViewDefinition { source_table: "src".into(), + source_namespace: Vec::new(), projections: vec![ crate::materialized_view::ViewProjection { output: "x".into(), @@ -2958,6 +2960,7 @@ mod tests { let narrower = crate::materialized_view::MaterializedViewDefinition { source_table: "src".into(), + source_namespace: Vec::new(), projections: vec![crate::materialized_view::ViewProjection { output: "x".into(), expression: "x".into(), From 7ebd3c222dfb6ae8b5e1fa8cd833572ca0a0a1ad Mon Sep 17 00:00:00 2001 From: Lance Release Date: Tue, 1 Sep 2026 13:15:27 +0000 Subject: [PATCH 165/206] =?UTF-8?q?Bump=20version:=200.38.0=20=E2=86=92=20?= =?UTF-8?q?0.39.0-beta.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index b88c14615..5bec58ffd 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.38.0" +current_version = "0.39.0-beta.0" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index d1f4675a9..2c1412d63 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5402,7 +5402,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.38.0" +version = "0.39.0-beta.0" dependencies = [ "ahash", "anyhow", @@ -5490,7 +5490,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.38.0" +version = "0.39.0-beta.0" dependencies = [ "arrow-array", "arrow-buffer", @@ -5515,7 +5515,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.38.0" +version = "0.39.0-beta.0" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index f3e7952f4..5660ea70d 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.38.0 + 0.39.0-beta.0 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 6a9059119..09aa7ed16 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.38.0-final.0 + 0.39.0-beta.0 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 91ece16a1..dd68f9c47 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.38.0-final.0 + 0.39.0-beta.0 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index b6f006327..98820f265 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.38.0" +version = "0.39.0-beta.0" 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 68ce67487..3a16bb193 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.38.0", + "version": "0.39.0-beta.0", "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 4cb228b9e..e3b1db92f 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.38.0", + "version": "0.39.0-beta.0", "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 ad22eecb7..7922272cb 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.38.0", + "version": "0.39.0-beta.0", "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 e6a8c566b..8d6c41f1a 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.38.0", + "version": "0.39.0-beta.0", "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 8c33306d3..eb26fccfb 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.38.0", + "version": "0.39.0-beta.0", "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 97977353e..e7b519cf3 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.38.0", + "version": "0.39.0-beta.0", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 6a1cb0f41..f8c517788 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.38.0", + "version": "0.39.0-beta.0", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 857952b5c..515aa13c0 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.38.0", + "version": "0.39.0-beta.0", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 7cbe5d418..bda38ac39 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.38.0" +version = "0.39.0-beta.0" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index faababd08..938be1a39 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.38.0" +version = "0.39.0-beta.0" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 193c5e34585f25bf85fb53451e76d0e1c1f28323 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 1 Sep 2026 23:50:57 +0800 Subject: [PATCH 166/206] feat: add list_functions client APIs (#4108) Function registration and exact lookup are exposed through the SDK, but clients cannot discover published versions even though the server provides `POST /v1/functions/list`. Add Rust and Python sync/async `list_functions()` APIs that return typed `FunctionVersion` values. The remote client requests canonical definitions and follows opaque page tokens until the listing is complete, including empty intermediate pages, while preserving the server's name/version ordering. Local databases retain the existing Function-catalog unsupported error. The SDK consumes protocol pagination internally so callers receive the complete catalog rather than handling server-specific page tokens. --- python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/db.py | 33 ++++ python/python/lancedb/remote/db.py | 4 + .../tests/test_first_class_function_slice2.py | 61 +++++++ python/src/connection.rs | 13 ++ rust/lancedb/src/connection.rs | 22 +++ rust/lancedb/src/database.rs | 4 + rust/lancedb/src/remote/db.rs | 165 +++++++++++++++++- 8 files changed, 302 insertions(+), 1 deletion(-) diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 2b2691139..78826df92 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -150,6 +150,7 @@ class Connection(object): def job(self, job_id: str) -> Job: ... async def create_function_async(self, request_json: str) -> Job: ... async def get_function(self, name: str, version: str) -> str: ... + async def list_functions(self) -> List[str]: ... async def drop_function(self, name: str, version: str) -> bool: ... async def list_jobs(self) -> List[JobInfo]: ... async def get_job(self, job_id: str) -> Optional[JobDescription]: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index ecaae42f8..2554e9908 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -712,6 +712,24 @@ class DBConnection(EnforceOverrides): "Function catalog operations are not supported for this connection type" ) + def list_functions(self) -> List[FunctionVersion]: + """List every published immutable Function version. + + Results are ordered by Function name then version. Local connections + raise ``NotImplementedError``. + + Examples + -------- + List the identities available to use in Function-backed columns: + + ```python + [(function.name, function.version) for function in db.list_functions()] + ``` + """ + raise NotImplementedError( + "Function catalog operations are not supported for this connection type" + ) + def drop_function(self, name: str, *, version: str) -> bool: """Drop one exact immutable Function version from the remote catalog. @@ -1423,6 +1441,10 @@ class LanceDBConnection(DBConnection): def get_function(self, name: str, *, version: str) -> FunctionVersion: return LOOP.run(self._conn.get_function(name, version=version)) + @override + def list_functions(self) -> List[FunctionVersion]: + return LOOP.run(self._conn.list_functions()) + @override def drop_function(self, name: str, *, version: str) -> bool: return LOOP.run(self._conn.drop_function(name, version=version)) @@ -2257,6 +2279,17 @@ class AsyncConnection(object): """Open one exact immutable Function version from the remote catalog.""" return FunctionVersion.from_json(await self._inner.get_function(name, version)) + async def list_functions(self) -> List[FunctionVersion]: + """List every published immutable Function version. + + Results are ordered by Function name then version. Local connections + raise ``NotImplementedError``. + """ + return [ + FunctionVersion.from_json(value) + for value in await self._inner.list_functions() + ] + async def drop_function(self, name: str, *, version: str) -> bool: """Drop one exact immutable Function version from the remote catalog.""" return await self._inner.drop_function(name, version) diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 27e21d200..0e95e035b 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -749,6 +749,10 @@ class RemoteDBConnection(DBConnection): def get_function(self, name: str, *, version: str) -> FunctionVersion: return LOOP.run(self._conn.get_function(name, version=version)) + @override + def list_functions(self) -> List[FunctionVersion]: + return LOOP.run(self._conn.list_functions()) + @override def drop_function(self, name: str, *, version: str) -> bool: return LOOP.run(self._conn.drop_function(name, version=version)) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 57b08e18d..b1308a2bc 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -1017,6 +1017,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="fv_exact") + with pytest.raises(NotImplementedError, match=message): + db.list_functions() with pytest.raises(NotImplementedError, match=message): db.drop_function("normalize_score", version="fv_exact") @@ -1064,6 +1066,22 @@ def _mock_remote_function_catalog(): "version": "fv_exact", } response = state["version"] + elif self.path == "/v1/functions/list": + assert body["include_definition"] is True + if "page_token" not in body: + response = { + "functions": [ + { + "name": "normalize_score", + "version": "fv_exact", + "definition": state["version"], + } + ], + "page_token": "next", + } + else: + assert body["page_token"] == "next" + response = {"functions": []} elif self.path == "/v1/functions/drop": assert body == { "name": "normalize_score", @@ -1130,6 +1148,49 @@ def test_blocking_remote_registration_returns_function_version(): ] +def test_remote_list_functions_paginates_and_returns_typed_versions(): + with _mock_remote_function_catalog() as (host, state): + db = lancedb.connect( + "db://dev", + api_key="fake", + host_override=host, + client_config={"retry_config": {"retries": 0}}, + ) + created = db.create_function(normalize_score) + state["requests"].clear() + functions = db.list_functions() + + assert functions == [created] + assert state["requests"] == [ + ("/v1/functions/list", {"include_definition": True}), + ( + "/v1/functions/list", + {"include_definition": True, "page_token": "next"}, + ), + ] + + +@pytest.mark.asyncio +async def test_async_remote_list_functions_returns_typed_versions(): + with _mock_remote_function_catalog() as (host, state): + db = await lancedb.connect_async( + "db://dev", + api_key="fake", + host_override=host, + client_config={"retry_config": {"retries": 0}}, + ) + registration = await db.create_function_async(normalize_score) + created = await registration.wait() + state["requests"].clear() + functions = await db.list_functions() + + assert functions == [created] + assert [path for path, _ in state["requests"]] == [ + "/v1/functions/list", + "/v1/functions/list", + ] + + def test_remote_drop_function_sends_exact_version(): with _mock_remote_function_catalog() as (host, state): db = lancedb.connect( diff --git a/python/src/connection.rs b/python/src/connection.rs index fc835f805..5477ab3d2 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -629,6 +629,19 @@ impl Connection { }) } + pub fn list_functions(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + inner + .list_functions() + .await + .infer_error()? + .into_iter() + .map(|function| function.to_canonical_json().infer_error()) + .collect::>>() + }) + } + pub fn drop_function( self_: PyRef<'_, Self>, name: String, diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 943ad51b7..35c5c0737 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -523,6 +523,28 @@ impl Connection { .await } + /// List every published immutable Function version in the remote catalog. + /// + /// Results are ordered by Function name then version. The client walks all + /// server pages before returning. Local databases return + /// [`Error::NotSupported`]. + /// + /// # Example + /// + /// ```no_run + /// # async fn list_functions( + /// # connection: &lancedb::Connection, + /// # ) -> Result<(), Box> { + /// for function in connection.list_functions().await? { + /// println!("{} {}", function.name(), function.version()); + /// } + /// # Ok(()) + /// # } + /// ``` + pub async fn list_functions(&self) -> Result> { + self.internal.list_functions().await + } + /// Drop one exact immutable Function version from the remote catalog. /// /// Returns `true` when the server appended a Dropped transition and diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 775b0b579..61424bb05 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -307,6 +307,10 @@ pub trait Database: ) -> Result { function_catalog_not_supported() } + /// List every published immutable Function version in the remote catalog. + async fn list_functions(&self) -> Result> { + function_catalog_not_supported() + } /// Drop one exact immutable Function version from the remote catalog. async fn drop_function(&self, _name: &str, _version: &str) -> Result { function_catalog_not_supported() diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 39b258a63..ecdadf464 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; use async_trait::async_trait; @@ -533,6 +533,19 @@ struct RemoteListJobsResponse { page_token: Option, } +#[derive(serde::Deserialize)] +struct RemoteListedFunctionVersion { + definition: FunctionVersion, +} + +#[derive(serde::Deserialize)] +struct RemoteListFunctionsResponse { + #[serde(default)] + functions: Vec, + #[serde(default)] + page_token: Option, +} + #[derive(serde::Deserialize)] struct RemoteDropFunctionResponse { dropped: bool, @@ -588,6 +601,43 @@ impl Database for RemoteDatabase { response.json().await.err_to_http(request_id) } + async fn list_functions(&self) -> Result> { + let mut functions = Vec::new(); + let mut page_token: Option = None; + let mut seen_page_tokens = HashSet::new(); + loop { + let mut body = serde_json::json!({ "include_definition": true }); + if let Some(token) = &page_token { + body["page_token"] = serde_json::Value::String(token.clone()); + } + let req = self.client.post("/v1/functions/list").json(&body); + let (request_id, response) = self.client.send(req).await?; + let response = self.client.check_response(&request_id, response).await?; + let status = response.status(); + let response: RemoteListFunctionsResponse = + response.json().await.err_to_http(request_id.clone())?; + functions.extend( + response + .functions + .into_iter() + .map(|listed| listed.definition), + ); + let Some(next_page_token) = response.page_token.filter(|token| !token.is_empty()) + else { + break; + }; + if !seen_page_tokens.insert(next_page_token.clone()) { + return Err(Error::Http { + source: "Function listing response repeated a page_token".into(), + request_id, + status_code: Some(status), + }); + } + page_token = Some(next_page_token); + } + Ok(functions) + } + async fn drop_function(&self, name: &str, version: &str) -> Result { let req = self .client @@ -2708,6 +2758,119 @@ mod tests { assert_eq!(version.version(), "fv_01K3EXACT"); } + #[tokio::test] + async fn test_list_functions_requests_definitions_and_paginates() { + const VERSION: &str = include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json" + ); + let version: serde_json::Value = serde_json::from_str(VERSION).unwrap(); + let page = Arc::new(AtomicUsize::new(0)); + let conn = Connection::new_with_handler(move |request| { + assert_eq!(request.method(), &reqwest::Method::POST); + assert_eq!(request.url().path(), "/v1/functions/list"); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["include_definition"], true); + match page.fetch_add(1, Ordering::SeqCst) { + 0 => { + assert!(body.get("page_token").is_none()); + http::Response::builder() + .status(200) + .body(r#"{"functions": [], "page_token": "next"}"#.to_string()) + .unwrap() + } + _ => { + assert_eq!(body["page_token"], "next"); + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "functions": [{ + "name": "embed", + "version": "fv_01K3EXACT", + "definition": version.clone(), + }], + }) + .to_string(), + ) + .unwrap() + } + } + }); + let functions = conn.list_functions().await.unwrap(); + assert_eq!(functions.len(), 1); + assert_eq!(functions[0].name(), "embed"); + assert_eq!(functions[0].version(), "fv_01K3EXACT"); + } + + #[tokio::test] + async fn test_list_functions_stops_on_an_empty_page_token() { + let requests = Arc::new(AtomicUsize::new(0)); + let seen = requests.clone(); + let conn = Connection::new_with_handler(move |request| { + seen.fetch_add(1, Ordering::SeqCst); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert!(body.get("page_token").is_none()); + http::Response::builder() + .status(200) + .body(r#"{"functions": [], "page_token": ""}"#) + .unwrap() + }); + + let functions = conn.list_functions().await.unwrap(); + assert!(functions.is_empty()); + assert_eq!(requests.load(Ordering::SeqCst), 1); + } + + #[tokio::test] + async fn test_list_functions_rejects_a_page_token_cycle() { + let page = Arc::new(AtomicUsize::new(0)); + let requests = page.clone(); + let conn = Connection::new_with_handler(move |request| { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + let next_page_token = match page.fetch_add(1, Ordering::SeqCst) { + 0 => { + assert!(body.get("page_token").is_none()); + "one" + } + 1 => { + assert_eq!(body["page_token"], "one"); + "two" + } + 2 => { + assert_eq!(body["page_token"], "two"); + "one" + } + page => panic!("unexpected page: {page}"), + }; + http::Response::builder() + .status(200) + .body( + serde_json::json!({ + "functions": [], + "page_token": next_page_token, + }) + .to_string(), + ) + .unwrap() + }); + + let error = conn.list_functions().await.unwrap_err(); + assert!( + matches!( + &error, + Error::Http { + status_code: Some(http::StatusCode::OK), + .. + } + ), + "got {error:?}" + ); + assert_eq!(requests.load(Ordering::SeqCst), 3); + } + #[tokio::test] async fn test_drop_function_sends_exact_version_and_decodes_replay() { let conn = Connection::new_with_handler(|request| { From e6867f7d0433054b140fc7a3b2c67787029bf3d0 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Tue, 1 Sep 2026 23:51:08 +0800 Subject: [PATCH 167/206] feat: support nested blob function signatures (#4109) Function signatures currently reject Blob v2 fields nested inside structs, preventing UDFs from accepting or returning structured values that contain blobs. Accept canonical Blob v2 fields as direct or recursive struct children while preserving exact field metadata and nullability. Blob fields under list, large-list, fixed-size-list, or map ancestors remain rejected because collection runtime adaptation is outside the supported Function ABI. A whole named struct result can bind directly to one destination column without introducing an extra wrapper level. --- python/python/lancedb/functions.py | 107 ++++++++- .../tests/test_first_class_function_slice2.py | 177 +++++++++++++-- rust/lancedb/src/table/computed_columns.rs | 206 ++++++++++++++++-- 3 files changed, 446 insertions(+), 44 deletions(-) diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 3bdd117cb..2815f7f17 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -521,6 +521,12 @@ class RefreshColumnResult(_RemoteValue): _FUNCTION_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]*$") _FUNCTION_BLOB_V2_TYPE = "blob_v2" +_ARROW_EXTENSION_NAME_KEY = "ARROW:extension:name" +_BLOB_V2_EXTENSION_NAME = "lance.blob.v2" +_NESTED_BLOB_COLLECTION_ERROR = ( + "unsupported Arrow type for Function signature: Blob v2 fields nested under " + "collection types are not supported" +) _GRAMMAR_PRIMITIVES = ( @@ -591,6 +597,19 @@ def _validate_exact_arrow_field(field: pa.Field) -> None: "unsupported Arrow type for Function signature: lance.blob.v2 " f"requires a supported Blob storage layout, got {field}" ) + metadata = { + (key.decode() if isinstance(key, bytes) else key): ( + value.decode() if isinstance(value, bytes) else value + ) + for key, value in (field.metadata or {}).items() + } + if metadata and metadata != { + _ARROW_EXTENSION_NAME_KEY: _BLOB_V2_EXTENSION_NAME + }: + raise TypeError( + "unsupported Arrow type for Function signature: lance.blob.v2 " + "field metadata must contain only its canonical extension marker" + ) elif field.metadata: raise TypeError( "unsupported Arrow type for Function signature: field metadata " @@ -655,23 +674,84 @@ def _canonical_arrow_field(field: pa.Field) -> str: return _canonical_arrow_type(field.type) -def _exact_arrow_field(field: pa.Field) -> dict[str, Any]: +def _blob_storage_type(field: pa.Field) -> pa.DataType: + data_type = field.type + if isinstance(data_type, pa.ExtensionType): + return data_type.storage_type + return data_type + + +def _exact_blob_storage_type(field: pa.Field) -> dict[str, Any]: + storage = _blob_storage_type(field) + if not pa.types.is_struct(storage): + raise TypeError( + "unsupported Arrow type for Function signature: lance.blob.v2 " + "requires struct storage" + ) + return { + "type": "struct", + "fields": [ + { + "name": child.name, + "nullable": child.nullable, + "type": ( + {"type": "large_binary"} + if pa.types.is_large_binary(child.type) + else _exact_arrow_type(child.type) + ), + } + for child in storage + ], + } + + +def _data_type_has_blob_v2(data_type: pa.DataType) -> bool: + if pa.types.is_struct(data_type): + return any( + _is_blob_v2_field(field) or _data_type_has_blob_v2(field.type) + for field in data_type + ) + if ( + pa.types.is_list(data_type) + or pa.types.is_large_list(data_type) + or pa.types.is_fixed_size_list(data_type) + ): + field = data_type.value_field + return _is_blob_v2_field(field) or _data_type_has_blob_v2(field.type) + if pa.types.is_map(data_type): + return any( + _is_blob_v2_field(field) or _data_type_has_blob_v2(field.type) + for field in (data_type.key_field, data_type.item_field) + ) + return False + + +def _exact_arrow_field( + field: pa.Field, *, inside_collection: bool = False +) -> dict[str, Any]: _validate_exact_arrow_field(field) if _is_blob_v2_field(field): - raise TypeError( - "unsupported Arrow type for Function signature: nested Blob v2 " - "fields are not supported; declare Blob parameters or named result " - "fields directly" - ) + if inside_collection: + raise TypeError(_NESTED_BLOB_COLLECTION_ERROR) + return { + "name": field.name, + "nullable": field.nullable, + "type": _exact_blob_storage_type(field), + "metadata": { + _ARROW_EXTENSION_NAME_KEY: _BLOB_V2_EXTENSION_NAME, + }, + } value = { "name": field.name, "nullable": field.nullable, - "type": _exact_arrow_type(field.type), + "type": _exact_arrow_type(field.type, inside_collection=inside_collection), } return value -def _exact_arrow_type(data_type: pa.DataType) -> dict[str, Any]: +def _exact_arrow_type( + data_type: pa.DataType, *, inside_collection: bool = False +) -> dict[str, Any]: for candidate, name in _GRAMMAR_PRIMITIVES: if data_type == candidate: return {"type": name} @@ -685,7 +765,10 @@ def _exact_arrow_type(data_type: pa.DataType) -> dict[str, Any]: ) return { "type": "struct", - "fields": [_exact_arrow_field(field) for field in fields], + "fields": [ + _exact_arrow_field(field, inside_collection=inside_collection) + for field in fields + ], } if ( pa.types.is_list(data_type) @@ -710,11 +793,15 @@ def _exact_arrow_type(data_type: pa.DataType) -> dict[str, Any]: if pa.types.is_large_list(data_type) else "fixed_size_list" ), - "fields": [_exact_arrow_field(data_type.value_field)], + "fields": [ + _exact_arrow_field(data_type.value_field, inside_collection=True) + ], } 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) raise TypeError(f"unsupported Arrow type for Function signature: {data_type}") diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index b1308a2bc..d8a9aeebf 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -668,6 +668,167 @@ def test_blob_fields_use_the_scalar_function_semantic_type(): assert signature.output.arrow_type == "blob_v2" +def test_whole_named_struct_function_can_include_a_blob_result_field(): + @udf( + input_schema=pa.schema([lancedb.blob("image", nullable=False)]), + output_schema=pa.field( + "payload", + pa.struct( + [ + pa.field("mime_type", pa.string(), nullable=False), + lancedb.blob("image", nullable=False), + ] + ), + nullable=False, + ), + ) + def inspect_blob(image): + return {"mime_type": "image/png", "image": image} + + output = inspect_blob.registration_request.signature.output + assert output.kind == "named_struct" + assert [(field.name, field.arrow_type) for field in output.fields] == [ + ("mime_type", "utf8"), + ("image", "blob_v2"), + ] + + +def test_struct_blob_signature_fields_preserve_exact_metadata_and_nullability(): + nested_input = pa.field( + "payload", + pa.struct( + [ + pa.field("mime_type", pa.string(), nullable=False), + pa.field( + "nested", + pa.struct([lancedb.blob("image", nullable=True)]), + nullable=True, + ), + ] + ), + nullable=True, + ) + nested_output = pa.field( + "result", + pa.struct( + [ + pa.field("mime_type", pa.string(), nullable=False), + pa.field( + "nested", + pa.struct([lancedb.blob("image", nullable=True)]), + nullable=False, + ), + ] + ), + nullable=False, + ) + + @udf(input_schema=pa.schema([nested_input]), output_schema=nested_output) + def copy_payload(payload): + return payload + + signature = copy_payload.registration_request.signature + input_type = json.loads(signature.inputs[0].arrow_type) + assert input_type["fields"][1]["nullable"] is True + input_blob = input_type["fields"][1]["type"]["fields"][0] + assert input_blob["nullable"] is True + assert input_blob["metadata"] == {"ARROW:extension:name": "lance.blob.v2"} + + assert signature.output.kind == "named_struct" + nested_result = next( + field for field in signature.output.fields if field.name == "nested" + ) + output_type = json.loads(nested_result.arrow_type) + output_blob = output_type["fields"][0] + assert output_blob["nullable"] is True + assert output_blob["metadata"] == {"ARROW:extension:name": "lance.blob.v2"} + + +def test_struct_blob_signature_supports_multiple_struct_levels(): + recursive = pa.field( + "value", + pa.struct( + [ + pa.field( + "level_1", + pa.struct( + [ + pa.field( + "level_2", + pa.struct([lancedb.blob("image", nullable=False)]), + nullable=False, + ) + ] + ), + nullable=False, + ) + ] + ), + nullable=False, + ) + + @udf( + input_schema=pa.schema([recursive]), + output_schema=pa.field("size", pa.int64(), nullable=False), + ) + def blob_size(value): + return len(value["level_1"]["level_2"]["image"]) + + encoded = json.loads(blob_size.registration_request.signature.inputs[0].arrow_type) + blob = encoded["fields"][0]["type"]["fields"][0]["type"]["fields"][0] + assert blob["metadata"]["ARROW:extension:name"] == "lance.blob.v2" + + +@pytest.mark.parametrize( + "data_type", + [ + pa.list_(lancedb.blob("item", nullable=False)), + pa.large_list(lancedb.blob("item", nullable=False)), + pa.list_(lancedb.blob("item", nullable=False), 2), + pa.map_(pa.string(), lancedb.blob("value", nullable=False).type), + ], +) +def test_blob_signature_rejects_collection_ancestors(data_type): + with pytest.raises( + TypeError, + match="Blob v2 fields nested under collection types are not supported", + ): + + @udf( + input_schema=pa.schema([pa.field("value", data_type, nullable=False)]), + output_schema=pa.field("size", pa.int64(), nullable=False), + ) + def blob_size(value): + return len(value) + + +def test_blob_signature_rejects_collection_below_a_struct(): + nested = pa.field( + "value", + pa.struct( + [ + pa.field( + "images", + pa.list_(lancedb.blob("item", nullable=False)), + nullable=False, + ) + ] + ), + nullable=False, + ) + with pytest.raises( + TypeError, + match="Blob v2 fields nested under collection types are not supported", + ): + + @udf( + input_schema=pa.schema([nested]), + output_schema=pa.field("size", pa.int64(), nullable=False), + ) + def blob_size(value): + return len(value["images"]) + + def test_named_struct_function_can_include_a_blob_result_field(): @udf( input_schema=pa.schema([lancedb.blob("image", nullable=False)]), @@ -729,22 +890,6 @@ def test_blob_marker_rejects_invalid_storage_layout(): return len(image) -def test_nested_blob_signature_field_has_a_clear_error(): - nested = pa.field( - "value", - pa.struct([lancedb.blob("image", nullable=False)]), - nullable=False, - ) - with pytest.raises(TypeError, match="nested Blob v2 fields are not supported"): - - @udf( - input_schema=pa.schema([nested]), - output_schema=pa.field("size", pa.int64(), nullable=False), - ) - def blob_size(value): - return len(value["image"]) - - def test_nested_non_blob_extension_is_not_silently_unwrapped(): class TestExtension(pa.ExtensionType): def __init__(self): diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 77e3d0a4d..085876a81 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -589,16 +589,13 @@ fn canonical_input_arrow_type(field: &JsonArrowField) -> Result { .and_then(|metadata| metadata.get(ARROW_EXT_NAME_KEY)) .map(String::as_str) == Some(BLOB_V2_EXT_NAME); - if is_blob_v2 { + if is_blob_v2 || field.r#type.fields.is_some() { let arrow_field = lance_namespace::schema::convert_json_arrow_field(field) .map_err(|e| invalid_function(format!("invalid Function input field: {e}")))?; - if !has_supported_blob_v2_layout(&arrow_field) { - return Err(invalid_function(format!( - "Function input '{}' has an invalid Blob v2 storage layout", - arrow_field.name() - ))); + validate_function_blob_nesting(&arrow_field, false)?; + if is_blob_v2 { + return Ok(FUNCTION_BLOB_V2_TYPE.to_string()); } - return Ok(FUNCTION_BLOB_V2_TYPE.to_string()); } if field.r#type.fields.is_none() && field.r#type.length.is_none() { Ok(field.r#type.r#type.clone()) @@ -617,6 +614,34 @@ fn has_supported_blob_v2_layout(field: &ArrowField) -> bool { ) } +fn validate_function_blob_nesting(field: &ArrowField, inside_collection: bool) -> Result<()> { + if field.is_blob_v2() { + if inside_collection { + return Err(invalid_function(format!( + "Function field '{}' nests Blob v2 under a collection, which Function signatures do not support", + field.name() + ))); + } + if !has_supported_blob_v2_layout(field) { + return Err(invalid_function(format!( + "Function field '{}' has an invalid Blob v2 storage layout", + field.name() + ))); + } + return Ok(()); + } + match field.data_type() { + DataType::Struct(fields) => fields + .iter() + .try_for_each(|field| validate_function_blob_nesting(field, inside_collection)), + DataType::List(field) + | DataType::LargeList(field) + | DataType::FixedSizeList(field, _) + | DataType::Map(field, _) => validate_function_blob_nesting(field, true), + _ => Ok(()), + } +} + /// `fixed_size_list` -> (`item`, `size`); the comma must sit outside /// any nested `<...>`. fn split_fixed_size_list(raw: &str) -> Option<(&str, i32)> { @@ -697,21 +722,22 @@ fn parse_output_arrow_type(raw: &str) -> Result { } fn function_output_field(name: &str, nullable: bool, raw: &str) -> Result { - if raw == FUNCTION_BLOB_V2_TYPE { - return lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ - crate::blob(name, nullable), - ])) + let field = if raw == FUNCTION_BLOB_V2_TYPE { + lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![crate::blob( + name, nullable, + )])) .map_err(|e| invalid_function(format!("could not encode Blob v2 output field: {e}")))? .fields .into_iter() .next() - .ok_or_else(|| invalid_function("Blob v2 output field is missing")); - } - Ok(JsonArrowField::new( - name.to_string(), - nullable, - parse_output_arrow_type(raw)?, - )) + .ok_or_else(|| invalid_function("Blob v2 output field is missing"))? + } else { + JsonArrowField::new(name.to_string(), nullable, parse_output_arrow_type(raw)?) + }; + let arrow_field = lance_namespace::schema::convert_json_arrow_field(&field) + .map_err(|e| invalid_function(format!("invalid Function output field: {e}")))?; + validate_function_blob_nesting(&arrow_field, false)?; + Ok(field) } fn function_output_field_matches(expected: &ArrowField, actual: &ArrowField) -> bool { @@ -2719,6 +2745,28 @@ mod tests { .unwrap() } + fn exact_arrow_type(field: ArrowField) -> String { + let json = + lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![field])).unwrap(); + serde_json::to_string(json.fields[0].r#type.as_ref()).unwrap() + } + + fn single_input_application(path: &str) -> FunctionApplication { + FunctionApplication::from_json( + &serde_json::json!({ + "function": {"name": "inspect", "version": "fv_nested_blob"}, + "inputs": [{ + "parameter": "value", + "kind": "column", + "value": {"path": path} + }], + "output": {"kind": "scalar", "arrow_type": "int64", "nullable": false} + }) + .to_string(), + ) + .unwrap() + } + fn binding_from_plan(plan: &FunctionDeclarationPlan) -> FunctionBinding { let inputs = plan .input_bindings @@ -3158,6 +3206,128 @@ mod tests { assert_eq!(fields[1].data_type(), &DataType::Int32); } + #[test] + fn test_struct_blob_input_preserves_exact_schema_and_nullability() { + let payload = ArrowField::new( + "payload", + DataType::Struct(Fields::from(vec![ + ArrowField::new("mime_type", DataType::Utf8, false), + ArrowField::new( + "nested", + DataType::Struct(Fields::from(vec![crate::blob("image", true)])), + true, + ), + ])), + true, + ); + let plan = plan_function_application( + &ArrowSchema::new(vec![payload]), + &single_input_application("payload"), + Some("size"), + ) + .unwrap(); + + let declared: JsonArrowDataType = + serde_json::from_str(&plan.input_bindings[0].arrow_type).unwrap(); + let DataType::Struct(fields) = + lance_namespace::schema::convert_json_arrow_type(&declared).unwrap() + else { + panic!("expected a struct Function input") + }; + assert!(fields[1].is_nullable()); + let DataType::Struct(nested) = fields[1].data_type() else { + panic!("expected a recursive struct Function input") + }; + assert!(nested[0].is_blob_v2()); + assert!(nested[0].is_nullable()); + + let exact = lance_namespace::schema::convert_json_arrow_schema(&plan.input_schema).unwrap(); + let DataType::Struct(fields) = exact.field(0).data_type() else { + panic!("expected exact input schema to retain the struct") + }; + let DataType::Struct(nested) = fields[1].data_type() else { + panic!("expected exact input schema to retain the nested struct") + }; + assert!(nested[0].is_blob_v2()); + } + + #[test] + fn test_recursive_blob_result_plans_one_whole_named_struct_column() { + let details_type = exact_arrow_type(ArrowField::new( + "details", + DataType::Struct(Fields::from(vec![crate::blob("image", true)])), + false, + )); + let application = FunctionApplication::from_json( + &serde_json::json!({ + "function": {"name": "inspect", "version": "fv_nested_blob"}, + "inputs": [], + "output": { + "kind": "named_struct", + "fields": [ + {"name": "mime_type", "arrow_type": "utf8", "nullable": false}, + {"name": "details", "arrow_type": details_type, "nullable": false} + ] + } + }) + .to_string(), + ) + .unwrap(); + let plan = plan_function_application(&ArrowSchema::empty(), &application, Some("payload")) + .unwrap(); + + assert_eq!(plan.outputs.len(), 1); + assert_eq!(plan.outputs[0].result_field, WHOLE_RESULT_FIELD); + let schema = + lance_namespace::schema::convert_json_arrow_schema(&plan.output_schema).unwrap(); + assert_eq!(schema.field(0).name(), "payload"); + let DataType::Struct(fields) = schema.field(0).data_type() else { + panic!("whole named result must be one struct column") + }; + assert_eq!( + fields.iter().map(|field| field.name()).collect::>(), + ["mime_type", "details"] + ); + let DataType::Struct(details) = fields[1].data_type() else { + panic!("expected recursive result struct") + }; + assert!(details[0].is_blob_v2()); + assert!(!fields.iter().any(|field| field.name() == "payload")); + } + + #[test] + fn test_blob_children_under_collections_are_rejected() { + let collections = vec![ + DataType::List(Arc::new(crate::blob("item", false))), + DataType::LargeList(Arc::new(crate::blob("item", false))), + DataType::FixedSizeList(Arc::new(crate::blob("item", false)), 2), + DataType::Map( + Arc::new(ArrowField::new( + "entries", + DataType::Struct(Fields::from(vec![ + ArrowField::new("key", DataType::Utf8, false), + crate::blob("value", false), + ])), + false, + )), + false, + ), + ]; + for data_type in collections { + let schema = ArrowSchema::new(vec![ArrowField::new("value", data_type, false)]); + let error = plan_function_application( + &schema, + &single_input_application("value"), + Some("size"), + ) + .unwrap_err(); + assert!( + error.to_string().contains("under a collection"), + "got: {error}" + ); + } + } + #[test] fn test_blob_whole_struct_binding_accepts_full_logical_layout() { let input = crate::blob("image", false); From f2eb4a245d252d2b4af512fc655ab3e45b55ea1a Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Tue, 1 Sep 2026 09:25:27 -0700 Subject: [PATCH 168/206] chore: update lance dependency to v12.0.0-beta.9 (#4116) Updates Lance dependencies from v12.0.0-beta.5 to v12.0.0-beta.9 across Rust and Java. No compatibility fixes were required; full workspace Clippy passes with all features. Lance tag: https://github.com/lance-format/lance/releases/tag/v12.0.0-beta.9 --- Cargo.lock | 89 ++++++++++++++++++++++++++-------------------------- Cargo.toml | 28 ++++++++--------- java/pom.xml | 2 +- 3 files changed, 60 insertions(+), 59 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2c1412d63..ac604fb83 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow", "arrow-array", @@ -5000,6 +5000,7 @@ dependencies = [ "datafusion-functions", "datafusion-physical-expr", "futures", + "half", "jsonb", "lance-arrow", "lance-core", @@ -5013,8 +5014,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow", "arrow-array", @@ -5031,8 +5032,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "proc-macro2", "quote", @@ -5041,8 +5042,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow-arith", "arrow-array", @@ -5075,8 +5076,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow-arith", "arrow-array", @@ -5107,8 +5108,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arc-swap", "arrow", @@ -5172,8 +5173,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow-array", "arrow-schema", @@ -5195,8 +5196,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow", "arrow-array", @@ -5236,8 +5237,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow-array", "arrow-schema", @@ -5251,8 +5252,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow", "async-trait", @@ -5264,8 +5265,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow", "arrow-ipc", @@ -5304,9 +5305,9 @@ dependencies = [ [[package]] name = "lance-namespace-reqwest-client" -version = "0.11.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a030196da1c994b63a96a4f0bf5b0cfa459fe6dadc9e962320246ca328da22a" +checksum = "1d06b1fbb5d41f93bc652b61e2872af92e8a6c5f6b4ce8839a8ecfa05365d359" dependencies = [ "reqwest 0.12.28", "serde", @@ -5318,8 +5319,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow-array", "arrow-buffer", @@ -5333,8 +5334,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow", "arrow-array", @@ -5374,8 +5375,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "arrow-array", "arrow-schema", @@ -5388,8 +5389,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "12.0.0-beta.5" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.5#556637791d0048c2b4f1342dd84b67c8bbd65259" +version = "12.0.0-beta.9" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 033da5907..0d684b3cc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=12.0.0-beta.5", default-features = false, "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=12.0.0-beta.5", default-features = false, "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=12.0.0-beta.5", default-features = false, "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=12.0.0-beta.5", "tag" = "v12.0.0-beta.5", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=12.0.0-beta.9", default-features = false, "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=12.0.0-beta.9", default-features = false, "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=12.0.0-beta.9", default-features = false, "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index dd68f9c47..823255b46 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 12.0.0-beta.5 + 12.0.0-beta.9 false 2.30.0 1.7 From 9a1ffb9e02bceddd6c3e57e8501cdaf788e5ad15 Mon Sep 17 00:00:00 2001 From: Bruno Ramirez Date: Tue, 1 Sep 2026 12:54:53 -0600 Subject: [PATCH 169/206] fix(remote): forward create index replace flag (#4115) Remote create-index requests already expose `replace` on the builder, but the remote client did not consistently forward an explicit `replace=false` over REST. That meant create-only intent could be lost before it reached a remote server, even though local builders and Python APIs can express it. This PR forwards `replace=false` on the existing `create_index` endpoint and keeps the current default behavior unchanged for compatibility. This was accomplished with the following changes: - Serialize `replace: false` into the existing remote create-index request body when the builder is configured with `.replace(false)`. - Forward `replace` through the synchronous Python remote `create_index` wrapper so `RemoteTable.create_index(..., replace=False)` reaches the repaired path. - Continue omitting `replace` for the default path so existing remote create-index requests keep their current semantics. - Document `name` and `replace` on the existing OpenAPI create-index request schema. - Add coverage that verifies the remote client uses the existing `/create_index/` route and forwards `replace=false`, including the synchronous Python unified API. ### Testing - `cargo fmt --all --check` - `cargo test -p lancedb --features remote test_create_index_forwards_replace_false_on_existing_route --locked` - `uv tool run maturin develop --extras tests,dev,embeddings` - `uv run --frozen pytest python/tests/test_remote_db.py::test_remote_create_index_new_api` - `uv run ruff format --check python/lancedb/remote/table.py python/tests/test_remote_db.py` - `cargo build -p lancedb --features remote --locked` - `cargo clippy -p lancedb --features remote --all-targets --locked -- -D warnings` --- docs/openapi.yml | 9 +++++++ python/python/lancedb/remote/table.py | 1 + python/python/tests/test_remote_db.py | 10 ++++++- rust/lancedb/src/remote/table.rs | 38 +++++++++++++++++++++++++++ 4 files changed, 57 insertions(+), 1 deletion(-) diff --git a/docs/openapi.yml b/docs/openapi.yml index 2f9ae7d99..c4cb19754 100644 --- a/docs/openapi.yml +++ b/docs/openapi.yml @@ -446,6 +446,15 @@ paths: properties: column: type: string + name: + type: string + description: Optional name for the created index. + replace: + type: boolean + default: true + description: | + Whether to replace an existing index with the same resolved + name. Defaults to true. metric_type: type: string nullable: false diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 55014a423..3eb9cbfa1 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -548,6 +548,7 @@ class RemoteTable(Table): LOOP.run( self._table.create_index( column, + replace=replace, config=config, wait_timeout=wait_timeout, name=name, diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 01e2cc4c5..add995de1 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -820,11 +820,13 @@ def test_table_create_indices(): scalar_req = received_requests[0] assert "name" in scalar_req assert scalar_req["name"] == "custom_scalar_idx" + assert scalar_req["replace"] is False # Check FTS index request has custom name fts_req = received_requests[1] assert "name" in fts_req assert fts_req["name"] == "custom_fts_idx" + assert fts_req["replace"] is False assert fts_req["block_size"] == 256 assert fts_req["custom_stop_words"] == ["cloud"] @@ -832,6 +834,7 @@ def test_table_create_indices(): vector_req = received_requests[2] assert "name" in vector_req assert vector_req["name"] == "custom_vector_idx" + assert "replace" not in vector_req table.wait_for_index(["custom_scalar_idx"], timedelta(seconds=2)) table.wait_for_index( @@ -1104,6 +1107,9 @@ def test_remote_create_index_new_api(): table.create_index("text", config=FTS(block_size=256)) # IvfRq via new API table.create_index("vector", config=IvfRq(distance_type="l2")) + table.create_index( + "vector", config=IvfPq(distance_type="l2"), replace=False + ) # Legacy index_type="IVF_RQ" routes to IvfRq config under the hood. with pytest.warns(DeprecationWarning, match="create_index"): @@ -1113,15 +1119,17 @@ def test_remote_create_index_new_api(): num_partitions=8, ) - assert len(received_requests) == 5 + assert len(received_requests) == 6 assert [req["column"] for req in received_requests] == [ "vector", "category", "text", "vector", "vector", + "vector", ] assert received_requests[2]["block_size"] == 256 + assert received_requests[4]["replace"] is False def test_table_wait_for_index_timeout(): diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index daea028e9..ae5338d65 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -527,6 +527,10 @@ impl RemoteTable { "column": canonical_column }); + if !index.replace { + body["replace"] = false.into(); + } + // Add name parameter if provided (for backwards compatibility, only include if Some) if let Some(ref name) = index.name { body["name"] = serde_json::Value::String(name.clone()); @@ -6233,6 +6237,40 @@ mod tests { } } + #[tokio::test] + async fn test_create_index_forwards_replace_false_on_existing_route() { + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.method(), "POST"); + match request.url().path() { + "/v1/table/my_table/describe/" => { + let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); + http::Response::builder() + .status(200) + .body(describe_response(&schema)) + .unwrap() + } + "/v1/table/my_table/create_index/" => { + let body = request.body().unwrap().as_bytes().unwrap(); + let body: serde_json::Value = serde_json::from_slice(body).unwrap(); + assert_eq!(body["replace"], json!(false)); + + http::Response::builder() + .status(200) + .body("{}".to_string()) + .unwrap() + } + path => panic!("Unexpected path: {}", path), + } + }); + + table + .create_index(&["a"], Index::BTree(Default::default())) + .replace(false) + .execute() + .await + .unwrap(); + } + #[tokio::test] async fn test_create_index_returns_job() { let describe_calls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); From d2ca0ce0abf89fbf378ba3eef4e1beb4f394925a Mon Sep 17 00:00:00 2001 From: Will Jones Date: Tue, 1 Sep 2026 16:32:04 -0700 Subject: [PATCH 170/206] feat: accept multiple `on` columns for merge insert on remote tables (#4102) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Merge insert has always taken a list of columns to match on, and local tables have always joined on all of them. Remote tables did not: any list longer than one was rejected with `MergeInsertBuilder only supports a single 'on' column`, so a composite-key upsert was impossible against LanceDB Cloud and Enterprise from Rust, Python or TypeScript. The remote request now carries `on` as a list and sends it as one repeated query parameter per column — `?on=shard_key&on=id`. That is how the lance-namespace spec encodes an array-valued `on`, so the server receives a composite key in the shape it expects. A single column still serializes to `?on=id`, exactly what clients sent before, so existing callers are unaffected. A column repeated within `on` is now rejected client-side rather than sent for the server to reject with a 400. No binding changes were needed: `Table.merge_insert` in Python and `Table.mergeInsert` in TypeScript already accepted a list, it just could not reach a remote table. Both gain a test for composite keys, and the doc comments now say what passing several columns means. Part of [ENT-2084](https://linear.app/lancedb/issue/ENT-2084/mergeinsertintotablerequest-support-multiple-columns-for-the). ## Example ```python table.merge_insert(["shard_key", "id"]) \ .when_matched_update_all() \ .when_not_matched_insert_all() \ .execute(new_data) ``` A row whose `id` matches an existing row but whose `shard_key` differs is an insert, not an update. ## Not included Java. Java callers reach merge insert through `org.lance.namespace.LanceNamespace`, whose `MergeInsertIntoTableRequest.on` is a single string until lance-namespace 0.12 ([lance-namespace#363](https://github.com/lance-format/lance-namespace/pull/363), [lance#8915](https://github.com/lance-format/lance/pull/8915)). There is nothing in this repo's Java SDK to change until the `lance-core` pin can move. Sending more than one column requires a server that accepts the repeated parameter ([sophon#7571](https://github.com/lancedb/sophon/pull/7571)); an older server returns a 400 rather than silently merging on one column. Co-authored-by: Claude Opus 5 (1M context) --- docs/src/js/classes/Table.md | 8 ++ nodejs/__test__/table.test.ts | 35 +++++++- nodejs/lancedb/table.ts | 10 +++ python/python/lancedb/table.py | 8 +- python/python/tests/test_table.py | 37 +++++++++ rust/lancedb/src/remote/table.rs | 103 ++++++++++++++++++++++-- rust/lancedb/src/remote/table/insert.rs | 3 +- rust/lancedb/src/table.rs | 4 +- 8 files changed, 196 insertions(+), 12 deletions(-) diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 159348450..894d7a464 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -676,9 +676,17 @@ List all the versions of the table abstract mergeInsert(on): MergeInsertBuilder ``` +Create a [MergeInsertBuilder](MergeInsertBuilder.md), which combines new data with the +existing table in a single transaction — inserting, updating and deleting +rows depending on how they match. + #### Parameters * **on**: `string` \| `string`[] + The column, or columns, to match source rows against target + rows on. Typically a key or id column. Several columns match on the + composite key: a source row updates a target row only when it agrees on + every one of them. #### Returns diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 554c7fcd3..6f80ca74e 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -737,11 +737,12 @@ it("should query documents with LangChain PDF metadata", async () => { describe("merge insert", () => { let tmpDir: tmp.DirResult; + let conn: Connection; let table: Table; beforeEach(async () => { tmpDir = tmp.dirSync({ unsafeCleanup: true }); - const conn = await connect(tmpDir.name); + conn = await connect(tmpDir.name); table = await conn.createTable("some_table", [ { a: 1, b: "a" }, @@ -779,6 +780,38 @@ describe("merge insert", () => { expect(result.map((row) => ({ ...row }))).toEqual(expected); }); + test("upsert on a composite key", async () => { + const composite = await conn.createTable("composite", [ + { shard: "a", id: 1, val: "x" }, + { shard: "a", id: 2, val: "y" }, + { shard: "b", id: 1, val: "z" }, + ]); + + // ("a", 1) matches an existing row and updates it. ("b", 2) agrees with an + // existing row on each key column separately but on neither pair, so it is + // an insert. + const mergeInsertRes = await composite + .mergeInsert(["shard", "id"]) + .whenMatchedUpdateAll() + .whenNotMatchedInsertAll() + .execute([ + { shard: "a", id: 1, val: "X" }, + { shard: "b", id: 2, val: "W" }, + ]); + expect(mergeInsertRes.numUpdatedRows).toBe(1); + expect(mergeInsertRes.numInsertedRows).toBe(1); + + const result = (await composite.toArrow()) + .toArray() + .sort((a, b) => a.shard.localeCompare(b.shard) || a.id - b.id); + + expect(result.map((row) => ({ ...row }))).toEqual([ + { shard: "a", id: 1, val: "X" }, + { shard: "a", id: 2, val: "y" }, + { shard: "b", id: 1, val: "z" }, + { shard: "b", id: 2, val: "W" }, + ]); + }); test("conditional update", async () => { const newData = [ { a: 2, b: "x" }, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index dc062e337..28591f51c 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -919,6 +919,16 @@ export abstract class Table { /** Return the table as an arrow table */ abstract toArrow(): Promise; + /** + * Create a {@link MergeInsertBuilder}, which combines new data with the + * existing table in a single transaction — inserting, updating and deleting + * rows depending on how they match. + * + * @param on - The column, or columns, to match source rows against target + * rows on. Typically a key or id column. Several columns match on the + * composite key: a source row updates a target row only when it agrees on + * every one of them. + */ abstract mergeInsert(on: string | string[]): MergeInsertBuilder; /** List all the stats of a specified index diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 287dff1f6..e397272fc 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1547,7 +1547,9 @@ class Table(ABC): on: Union[str, Iterable[str]] A column (or columns) to join on. This is how records from the source table and target table are matched. Typically this is some - kind of key or id column. + kind of key or id column. Passing several columns matches on the + composite key: a source row updates a target row only when it + agrees on every one of them. Examples -------- @@ -5701,7 +5703,9 @@ class AsyncTable: on: Union[str, Iterable[str]] A column (or columns) to join on. This is how records from the source table and target table are matched. Typically this is some - kind of key or id column. + kind of key or id column. Passing several columns matches on the + composite key: a source row updates a target row only when it + agrees on every one of them. Examples -------- diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index fbdfac5d8..82ad045c8 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -2682,6 +2682,43 @@ def test_merge_insert(mem_db: DBConnection): ) +def test_merge_insert_composite_key(mem_db: DBConnection): + table = mem_db.create_table( + "my_table", + data=pa.table( + { + "shard": ["a", "a", "b"], + "id": [1, 2, 1], + "val": ["x", "y", "z"], + } + ), + ) + + # ("a", 1) matches an existing row and updates it. ("b", 2) agrees with an + # existing row on each key column separately but on neither pair, so it is + # an insert. + new_data = pa.table({"shard": ["a", "b"], "id": [1, 2], "val": ["X", "W"]}) + res = ( + table.merge_insert(["shard", "id"]) + .when_matched_update_all() + .when_not_matched_insert_all() + .execute(new_data) + ) + assert res.num_updated_rows == 1 + assert res.num_inserted_rows == 1 + + expected = pa.table( + { + "shard": ["a", "a", "b", "b"], + "id": [1, 2, 1, 2], + "val": ["X", "y", "z", "W"], + } + ) + assert table.to_arrow().sort_by([("shard", "ascending"), ("id", "ascending")]) == ( + expected + ) + + def test_merge_insert_nullable_pandas_into_pydantic_schema(mem_db: DBConnection): # Regression test for https://github.com/lancedb/lancedb/issues/2366 pd = pytest.importorskip("pandas") diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index ae5338d65..5faffa8c7 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -72,7 +72,7 @@ use lance_datafusion::exec::{OneShotExec, execute_plan}; use reqwest::{RequestBuilder, Response}; use serde::{Deserialize, Serialize}; use serde_json::Number; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::io::Cursor; use std::pin::Pin; use std::sync::{Arc, Mutex}; @@ -3651,7 +3651,12 @@ impl BaseTable for RemoteTable { #[derive(Serialize, Clone, Debug)] pub struct MergeInsertRequest { - on: String, + // Sent as one repeated `on` query parameter per column, which is how the + // namespace spec encodes an array-valued `on`. serde_urlencoded (which + // reqwest's `query()` uses) cannot serialize a sequence nested in a struct, + // so this field is emitted separately by [`Self::on_query_params`]. + #[serde(skip_serializing)] + on: Vec, when_matched_update_all: bool, when_matched_update_all_filt: Option, when_not_matched_insert_all: bool, @@ -3667,6 +3672,17 @@ pub struct MergeInsertRequest { use_lsm: Option, } +impl MergeInsertRequest { + /// The `on` columns as repeated query parameters: `?on=a&on=b`. + /// + /// A single column serializes to `?on=a`, exactly what clients sent before + /// `on` became a list, so a server that predates composite keys sees no + /// change from a single-column caller. + pub(crate) fn on_query_params(&self) -> Vec<(&str, &str)> { + self.on.iter().map(|col| ("on", col.as_str())).collect() + } +} + fn is_true(b: &bool) -> bool { *b } @@ -3679,12 +3695,15 @@ impl TryFrom for MergeInsertRequest { return Err(Error::InvalidInput { message: "MergeInsertBuilder missing required 'on' field".into(), }); - } else if value.on.len() > 1 { - return Err(Error::NotSupported { - message: "MergeInsertBuilder only supports a single 'on' column".into(), + } + // The server rejects a repeated column with a 400; catching it here + // names the offending column and costs no round trip. + let mut seen = HashSet::with_capacity(value.on.len()); + if let Some(dup) = value.on.iter().find(|col| !seen.insert(*col)) { + return Err(Error::InvalidInput { + message: format!("MergeInsertBuilder 'on' column '{dup}' is repeated"), }); } - let on = value.on[0].clone(); let when_matched_update_all_filt = match value.when_matched_update_all_filt { Some(MergeFilter::Sql(sql)) => Some(sql), @@ -3708,7 +3727,7 @@ impl TryFrom for MergeInsertRequest { }; Ok(Self { - on, + on: value.on, when_matched_update_all: value.when_matched_update_all, when_matched_update_all_filt, when_not_matched_insert_all: value.when_not_matched_insert_all, @@ -4552,6 +4571,76 @@ mod tests { } } + #[tokio::test] + async fn test_merge_insert_composite_key() { + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])), + vec![Arc::new(Int32Array::from(vec![1, 2, 3]))], + ) + .unwrap(); + let data: Box = Box::new(RecordBatchIterator::new( + [Ok(batch.clone())], + batch.schema(), + )); + + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/merge_insert/"); + + // One repeated `on` per column, in the order the caller gave them. + let on = request + .url() + .query_pairs() + .filter(|(key, _)| key == "on") + .map(|(_, value)| value.into_owned()) + .collect::>(); + assert_eq!(on, vec!["shard_key".to_string(), "id".to_string()]); + + let params = request.url().query_pairs().collect::>(); + assert_eq!(params["when_matched_update_all"], "true"); + assert_eq!(params["when_not_matched_insert_all"], "true"); + + http::Response::builder() + .status(200) + .body(r#"{"version": 43, "num_deleted_rows": 0, "num_inserted_rows": 3, "num_updated_rows": 0}"#) + .unwrap() + }); + + let mut merge = table.merge_insert(&["shard_key", "id"]); + merge.when_matched_update_all(None); + merge.when_not_matched_insert_all(); + let result = table.base_table().merge_insert(merge, data).await.unwrap(); + + assert_eq!(result.num_inserted_rows, 3); + } + + #[tokio::test] + async fn test_merge_insert_rejects_repeated_on_column() { + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])), + vec![Arc::new(Int32Array::from(vec![1]))], + ) + .unwrap(); + let data: Box = Box::new(RecordBatchIterator::new( + [Ok(batch.clone())], + batch.schema(), + )); + + let table = Table::new_with_handler::<&str>("my_table", |request| { + panic!("Unexpected request: {}", request.url()); + }); + + let merge = table.merge_insert(&["id", "id"]); + let err = table + .base_table() + .merge_insert(merge, data) + .await + .unwrap_err(); + assert!( + matches!(&err, Error::InvalidInput { message } if message.contains("'id' is repeated")), + "unexpected error: {err}" + ); + } + #[tokio::test] async fn test_merge_insert_retries_on_409() { let batch = RecordBatch::try_new( diff --git a/rust/lancedb/src/remote/table/insert.rs b/rust/lancedb/src/remote/table/insert.rs index 4e0e0d666..eef1d8e42 100644 --- a/rust/lancedb/src/remote/table/insert.rs +++ b/rust/lancedb/src/remote/table/insert.rs @@ -734,6 +734,7 @@ impl ExecutionPlan for RemoteWriteExec { WriteOp::MergeInsert { query, timeout } => { let mut request = client .post(&format!("/v1/table/{}/merge_insert/", identifier)) + .query(&query.on_query_params()) .query(query) .header(CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE); if let Some(timeout) = timeout { @@ -1489,7 +1490,7 @@ mod tests { }); let query = MergeInsertRequest { - on: "id".to_string(), + on: vec!["id".to_string()], when_matched_update_all: false, when_matched_update_all_filt: None, when_not_matched_insert_all: false, diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 4602d35ed..33b6ea8ce 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1506,7 +1506,9 @@ impl Table { /// /// * `on` One or more columns to join on. This is how records from the /// source table and target table are matched. Typically this is some - /// kind of key or id column. + /// kind of key or id column. Several columns match on the composite + /// key: a source row updates a target row only when it agrees on every + /// one of them. /// /// # Examples /// From 904bd975e5cddd9a034ee457909107fbb0f270e4 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Tue, 1 Sep 2026 22:27:12 -0700 Subject: [PATCH 171/206] chore: update lance dependency to v12.0.0-beta.11 (#4118) Updates the Rust workspace Lance dependencies and Java lance-core dependency to v12.0.0-beta.11. No compatibility fixes were required. Trigger: https://github.com/lance-format/lance/releases/tag/v12.0.0-beta.11 --- Cargo.lock | 84 ++++++++++++++++++++++++++-------------------------- Cargo.toml | 28 +++++++++--------- java/pom.xml | 2 +- 3 files changed, 57 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ac604fb83..2a9f68170 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3455,8 +3455,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4815,8 +4815,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arc-swap", "arrow", @@ -4888,8 +4888,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow-array", "arrow-buffer", @@ -4911,7 +4911,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow-array", "arrow-buffer", @@ -4925,7 +4925,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow-array", "arrow-schema", @@ -4934,8 +4934,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrayref", "crunchy", @@ -4945,8 +4945,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow-array", "arrow-buffer", @@ -4983,8 +4983,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow", "arrow-array", @@ -5014,8 +5014,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow", "arrow-array", @@ -5032,8 +5032,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "proc-macro2", "quote", @@ -5042,8 +5042,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow-arith", "arrow-array", @@ -5076,8 +5076,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow-arith", "arrow-array", @@ -5108,8 +5108,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arc-swap", "arrow", @@ -5173,8 +5173,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow-array", "arrow-schema", @@ -5196,8 +5196,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow", "arrow-array", @@ -5237,8 +5237,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow-array", "arrow-schema", @@ -5252,8 +5252,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow", "async-trait", @@ -5265,8 +5265,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow", "arrow-ipc", @@ -5319,8 +5319,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow-array", "arrow-buffer", @@ -5334,8 +5334,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow", "arrow-array", @@ -5375,8 +5375,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "arrow-array", "arrow-schema", @@ -5389,8 +5389,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "12.0.0-beta.9" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.9#6f93e3fe389f5a661a02aff00c14df6be7bf0505" +version = "12.0.0-beta.11" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 0d684b3cc..eba5a421a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=12.0.0-beta.9", default-features = false, "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=12.0.0-beta.9", default-features = false, "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=12.0.0-beta.9", default-features = false, "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=12.0.0-beta.9", "tag" = "v12.0.0-beta.9", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=12.0.0-beta.11", default-features = false, "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=12.0.0-beta.11", default-features = false, "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=12.0.0-beta.11", default-features = false, "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index 823255b46..aa6e3e5f7 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 12.0.0-beta.9 + 12.0.0-beta.11 false 2.30.0 1.7 From c0f33f8627a726150df83646711fadc1bf0975bf Mon Sep 17 00:00:00 2001 From: Lance Release Date: Wed, 2 Sep 2026 05:28:10 +0000 Subject: [PATCH 172/206] =?UTF-8?q?Bump=20version:=200.39.0-beta.0=20?= =?UTF-8?q?=E2=86=92=200.39.0-beta.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 5bec58ffd..bd1db72ee 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.39.0-beta.0" +current_version = "0.39.0-beta.1" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 2a9f68170..bcc7526c8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5403,7 +5403,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.39.0-beta.0" +version = "0.39.0-beta.1" dependencies = [ "ahash", "anyhow", @@ -5491,7 +5491,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.39.0-beta.0" +version = "0.39.0-beta.1" dependencies = [ "arrow-array", "arrow-buffer", @@ -5516,7 +5516,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.39.0-beta.0" +version = "0.39.0-beta.1" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 5660ea70d..80245cc15 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.39.0-beta.0 + 0.39.0-beta.1 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 09aa7ed16..1b9e68776 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.0 + 0.39.0-beta.1 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index aa6e3e5f7..01fe2ce85 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.0 + 0.39.0-beta.1 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 98820f265..4968bc7ca 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.39.0-beta.0" +version = "0.39.0-beta.1" 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 3a16bb193..d7b592fa4 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.39.0-beta.0", + "version": "0.39.0-beta.1", "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 e3b1db92f..8aad32ca9 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.39.0-beta.0", + "version": "0.39.0-beta.1", "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 7922272cb..72fd1b4ec 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.39.0-beta.0", + "version": "0.39.0-beta.1", "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 8d6c41f1a..0d9c4b92b 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.39.0-beta.0", + "version": "0.39.0-beta.1", "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 eb26fccfb..ed5388426 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.39.0-beta.0", + "version": "0.39.0-beta.1", "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 e7b519cf3..35a650b22 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.39.0-beta.0", + "version": "0.39.0-beta.1", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index f8c517788..b4fedadfa 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.39.0-beta.0", + "version": "0.39.0-beta.1", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 515aa13c0..2853a4378 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.39.0-beta.0", + "version": "0.39.0-beta.1", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index bda38ac39..98ae17fef 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.39.0-beta.0" +version = "0.39.0-beta.1" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 938be1a39..a5aa12e52 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.39.0-beta.0" +version = "0.39.0-beta.1" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 0d19a6c546f766c489588beef827604e341a3d0d Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Wed, 2 Sep 2026 17:51:21 +0800 Subject: [PATCH 173/206] fix: support nested-list FTS indexing (#4059) ## Summary - validate native FTS fields against the recursively resolved terminal text leaf - preserve canonical public paths and list depth for Lance document-boundary handling - cover async nested-list index creation and deepest-list `_doc_index` search coordinates ## Root cause The FTS resolver recursively found the terminal text field but returned the outer list field. Native validation therefore rejected `List(List(Utf8))` before Lance could create a list-element index. ## Validation - `cargo test --quiet --features remote -p lancedb test_nested_list_fts_uses_deepest_document_coordinates -- --nocapture` - `cargo test --quiet --features remote -p lancedb test_execute_async_validates_fts_input_before_starting_job` - `cargo test --quiet --features remote -p lancedb test_public_fts_field_path_prefers_exact_case` - `cargo check --quiet --features remote --tests --examples` - `cargo clippy --quiet --features remote --tests --examples` - `cargo fmt --all -- --check` Fixes #4058 Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> --- rust/lancedb/src/table/create_index.rs | 80 +++++++++++++++++++++++++- rust/lancedb/src/utils/mod.rs | 9 +-- 2 files changed, 83 insertions(+), 6 deletions(-) diff --git a/rust/lancedb/src/table/create_index.rs b/rust/lancedb/src/table/create_index.rs index c7d6b5675..e30c310ac 100644 --- a/rust/lancedb/src/table/create_index.rs +++ b/rust/lancedb/src/table/create_index.rs @@ -133,7 +133,7 @@ impl NativeTable { ), }); } - (resolved.canonical_path, resolved.field) + (resolved.canonical_path, resolved.terminal_field) } else { Self::resolve_index_field(dataset.schema(), &opts.columns[0])? }; @@ -439,7 +439,8 @@ mod tests { use arrow_array::record_batch; use arrow_array::{ Array, ArrayRef, BinaryArray, BooleanArray, FixedSizeListArray, Float32Array, Int32Array, - LargeBinaryArray, LargeStringArray, RecordBatch, StringArray, StructArray, + LargeBinaryArray, LargeStringArray, ListArray, RecordBatch, StringArray, StructArray, + UInt32Array, }; use arrow_data::ArrayDataBuilder; use arrow_schema::{DataType, Field, Schema}; @@ -458,6 +459,7 @@ mod tests { use crate::query::{ExecutableQuery, QueryBase}; use crate::table::optimize::{CompactionOptions, OptimizeAction}; use lance_index::scalar::FullTextSearchQuery; + use lance_index::scalar::inverted::query::{FtsQuery, MatchQuery}; fn create_fixed_size_list( values: T, @@ -599,6 +601,80 @@ mod tests { assert!(invalid_granularity.is_err()); } + #[tokio::test] + async fn test_nested_list_fts_uses_deepest_document_coordinates() { + let conn = connect("memory://").execute().await.unwrap(); + let mut docs = ListBuilder::new(ListBuilder::new(StringBuilder::new())); + + docs.values().values().append_value("alpha"); + docs.values().values().append_value("beta"); + docs.values().append(true); + docs.values().values().append_value("gamma"); + docs.values().values().append_value("alpha delta"); + docs.values().append(true); + docs.append(true); + + docs.values().append(true); + docs.values().values().append_value("alpha"); + docs.values().append(true); + docs.append(true); + + let batch = RecordBatch::try_from_iter(vec![ + ("id", Arc::new(Int32Array::from(vec![0, 1])) as ArrayRef), + ("docs", Arc::new(docs.finish()) as ArrayRef), + ]) + .unwrap(); + let table = conn.create_table("nested", batch).execute().await.unwrap(); + + let job = table + .create_index( + &["docs"], + Index::FTS( + FtsIndexBuilder::default() + .document_granularity(DocumentGranularity::ListElement), + ), + ) + .execute_async() + .await + .unwrap(); + job.wait().await.unwrap(); + + let query = FullTextSearchQuery::new_query(FtsQuery::Match( + MatchQuery::new("alpha".to_string()) + .with_column(Some("docs".to_string())) + .with_document_granularity(DocumentGranularity::ListElement), + )); + let batches = table + .query() + .full_text_search(query) + .limit(10) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + + let mut hits = Vec::new(); + for batch in batches { + let ids = batch["id"].as_any().downcast_ref::().unwrap(); + let coordinates = batch["_doc_index"] + .as_any() + .downcast_ref::() + .unwrap(); + for row in 0..batch.num_rows() { + let coordinate = coordinates.value(row); + let coordinate = coordinate.as_any().downcast_ref::().unwrap(); + hits.push((ids.value(row), coordinate.values().to_vec())); + } + } + hits.sort_unstable(); + assert_eq!( + hits, + vec![(0, vec![0, 0]), (0, vec![1, 1]), (1, vec![1, 0])] + ); + } + /// Concurrent waiters, and a wait issued after the job settled, all /// succeed once the build does. #[tokio::test] diff --git a/rust/lancedb/src/utils/mod.rs b/rust/lancedb/src/utils/mod.rs index 07d1836a1..352e55f2f 100644 --- a/rust/lancedb/src/utils/mod.rs +++ b/rust/lancedb/src/utils/mod.rs @@ -227,7 +227,7 @@ pub(crate) fn resolve_arrow_field_path(schema: &Schema, column: &str) -> Result< pub(crate) struct ResolvedFtsField { pub canonical_path: String, - pub field: Field, + pub terminal_field: Field, pub list_depth: usize, } @@ -309,7 +309,7 @@ pub(crate) fn resolve_lance_fts_field_path( ); Ok(ResolvedFtsField { canonical_path, - field: Field::from(field), + terminal_field: Field::from(terminal), list_depth, }) } @@ -375,7 +375,7 @@ pub(crate) fn resolve_arrow_fts_field_path( message: format!("Invalid schema: {}", e), })?; let resolved = resolve_lance_fts_field_path(&lance_schema, column)?; - Ok((resolved.canonical_path, resolved.field)) + Ok((resolved.canonical_path, resolved.terminal_field)) } pub fn supported_btree_data_type(dtype: &DataType) -> bool { @@ -647,8 +647,9 @@ mod tests { Field::new("docs", text_list(), true), ]); - let (path, _) = resolve_arrow_fts_field_path(&schema, "docs.content").unwrap(); + let (path, field) = resolve_arrow_fts_field_path(&schema, "docs.content").unwrap(); assert_eq!(path, "docs.content"); + assert_eq!(field.data_type(), &DataType::Utf8); let lance_schema = lance_core::datatypes::Schema::try_from(&schema).unwrap(); let field_id = lance_schema From 2779b75d0d0252a324bc39ab73c9132d3b212484 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Wed, 2 Sep 2026 16:31:03 -0700 Subject: [PATCH 174/206] fix(node): resolve remaining pnpm audit findings (#4073) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `pnpm audit` in `nodejs/` reported a number of vulnerable transitive dependencies. Most were resolved by `pnpm audit --fix`, which bumped the affected packages in the lockfile; the `minimumReleaseAgeExclude` additions in `pnpm-workspace.yaml` are its bookkeeping, exempting the specific patched versions from the repository's 24-hour hold on newly published packages. Two findings needed handling by hand, because the vulnerable package could not simply be moved to a newer release in place. `@opentelemetry/sdk-metrics` 1.30.1 pins `@opentelemetry/core` to its own exact version, and the 1.x line is end-of-life, so GHSA-8988-4f7v-96qf (unbounded memory allocation in W3C Baggage propagation) has no fix available on 1.x. This PR moves the dependency to 2.x, which brings in a patched `@opentelemetry/core`. It is a dev-only dependency with a single consumer, `__test__/otel.test.ts`, and the parts of the API that test uses are unchanged between 1.x and 2.x. `@huggingface/transformers` pins `sharp: ^0.33.5`, and no released version of transformers has moved past `^0.34.5` — every version in those ranges inherits the libvips CVEs in GHSA-f88m-g3jw-g9cj, so there is no upstream release to upgrade to. This PR adds a pnpm `overrides` entry pinning sharp to the patched `^0.35.4` line instead. `pnpm audit` now reports no known vulnerabilities. ## Not included The sharp override only applies to this repository's own dependency tree, since pnpm overrides are not published to npm. Anyone installing `@lancedb/lancedb` together with the optional `@huggingface/transformers` still resolves sharp 0.33.5, and will until transformers itself moves to sharp 0.35. Practical exposure there is low: the CVEs require decoding untrusted images, and LanceDB's transformers embedding function is text-only. `nodejs/examples/` is a separate install with its own lockfile and is untouched here. It pins `sharp: "0.33.5"` directly and `pnpm audit` reports 19 findings against it. Bumping sharp there is more involved than it looks, because sharp 0.35 requires Node >= 20.9 while the examples tests run on the Node 18/20 CI matrix, so it is left for separate work. --------- Co-authored-by: Claude Opus 5 (1M context) Co-authored-by: Xuanwo --- nodejs/package.json | 4 +- nodejs/pnpm-lock.yaml | 1030 +++++++++++++++++++++--------------- nodejs/pnpm-workspace.yaml | 38 ++ 3 files changed, 633 insertions(+), 439 deletions(-) diff --git a/nodejs/package.json b/nodejs/package.json index 2853a4378..49de9080b 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -44,7 +44,7 @@ "@biomejs/biome": "^1.7.3", "@jest/globals": "^29.7.0", "@napi-rs/cli": "3.7.0", - "@opentelemetry/sdk-metrics": "^1.30.0", + "@opentelemetry/sdk-metrics": "^2.10.0", "@types/axios": "^0.14.0", "@types/jest": "^29.1.2", "@types/node": "22.7.4", @@ -56,7 +56,7 @@ "eslint": "^8.57.0", "jest": "^29.7.0", "shx": "^0.3.4", - "tmp": "^0.2.3", + "tmp": "^0.2.7", "ts-jest": "^29.1.2", "typedoc": "0.26.4", "typedoc-plugin-markdown": "4.2.1", diff --git a/nodejs/pnpm-lock.yaml b/nodejs/pnpm-lock.yaml index c21c636d2..f10db2f3f 100644 --- a/nodejs/pnpm-lock.yaml +++ b/nodejs/pnpm-lock.yaml @@ -4,6 +4,9 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false +overrides: + sharp: ^0.35.4 + importers: .: @@ -35,10 +38,10 @@ importers: version: 29.7.0 '@napi-rs/cli': specifier: 3.7.0 - version: 3.7.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)(@types/node@22.7.4) + version: 3.7.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)(@types/node@22.7.4) '@opentelemetry/sdk-metrics': - specifier: ^1.30.0 - version: 1.30.1(@opentelemetry/api@1.9.1) + specifier: ^2.10.0 + version: 2.10.0(@opentelemetry/api@1.9.1) '@types/axios': specifier: ^0.14.0 version: 0.14.4 @@ -73,11 +76,11 @@ importers: specifier: ^0.3.4 version: 0.3.4 tmp: - specifier: ^0.2.3 - version: 0.2.5 + specifier: ^0.2.7 + version: 0.2.7 ts-jest: specifier: ^29.1.2 - version: 29.4.9(@babel/core@7.29.0)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.0))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4) + version: 29.4.9(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4) typedoc: specifier: 0.26.4 version: 0.26.4(typescript@5.5.4) @@ -93,7 +96,7 @@ importers: optionalDependencies: '@huggingface/transformers': specifier: 3.0.2 - version: 3.0.2 + version: 3.0.2(@types/node@22.7.4) openai: specifier: 4.29.2 version: 4.29.2 @@ -283,32 +286,40 @@ packages: resolution: {integrity: sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==} engines: {node: '>=6.9.0'} - '@babel/compat-data@7.29.3': - resolution: {integrity: sha512-LIVqM46zQWZhj17qA8wb4nW/ixr2y1Nw+r1etiAWgRM6U1IqP+LNhL1yg440jYZR72jCWcWbLWzIosH+uP1fqg==} + '@babel/code-frame@7.29.7': + resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} engines: {node: '>=6.9.0'} - '@babel/core@7.29.0': - resolution: {integrity: sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==} + '@babel/compat-data@7.29.7': + resolution: {integrity: sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==} + engines: {node: '>=6.9.0'} + + '@babel/core@7.29.7': + resolution: {integrity: sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==} engines: {node: '>=6.9.0'} '@babel/generator@7.29.1': resolution: {integrity: sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==} engines: {node: '>=6.9.0'} - '@babel/helper-compilation-targets@7.28.6': - resolution: {integrity: sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==} + '@babel/generator@7.29.8': + resolution: {integrity: sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==} engines: {node: '>=6.9.0'} - '@babel/helper-globals@7.28.0': - resolution: {integrity: sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==} + '@babel/helper-compilation-targets@7.29.7': + resolution: {integrity: sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==} engines: {node: '>=6.9.0'} - '@babel/helper-module-imports@7.28.6': - resolution: {integrity: sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==} + '@babel/helper-globals@7.29.7': + resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==} engines: {node: '>=6.9.0'} - '@babel/helper-module-transforms@7.28.6': - resolution: {integrity: sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==} + '@babel/helper-module-imports@7.29.7': + resolution: {integrity: sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==} + engines: {node: '>=6.9.0'} + + '@babel/helper-module-transforms@7.29.7': + resolution: {integrity: sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==} engines: {node: '>=6.9.0'} peerDependencies: '@babel/core': ^7.0.0 @@ -321,16 +332,24 @@ packages: resolution: {integrity: sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==} engines: {node: '>=6.9.0'} + '@babel/helper-string-parser@7.29.7': + resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==} + engines: {node: '>=6.9.0'} + '@babel/helper-validator-identifier@7.28.5': resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==} engines: {node: '>=6.9.0'} - '@babel/helper-validator-option@7.27.1': - resolution: {integrity: sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==} + '@babel/helper-validator-identifier@7.29.7': + resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} engines: {node: '>=6.9.0'} - '@babel/helpers@7.29.2': - resolution: {integrity: sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==} + '@babel/helper-validator-option@7.29.7': + resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==} + engines: {node: '>=6.9.0'} + + '@babel/helpers@7.29.7': + resolution: {integrity: sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==} engines: {node: '>=6.9.0'} '@babel/parser@7.29.3': @@ -338,6 +357,11 @@ packages: engines: {node: '>=6.0.0'} hasBin: true + '@babel/parser@7.29.8': + resolution: {integrity: sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==} + engines: {node: '>=6.0.0'} + hasBin: true + '@babel/plugin-syntax-async-generators@7.8.4': resolution: {integrity: sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==} peerDependencies: @@ -433,14 +457,22 @@ packages: resolution: {integrity: sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==} engines: {node: '>=6.9.0'} - '@babel/traverse@7.29.0': - resolution: {integrity: sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==} + '@babel/template@7.29.7': + resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==} + engines: {node: '>=6.9.0'} + + '@babel/traverse@7.29.8': + resolution: {integrity: sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==} engines: {node: '>=6.9.0'} '@babel/types@7.29.0': resolution: {integrity: sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==} engines: {node: '>=6.9.0'} + '@babel/types@7.29.8': + resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==} + engines: {node: '>=6.9.0'} + '@bcoe/v8-coverage@0.2.3': resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==} @@ -504,8 +536,8 @@ packages: '@emnapi/core@1.10.0': resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==} - '@emnapi/runtime@1.10.0': - resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==} + '@emnapi/runtime@1.11.3': + resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} '@emnapi/wasi-threads@1.2.1': resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==} @@ -548,120 +580,165 @@ packages: resolution: {integrity: sha512-93zYdMES/c1D69yZiKDBj0V24vqNzB/koF26KPaagAfd3P/4gUlh3Dys5ogAK+Exi9QyzlD8x/08Zt7wIKcDcA==} deprecated: Use @eslint/object-schema instead - '@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} + '@img/colour@1.1.0': + 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==} + 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.4': + resolution: {integrity: sha512-hWniXY3bG5qKpkKrAwPe4y+VTPmf086YQAnkxWh7uA1YrlRouWGa0M0Mxj3ZjnXFkv7/TD1bTy9lGUK26vRvWw==} + 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.4': + resolution: {integrity: sha512-lIsKw/BU+kjB4eZjxrYrZmwOJYi3Ajrv66iAlBmUPyKc3HpnloevB1g3wxGD9P/5BbQ1brBGl65VRRrCvQDEqA==} + engines: {node: '>=20.9.0'} + os: [freebsd] + + '@img/sharp-libvips-darwin-arm64@1.3.3': + resolution: {integrity: sha512-suTBPTDGrI9WodccaDdwZItTSaBYASlBk1NSfElSHrUfzu3szG6lvIF58+WiFvnfzuK8ZBFS5zE00PxqxnRiPg==} 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.3': + resolution: {integrity: sha512-FVJZ5mITMobmXIz/hPDTw0EintTW5H3WfrxwLqEqjiIihlu+hVRyGrFQ60xl0Lxn7Bt3zdpevPaQi0HEzqz9fw==} 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.3': + resolution: {integrity: sha512-0DaL0A6Xu6sQSQFwe4iVCrKWU2cCTItnRsYsCdxAMm9NF6twAA9BKnoqy4hqz4+azQ0JHuA26qiUKsf1XJ/v5A==} 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.3': + resolution: {integrity: sha512-3rbU4vqXXc3hY/OiXdl52xZvT0F1yEngWfvqudtPJg/KkyiaQw2DRsFrNzpmLvfavbwOq3qXn36GP8obHRULQA==} 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.3': + resolution: {integrity: sha512-cdn1OvUBwsXhbC0zSzJnNzf5MZ/mTrobawDvNXBTxe8VtqKAm0sRuEY2Evzovb/w9JMk4TvRxqt1mekSuJz64w==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-riscv64@1.3.3': + resolution: {integrity: sha512-HjPVx7yKz+0lqdhDlTw1tt90wamBoxhiXpvl1XZpJLiHH4RCJ5yDTqH+VlYPv2fwFs89JFw4c1IexYOcQUi4IQ==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@img/sharp-libvips-linux-s390x@1.3.3': + resolution: {integrity: sha512-neWLh+3yCNThxnfy3c4BbVBeGgt9aftno+XbT56iK28RgeDs3UOFWviLWlUu0bArYVYJaFDK+RRohbicUNCm8Q==} 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.3': + resolution: {integrity: sha512-4vKmvAst9nrowcqquKFAyZJUDolUaIp8uRiN0mWFguJ1IplC9/pitXtlnnlU4aa/eJw3J7i67V+pwUL+wZGdsA==} 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.3': + resolution: {integrity: sha512-Y9kQaLMuNoB0bPYOOdcZMaseNrFpPodIWWMrx+CZyydf2xn68j9WYc6sWWRrDwNkzCQjKYfc68L7jKjGlHMibw==} 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.3': + resolution: {integrity: sha512-fj8Mv0HHfD1Rr+4I68+3agJynxDWtBFgicTbSOb9Bke6pIwzGcJ+RX/yHjmiEGFMCavY/dxvem7MyNaJF+wDiw==} 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.4': + resolution: {integrity: sha512-De4jpEnAU8Hd5oT0j1G3uL4ZvTuipVMn7YC6vPaJhy6/7EwEae0SVAoBrUMYQbkLGDm85taVWwuPc1a44LTzCQ==} + 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.4': + resolution: {integrity: sha512-7OAS8gI0EReKGVN2HssHlM6umJgxF5VI3xN0p9FA91p/YO+ou5hiNghLdZ5BEHztwaaK5+bLKRf8x/o2L2nk9A==} + 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.4': + resolution: {integrity: sha512-2oYZJeIl4kCcMGk4ouZVjnkCtFrpQFlNEtJ6GbxzhHQchwH0NH/qEb9ykmOl29dqwMq+JhFdZn+1ak2FKhI9fQ==} + engines: {node: '>=20.9.0'} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@img/sharp-linux-riscv64@0.35.4': + resolution: {integrity: sha512-cPbNChoRURAWdebDIHSenxRpgEdy7JkPydSnUxRm9VvKD7m0/xVaR/8Fzlu81pk5nHEvHH87UZUA7cTtwnbJSA==} + 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==} + 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.4': + resolution: {integrity: sha512-9qvvEAuk8k89TfWUoX2htWjbAMX8p+NxCppjpcg5k6xMsjhBQPTsoIh36h9Qde4WRuGpJeYnOjdosDn/cnv+OA==} + 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.4': + resolution: {integrity: sha512-KB5jxpfWQTr0nc3xdHtWChdbifHrBGsd2SM62Eyxrl8afikm+f5qGBU75SJIZBT/S1MC8XyacdlXBMSWq6OURA==} + 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.4': + resolution: {integrity: sha512-f+eZJZIQNEEd26RPSW+76chwOf1XtA2Y/O+5ocVyLliHkeih3e+jhLVBdNTd2rS3IbNXK8+ug93Vf5ZXtF5Lxg==} + 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.4': + resolution: {integrity: sha512-zQnl4Kwp7Q6NHsENtU2T/00Zi+w3AQNwz3+UaTyVBy2FpXrzXzGjndpK61onhZjRtRpQXxCTeqw19bVyXOh7jA==} + engines: {node: '>=20.9.0'} + + '@img/sharp-webcontainers-wasm32@0.35.4': + resolution: {integrity: sha512-ESfNkywmCfPNyaZjxooddJQiQ+l/nTpGEOGthxiLnIHXC/CmcBixnfwUleX9mCz9ovrUUvKMap/pm8RYbzfwaA==} + 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.4': + resolution: {integrity: sha512-iNdlBX9gLVvqe2I3uIJSIKTq6wckP/DYxZtcqxm09x5Gi24DnFBmPAWZmr60ZyYMG0xlzo6goG3670ar+RXvRw==} + engines: {node: '>=20.9.0'} + cpu: [arm64] + os: [win32] + + '@img/sharp-win32-ia32@0.35.4': + resolution: {integrity: sha512-kqRsbaa5CS6KHlpxnN7WhE6vAAugXyZButpRdvDWetlv6Qv4N9WTcrWzF7tXfB9T7MsoadqdI8hmwLq6UlLvtw==} + 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.4': + resolution: {integrity: sha512-XtmnYhBcrORsJ4XJngyzr/EWP0hRZLAZRFaApdKuviyqF78+ylxh2y06ZmtULAMOnObJ3ucpN0AcwSWnMowTRg==} + engines: {node: '>=20.9.0'} cpu: [x64] os: [win32] @@ -1317,26 +1394,26 @@ packages: resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==} engines: {node: '>=8.0.0'} - '@opentelemetry/core@1.30.1': - resolution: {integrity: sha512-OOCM2C/QIURhJMuKaekP3TRBxBKxG/TWWA0TL2J6nXUtDnuCtccy49LUJF8xPFXMX+0LMcxFpCo8M9cGY1W6rQ==} - engines: {node: '>=14'} + '@opentelemetry/core@2.10.0': + resolution: {integrity: sha512-/wNZ8twnEQQA4HoHu22+vcsdru6pWPWxW+7w+FlxT6Id7PE/WIbZmVKkte+PF72e0F2dnImFeHD2syyE1Mw6MQ==} + engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.0.0 <1.10.0' - '@opentelemetry/resources@1.30.1': - resolution: {integrity: sha512-5UxZqiAgLYGFjS4s9qm5mBVo433u+dSPUFWVWXmLAD4wB65oMCoXaJP1KJa9DIYYMeHu3z4BZcStG3LC593cWA==} - engines: {node: '>=14'} - peerDependencies: - '@opentelemetry/api': '>=1.0.0 <1.10.0' - - '@opentelemetry/sdk-metrics@1.30.1': - resolution: {integrity: sha512-q9zcZ0Okl8jRgmy7eNW3Ku1XSgg3sDLa5evHZpCwjspw7E8Is4K/haRPDJrBcX3YSn/Y7gUvFnByNYEKQNbNog==} - engines: {node: '>=14'} + '@opentelemetry/resources@2.10.0': + resolution: {integrity: sha512-q6MMm2zhggzsHVNbabYwut+a6nbuQQe3URUoxaojM/8K1IBfwwPzvxIjNi2/lI1TFe+fMHMW9MWhrtDLEXEnkA==} + engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.3.0 <1.10.0' - '@opentelemetry/semantic-conventions@1.28.0': - resolution: {integrity: sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==} + '@opentelemetry/sdk-metrics@2.10.0': + resolution: {integrity: sha512-t6r1VSvXNtSDnPXU1FbZeetJb7yyovHmgu0wRSoftxtE0g2rSNhQZQUy69sRUCL+iioJpX8SN/S6wq6ZtvLySQ==} + 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==} engines: {node: '>=14'} '@protobufjs/aspromise@1.1.2': @@ -1348,18 +1425,15 @@ packages: '@protobufjs/codegen@2.0.5': resolution: {integrity: sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==} - '@protobufjs/eventemitter@1.1.0': - resolution: {integrity: sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==} + '@protobufjs/eventemitter@1.1.1': + resolution: {integrity: sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==} - '@protobufjs/fetch@1.1.0': - resolution: {integrity: sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==} + '@protobufjs/fetch@1.1.1': + resolution: {integrity: sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==} '@protobufjs/float@1.0.2': resolution: {integrity: sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==} - '@protobufjs/inquire@1.1.1': - resolution: {integrity: sha512-mnzgDV26ueAvk7rsbt9L7bE0SuAoqyuys/sMMrmVcN5x9VsxpcG3rqAUSgDyLp0UZlmNfIbQ4fHfCtreVBk8Ew==} - '@protobufjs/path@1.1.2': resolution: {integrity: sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==} @@ -1718,6 +1792,10 @@ packages: engines: {node: '>=0.4.0'} hasBin: true + agent-base@6.0.2: + resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==} + engines: {node: '>= 6.0.0'} + agentkeepalive@4.6.0: resolution: {integrity: sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==} engines: {node: '>= 8.0.0'} @@ -1786,8 +1864,8 @@ packages: asynckit@0.4.0: resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} - axios@1.16.0: - resolution: {integrity: sha512-6hp5CwvTPlN2A31g5dxnwAX0orzM7pmCRDLnZSX772mv8WDqICwFjowHuPs04Mc8deIld1+ejhtaMn5vp6b+1w==} + axios@1.20.0: + resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==} babel-jest@29.7.0: resolution: {integrity: sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==} @@ -1820,8 +1898,8 @@ packages: base-64@0.1.0: resolution: {integrity: sha512-Y5gU45svrR5tI2Vt/X9GPd3L0HNIKzGu202EjxrXMpuc2V2CiKgemAbUUsqYmZJvPtCXoUKjNZwBJzsNScUbXA==} - baseline-browser-mapping@2.10.29: - resolution: {integrity: sha512-Asa2krT+XTPZINCS+2QcyS8WTkObE77RwkydwF7h6DmnKqbvlalz93m/dnphUyCa6SWSP51VgtEUf2FN+gelFQ==} + baseline-browser-mapping@2.11.19: + resolution: {integrity: sha512-Grytf1xOxOEMTGRwx6rLGKkTabd4vMg3VrKdj/7joCmV0qgh4QwMMO6xh34YEXQqirAuUdgQGa5orJQQ+69RBw==} engines: {node: '>=6.0.0'} hasBin: true @@ -1831,18 +1909,18 @@ packages: bowser@2.14.1: resolution: {integrity: sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==} - brace-expansion@1.1.14: - resolution: {integrity: sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==} + brace-expansion@1.1.18: + resolution: {integrity: sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==} - brace-expansion@2.1.0: - resolution: {integrity: sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==} + brace-expansion@2.1.4: + resolution: {integrity: sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==} braces@3.0.3: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} - browserslist@4.28.2: - resolution: {integrity: sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==} + browserslist@4.28.8: + resolution: {integrity: sha512-V2NpofLblG64mfOtSgDhOJESZEGogzDMBv/q+W6oc4LXWP/q75eOXoOaaOu1EOadB9U4Bwx/e0yzbvwKH8zalA==} engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true @@ -1872,8 +1950,8 @@ packages: resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==} engines: {node: '>=10'} - caniuse-lite@1.0.30001792: - resolution: {integrity: sha512-hVLMUZFgR4JJ6ACt1uEESvQN1/dBVqPAKY0hgrV70eN3391K6juAfTjKZLKvOMsx8PxA7gsY1/tLMMTcfFLLpw==} + caniuse-lite@1.0.30001810: + resolution: {integrity: sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==} ccount@2.0.1: resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==} @@ -1940,13 +2018,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'} - colorette@2.0.20: resolution: {integrity: sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==} @@ -2045,8 +2116,8 @@ packages: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} - electron-to-chromium@1.5.353: - resolution: {integrity: sha512-kOrWphBi8TOZyiJZqsgqIle0lw+tzmnQK83pV9dZUd01Nm2POECSyFQMAuarzZdYqQW7FH9RaYOuaRo3h+bQ3w==} + electron-to-chromium@1.5.415: + resolution: {integrity: sha512-958V+Kbhtgz+SxXeEVKBjrlKRBIDAYvUJfwhjxMZ5S6ut9jAl7l9ZKBkBrvjyjZE36PabLUo2L8kEeV5O4vgJg==} emittery@0.13.1: resolution: {integrity: sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==} @@ -2245,8 +2316,8 @@ packages: form-data-encoder@1.7.2: resolution: {integrity: sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==} - form-data@4.0.5: - resolution: {integrity: sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==} + form-data@4.0.6: + resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==} engines: {node: '>= 6'} formdata-node@4.4.1: @@ -2342,6 +2413,10 @@ packages: resolution: {integrity: sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==} engines: {node: '>= 0.4'} + hasown@2.0.4: + resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} + engines: {node: '>= 0.4'} + hast-util-to-html@9.0.5: resolution: {integrity: sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==} @@ -2354,6 +2429,10 @@ packages: html-void-elements@3.0.0: resolution: {integrity: sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==} + https-proxy-agent@5.0.1: + resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==} + engines: {node: '>= 6'} + human-signals@2.1.0: resolution: {integrity: sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==} engines: {node: '>=10.17.0'} @@ -2396,9 +2475,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==} @@ -2593,12 +2669,12 @@ packages: js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} - js-yaml@3.14.2: - resolution: {integrity: sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==} + js-yaml@3.15.1: + resolution: {integrity: sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==} hasBin: true - js-yaml@4.1.1: - resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} + js-yaml@4.3.1: + resolution: {integrity: sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==} hasBin: true jsesc@3.1.0: @@ -2648,8 +2724,8 @@ packages: lines-and-columns@1.2.4: resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} - linkify-it@5.0.0: - resolution: {integrity: sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==} + linkify-it@5.0.2: + resolution: {integrity: sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q==} locate-path@5.0.0: resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==} @@ -2687,8 +2763,8 @@ packages: makeerror@1.0.12: resolution: {integrity: sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==} - markdown-it@14.1.1: - resolution: {integrity: sha512-BuU2qnTti9YKgK5N+IeMubp14ZUKUUw7yeJbkjtosvHiP0AZ5c8IAgEMk79D0eC8F23r4Ac/q8cAIFdm2FtyoA==} + markdown-it@14.3.0: + resolution: {integrity: sha512-RCEsPjR+sr0x+AuYp601tKTkgFG4YEPLCzHST3cQ/fhlJkqAkz1L2/Qbp1j9qw5SBwQHFBoW8+hoN5xssOF0Tw==} hasBin: true math-intrinsics@1.1.0: @@ -2793,8 +2869,9 @@ packages: node-int64@0.4.0: resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==} - node-releases@2.0.38: - resolution: {integrity: sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==} + node-releases@2.0.53: + resolution: {integrity: sha512-D9UOmYG3UH1V+ENW56t5QXBwJw1YEY18ruVeus89Rw+SyIgjPkCO84bRzO3uNIYosJbNwiabWVn48o3uJLjxFQ==} + engines: {node: '>=18'} normalize-path@3.0.0: resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} @@ -2925,8 +3002,8 @@ packages: property-information@7.1.0: resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==} - protobufjs@7.5.7: - resolution: {integrity: sha512-NGnrxS/nLKUo5nkbVQxlC71sB4hdfImdYIbFeSCidxtwATx0AHRPcANSLd0q5Bb2BkoSWo2iisQhGg5/r+ihbA==} + protobufjs@7.6.5: + resolution: {integrity: sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw==} engines: {node: '>=12.0.0'} proxy-from-env@2.1.0: @@ -3015,9 +3092,19 @@ packages: 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} + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + + sharp@0.35.4: + resolution: {integrity: sha512-n++8XWcj+jCOr2IOl7h8LbKnGBDY4aPbmprMONBNFdn0ImXqpGVv5zliDs0V9HbmbCQLpbuo2ej9rAoOQTvMDA==} + 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==} @@ -3047,9 +3134,6 @@ packages: resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} engines: {node: '>=14'} - simple-swizzle@0.2.4: - resolution: {integrity: sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==} - sisteransi@1.0.5: resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==} @@ -3120,8 +3204,8 @@ packages: resolution: {integrity: sha512-iK5/YhZxq5GO5z8wb0bY1317uDF3Zjpha0QFFLA8/trAoiLbQD0HUbMesEaxyzUgDxi2QlcbM8IvqOlEjgoXBA==} engines: {node: '>=12.17'} - tar@7.5.15: - resolution: {integrity: sha512-dzGK0boVlC4W5QFuQN1EFSl3bIDYsk7Tj40U6eIBnK2k/8ml7TZ5agbI5j5+qnoVcAA+rNtBml8SEiLxZpNqRQ==} + tar@7.5.22: + resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==} engines: {node: '>=18'} test-exclude@6.0.0: @@ -3131,8 +3215,8 @@ packages: text-table@0.2.0: resolution: {integrity: sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==} - tmp@0.2.5: - resolution: {integrity: sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==} + tmp@0.2.7: + resolution: {integrity: sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==} engines: {node: '>=14.14'} tmpl@1.0.5: @@ -3278,8 +3362,8 @@ packages: universal-user-agent@7.0.3: resolution: {integrity: sha512-TmnEAEAsBJVZM/AADELsK76llnwcf9vMKuPz8JflO1frO8Lchitr0fNaN9d+Ap0BjKtqWqd/J17qeDnXh8CL2A==} - update-browserslist-db@1.2.3: - resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==} + update-browserslist-db@1.3.1: + resolution: {integrity: sha512-ZZ61DsRsOnakl74HAmp3oSN4aXUmEWXf+i/yv0h7tIBfICc3VdrFErQKUUKPgu3AMsTUMbcongALEN4l6GSUrQ==} hasBin: true peerDependencies: browserslist: '>= 4.21.0' @@ -3944,19 +4028,25 @@ snapshots: js-tokens: 4.0.0 picocolors: 1.1.1 - '@babel/compat-data@7.29.3': {} - - '@babel/core@7.29.0': + '@babel/code-frame@7.29.7': dependencies: - '@babel/code-frame': 7.29.0 - '@babel/generator': 7.29.1 - '@babel/helper-compilation-targets': 7.28.6 - '@babel/helper-module-transforms': 7.28.6(@babel/core@7.29.0) - '@babel/helpers': 7.29.2 - '@babel/parser': 7.29.3 - '@babel/template': 7.28.6 - '@babel/traverse': 7.29.0 - '@babel/types': 7.29.0 + '@babel/helper-validator-identifier': 7.29.7 + js-tokens: 4.0.0 + picocolors: 1.1.1 + + '@babel/compat-data@7.29.7': {} + + '@babel/core@7.29.7': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/generator': 7.29.8 + '@babel/helper-compilation-targets': 7.29.7 + '@babel/helper-module-transforms': 7.29.7(@babel/core@7.29.7) + '@babel/helpers': 7.29.7 + '@babel/parser': 7.29.8 + '@babel/template': 7.29.7 + '@babel/traverse': 7.29.8 + '@babel/types': 7.29.8 '@jridgewell/remapping': 2.3.5 convert-source-map: 2.0.0 debug: 4.4.3 @@ -3974,29 +4064,37 @@ snapshots: '@jridgewell/trace-mapping': 0.3.31 jsesc: 3.1.0 - '@babel/helper-compilation-targets@7.28.6': + '@babel/generator@7.29.8': dependencies: - '@babel/compat-data': 7.29.3 - '@babel/helper-validator-option': 7.27.1 - browserslist: 4.28.2 + '@babel/parser': 7.29.8 + '@babel/types': 7.29.8 + '@jridgewell/gen-mapping': 0.3.13 + '@jridgewell/trace-mapping': 0.3.31 + jsesc: 3.1.0 + + '@babel/helper-compilation-targets@7.29.7': + dependencies: + '@babel/compat-data': 7.29.7 + '@babel/helper-validator-option': 7.29.7 + browserslist: 4.28.8 lru-cache: 5.1.1 semver: 6.3.1 - '@babel/helper-globals@7.28.0': {} + '@babel/helper-globals@7.29.7': {} - '@babel/helper-module-imports@7.28.6': + '@babel/helper-module-imports@7.29.7': dependencies: - '@babel/traverse': 7.29.0 - '@babel/types': 7.29.0 + '@babel/traverse': 7.29.8 + '@babel/types': 7.29.8 transitivePeerDependencies: - supports-color - '@babel/helper-module-transforms@7.28.6(@babel/core@7.29.0)': + '@babel/helper-module-transforms@7.29.7(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 - '@babel/helper-module-imports': 7.28.6 - '@babel/helper-validator-identifier': 7.28.5 - '@babel/traverse': 7.29.0 + '@babel/core': 7.29.7 + '@babel/helper-module-imports': 7.29.7 + '@babel/helper-validator-identifier': 7.29.7 + '@babel/traverse': 7.29.8 transitivePeerDependencies: - supports-color @@ -4004,102 +4102,110 @@ snapshots: '@babel/helper-string-parser@7.27.1': {} + '@babel/helper-string-parser@7.29.7': {} + '@babel/helper-validator-identifier@7.28.5': {} - '@babel/helper-validator-option@7.27.1': {} + '@babel/helper-validator-identifier@7.29.7': {} - '@babel/helpers@7.29.2': + '@babel/helper-validator-option@7.29.7': {} + + '@babel/helpers@7.29.7': dependencies: - '@babel/template': 7.28.6 - '@babel/types': 7.29.0 + '@babel/template': 7.29.7 + '@babel/types': 7.29.8 '@babel/parser@7.29.3': dependencies: '@babel/types': 7.29.0 - '@babel/plugin-syntax-async-generators@7.8.4(@babel/core@7.29.0)': + '@babel/parser@7.29.8': dependencies: - '@babel/core': 7.29.0 + '@babel/types': 7.29.8 + + '@babel/plugin-syntax-async-generators@7.8.4(@babel/core@7.29.7)': + dependencies: + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-bigint@7.8.3(@babel/core@7.29.0)': + '@babel/plugin-syntax-bigint@7.8.3(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-class-properties@7.12.13(@babel/core@7.29.0)': + '@babel/plugin-syntax-class-properties@7.12.13(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-class-static-block@7.14.5(@babel/core@7.29.0)': + '@babel/plugin-syntax-class-static-block@7.14.5(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-import-attributes@7.28.6(@babel/core@7.29.0)': + '@babel/plugin-syntax-import-attributes@7.28.6(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-import-meta@7.10.4(@babel/core@7.29.0)': + '@babel/plugin-syntax-import-meta@7.10.4(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-json-strings@7.8.3(@babel/core@7.29.0)': + '@babel/plugin-syntax-json-strings@7.8.3(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.0)': + '@babel/plugin-syntax-jsx@7.28.6(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-logical-assignment-operators@7.10.4(@babel/core@7.29.0)': + '@babel/plugin-syntax-logical-assignment-operators@7.10.4(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-nullish-coalescing-operator@7.8.3(@babel/core@7.29.0)': + '@babel/plugin-syntax-nullish-coalescing-operator@7.8.3(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-numeric-separator@7.10.4(@babel/core@7.29.0)': + '@babel/plugin-syntax-numeric-separator@7.10.4(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-object-rest-spread@7.8.3(@babel/core@7.29.0)': + '@babel/plugin-syntax-object-rest-spread@7.8.3(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-optional-catch-binding@7.8.3(@babel/core@7.29.0)': + '@babel/plugin-syntax-optional-catch-binding@7.8.3(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-optional-chaining@7.8.3(@babel/core@7.29.0)': + '@babel/plugin-syntax-optional-chaining@7.8.3(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-private-property-in-object@7.14.5(@babel/core@7.29.0)': + '@babel/plugin-syntax-private-property-in-object@7.14.5(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-top-level-await@7.14.5(@babel/core@7.29.0)': + '@babel/plugin-syntax-top-level-await@7.14.5(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 - '@babel/plugin-syntax-typescript@7.28.6(@babel/core@7.29.0)': + '@babel/plugin-syntax-typescript@7.28.6(@babel/core@7.29.7)': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/helper-plugin-utils': 7.28.6 '@babel/template@7.28.6': @@ -4108,14 +4214,20 @@ snapshots: '@babel/parser': 7.29.3 '@babel/types': 7.29.0 - '@babel/traverse@7.29.0': + '@babel/template@7.29.7': dependencies: - '@babel/code-frame': 7.29.0 - '@babel/generator': 7.29.1 - '@babel/helper-globals': 7.28.0 - '@babel/parser': 7.29.3 - '@babel/template': 7.28.6 - '@babel/types': 7.29.0 + '@babel/code-frame': 7.29.7 + '@babel/parser': 7.29.8 + '@babel/types': 7.29.8 + + '@babel/traverse@7.29.8': + dependencies: + '@babel/code-frame': 7.29.7 + '@babel/generator': 7.29.8 + '@babel/helper-globals': 7.29.7 + '@babel/parser': 7.29.8 + '@babel/template': 7.29.7 + '@babel/types': 7.29.8 debug: 4.4.3 transitivePeerDependencies: - supports-color @@ -4125,6 +4237,11 @@ snapshots: '@babel/helper-string-parser': 7.27.1 '@babel/helper-validator-identifier': 7.28.5 + '@babel/types@7.29.8': + dependencies: + '@babel/helper-string-parser': 7.29.7 + '@babel/helper-validator-identifier': 7.29.7 + '@bcoe/v8-coverage@0.2.3': {} '@biomejs/biome@1.9.4': @@ -4168,7 +4285,7 @@ snapshots: tslib: 2.8.1 optional: true - '@emnapi/runtime@1.10.0': + '@emnapi/runtime@1.11.3': dependencies: tslib: 2.8.1 optional: true @@ -4193,7 +4310,7 @@ snapshots: globals: 13.24.0 ignore: 5.3.2 import-fresh: 3.3.1 - js-yaml: 4.1.1 + js-yaml: 4.3.1 minimatch: 3.1.5 strip-json-comments: 3.1.1 transitivePeerDependencies: @@ -4204,12 +4321,14 @@ snapshots: '@huggingface/jinja@0.3.4': optional: true - '@huggingface/transformers@3.0.2': + '@huggingface/transformers@3.0.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.33.5 + sharp: 0.35.4(@types/node@22.7.4) + transitivePeerDependencies: + - '@types/node' optional: true '@humanwhocodes/config-array@0.13.0': @@ -4224,79 +4343,111 @@ snapshots: '@humanwhocodes/object-schema@2.0.3': {} - '@img/sharp-darwin-arm64@0.33.5': + '@img/colour@1.1.0': + optional: true + + '@img/sharp-darwin-arm64@0.35.4': optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.0.4 + '@img/sharp-libvips-darwin-arm64': 1.3.3 optional: true - '@img/sharp-darwin-x64@0.33.5': + '@img/sharp-darwin-x64@0.35.4': optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.0.4 + '@img/sharp-libvips-darwin-x64': 1.3.3 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.4': dependencies: - '@emnapi/runtime': 1.10.0 + '@img/sharp-wasm32': 0.35.4 optional: true - '@img/sharp-win32-ia32@0.33.5': + '@img/sharp-libvips-darwin-arm64@1.3.3': optional: true - '@img/sharp-win32-x64@0.33.5': + '@img/sharp-libvips-darwin-x64@1.3.3': + optional: true + + '@img/sharp-libvips-linux-arm64@1.3.3': + optional: true + + '@img/sharp-libvips-linux-arm@1.3.3': + optional: true + + '@img/sharp-libvips-linux-ppc64@1.3.3': + optional: true + + '@img/sharp-libvips-linux-riscv64@1.3.3': + optional: true + + '@img/sharp-libvips-linux-s390x@1.3.3': + optional: true + + '@img/sharp-libvips-linux-x64@1.3.3': + optional: true + + '@img/sharp-libvips-linuxmusl-arm64@1.3.3': + optional: true + + '@img/sharp-libvips-linuxmusl-x64@1.3.3': + optional: true + + '@img/sharp-linux-arm64@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linux-arm64': 1.3.3 + optional: true + + '@img/sharp-linux-arm@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linux-arm': 1.3.3 + optional: true + + '@img/sharp-linux-ppc64@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linux-ppc64': 1.3.3 + optional: true + + '@img/sharp-linux-riscv64@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linux-riscv64': 1.3.3 + optional: true + + '@img/sharp-linux-s390x@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linux-s390x': 1.3.3 + optional: true + + '@img/sharp-linux-x64@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linux-x64': 1.3.3 + optional: true + + '@img/sharp-linuxmusl-arm64@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-arm64': 1.3.3 + optional: true + + '@img/sharp-linuxmusl-x64@0.35.4': + optionalDependencies: + '@img/sharp-libvips-linuxmusl-x64': 1.3.3 + optional: true + + '@img/sharp-wasm32@0.35.4': + dependencies: + '@emnapi/runtime': 1.11.3 + optional: true + + '@img/sharp-webcontainers-wasm32@0.35.4': + dependencies: + '@img/sharp-wasm32': 0.35.4 + optional: true + + '@img/sharp-win32-arm64@0.35.4': + optional: true + + '@img/sharp-win32-ia32@0.35.4': + optional: true + + '@img/sharp-win32-x64@0.35.4': optional: true '@inquirer/ansi@2.0.5': {} @@ -4428,7 +4579,7 @@ snapshots: camelcase: 5.3.1 find-up: 4.1.0 get-package-type: 0.1.0 - js-yaml: 3.14.2 + js-yaml: 3.15.1 resolve-from: 5.0.0 '@istanbuljs/schema@0.1.6': {} @@ -4568,7 +4719,7 @@ snapshots: '@jest/transform@29.7.0': dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@jest/types': 29.6.3 '@jridgewell/trace-mapping': 0.3.31 babel-plugin-istanbul: 6.1.1 @@ -4614,22 +4765,22 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 - '@napi-rs/cli@3.7.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)(@types/node@22.7.4)': + '@napi-rs/cli@3.7.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)(@types/node@22.7.4)': dependencies: '@inquirer/prompts': 8.4.3(@types/node@22.7.4) - '@napi-rs/cross-toolchain': 1.0.3(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) - '@napi-rs/wasm-tools': 1.0.1(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) + '@napi-rs/cross-toolchain': 1.0.3(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3) + '@napi-rs/wasm-tools': 1.0.1(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3) '@octokit/rest': 22.0.1 clipanion: 4.0.0-rc.4(typanion@3.14.0) colorette: 2.0.20 emnapi: 1.10.0 es-toolkit: 1.46.1 - js-yaml: 4.1.1 + js-yaml: 4.3.1 obug: 2.1.1 semver: 7.8.0 typanion: 3.14.0 optionalDependencies: - '@emnapi/runtime': 1.10.0 + '@emnapi/runtime': 1.11.3 transitivePeerDependencies: - '@emnapi/core' - '@napi-rs/cross-toolchain-arm64-target-aarch64' @@ -4646,10 +4797,10 @@ snapshots: - node-addon-api - supports-color - '@napi-rs/cross-toolchain@1.0.3(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': + '@napi-rs/cross-toolchain@1.0.3(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)': dependencies: - '@napi-rs/lzma': 1.4.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) - '@napi-rs/tar': 1.1.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) + '@napi-rs/lzma': 1.4.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3) + '@napi-rs/tar': 1.1.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3) debug: 4.4.3 transitivePeerDependencies: - '@emnapi/core' @@ -4695,9 +4846,9 @@ snapshots: '@napi-rs/lzma-linux-x64-musl@1.4.5': optional: true - '@napi-rs/lzma-wasm32-wasi@1.4.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': + '@napi-rs/lzma-wasm32-wasi@1.4.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)': dependencies: - '@napi-rs/wasm-runtime': 1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) + '@napi-rs/wasm-runtime': 1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3) transitivePeerDependencies: - '@emnapi/core' - '@emnapi/runtime' @@ -4712,7 +4863,7 @@ snapshots: '@napi-rs/lzma-win32-x64-msvc@1.4.5': optional: true - '@napi-rs/lzma@1.4.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': + '@napi-rs/lzma@1.4.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)': optionalDependencies: '@napi-rs/lzma-android-arm-eabi': 1.4.5 '@napi-rs/lzma-android-arm64': 1.4.5 @@ -4727,7 +4878,7 @@ snapshots: '@napi-rs/lzma-linux-s390x-gnu': 1.4.5 '@napi-rs/lzma-linux-x64-gnu': 1.4.5 '@napi-rs/lzma-linux-x64-musl': 1.4.5 - '@napi-rs/lzma-wasm32-wasi': 1.4.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) + '@napi-rs/lzma-wasm32-wasi': 1.4.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3) '@napi-rs/lzma-win32-arm64-msvc': 1.4.5 '@napi-rs/lzma-win32-ia32-msvc': 1.4.5 '@napi-rs/lzma-win32-x64-msvc': 1.4.5 @@ -4771,9 +4922,9 @@ snapshots: '@napi-rs/tar-linux-x64-musl@1.1.0': optional: true - '@napi-rs/tar-wasm32-wasi@1.1.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': + '@napi-rs/tar-wasm32-wasi@1.1.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)': dependencies: - '@napi-rs/wasm-runtime': 1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) + '@napi-rs/wasm-runtime': 1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3) transitivePeerDependencies: - '@emnapi/core' - '@emnapi/runtime' @@ -4788,7 +4939,7 @@ snapshots: '@napi-rs/tar-win32-x64-msvc@1.1.0': optional: true - '@napi-rs/tar@1.1.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': + '@napi-rs/tar@1.1.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)': optionalDependencies: '@napi-rs/tar-android-arm-eabi': 1.1.0 '@napi-rs/tar-android-arm64': 1.1.0 @@ -4802,7 +4953,7 @@ snapshots: '@napi-rs/tar-linux-s390x-gnu': 1.1.0 '@napi-rs/tar-linux-x64-gnu': 1.1.0 '@napi-rs/tar-linux-x64-musl': 1.1.0 - '@napi-rs/tar-wasm32-wasi': 1.1.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) + '@napi-rs/tar-wasm32-wasi': 1.1.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3) '@napi-rs/tar-win32-arm64-msvc': 1.1.0 '@napi-rs/tar-win32-ia32-msvc': 1.1.0 '@napi-rs/tar-win32-x64-msvc': 1.1.0 @@ -4810,10 +4961,10 @@ snapshots: - '@emnapi/core' - '@emnapi/runtime' - '@napi-rs/wasm-runtime@1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': + '@napi-rs/wasm-runtime@1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)': dependencies: '@emnapi/core': 1.10.0 - '@emnapi/runtime': 1.10.0 + '@emnapi/runtime': 1.11.3 '@tybys/wasm-util': 0.10.2 optional: true @@ -4844,9 +4995,9 @@ snapshots: '@napi-rs/wasm-tools-linux-x64-musl@1.0.1': optional: true - '@napi-rs/wasm-tools-wasm32-wasi@1.0.1(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': + '@napi-rs/wasm-tools-wasm32-wasi@1.0.1(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)': dependencies: - '@napi-rs/wasm-runtime': 1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) + '@napi-rs/wasm-runtime': 1.1.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3) transitivePeerDependencies: - '@emnapi/core' - '@emnapi/runtime' @@ -4861,7 +5012,7 @@ snapshots: '@napi-rs/wasm-tools-win32-x64-msvc@1.0.1': optional: true - '@napi-rs/wasm-tools@1.0.1(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)': + '@napi-rs/wasm-tools@1.0.1(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3)': optionalDependencies: '@napi-rs/wasm-tools-android-arm-eabi': 1.0.1 '@napi-rs/wasm-tools-android-arm64': 1.0.1 @@ -4872,7 +5023,7 @@ snapshots: '@napi-rs/wasm-tools-linux-arm64-musl': 1.0.1 '@napi-rs/wasm-tools-linux-x64-gnu': 1.0.1 '@napi-rs/wasm-tools-linux-x64-musl': 1.0.1 - '@napi-rs/wasm-tools-wasm32-wasi': 1.0.1(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0) + '@napi-rs/wasm-tools-wasm32-wasi': 1.0.1(@emnapi/core@1.10.0)(@emnapi/runtime@1.11.3) '@napi-rs/wasm-tools-win32-arm64-msvc': 1.0.1 '@napi-rs/wasm-tools-win32-ia32-msvc': 1.0.1 '@napi-rs/wasm-tools-win32-x64-msvc': 1.0.1 @@ -4959,24 +5110,24 @@ snapshots: '@opentelemetry/api@1.9.1': {} - '@opentelemetry/core@1.30.1(@opentelemetry/api@1.9.1)': + '@opentelemetry/core@2.10.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/semantic-conventions': 1.28.0 + '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/resources@1.30.1(@opentelemetry/api@1.9.1)': + '@opentelemetry/resources@2.10.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 1.30.1(@opentelemetry/api@1.9.1) - '@opentelemetry/semantic-conventions': 1.28.0 + '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) + '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/sdk-metrics@1.30.1(@opentelemetry/api@1.9.1)': + '@opentelemetry/sdk-metrics@2.10.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 1.30.1(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 1.30.1(@opentelemetry/api@1.9.1) + '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) + '@opentelemetry/resources': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/semantic-conventions@1.28.0': {} + '@opentelemetry/semantic-conventions@1.43.0': {} '@protobufjs/aspromise@1.1.2': optional: true @@ -4987,21 +5138,17 @@ snapshots: '@protobufjs/codegen@2.0.5': optional: true - '@protobufjs/eventemitter@1.1.0': + '@protobufjs/eventemitter@1.1.1': optional: true - '@protobufjs/fetch@1.1.0': + '@protobufjs/fetch@1.1.1': dependencies: '@protobufjs/aspromise': 1.1.2 - '@protobufjs/inquire': 1.1.1 optional: true '@protobufjs/float@1.0.2': optional: true - '@protobufjs/inquire@1.1.1': - optional: true - '@protobufjs/path@1.1.2': optional: true @@ -5281,9 +5428,10 @@ snapshots: '@types/axios@0.14.4': dependencies: - axios: 1.16.0 + axios: 1.20.0 transitivePeerDependencies: - debug + - supports-color '@types/babel__core@7.20.5': dependencies: @@ -5340,7 +5488,7 @@ snapshots: '@types/node-fetch@2.6.13': dependencies: '@types/node': 22.7.4 - form-data: 4.0.5 + form-data: 4.0.6 optional: true '@types/node@18.19.130': @@ -5462,6 +5610,12 @@ snapshots: acorn@8.16.0: {} + agent-base@6.0.2: + dependencies: + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + agentkeepalive@4.6.0: dependencies: humanize-ms: 1.2.1 @@ -5565,21 +5719,23 @@ snapshots: asynckit@0.4.0: {} - axios@1.16.0: + axios@1.20.0: dependencies: follow-redirects: 1.16.0 - form-data: 4.0.5 + form-data: 4.0.6 + https-proxy-agent: 5.0.1 proxy-from-env: 2.1.0 transitivePeerDependencies: - debug + - supports-color - babel-jest@29.7.0(@babel/core@7.29.0): + babel-jest@29.7.0(@babel/core@7.29.7): dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@jest/transform': 29.7.0 '@types/babel__core': 7.20.5 babel-plugin-istanbul: 6.1.1 - babel-preset-jest: 29.6.3(@babel/core@7.29.0) + babel-preset-jest: 29.6.3(@babel/core@7.29.7) chalk: 4.1.2 graceful-fs: 4.2.11 slash: 3.0.0 @@ -5603,48 +5759,48 @@ snapshots: '@types/babel__core': 7.20.5 '@types/babel__traverse': 7.28.0 - babel-preset-current-node-syntax@1.2.0(@babel/core@7.29.0): + babel-preset-current-node-syntax@1.2.0(@babel/core@7.29.7): dependencies: - '@babel/core': 7.29.0 - '@babel/plugin-syntax-async-generators': 7.8.4(@babel/core@7.29.0) - '@babel/plugin-syntax-bigint': 7.8.3(@babel/core@7.29.0) - '@babel/plugin-syntax-class-properties': 7.12.13(@babel/core@7.29.0) - '@babel/plugin-syntax-class-static-block': 7.14.5(@babel/core@7.29.0) - '@babel/plugin-syntax-import-attributes': 7.28.6(@babel/core@7.29.0) - '@babel/plugin-syntax-import-meta': 7.10.4(@babel/core@7.29.0) - '@babel/plugin-syntax-json-strings': 7.8.3(@babel/core@7.29.0) - '@babel/plugin-syntax-logical-assignment-operators': 7.10.4(@babel/core@7.29.0) - '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/core@7.29.0) - '@babel/plugin-syntax-numeric-separator': 7.10.4(@babel/core@7.29.0) - '@babel/plugin-syntax-object-rest-spread': 7.8.3(@babel/core@7.29.0) - '@babel/plugin-syntax-optional-catch-binding': 7.8.3(@babel/core@7.29.0) - '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/core@7.29.0) - '@babel/plugin-syntax-private-property-in-object': 7.14.5(@babel/core@7.29.0) - '@babel/plugin-syntax-top-level-await': 7.14.5(@babel/core@7.29.0) + '@babel/core': 7.29.7 + '@babel/plugin-syntax-async-generators': 7.8.4(@babel/core@7.29.7) + '@babel/plugin-syntax-bigint': 7.8.3(@babel/core@7.29.7) + '@babel/plugin-syntax-class-properties': 7.12.13(@babel/core@7.29.7) + '@babel/plugin-syntax-class-static-block': 7.14.5(@babel/core@7.29.7) + '@babel/plugin-syntax-import-attributes': 7.28.6(@babel/core@7.29.7) + '@babel/plugin-syntax-import-meta': 7.10.4(@babel/core@7.29.7) + '@babel/plugin-syntax-json-strings': 7.8.3(@babel/core@7.29.7) + '@babel/plugin-syntax-logical-assignment-operators': 7.10.4(@babel/core@7.29.7) + '@babel/plugin-syntax-nullish-coalescing-operator': 7.8.3(@babel/core@7.29.7) + '@babel/plugin-syntax-numeric-separator': 7.10.4(@babel/core@7.29.7) + '@babel/plugin-syntax-object-rest-spread': 7.8.3(@babel/core@7.29.7) + '@babel/plugin-syntax-optional-catch-binding': 7.8.3(@babel/core@7.29.7) + '@babel/plugin-syntax-optional-chaining': 7.8.3(@babel/core@7.29.7) + '@babel/plugin-syntax-private-property-in-object': 7.14.5(@babel/core@7.29.7) + '@babel/plugin-syntax-top-level-await': 7.14.5(@babel/core@7.29.7) - babel-preset-jest@29.6.3(@babel/core@7.29.0): + babel-preset-jest@29.6.3(@babel/core@7.29.7): dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 babel-plugin-jest-hoist: 29.6.3 - babel-preset-current-node-syntax: 1.2.0(@babel/core@7.29.0) + babel-preset-current-node-syntax: 1.2.0(@babel/core@7.29.7) balanced-match@1.0.2: {} base-64@0.1.0: optional: true - baseline-browser-mapping@2.10.29: {} + baseline-browser-mapping@2.11.19: {} before-after-hook@4.0.0: {} bowser@2.14.1: {} - brace-expansion@1.1.14: + brace-expansion@1.1.18: dependencies: balanced-match: 1.0.2 concat-map: 0.0.1 - brace-expansion@2.1.0: + brace-expansion@2.1.4: dependencies: balanced-match: 1.0.2 @@ -5652,13 +5808,13 @@ snapshots: dependencies: fill-range: 7.1.1 - browserslist@4.28.2: + browserslist@4.28.8: dependencies: - baseline-browser-mapping: 2.10.29 - caniuse-lite: 1.0.30001792 - electron-to-chromium: 1.5.353 - node-releases: 2.0.38 - update-browserslist-db: 1.2.3(browserslist@4.28.2) + baseline-browser-mapping: 2.11.19 + caniuse-lite: 1.0.30001810 + electron-to-chromium: 1.5.415 + node-releases: 2.0.53 + update-browserslist-db: 1.3.1(browserslist@4.28.8) bs-logger@0.2.6: dependencies: @@ -5681,7 +5837,7 @@ snapshots: camelcase@6.3.0: {} - caniuse-lite@1.0.30001792: {} + caniuse-lite@1.0.30001810: {} ccount@2.0.1: {} @@ -5734,18 +5890,6 @@ snapshots: color-name@1.1.4: {} - color-string@1.9.1: - dependencies: - color-name: 1.1.4 - simple-swizzle: 0.2.4 - optional: true - - color@4.2.3: - dependencies: - color-convert: 2.0.1 - color-string: 1.9.1 - optional: true - colorette@2.0.20: {} combined-stream@1.0.8: @@ -5841,7 +5985,7 @@ snapshots: es-errors: 1.3.0 gopd: 1.2.0 - electron-to-chromium@1.5.353: {} + electron-to-chromium@1.5.415: {} emittery@0.13.1: {} @@ -5870,7 +6014,7 @@ snapshots: es-errors: 1.3.0 get-intrinsic: 1.3.0 has-tostringtag: 1.0.2 - hasown: 2.0.3 + hasown: 2.0.4 es-toolkit@1.46.1: {} @@ -5918,7 +6062,7 @@ snapshots: imurmurhash: 0.1.4 is-glob: 4.0.3 is-path-inside: 3.0.3 - js-yaml: 4.1.1 + js-yaml: 4.3.1 json-stable-stringify-without-jsonify: 1.0.1 levn: 0.4.1 lodash.merge: 4.6.2 @@ -6063,12 +6207,12 @@ snapshots: form-data-encoder@1.7.2: optional: true - form-data@4.0.5: + form-data@4.0.6: dependencies: asynckit: 0.4.0 combined-stream: 1.0.8 es-set-tostringtag: 2.1.0 - hasown: 2.0.3 + hasown: 2.0.4 mime-types: 2.1.35 formdata-node@4.4.1: @@ -6098,7 +6242,7 @@ snapshots: get-proto: 1.0.1 gopd: 1.2.0 has-symbols: 1.1.0 - hasown: 2.0.3 + hasown: 2.0.4 math-intrinsics: 1.1.0 get-package-type@0.1.0: {} @@ -6170,6 +6314,10 @@ snapshots: dependencies: function-bind: 1.1.2 + hasown@2.0.4: + dependencies: + function-bind: 1.1.2 + hast-util-to-html@9.0.5: dependencies: '@types/hast': 3.0.4 @@ -6192,6 +6340,13 @@ snapshots: html-void-elements@3.0.0: {} + https-proxy-agent@5.0.1: + dependencies: + agent-base: 6.0.2 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + human-signals@2.1.0: {} humanize-ms@1.2.1: @@ -6228,9 +6383,6 @@ snapshots: is-arrayish@0.2.1: {} - is-arrayish@0.3.4: - optional: true - is-buffer@1.1.6: optional: true @@ -6260,7 +6412,7 @@ snapshots: istanbul-lib-instrument@5.2.1: dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/parser': 7.29.3 '@istanbuljs/schema': 0.1.6 istanbul-lib-coverage: 3.2.2 @@ -6270,7 +6422,7 @@ snapshots: istanbul-lib-instrument@6.0.3: dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/parser': 7.29.3 '@istanbuljs/schema': 0.1.6 istanbul-lib-coverage: 3.2.2 @@ -6350,10 +6502,10 @@ snapshots: jest-config@29.7.0(@types/node@22.7.4): dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@jest/test-sequencer': 29.7.0 '@jest/types': 29.6.3 - babel-jest: 29.7.0(@babel/core@7.29.0) + babel-jest: 29.7.0(@babel/core@7.29.7) chalk: 4.1.2 ci-info: 3.9.0 deepmerge: 4.3.1 @@ -6534,15 +6686,15 @@ snapshots: jest-snapshot@29.7.0: dependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@babel/generator': 7.29.1 - '@babel/plugin-syntax-jsx': 7.28.6(@babel/core@7.29.0) - '@babel/plugin-syntax-typescript': 7.28.6(@babel/core@7.29.0) + '@babel/plugin-syntax-jsx': 7.28.6(@babel/core@7.29.7) + '@babel/plugin-syntax-typescript': 7.28.6(@babel/core@7.29.7) '@babel/types': 7.29.0 '@jest/expect-utils': 29.7.0 '@jest/transform': 29.7.0 '@jest/types': 29.6.3 - babel-preset-current-node-syntax: 1.2.0(@babel/core@7.29.0) + babel-preset-current-node-syntax: 1.2.0(@babel/core@7.29.7) chalk: 4.1.2 expect: 29.7.0 graceful-fs: 4.2.11 @@ -6607,12 +6759,12 @@ snapshots: js-tokens@4.0.0: {} - js-yaml@3.14.2: + js-yaml@3.15.1: dependencies: argparse: 1.0.10 esprima: 4.0.1 - js-yaml@4.1.1: + js-yaml@4.3.1: dependencies: argparse: 2.0.1 @@ -6647,7 +6799,7 @@ snapshots: lines-and-columns@1.2.4: {} - linkify-it@5.0.0: + linkify-it@5.0.2: dependencies: uc.micro: 2.1.0 @@ -6684,11 +6836,11 @@ snapshots: dependencies: tmpl: 1.0.5 - markdown-it@14.1.1: + markdown-it@14.3.0: dependencies: argparse: 2.0.1 entities: 4.5.0 - linkify-it: 5.0.0 + linkify-it: 5.0.2 mdurl: 2.0.0 punycode.js: 2.3.1 uc.micro: 2.1.0 @@ -6752,11 +6904,11 @@ snapshots: minimatch@3.1.5: dependencies: - brace-expansion: 1.1.14 + brace-expansion: 1.1.18 minimatch@9.0.9: dependencies: - brace-expansion: 2.1.0 + brace-expansion: 2.1.4 minimist@1.2.8: {} @@ -6790,7 +6942,7 @@ snapshots: node-int64@0.4.0: {} - node-releases@2.0.38: {} + node-releases@2.0.53: {} normalize-path@3.0.0: {} @@ -6825,7 +6977,7 @@ snapshots: onnxruntime-node@1.19.2: dependencies: onnxruntime-common: 1.19.2 - tar: 7.5.15 + tar: 7.5.22 optional: true onnxruntime-web@1.21.0-dev.20241024-d9ca84ef96: @@ -6835,7 +6987,7 @@ snapshots: long: 5.3.2 onnxruntime-common: 1.20.0-dev.20241016-2b8fc5529b platform: 1.3.6 - protobufjs: 7.5.7 + protobufjs: 7.6.5 optional: true openai@4.29.2: @@ -6931,15 +7083,14 @@ snapshots: property-information@7.1.0: {} - protobufjs@7.5.7: + protobufjs@7.6.5: dependencies: '@protobufjs/aspromise': 1.1.2 '@protobufjs/base64': 1.1.2 '@protobufjs/codegen': 2.0.5 - '@protobufjs/eventemitter': 1.1.0 - '@protobufjs/fetch': 1.1.0 + '@protobufjs/eventemitter': 1.1.1 + '@protobufjs/fetch': 1.1.1 '@protobufjs/float': 1.0.2 - '@protobufjs/inquire': 1.1.1 '@protobufjs/path': 1.1.2 '@protobufjs/pool': 1.1.0 '@protobufjs/utf8': 1.1.1 @@ -7011,31 +7162,41 @@ snapshots: semver@7.8.0: {} - sharp@0.33.5: + semver@7.8.5: + optional: true + + sharp@0.35.4(@types/node@22.7.4): dependencies: - color: 4.2.3 + '@img/colour': 1.1.0 detect-libc: 2.1.2 - semver: 7.8.0 + semver: 7.8.5 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.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 + '@types/node': 22.7.4 optional: true shebang-command@2.0.0: @@ -7070,11 +7231,6 @@ snapshots: signal-exit@4.1.0: {} - simple-swizzle@0.2.4: - dependencies: - is-arrayish: 0.3.4 - optional: true - sisteransi@1.0.5: {} slash@3.0.0: {} @@ -7137,7 +7293,7 @@ snapshots: array-back: 6.2.3 wordwrapjs: 5.1.1 - tar@7.5.15: + tar@7.5.22: dependencies: '@isaacs/fs-minipass': 4.0.1 chownr: 3.0.0 @@ -7154,7 +7310,7 @@ snapshots: text-table@0.2.0: {} - tmp@0.2.5: {} + tmp@0.2.7: {} tmpl@1.0.5: {} @@ -7171,7 +7327,7 @@ snapshots: dependencies: typescript: 5.5.4 - ts-jest@29.4.9(@babel/core@7.29.0)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.0))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4): + ts-jest@29.4.9(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4): dependencies: bs-logger: 0.2.6 fast-json-stable-stringify: 2.1.0 @@ -7185,10 +7341,10 @@ snapshots: typescript: 5.5.4 yargs-parser: 21.1.1 optionalDependencies: - '@babel/core': 7.29.0 + '@babel/core': 7.29.7 '@jest/transform': 29.7.0 '@jest/types': 29.6.3 - babel-jest: 29.7.0(@babel/core@7.29.0) + babel-jest: 29.7.0(@babel/core@7.29.7) jest-util: 29.7.0 tslib@2.8.1: {} @@ -7214,7 +7370,7 @@ snapshots: typedoc@0.26.4(typescript@5.5.4): dependencies: lunr: 2.3.9 - markdown-it: 14.1.1 + markdown-it: 14.3.0 minimatch: 9.0.9 shiki: 1.29.2 typescript: 5.5.4 @@ -7274,9 +7430,9 @@ snapshots: universal-user-agent@7.0.3: {} - update-browserslist-db@1.2.3(browserslist@4.28.2): + update-browserslist-db@1.3.1(browserslist@4.28.8): dependencies: - browserslist: 4.28.2 + browserslist: 4.28.8 escalade: 3.2.0 picocolors: 1.1.1 diff --git a/nodejs/pnpm-workspace.yaml b/nodejs/pnpm-workspace.yaml index 06024e2f4..b6be57977 100644 --- a/nodejs/pnpm-workspace.yaml +++ b/nodejs/pnpm-workspace.yaml @@ -16,3 +16,41 @@ allowBuilds: onnxruntime-node: true protobufjs: true sharp: true + +minimumReleaseAgeExclude: + - protobufjs@7.5.8 + - tmp@0.2.6 + - form-data@4.0.6 + - tar@7.5.16 + - markdown-it@14.1.2 + - linkify-it@5.0.1 + - js-yaml@3.15.0 + - js-yaml@4.1.2 + - protobufjs@7.6.1 + - protobufjs@7.6.3 + - '@babel/core@7.29.1' + - axios@1.18.0 + - brace-expansion@2.1.2 + - brace-expansion@1.1.16 + - js-yaml@4.3.0 + - tar@7.5.18 + - tar@7.5.19 + - tar@7.5.17 + - protobufjs@7.6.5 + - linkify-it@5.0.2 + - sharp@0.35.0 + - brace-expansion@1.1.17 + - brace-expansion@2.1.3 + - brace-expansion@2.1.4 + - brace-expansion@1.1.18 + - js-yaml@3.15.1 + - 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 e639b1b6502345ca5632be3f61342980c1a7ba4a Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 3 Sep 2026 14:59:14 -0700 Subject: [PATCH 175/206] feat: add asynchronous remote SQL queries (#4070) ## Summary Add SQL execution to remote LanceDB connections. On the standard synchronous connection, `execute_query` waits for the initial result stream and returns its Arrow reader. `execute_query_async` is called without Python `await` and immediately returns a query handle for status inspection, streaming, or cancellation. Local databases report that SQL is not supported. The transport and query lifecycle live in Rust. Python exposes native-backed synchronous and asynchronous connection methods and query wrappers; it does not use PyArrow's Flight client. ## User experience The standard synchronous connection supports both direct reads and background query execution: ```python db = lancedb.connect( "db://analytics", api_key="ldb_...", sql_host_override="grpc+tls://sql.example.com:10026", ) # Direct execution waits only until the initial result stream is available. # Later batches continue streaming as the query progresses. reader = db.execute_query( "SELECT * FROM events", default_namespace_path=["production"], ) for batch in reader: print(batch.num_rows) # Background execution returns a query handle immediately. Despite the # `_async` suffix, no Python `await` is needed on a synchronous connection. query = db.execute_query_async("SELECT * FROM events") print(query.id) description = db.describe_query(query.id) print(description.status) print(description.progress) print(description.expires_at) # Start reading as soon as the service advertises partial results. The reader # continues polling and yields newly available record batches until the query # and all result endpoints are complete. reader = query.reader() for batch in reader: print(batch.num_rows) # Or cancel a different still-running query. Its status becomes "cancelling" # while the server is still working, then "cancelled" once confirmed. cancelled_query = db.execute_query_async("SELECT * FROM large_events") cancelled_query.cancel() ``` The less commonly used asynchronous connection exposes the same operations as coroutines: ```python async_db = await lancedb.connect_async( "db://analytics", api_key="ldb_...", sql_host_override="grpc+tls://sql.example.com:10026", ) query = await async_db.execute_query_async("SELECT * FROM events") async for batch in await query.reader(): print(batch.num_rows) ``` The UUIDv7 query id is scoped to the connection that submitted it. The connection retains lightweight shared query state used by `query.describe()` and `db.describe_query(query.id)`; the id does not encode SQL or a Flight continuation token and is not a cross-connection resume token. Abandoned state has bounded retention, and terminal state remains available briefly. Unqualified table names use the connected database and the `public` namespace by default. `default_namespace_path` accepts a list such as `["production", "events"]`. SQL can still use qualified names to reference other databases and namespaces available to the deployment. ## Design - Uses Arrow Flight `PollFlightInfo` for submission and long polling, `DoGet` for results, and `CancelFlightInfo` for cancellation. Each `PollInfo.info` is treated as the cumulative set of currently available endpoints, so advertised tickets are consumed once and batches can be delivered before execution is complete. - Serializes result completion and cancellation into one lifecycle. A server-accepted request reports `cancelling` and wakes blocked status/result work; a later retry can confirm `cancelled`. Result retrieval is rejected after cancellation is accepted, while cancellation after a result was already delivered is a no-op. - Assigns a time-ordered UUIDv7 connection-scoped query id and retains only shared evolving lifecycle state, keeping SQL, Flight continuation tokens, and Arrow result data out of public ids and the registry. - Leaves admission control to the server while honoring server expiration and a local fallback retention window for abandoned entries. - Retains terminal ids for five minutes so they remain available for connection-level description. - Keeps one lazily initialized SQL client on each remote database connection and attaches fresh authentication, routing, namespace, and request metadata to every operation. - Applies the configured overall timeout to each execution, description, reader, and cancellation operation. A result reader carries one absolute deadline from `reader()` through the end of streaming; connect and read timeouts continue to bound their individual phases. - Returns a bounded, backpressured, single-consumer Arrow stream rather than collecting the full result in memory. Dropping the reader stops downloading but does not implicitly cancel the server query. - Preserves typed schemas for empty result sets through the stream schema. - Accepts Flight result messages up to 1 GiB so a valid row containing a large blob, string, or vector is not rejected by tonic's 4 MiB default receive limit. - Supports the Python client first while keeping the authoritative implementation in the Rust core. --- .github/workflows/rust.yml | 5 +- Cargo.lock | 91 +- Cargo.toml | 4 +- docs/src/python/python.md | 59 + python/Cargo.toml | 3 +- python/pyproject.toml | 1 + python/python/lancedb/__init__.py | 17 + python/python/lancedb/_lancedb.pyi | 26 + python/python/lancedb/db.py | 80 + python/python/lancedb/namespace.py | 35 + python/python/lancedb/remote/db.py | 38 + python/python/lancedb/remote/header.py | 5 +- python/python/lancedb/sql.py | 88 ++ python/python/tests/test_header_provider.py | 30 +- python/python/tests/test_sql.py | 162 ++ python/src/connection.rs | 63 +- python/src/lib.rs | 3 + python/src/sql.rs | 90 ++ rust/lancedb/Cargo.toml | 6 + rust/lancedb/src/connection.rs | 124 +- rust/lancedb/src/database.rs | 16 + rust/lancedb/src/lib.rs | 1 + rust/lancedb/src/remote.rs | 1 + rust/lancedb/src/remote/db.rs | 51 +- rust/lancedb/src/remote/oauth.rs | 12 +- rust/lancedb/src/remote/sql.rs | 1471 +++++++++++++++++++ rust/lancedb/src/remote/sql_test.rs | 1040 +++++++++++++ rust/lancedb/src/sql.rs | 124 ++ 28 files changed, 3620 insertions(+), 26 deletions(-) create mode 100644 python/python/lancedb/sql.py create mode 100644 python/python/tests/test_sql.py create mode 100644 python/src/sql.rs create mode 100644 rust/lancedb/src/remote/sql.rs create mode 100644 rust/lancedb/src/remote/sql_test.rs create mode 100644 rust/lancedb/src/sql.rs diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index cd872621b..4ac2c3070 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -232,7 +232,10 @@ jobs: ALL_FEATURES=`cargo metadata --format-version=1 --no-deps \ | jq -r '.packages[] | .features | keys | .[]' \ | grep -v s3-test | sort | uniq | paste -s -d "," -` - cargo test --profile ci --features $ALL_FEATURES --locked + # 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 windows: strategy: diff --git a/Cargo.lock b/Cargo.lock index bcc7526c8..d0c3dc408 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -332,6 +332,34 @@ dependencies = [ "num-traits", ] +[[package]] +name = "arrow-flight" +version = "58.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2dbe34824c639e43136af8f106992792ab456540d54b880bc320a3192502d2e" +dependencies = [ + "arrow-arith", + "arrow-array", + "arrow-buffer", + "arrow-cast", + "arrow-data", + "arrow-ipc", + "arrow-ord", + "arrow-row", + "arrow-schema", + "arrow-select", + "arrow-string", + "base64 0.22.1", + "bytes", + "futures", + "once_cell", + "paste", + "prost", + "prost-types", + "tonic", + "tonic-prost", +] + [[package]] name = "arrow-ipc" version = "58.4.0" @@ -1129,7 +1157,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" dependencies = [ "async-trait", - "axum-core", + "axum-core 0.4.5", "bytes", "futures-util", "http 1.5.0", @@ -1138,7 +1166,7 @@ dependencies = [ "hyper 1.9.0", "hyper-util", "itoa", - "matchit", + "matchit 0.7.3", "memchr", "mime", "percent-encoding", @@ -1156,6 +1184,31 @@ dependencies = [ "tracing", ] +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core 0.5.6", + "bytes", + "futures-util", + "http 1.5.0", + "http-body 1.1.0", + "http-body-util", + "itoa", + "matchit 0.8.4", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "sync_wrapper", + "tower", + "tower-layer", + "tower-service", +] + [[package]] name = "axum-core" version = "0.4.5" @@ -1177,6 +1230,24 @@ dependencies = [ "tracing", ] +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http 1.5.0", + "http-body 1.1.0", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + [[package]] name = "backoff" version = "0.4.0" @@ -5272,7 +5343,7 @@ dependencies = [ "arrow-ipc", "arrow-schema", "async-trait", - "axum", + "axum 0.7.9", "base64 0.22.1", "bytes", "chrono", @@ -5412,6 +5483,7 @@ dependencies = [ "arrow-buffer", "arrow-cast", "arrow-data", + "arrow-flight", "arrow-ipc", "arrow-ord", "arrow-schema", @@ -5467,6 +5539,7 @@ dependencies = [ "polars", "polars-arrow", "pprof 0.14.1", + "prost", "rand 0.9.5", "random_word", "regex", @@ -5483,6 +5556,7 @@ dependencies = [ "test-log", "tokenizers", "tokio", + "tonic", "url", "urlencoding", "uuid", @@ -5540,6 +5614,7 @@ dependencies = [ "serde_json", "snafu 0.8.9", "tokio", + "uuid", ] [[package]] @@ -5860,6 +5935,12 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94" +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "matrixmultiply" version = "0.3.10" @@ -7735,6 +7816,7 @@ dependencies = [ "pyo3-build-config", "pyo3-ffi", "pyo3-macros", + "uuid", ] [[package]] @@ -10087,6 +10169,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" dependencies = [ "async-trait", + "axum 0.8.9", "base64 0.22.1", "bytes", "h2 0.4.16", @@ -10098,9 +10181,11 @@ dependencies = [ "hyper-util", "percent-encoding", "pin-project", + "rustls-native-certs", "socket2 0.6.3", "sync_wrapper", "tokio", + "tokio-rustls 0.26.4", "tokio-stream", "tower", "tower-layer", diff --git a/Cargo.toml b/Cargo.toml index eba5a421a..63ebeb75a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -39,6 +39,7 @@ arrow-ord = "58.0.0" arrow-schema = "58.0.0" arrow-select = "58.0.0" arrow-cast = "58.0.0" +arrow-flight = { version = "58.0.0", features = ["flight-sql-experimental"] } async-trait = "0" bytes = "1" datafusion = { version = "54.0.0", default-features = false } @@ -71,7 +72,8 @@ serde = "1" serde_json = "1" tempfile = "3.5.0" tokio = { version = "1.23", features = ["rt-multi-thread", "sync"] } -uuid = { version = "1.7.0", features = ["v4"] } +tonic = { version = "0.14", features = ["tls-native-roots", "tls-ring"] } +uuid = { version = "1.7.0", features = ["v4", "v7"] } chrono = { version = "0.4", default-features = false, features = ["clock"] } [profile.ci] diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 5f359f4b7..f2bc72b3a 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -28,6 +28,59 @@ is also an [asynchronous API client](#connections-asynchronous). ::: lancedb.Session +## Remote SQL + +Submit SQL against a remote LanceDB database through the connection. +The connected database and `default_namespace_path=["public"]` are used for +unqualified tables. Fully qualified references can still query other databases +and namespaces available to the same deployment. `execute_query` returns a +reader as soon as its initial result stream is available. `execute_query_async` +returns a query handle immediately; use it to inspect progress, open a reader, +or cancel the query. The SQL client is initialized by the first query and +retained for the lifetime of the remote connection. Query ids are random, +connection-scoped references rather than encoded SQL or durable resume tokens: + +```python +import lancedb + +db = lancedb.connect( + "db://analytics", + api_key="ldb_...", + host_override="https://api.example.com", + sql_host_override="grpc+tls://sql.example.com:10026", +) +reader = db.execute_query( + """ + SELECT events.id, accounts.name + FROM analytics.public.events AS events + JOIN users.public.accounts AS accounts ON events.user_id = accounts.id + """, + default_namespace_path=["public"], +) +for batch in reader: + print(batch.num_rows) + +query = db.execute_query_async("SELECT * FROM events") +print(query.id) +print(query.describe().status) +for batch in query.reader(): + print(batch.num_rows) + +# The async connection exposes the same lifecycle without blocking: +# async_db = await lancedb.connect_async( +# "db://analytics", +# api_key="ldb_...", +# host_override="https://api.example.com", +# sql_host_override="grpc+tls://sql.example.com:10026", +# ) +# reader = await async_db.execute_query("SELECT * FROM events") +# query = await async_db.execute_query_async("SELECT * FROM events") +# description = await async_db.describe_query(query.id) +# async for batch in await query.reader(): +# print(batch.num_rows) +# await query.cancel() +``` + ## Namespaces (Synchronous) A namespace-backed connection resolves tables through a @@ -102,6 +155,12 @@ listing a storage directory. ::: lancedb.job.AsyncJob +::: lancedb.sql.Query + +::: lancedb.sql.AsyncQuery + +::: lancedb.sql.QueryDescription + ## Materialized Views (Synchronous) ::: lancedb.materialized_view.MaterializedView diff --git a/python/Cargo.toml b/python/Cargo.toml index 98ae17fef..850752925 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -28,7 +28,7 @@ env_logger.workspace = true log.workspace = true # Maturin enables extension-module mode for Python builds. Keeping it out of # Cargo features lets Rust unit tests link against libpython. -pyo3 = { version = "0.28", features = ["abi3-py310", "chrono"] } +pyo3 = { version = "0.28", features = ["abi3-py310", "chrono", "uuid"] } chrono.workspace = true pyo3-async-runtimes = { version = "0.28", features = [ "attributes", @@ -40,6 +40,7 @@ serde.workspace = true serde_json.workspace = true snafu.workspace = true tokio.workspace = true +uuid.workspace = true libc = "0.2" [build-dependencies] diff --git a/python/pyproject.toml b/python/pyproject.toml index 22a41a8a9..ffdfdd948 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -139,6 +139,7 @@ include = [ "python/lancedb/exceptions.py", "python/lancedb/background_loop.py", "python/lancedb/schema.py", + "python/lancedb/sql.py", "python/lancedb/remote/__init__.py", "python/lancedb/remote/errors.py", "python/lancedb/embeddings/__init__.py", diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index 21ffc8860..af325a29b 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -22,6 +22,9 @@ from .remote.db import RemoteDBConnection from .expr import Expr, col, lit, func from .schema import blob, vector from .job import AsyncJob, Job +from .sql import AsyncQuery as AsyncSqlQuery +from .sql import Query as SqlQuery +from .sql import QueryDescription from .functions import ( FunctionArtifactRequest as FunctionArtifactRequest, FunctionApplication as FunctionApplication, @@ -101,6 +104,7 @@ def connect( api_key: Optional[str] = None, region: str = "us-east-1", 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: Union[ClientConfig, Dict[str, Any], None] = None, @@ -129,6 +133,9 @@ def connect( The region to use for LanceDB Cloud. host_override: str, optional The override url for LanceDB Cloud. + sql_host_override: str, optional + The remote SQL service endpoint override. The client connects lazily when SQL + is first executed and retains that connection. read_consistency_interval: timedelta, default None The interval at which to check for updates to the table from other processes. If None, then consistency is not checked. For performance @@ -270,6 +277,7 @@ def connect( api_key, region, host_override, + sql_host_override=sql_host_override, # TODO: remove this (deprecation warning downstream) request_thread_pool=request_thread_pool, client_config=client_config, @@ -412,6 +420,7 @@ def deserialize_conn( parsed["api_key"], parsed.get("region", "us-east-1"), host_override=parsed.get("host_override"), + sql_host_override=parsed.get("sql_host_override"), client_config=parsed.get("client_config"), storage_options=storage_options, ) @@ -425,6 +434,7 @@ async def connect_async( api_key: Optional[str] = None, region: str = "us-east-1", 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, @@ -447,6 +457,9 @@ async def connect_async( The region to use for LanceDB Cloud. host_override: str, optional The override url for LanceDB Cloud. + sql_host_override: str, optional + The remote SQL service endpoint override. The client connects lazily when SQL + is first executed and retains that connection. read_consistency_interval: timedelta, default None The interval at which to check for updates to the table from other processes. If None, then consistency is not checked. For performance @@ -534,6 +547,7 @@ async def connect_async( api_key, region, host_override, + sql_host_override, read_consistency_interval_secs, client_config, storage_options, @@ -556,6 +570,7 @@ __all__ = [ "connect_namespace_async", "AsyncConnection", "AsyncJob", + "AsyncSqlQuery", "AsyncLanceNamespaceDBConnection", "AsyncTable", "FtsToken", @@ -570,6 +585,8 @@ __all__ = [ "vector", "DBConnection", "Job", + "QueryDescription", + "SqlQuery", "LanceDBConnection", "LanceNamespaceDBConnection", "LsmWriteSpec", diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 78826df92..3ea8d15c7 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1,6 +1,7 @@ from datetime import date, datetime, timedelta from decimal import Decimal from typing import Dict, List, Optional, Tuple, Any, TypedDict, Union, Literal +from uuid import UUID import pyarrow as pa @@ -158,6 +159,13 @@ class Connection(object): async def job_history( self, job_id: Optional[str] = None ) -> List[pa.RecordBatch]: ... + async def execute_query_async( + self, + query: str, + *, + default_namespace_path: Optional[List[str]] = None, + ) -> SqlQuery: ... + async def describe_query(self, query_id: UUID) -> QueryDescription: ... async def create_table( self, name: str, @@ -274,6 +282,23 @@ class JobDescription: @property def failure(self) -> Optional[JobFailureInfo]: ... +class SqlQuery: + @property + def id(self) -> UUID: ... + async def describe(self) -> QueryDescription: ... + async def reader(self) -> RecordBatchStream: ... + async def cancel(self) -> None: ... + +class QueryDescription: + @property + def id(self) -> UUID: ... + @property + def status(self) -> str: ... + @property + def progress(self) -> Optional[float]: ... + @property + def expires_at(self) -> Optional[datetime]: ... + class Table: def name(self) -> str: ... def __repr__(self) -> str: ... @@ -452,6 +477,7 @@ async def connect( api_key: Optional[str], region: Optional[str], host_override: Optional[str], + sql_host_override: Optional[str], read_consistency_interval: Optional[float], client_config: Optional[Union[ClientConfig, Dict[str, Any]]], storage_options: Optional[Dict[str, str]], diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 2554e9908..82dfa22f1 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -19,6 +19,7 @@ from typing import ( Optional, Union, ) +from uuid import UUID if sys.version_info >= (3, 12): from typing import override @@ -47,6 +48,9 @@ from . import __version__ from ._lancedb import connect as lancedb_connect # type: ignore from .functions import FunctionVersion, UdfDefinition from .job import AsyncJob, Job, _typed_job +from .sql import AsyncQuery as AsyncSqlQuery +from .sql import Query as SqlQuery +from .sql import QueryDescription from .materialized_view import ( AsyncMaterializedView, MaterializedView, @@ -68,6 +72,7 @@ import deprecation if TYPE_CHECKING: import pyarrow as pa + from .arrow import AsyncRecordBatchReader from .pydantic import LanceModel from ._lancedb import Connection as LanceDbConnection @@ -780,6 +785,39 @@ class DBConnection(EnforceOverrides): "job_history is not supported for this connection type" ) + def execute_query( + self, + query: str, + *, + default_namespace_path: Optional[List[str]] = None, + ) -> pa.RecordBatchReader: + """Execute SQL and return a blocking Arrow reader. + + 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. + """ + return self.execute_query_async( + query, + default_namespace_path=default_namespace_path, + ).reader() + + def execute_query_async( + self, + query: str, + *, + default_namespace_path: Optional[List[str]] = None, + ) -> SqlQuery: + """Start executing SQL and return its query handle. + + Local connections do not support SQL. + """ + raise NotImplementedError("SQL is not supported for this connection type") + + def describe_query(self, query_id: UUID) -> QueryDescription: + """Describe a submitted SQL query by its connection-scoped id.""" + raise NotImplementedError("SQL is not supported for this connection type") + class LanceDBConnection(DBConnection): """ @@ -875,6 +913,7 @@ class LanceDBConnection(DBConnection): None, None, None, + None, read_consistency_interval_secs, None, storage_options, @@ -2321,6 +2360,47 @@ class AsyncConnection(object): """ return await self._inner.job_history(job_id) + async def execute_query( + self, + query: str, + *, + default_namespace_path: Optional[List[str]] = None, + ) -> AsyncRecordBatchReader: + """Execute SQL and return an asynchronous Arrow reader. + + 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. + """ + submitted = await self.execute_query_async( + query, + default_namespace_path=default_namespace_path, + ) + return await submitted.reader() + + async def execute_query_async( + self, + query: str, + *, + default_namespace_path: Optional[List[str]] = None, + ) -> AsyncSqlQuery: + """Start executing SQL and return its query handle. + + The database from ``connect_async`` is used for unqualified database + references. The namespace defaults to ``["public"]``. Local + connections raise ``NotImplementedError``. + """ + return AsyncSqlQuery( + await self._inner.execute_query_async( + query, + default_namespace_path=default_namespace_path, + ) + ) + + async def describe_query(self, query_id: UUID) -> QueryDescription: + """Describe a submitted SQL query by its connection-scoped id.""" + return await self._inner.describe_query(query_id) + async def namespace_client(self) -> LanceNamespace: """Get the equivalent namespace client for this connection. diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index f2e553321..61d2122f3 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -12,6 +12,7 @@ from __future__ import annotations import sys from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union +from uuid import UUID if sys.version_info >= (3, 12): from typing import override @@ -48,8 +49,11 @@ from lancedb._lancedb import ( connect_namespace_client as _connect_namespace_client, ) from lancedb.background_loop import LOOP +from lancedb.arrow import AsyncRecordBatchReader from lancedb.db import AsyncConnection, DBConnection from lancedb.job import AsyncJob, Job +from lancedb.sql import AsyncQuery as AsyncSqlQuery +from lancedb.sql import QueryDescription from lance_namespace import ( LanceNamespace, connect as namespace_connect, @@ -1447,6 +1451,37 @@ class AsyncLanceNamespaceDBConnection: namespace_path=namespace_path, page_token=page_token, limit=limit ) + async def execute_query( + self, + query: str, + *, + default_namespace_path: Optional[List[str]] = None, + ) -> AsyncRecordBatchReader: + """Execute SQL when supported by the underlying connection.""" + return await self._inner.execute_query( + query, + default_namespace_path=default_namespace_path, + ) + + async def execute_query_async( + self, + query: str, + *, + default_namespace_path: Optional[List[str]] = None, + ) -> AsyncSqlQuery: + """Start executing SQL when supported by the underlying connection. + + Namespace-backed local connections do not support SQL. + """ + return await self._inner.execute_query_async( + query, + default_namespace_path=default_namespace_path, + ) + + async def describe_query(self, query_id: UUID) -> QueryDescription: + """Describe a submitted SQL query when supported.""" + return await self._inner.describe_query(query_id) + async def namespace_client(self) -> LanceNamespace: """Get the namespace client for this connection. diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 0e95e035b..1c0dd3afa 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -9,6 +9,7 @@ from concurrent.futures import ThreadPoolExecutor import sys from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Union from urllib.parse import urlparse +from uuid import UUID import warnings if sys.version_info >= (3, 12): @@ -25,6 +26,8 @@ from ..common import DATA from ..db import DBConnection, LOOP from ..functions import FunctionVersion, UdfDefinition from ..job import AsyncJob, Job +from ..sql import Query as SqlQuery +from ..sql import QueryDescription from ..materialized_view import MaterializedView, SelectArg if TYPE_CHECKING: @@ -116,6 +119,7 @@ class RemoteDBConnection(DBConnection): read_timeout: Optional[float] = None, storage_options: Optional[Dict[str, str]] = None, read_consistency_interval: Optional[timedelta] = None, + sql_host_override: Optional[str] = None, ): """Connect to a remote LanceDB database.""" if isinstance(client_config, dict): @@ -161,6 +165,7 @@ class RemoteDBConnection(DBConnection): self.api_key = api_key self.region = region self.host_override = host_override + self.sql_host_override = sql_host_override self.storage_options = storage_options self.db_name = parsed.netloc @@ -175,6 +180,7 @@ class RemoteDBConnection(DBConnection): api_key=api_key, region=region, host_override=host_override, + sql_host_override=sql_host_override, client_config=client_config, storage_options=storage_options, read_consistency_interval=read_consistency_interval, @@ -193,6 +199,7 @@ class RemoteDBConnection(DBConnection): "api_key": self.api_key, "region": self.region, "host_override": self.host_override, + "sql_host_override": self.sql_host_override, "client_config": _client_config_to_dict(self.client_config), "storage_options": self.storage_options, } @@ -788,6 +795,37 @@ class RemoteDBConnection(DBConnection): """ return LOOP.run(self._conn.job_history(job_id)) + @override + def execute_query_async( + self, + query: str, + *, + default_namespace_path: Optional[List[str]] = None, + ) -> SqlQuery: + """Start executing SQL through this remote connection. + + Unqualified tables use this connection's database and the + ``["public"]`` namespace by default. Fully qualified table names may + reference other databases available to the same deployment. + """ + return SqlQuery( + LOOP.run( + self._conn.execute_query_async( + query, + default_namespace_path=default_namespace_path, + ) + ) + ) + + @override + def describe_query(self, query_id: UUID) -> QueryDescription: + """Describe a submitted SQL query by its connection-scoped id.""" + return LOOP.run( + self._conn.describe_query( + query_id, + ) + ) + @override def namespace_client(self) -> LanceNamespace: """Get the equivalent namespace client for this connection. diff --git a/python/python/lancedb/remote/header.py b/python/python/lancedb/remote/header.py index 06e3599f5..206b7a7cb 100644 --- a/python/python/lancedb/remote/header.py +++ b/python/python/lancedb/remote/header.py @@ -177,4 +177,7 @@ class OAuthProvider(HeaderProvider): if not self._current_token: raise RuntimeError("Failed to obtain OAuth token") - return {"Authorization": f"Bearer {self._current_token}"} + return { + "Authorization": f"Bearer {self._current_token}", + "x-lancedb-credential-type": "oidc", + } diff --git a/python/python/lancedb/sql.py b/python/python/lancedb/sql.py new file mode 100644 index 000000000..41bbb5328 --- /dev/null +++ b/python/python/lancedb/sql.py @@ -0,0 +1,88 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Handles to SQL queries running on a remote database.""" + +from uuid import UUID + +import pyarrow as pa + +from lancedb.background_loop import LOOP + +from . import _lancedb +from .arrow import AsyncRecordBatchReader + +QueryDescription = _lancedb.QueryDescription + + +class AsyncQuery: + """A handle to a submitted SQL query on an asynchronous connection.""" + + def __init__(self, inner: "_lancedb.SqlQuery"): + self._inner = inner + + @property + def id(self) -> UUID: + """The stable identifier scoped to the connection that submitted it.""" + return self._inner.id + + async def describe(self) -> QueryDescription: + """Get a point-in-time description of the query.""" + return await self._inner.describe() + + async def reader(self) -> AsyncRecordBatchReader: + """Wait for the initial result stream and return its Arrow reader. + + Results are single-consumer. Calling this method more than once on the + same query raises an error. Later batches are streamed as they become + available without waiting for the full query to finish. + """ + return AsyncRecordBatchReader(await self._inner.reader()) + + async def cancel(self) -> None: + """Request cancellation of the query.""" + await self._inner.cancel() + + +class Query: + """Synchronous counterpart of :class:`AsyncQuery`.""" + + def __init__(self, inner: AsyncQuery): + self._inner = inner + + @property + def id(self) -> UUID: + """The stable identifier scoped to the connection that submitted it.""" + return self._inner.id + + def describe(self) -> QueryDescription: + """Get a point-in-time description of the query.""" + return LOOP.run(self._inner.describe()) + + def reader(self) -> pa.RecordBatchReader: + """Wait for the initial result stream and return a blocking reader. + + Results are single-consumer. Calling this method more than once on the + same query raises an error. Later batches block only until they become + available, without waiting for the full query to finish. + """ + reader = LOOP.run(self._inner.reader()) + + def next_batch(): + try: + return LOOP.run(reader.__anext__()) + except StopAsyncIteration: + return None + + def batches(): + while (batch := next_batch()) is not None: + yield batch + + return pa.RecordBatchReader.from_batches(reader.schema, batches()) + + def cancel(self) -> None: + """Request cancellation of the query.""" + LOOP.run(self._inner.cancel()) + + +__all__ = ["AsyncQuery", "Query", "QueryDescription"] diff --git a/python/python/tests/test_header_provider.py b/python/python/tests/test_header_provider.py index 84c5d7729..187b0a50a 100644 --- a/python/python/tests/test_header_provider.py +++ b/python/python/tests/test_header_provider.py @@ -54,7 +54,10 @@ class TestOAuthProvider: provider = OAuthProvider(fetcher) headers = provider.get_headers() - assert headers == {"Authorization": "Bearer token123"} + assert headers == { + "Authorization": "Bearer token123", + "x-lancedb-credential-type": "oidc", + } assert provider._current_token == "token123" assert provider._token_expires_at is not None @@ -73,14 +76,20 @@ class TestOAuthProvider: # First call headers1 = provider.get_headers() - assert headers1 == {"Authorization": "Bearer token1"} + assert headers1 == { + "Authorization": "Bearer token1", + "x-lancedb-credential-type": "oidc", + } # Wait for token to expire time.sleep(1.1) # Second call should refresh headers2 = provider.get_headers() - assert headers2 == {"Authorization": "Bearer token2"} + assert headers2 == { + "Authorization": "Bearer token2", + "x-lancedb-credential-type": "oidc", + } assert call_count == 2 def test_no_expiry_info(self): @@ -92,12 +101,18 @@ class TestOAuthProvider: provider = OAuthProvider(fetcher) headers = provider.get_headers() - assert headers == {"Authorization": "Bearer permanent_token"} + assert headers == { + "Authorization": "Bearer permanent_token", + "x-lancedb-credential-type": "oidc", + } assert provider._token_expires_at is None # Should not refresh on second call headers2 = provider.get_headers() - assert headers2 == {"Authorization": "Bearer permanent_token"} + assert headers2 == { + "Authorization": "Bearer permanent_token", + "x-lancedb-credential-type": "oidc", + } def test_missing_access_token(self): """Test error handling when access_token is missing.""" @@ -121,7 +136,10 @@ class TestOAuthProvider: provider = OAuthProvider(fetcher) headers = provider.get_headers() - assert headers == {"Authorization": "Bearer sync_token"} + assert headers == { + "Authorization": "Bearer sync_token", + "x-lancedb-credential-type": "oidc", + } class TestClientConfigIntegration: diff --git a/python/python/tests/test_sql.py b/python/python/tests/test_sql.py new file mode 100644 index 000000000..eeadb3a33 --- /dev/null +++ b/python/python/tests/test_sql.py @@ -0,0 +1,162 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +from uuid import UUID + +import pytest +import pyarrow as pa + +import lancedb +from lancedb import _lancedb +from lancedb.arrow import AsyncRecordBatchReader +from lancedb.db import AsyncConnection +from lancedb.remote.db import RemoteDBConnection +from lancedb.sql import AsyncQuery, Query + +NIL_QUERY_ID = UUID(int=0) + + +class FakeNativeQuery: + id = UUID("0198f1b2-c3d4-7e5f-8123-456789abcdef") + + async def reader(self): + return pa.table({"value": [1, 2]}) + + +class FakeNativeConnection: + async def execute_query_async(self, query, *, default_namespace_path=None): + return FakeNativeQuery() + + +class FakeAsyncConnection: + async def execute_query_async(self, query, *, default_namespace_path=None): + return AsyncQuery(FakeNativeQuery()) + + +def remote_connection(sql_host_override=None): + return lancedb.connect( + "db://analytics", + api_key="test-key", + host_override="http://localhost:10024", + sql_host_override=sql_host_override, + ) + + +def test_sql_is_connection_scoped(): + assert hasattr(lancedb, "sql") + assert not callable(lancedb.sql) + assert not hasattr(_lancedb, "sql") + assert not hasattr(remote_connection(), "sql") + assert hasattr(remote_connection(), "execute_query") + assert hasattr(remote_connection(), "execute_query_async") + assert hasattr(remote_connection(), "describe_query") + + +def test_query_id_is_uuid(): + query = AsyncQuery(FakeNativeQuery()) + assert isinstance(query.id, UUID) + assert Query(query).id == query.id + + +def test_connection_serializes_sql_host_override(): + endpoint = "grpc+tls://sql.example.com:10026" + restored = lancedb.deserialize_conn( + remote_connection(sql_host_override=endpoint).serialize() + ) + assert restored.sql_host_override == endpoint + + +@pytest.mark.asyncio +async def test_async_sql_reader_is_record_batch_stream(): + reader = await AsyncQuery(FakeNativeQuery()).reader() + assert isinstance(reader, AsyncRecordBatchReader) + assert (await reader.read_all())[0].column(0).to_pylist() == [1, 2] + + +def test_sync_sql_reader_is_record_batch_reader(): + reader = Query(AsyncQuery(FakeNativeQuery())).reader() + assert isinstance(reader, pa.RecordBatchReader) + assert reader.read_all().column(0).to_pylist() == [1, 2] + + +def test_execute_query_returns_blocking_reader(): + connection = RemoteDBConnection.__new__(RemoteDBConnection) + connection._conn = FakeAsyncConnection() + reader = connection.execute_query("SELECT 1") + assert isinstance(reader, pa.RecordBatchReader) + assert reader.read_all().column(0).to_pylist() == [1, 2] + + +@pytest.mark.asyncio +async def test_async_execute_query_returns_async_reader(): + connection = AsyncConnection(FakeNativeConnection()) + reader = await connection.execute_query("SELECT 1") + assert isinstance(reader, AsyncRecordBatchReader) + assert (await reader.read_all())[0].column(0).to_pylist() == [1, 2] + + +def test_local_connection_rejects_sql(tmp_path): + connection = lancedb.connect(tmp_path) + with pytest.raises(NotImplementedError, match="SQL"): + connection.execute_query("SELECT 1") + with pytest.raises(NotImplementedError, match="SQL"): + connection.execute_query_async("SELECT 1") + with pytest.raises(NotImplementedError, match="SQL"): + connection.describe_query(NIL_QUERY_ID) + + +@pytest.mark.asyncio +async def test_local_async_connection_rejects_sql(tmp_path): + connection = await lancedb.connect_async(tmp_path) + with pytest.raises(NotImplementedError, match="SQL"): + await connection.execute_query("SELECT 1") + with pytest.raises(NotImplementedError, match="SQL"): + await connection.execute_query_async("SELECT 1") + with pytest.raises(NotImplementedError, match="SQL"): + await connection.describe_query(NIL_QUERY_ID) + + +@pytest.mark.asyncio +async def test_async_namespace_connection_rejects_sql(tmp_path): + connection = lancedb.connect_namespace_async("dir", {"root": str(tmp_path)}) + with pytest.raises(NotImplementedError, match="SQL"): + await connection.execute_query("SELECT 1") + with pytest.raises(NotImplementedError, match="SQL"): + await connection.execute_query_async("SELECT 1") + with pytest.raises(NotImplementedError, match="SQL"): + await connection.describe_query(NIL_QUERY_ID) + + +def test_describe_query_requires_uuid(): + with pytest.raises(TypeError, match="UUID"): + remote_connection().describe_query(str(NIL_QUERY_ID)) + + +@pytest.mark.parametrize( + "default_namespace_path", + ["public", ("public",), [1]], +) +def test_execute_query_async_requires_namespace_path_list(default_namespace_path): + with pytest.raises(ValueError, match="default_namespace_path"): + remote_connection().execute_query_async( + "SELECT 1", default_namespace_path=default_namespace_path + ) + + +def test_execute_query_async_rejects_invalid_endpoint(): + connection = remote_connection(sql_host_override="invalid://localhost") + with pytest.raises(ValueError, match="sql_host_override"): + connection.execute_query_async("SELECT 1") + + +@pytest.mark.parametrize( + "default_namespace_path", + [[""], ["café"], ["pub\tlic"], ["events$raw"]], +) +def test_execute_query_async_rejects_invalid_namespace_components( + default_namespace_path, +): + with pytest.raises(ValueError, match="default_namespace_path"): + remote_connection().execute_query_async( + "SELECT 1", default_namespace_path=default_namespace_path + ) diff --git a/python/src/connection.rs b/python/src/connection.rs index 5477ab3d2..882fdfd29 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -28,7 +28,7 @@ use pyo3::{ Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python, exceptions::{PyRuntimeError, PyValueError}, pyclass, pyfunction, pymethods, - types::{PyDict, PyDictMethods, PyList, PyListMethods}, + types::{PyAnyMethods, PyDict, PyDictMethods, PyList, PyListMethods}, }; #[pyclass] @@ -86,6 +86,24 @@ impl Connection { } } +fn parse_default_namespace_path(path: Option>) -> PyResult> { + match path { + Some(path) => { + if !path.is_instance_of::() { + return Err(PyValueError::new_err( + "Connection.execute_query_async default_namespace_path must be a list", + )); + } + path.extract::>().map_err(|_| { + PyValueError::new_err( + "Connection.execute_query_async default_namespace_path components must be strings", + ) + }) + } + None => Ok(vec!["public".to_string()]), + } +} + #[pymethods] impl Connection { fn __repr__(&self) -> String { @@ -108,6 +126,40 @@ impl Connection { self.get_inner().map(|inner| inner.uri().to_string()) } + #[pyo3(signature = (query, *, default_namespace_path=None))] + pub fn execute_query_async<'a>( + self_: PyRef<'a, Self>, + query: String, + default_namespace_path: Option>, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + let default_namespace_path = parse_default_namespace_path(default_namespace_path)?; + future_into_py(self_.py(), async move { + let operation = inner + .execute_query_async(query) + .default_namespace_path(default_namespace_path); + operation + .execute() + .await + .map(crate::sql::Query::new) + .infer_error() + }) + } + + pub fn describe_query<'a>( + self_: PyRef<'a, Self>, + query_id: uuid::Uuid, + ) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + inner + .describe_query(query_id) + .await + .map(crate::sql::QueryDescription::from) + .infer_error() + }) + } + #[pyo3(signature = ())] pub fn get_read_consistency_interval(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.get_inner()?.clone(); @@ -699,7 +751,7 @@ impl Connection { } #[pyfunction] -#[pyo3(signature = (uri, api_key=None, region=None, host_override=None, read_consistency_interval=None, client_config=None, storage_options=None, session=None, manifest_enabled=false, namespace_client_properties=None, oauth_config=None))] +#[pyo3(signature = (uri, api_key=None, region=None, host_override=None, sql_host_override=None, read_consistency_interval=None, client_config=None, storage_options=None, session=None, manifest_enabled=false, namespace_client_properties=None, oauth_config=None))] #[allow(clippy::too_many_arguments)] pub fn connect( py: Python<'_>, @@ -707,6 +759,7 @@ pub fn connect( api_key: Option, region: Option, host_override: Option, + sql_host_override: Option, read_consistency_interval: Option, client_config: Option, storage_options: Option>, @@ -726,6 +779,12 @@ pub fn connect( if let Some(host_override) = host_override { builder = builder.host_override(&host_override); } + #[cfg(feature = "remote")] + if let Some(sql_host_override) = sql_host_override { + builder = builder.sql_host_override(&sql_host_override); + } + #[cfg(not(feature = "remote"))] + let _ = sql_host_override; if let Some(read_consistency_interval) = read_consistency_interval { let read_consistency_interval = Duration::from_secs_f64(read_consistency_interval); builder = builder.read_consistency_interval(read_consistency_interval); diff --git a/python/src/lib.rs b/python/src/lib.rs index 8d3eab787..06b31d033 100644 --- a/python/src/lib.rs +++ b/python/src/lib.rs @@ -34,6 +34,7 @@ pub mod permutation; pub mod query; pub mod runtime; pub mod session; +pub mod sql; pub mod table; pub mod util; @@ -50,6 +51,8 @@ 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::()?; diff --git a/python/src/sql.rs b/python/src/sql.rs new file mode 100644 index 000000000..612521207 --- /dev/null +++ b/python/src/sql.rs @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::sync::Arc; + +use chrono::{DateTime, Utc}; +use pyo3::{Bound, PyAny, PyRef, PyResult, pyclass, pymethods}; +use uuid::Uuid; + +use crate::arrow::RecordBatchStream; +use crate::error::PythonErrorExt; +use crate::runtime::future_into_py; + +#[pyclass(name = "SqlQuery")] +pub struct Query { + inner: Arc, +} + +impl Query { + pub(crate) fn new(inner: lancedb::sql::Query) -> Self { + Self { + inner: Arc::new(inner), + } + } +} + +#[pymethods] +impl Query { + #[getter] + pub fn id(&self) -> Uuid { + self.inner.id() + } + + pub fn describe(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + inner + .describe() + .await + .map(QueryDescription::from) + .infer_error() + }) + } + + pub fn reader(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + let stream = inner.reader().await.infer_error()?; + Ok(RecordBatchStream::new(stream)) + }) + } + + pub fn cancel(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + inner.cancel().await.infer_error()?; + Ok(()) + }) + } +} + +#[pyclass(get_all, skip_from_py_object)] +#[derive(Clone)] +pub struct QueryDescription { + id: Uuid, + status: String, + progress: Option, + expires_at: Option>, +} + +#[pymethods] +impl QueryDescription { + fn __repr__(&self) -> String { + format!( + "QueryDescription(id={:?}, status={:?}, progress={:?}, expires_at={:?})", + self.id, self.status, self.progress, self.expires_at + ) + } +} + +impl From for QueryDescription { + fn from(description: lancedb::sql::QueryDescription) -> Self { + Self { + id: description.id, + status: description.status.to_string(), + progress: description.progress, + expires_at: description.expires_at, + } + } +} diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index a5aa12e52..836bffa4f 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -21,6 +21,8 @@ arrow-select = { workspace = true } arrow-ord = { workspace = true } arrow-cast = { workspace = true } arrow-ipc.workspace = true +arrow-flight = { workspace = true, optional = true } +prost = { version = "0.14", optional = true } chrono = { workspace = true } datafusion-catalog.workspace = true datafusion-common.workspace = true @@ -77,6 +79,7 @@ reqwest = { version = "0.12.0", default-features = false, features = [ "rustls-tls-native-roots", "stream", ], optional = true } +tonic = { workspace = true, optional = true } http = { version = "1", optional = true } # Matching what is in reqwest urlencoding = { version = "2", optional = true } uuid = { workspace = true, features = ["v5"] } @@ -145,8 +148,11 @@ huggingface = [ ] dynamodb = ["lance/dynamodb", "aws"] remote = [ + "dep:arrow-flight", + "dep:prost", "dep:reqwest", "dep:http", + "dep:tonic", "dep:urlencoding", "lance-namespace-impls/rest", "lance-namespace-impls/rest-adapter", diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 35c5c0737..f04f04ce2 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -31,7 +31,10 @@ use crate::error::{Error, Result}; #[cfg(feature = "remote")] use crate::remote::{ client::ClientConfig, - db::{OPT_REMOTE_API_KEY, OPT_REMOTE_HOST_OVERRIDE, OPT_REMOTE_REGION}, + db::{ + OPT_REMOTE_API_KEY, OPT_REMOTE_HOST_OVERRIDE, OPT_REMOTE_REGION, + OPT_REMOTE_SQL_HOST_OVERRIDE, + }, }; use lance::io::ObjectStoreParams; pub use lance_file::version::LanceFileVersion; @@ -322,6 +325,43 @@ pub struct CloneTableBuilder { request: CloneTableRequest, } +/// Builder for asynchronously executing a SQL statement on a remote database. +pub struct ExecuteQueryAsyncBuilder { + parent: Arc, + query: String, + default_namespace_path: Vec, +} + +impl ExecuteQueryAsyncBuilder { + fn new(parent: Arc, query: String) -> Self { + Self { + parent, + query, + default_namespace_path: vec!["public".to_string()], + } + } + + /// Set the namespace used for unqualified table names. + /// + /// An empty path is treated as `public`, which is the SQL name for the + /// root Lance namespace. + pub fn default_namespace_path(mut self, path: I) -> Self + where + I: IntoIterator, + S: Into, + { + self.default_namespace_path = path.into_iter().map(Into::into).collect(); + self + } + + /// Start the statement and return its asynchronous query handle. + pub async fn execute(self) -> Result { + self.parent + .execute_query_async(&self.query, &self.default_namespace_path) + .await + } +} + impl CloneTableBuilder { fn new(parent: Arc, target_table_name: String, source_uri: String) -> Self { Self { @@ -405,6 +445,51 @@ impl Connection { &self.internal } + /// Start executing SQL on a remote LanceDB database. + /// + /// The query can reference tables in other databases with SQL dot notation. + /// Use [`ExecuteQueryAsyncBuilder::default_namespace_path`] to avoid qualifying + /// tables in the default namespace. Local connections return + /// [`Error::NotSupported`]. + /// + /// # Example + /// + /// ```no_run + /// # async fn query(db: &lancedb::Connection) -> lancedb::Result<()> { + /// use futures::TryStreamExt; + /// + /// let query = db + /// .execute_query_async("SELECT * FROM events LIMIT 10") + /// .default_namespace_path(["public"]) + /// .execute() + /// .await?; + /// println!("query id: {}", query.id()); + /// let mut batches = query.reader().await?; + /// while let Some(batch) = batches.try_next().await? { + /// println!("received {} rows", batch.num_rows()); + /// } + /// # Ok(()) + /// # } + /// ``` + pub fn execute_query_async(&self, query: impl Into) -> ExecuteQueryAsyncBuilder { + ExecuteQueryAsyncBuilder::new(self.internal.clone(), query.into()) + } + + /// Describe a submitted SQL query by its connection-scoped id. + /// + /// This performs one bounded status poll using state retained by this + /// connection. Running state with a live query handle is not evicted; + /// abandoned state has bounded retention, and server expiration is + /// honored. Terminal state is retained briefly. + /// Query ids are not portable to another connection. Local connections + /// return [`Error::NotSupported`]. + pub async fn describe_query( + &self, + query_id: uuid::Uuid, + ) -> Result { + self.internal.describe_query(query_id).await + } + /// Get the names of all tables in the database /// /// The names will be returned in lexicographical order (ascending) @@ -864,6 +949,19 @@ impl ConnectBuilder { self } + /// Set the SQL service host override for a remote connection. + /// + /// The SQL client is initialized lazily when the connection first executes + /// SQL and is retained for the connection's lifetime. + #[cfg(feature = "remote")] + pub fn sql_host_override(mut self, sql_host_override: &str) -> Self { + self.request.options.insert( + OPT_REMOTE_SQL_HOST_OVERRIDE.to_string(), + sql_host_override.to_string(), + ); + self + } + /// Set the database specific options /// /// See [crate::database::listing::ListingDatabaseOptions] for the options available for @@ -1053,6 +1151,7 @@ impl ConnectBuilder { let mut merged_options = self.request.options.clone(); Self::apply_env_defaults(&ENV_VARS_TO_STORAGE_OPTS, &mut merged_options); + let sql_host_override = merged_options.get(OPT_REMOTE_SQL_HOST_OVERRIDE).cloned(); let options = RemoteDatabaseOptions::parse_from_map(&merged_options)?; let region = options.region.ok_or_else(|| Error::InvalidInput { @@ -1094,11 +1193,15 @@ impl ConnectBuilder { } let storage_options = StorageOptions(options.storage_options.clone()); + let host_overrides = crate::remote::db::RemoteHostOverrides { + rest: options.host_override, + sql: sql_host_override, + }; let internal = Arc::new(crate::remote::db::RemoteDatabase::try_new( &self.request.uri, &api_key, ®ion, - options.host_override, + host_overrides, client_config, storage_options.into(), self.request.read_consistency_interval, @@ -1392,6 +1495,23 @@ mod tests { assert_eq!(tc.connection.uri(), tc.uri); } + #[tokio::test] + async fn test_local_connection_rejects_sql_queries() { + let directory = tempdir().unwrap(); + let connection = connect(directory.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + assert!(matches!( + connection.execute_query_async("SELECT 1").execute().await, + Err(Error::NotSupported { .. }) + )); + assert!(matches!( + connection.describe_query(uuid::Uuid::nil()).await, + Err(Error::NotSupported { .. }) + )); + } + #[cfg(feature = "remote")] #[test] fn test_apply_env_defaults() { diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 61424bb05..532ea3658 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -340,6 +340,22 @@ pub trait Database: async fn job_history(&self, _job_id: Option<&str>) -> Result> { job_op_not_supported("job_history") } + /// Start executing a SQL statement on a remote database. + async fn execute_query_async( + &self, + _query: &str, + _default_namespace_path: &[String], + ) -> Result { + Err(crate::error::Error::NotSupported { + message: "SQL is not supported by this database".to_string(), + }) + } + /// Describe a submitted SQL query by its connection-scoped id. + async fn describe_query(&self, _query_id: uuid::Uuid) -> Result { + Err(crate::error::Error::NotSupported { + message: "SQL is not supported by this database".to_string(), + }) + } /// Open a table in the database async fn open_table(&self, request: OpenTableRequest) -> Result>; /// Rename a table in the database diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index 9c3c199ff..44c5dd616 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -195,6 +195,7 @@ pub mod query; #[cfg(feature = "remote")] pub mod remote; pub mod rerankers; +pub mod sql; pub mod table; #[cfg(test)] pub mod test_utils; diff --git a/rust/lancedb/src/remote.rs b/rust/lancedb/src/remote.rs index be9d0eef6..6c37ec6a0 100644 --- a/rust/lancedb/src/remote.rs +++ b/rust/lancedb/src/remote.rs @@ -11,6 +11,7 @@ pub(crate) mod db; pub(crate) mod job; pub mod oauth; mod retry; +pub(crate) mod sql; pub(crate) mod table; pub(crate) mod util; diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index ecdadf464..87486a522 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -33,6 +33,7 @@ use crate::table::BaseTable; use super::client::{ ClientConfig, HeaderProvider, HttpSend, RequestResultExt, RestfulLanceDbClient, Sender, }; +use super::sql::SqlClient; use super::table::RemoteTable; use super::util::parse_server_version; use super::{ARROW_STREAM_CONTENT_TYPE, extract_job_id}; @@ -97,6 +98,7 @@ pub const OPT_REMOTE_PREFIX: &str = "remote_database_"; pub const OPT_REMOTE_API_KEY: &str = "remote_database_api_key"; pub const OPT_REMOTE_REGION: &str = "remote_database_region"; pub const OPT_REMOTE_HOST_OVERRIDE: &str = "remote_database_host_override"; +pub const OPT_REMOTE_SQL_HOST_OVERRIDE: &str = "remote_database_sql_host_override"; // TODO: add support for configuring client config via key/value options #[derive(Clone, Debug, Default)] @@ -212,6 +214,7 @@ pub struct RemoteDatabase { namespace_context_provider: Option>, /// TLS configuration for mTLS support tls_config: Option, + sql_client: Option, } #[derive(Clone)] @@ -269,22 +272,35 @@ impl DynamicContextProvider for NamespaceHeaderProviderContext { } } +pub struct RemoteHostOverrides { + pub rest: Option, + pub sql: Option, +} + impl RemoteDatabase { - pub fn try_new( + pub(crate) fn try_new( uri: &str, api_key: &str, region: &str, - host_override: Option, + host_overrides: RemoteHostOverrides, client_config: ClientConfig, options: RemoteOptions, read_consistency_interval: Option, ) -> Result { let parsed = super::client::parse_db_url(uri)?; + 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, &parsed.db_name, - host_override.is_some(), + host_overrides.rest.is_some(), &options, parsed.db_prefix.as_deref(), &client_config, @@ -312,7 +328,7 @@ impl RemoteDatabase { let client = RestfulLanceDbClient::try_new( &parsed, region, - host_override, + host_overrides.rest, header_map, client_config.clone(), read_consistency_interval, @@ -330,6 +346,7 @@ impl RemoteDatabase { namespace_headers, namespace_context_provider, tls_config: client_config.tls_config, + sql_client: Some(sql_client), }) } } @@ -427,6 +444,7 @@ mod test_utils { namespace_headers: HashMap::new(), namespace_context_provider: None, tls_config: None, + sql_client: None, } } @@ -449,6 +467,7 @@ mod test_utils { namespace_headers: config.extra_headers.clone(), namespace_context_provider, tls_config: config.tls_config.clone(), + sql_client: None, } } } @@ -749,6 +768,30 @@ impl Database for RemoteDatabase { .map_err(Into::into) } + async fn execute_query_async( + &self, + query: &str, + default_namespace_path: &[String], + ) -> Result { + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "SQL is unavailable for this remote database client".to_string(), + })?; + client.submit(query, default_namespace_path).await + } + + async fn describe_query(&self, query_id: uuid::Uuid) -> Result { + let client = self + .sql_client + .as_ref() + .ok_or_else(|| Error::NotSupported { + message: "SQL is unavailable for this remote database client".to_string(), + })?; + client.describe(query_id).await + } + async fn table_names(&self, request: TableNamesRequest) -> Result> { let (tables, version) = if request.namespace_path.is_empty() { // The flat route resumes after a table name and orders by name, which is exactly diff --git a/rust/lancedb/src/remote/oauth.rs b/rust/lancedb/src/remote/oauth.rs index fd61db919..3ebe8f86e 100644 --- a/rust/lancedb/src/remote/oauth.rs +++ b/rust/lancedb/src/remote/oauth.rs @@ -466,7 +466,9 @@ impl TokenSource for AzureImdsSource { /// OAuth header provider that manages the full token lifecycle. /// /// Implements [`HeaderProvider`] to inject `Authorization: Bearer ` -/// headers into every LanceDB request, with automatic token refresh. +/// headers into every LanceDB request, with automatic token refresh. It also +/// identifies the bearer credential as OIDC so LanceDB's SQL service selects +/// OIDC validation instead of API-key validation. pub struct OAuthHeaderProvider { token_source: Box, token_state: Arc>, @@ -554,10 +556,10 @@ impl OAuthHeaderProvider { impl HeaderProvider for OAuthHeaderProvider { async fn get_headers(&self) -> Result> { let token = self.get_valid_token().await?; - Ok(HashMap::from([( - "authorization".to_string(), - format!("Bearer {token}"), - )])) + Ok(HashMap::from([ + ("authorization".to_string(), format!("Bearer {token}")), + ("x-lancedb-credential-type".to_string(), "oidc".to_string()), + ])) } } diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs new file mode 100644 index 000000000..489158922 --- /dev/null +++ b/rust/lancedb/src/remote/sql.rs @@ -0,0 +1,1471 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::collections::HashMap; +use std::fs; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex as StdMutex, OnceLock}; +use std::time::{Duration, Instant}; + +use arrow_array::RecordBatch; +use arrow_flight::decode::FlightRecordBatchStream; +use arrow_flight::error::FlightError; +use arrow_flight::flight_service_client::FlightServiceClient; +use arrow_flight::sql::{CommandStatementQuery, ProstMessageExt}; +use arrow_flight::{ + Action, CancelFlightInfoRequest, CancelFlightInfoResult, CancelStatus, FlightClient, + FlightDescriptor, FlightEndpoint, FlightInfo, PollInfo, +}; +use arrow_schema::{Schema, SchemaRef}; +use futures::TryStreamExt; +use http::header::{HeaderMap, HeaderName, HeaderValue}; +use prost::Message; +use tokio::sync::{Mutex, Notify, OnceCell, mpsc}; +use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint, Identity}; +use uuid::Uuid; + +use crate::arrow::{SendableRecordBatchStream, SimpleRecordBatchStream}; +use crate::error::{Error, Result}; +use crate::remote::client::{ClientConfig, TlsConfig}; +use crate::remote::retry::ResolvedRetryConfig; +use crate::sql::{Query, QueryDescription, QueryHandle, QueryStatus}; + +const DEFAULT_SQL_PORT: u16 = 10025; +const DEFAULT_SQL_TLS_PORT: u16 = 10026; +const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(120); +const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(300); +const STATUS_POLL_TIMEOUT: Duration = Duration::from_secs(1); +const MIN_POLL_INTERVAL: Duration = Duration::from_millis(50); +const MAX_SQL_MESSAGE_SIZE: usize = 1024 * 1024 * 1024; +const TERMINAL_QUERY_RETENTION: Duration = Duration::from_secs(300); +const ABANDONED_QUERY_RETENTION: Duration = Duration::from_secs(24 * 60 * 60); + +#[derive(Clone)] +pub(super) struct SqlClient { + inner: Arc, + queries: Arc, +} + +struct SqlClientInner { + database: String, + database_prefix: Option, + api_key: String, + host_override: Option, + sql_host_override: Option, + client_config: ClientConfig, + client: Arc>, +} + +struct SqlConnection { + // FlightClient does not expose its transport. Cancellation retains the channel so it can + // install a per-call interceptor that records whether a request was dispatched. + channel: Channel, + client: FlightServiceClient, +} + +struct ResultEndpointStream { + stream: FlightRecordBatchStream, + request_id: String, + read_timeout: Duration, +} + +struct PreparedSqlResult { + schema: SchemaRef, + next_endpoint: usize, + endpoint_stream: Option, + buffered_batch: Option, +} + +impl ResultEndpointStream { + async fn next_batch(&mut self) -> Result> { + tokio::time::timeout(self.read_timeout, self.stream.try_next()) + .await + .map_err(|_| sql_error(&self.request_id, "SQL result read timed out"))? + .map_err(|err| sql_error(&self.request_id, err)) + } +} + +enum CancelOutcome { + Status(CancelStatus), + NotFound(String), +} + +struct CancelAttempt { + dispatched: Arc, + unresolved: Arc, + resolved: bool, +} + +struct ResultStartGuard<'a> { + started: &'a AtomicBool, + committed: bool, +} + +impl<'a> ResultStartGuard<'a> { + fn new(started: &'a AtomicBool) -> Self { + Self { + started, + committed: false, + } + } + + fn commit(mut self) { + self.committed = true; + } +} + +impl Drop for ResultStartGuard<'_> { + fn drop(&mut self) { + if !self.committed { + self.started.store(false, Ordering::SeqCst); + } + } +} + +impl CancelAttempt { + fn new(dispatched: Arc, unresolved: Arc) -> Self { + Self { + dispatched, + unresolved, + resolved: false, + } + } + + fn resolve(&mut self) { + self.resolved = true; + } +} + +impl Drop for CancelAttempt { + fn drop(&mut self) { + if !self.resolved && self.dispatched.load(Ordering::SeqCst) { + self.unresolved.store(true, Ordering::SeqCst); + } + } +} + +impl std::fmt::Debug for SqlClient { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("SqlClient") + .field("database", &self.inner.database) + .field("database_prefix", &self.inner.database_prefix) + .field("api_key", &"") + .field("host_override", &self.inner.host_override) + .field("sql_host_override", &self.inner.sql_host_override) + .field("client_config", &"") + .field("initialized", &self.inner.client.get().is_some()) + .finish() + } +} + +impl SqlClient { + pub(super) fn new( + database: String, + database_prefix: Option, + api_key: String, + host_override: Option, + sql_host_override: Option, + client_config: ClientConfig, + ) -> Self { + Self { + inner: Arc::new(SqlClientInner { + database, + database_prefix, + api_key, + host_override, + sql_host_override, + client_config, + client: Arc::new(OnceCell::new()), + }), + queries: Arc::new(QueryRegistry::new()), + } + } + + pub(super) async fn submit( + &self, + query: &str, + default_namespace_path: &[String], + ) -> Result { + let timeout = self.inner.overall_timeout()?; + with_overall_timeout(timeout, "SQL query submission", async { + validate_namespace_path(default_namespace_path)?; + let command = CommandStatementQuery { + query: query.to_string(), + transaction_id: None, + }; + let descriptor = FlightDescriptor::new_cmd(command.as_any().encode_to_vec()); + let poll_info = self.inner.poll(descriptor, default_namespace_path).await?; + let query_id = Uuid::now_v7(); + let query = Arc::new(RemoteQuery::new( + query_id, + self.inner.clone(), + default_namespace_path.to_vec(), + poll_info, + )?); + self.queries.insert(query_id, query.clone()); + Ok(Query::new(Arc::new(RemoteQueryHandle::new(query)))) + }) + .await + } + + pub(super) async fn describe(&self, query_id: Uuid) -> Result { + let query = self + .queries + .get(query_id) + .ok_or_else(|| Error::InvalidInput { + message: "Unknown or expired SQL query id for this connection".to_string(), + })?; + query.describe().await + } + + #[cfg(test)] + async fn initialized_client_count(&self) -> usize { + usize::from(self.inner.client.get().is_some()) + } +} + +impl SqlClientInner { + fn overall_timeout(&self) -> Result> { + resolve_timeout( + self.client_config.timeout_config.timeout, + "LANCE_CLIENT_TIMEOUT", + None, + ) + } + + async fn poll( + &self, + descriptor: FlightDescriptor, + default_namespace_path: &[String], + ) -> Result { + let request_id = uuid::Uuid::new_v4().to_string(); + let read_timeout = resolve_timeout( + self.client_config.timeout_config.read_timeout, + "LANCE_CLIENT_READ_TIMEOUT", + Some(DEFAULT_READ_TIMEOUT), + )? + .unwrap(); + let mut client = self + .client_with_headers(default_namespace_path, &request_id) + .await?; + tokio::time::timeout(read_timeout, client.poll_flight_info(descriptor)) + .await + .map_err(|_| sql_error(&request_id, "SQL query poll timed out"))? + .map_err(|err| sql_error(&request_id, err)) + } + + async fn poll_status( + &self, + descriptor: FlightDescriptor, + default_namespace_path: &[String], + ) -> 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_error(&request_id, err)), + Err(_) => Ok(None), + } + } + + async fn poll_continuation( + &self, + descriptor: FlightDescriptor, + default_namespace_path: &[String], + ) -> Result { + let read_timeout = resolve_timeout( + self.client_config.timeout_config.read_timeout, + "LANCE_CLIENT_READ_TIMEOUT", + Some(DEFAULT_READ_TIMEOUT), + )? + .unwrap(); + let retry_config = ResolvedRetryConfig::try_from(self.client_config.retry_config.clone())?; + let mut retry_count = 0_u8; + 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 poll_info = match result { + Err(_) if retry_count < retry_config.read_retries => { + retry_count += 1; + tokio::time::sleep(poll_retry_delay(&retry_config, retry_count)).await; + continue; + } + Err(_) => return Err(sql_error(&request_id, "SQL query poll timed out")), + Ok(Err(FlightError::Tonic(status))) + if matches!( + status.code(), + tonic::Code::DeadlineExceeded | tonic::Code::Unavailable + ) && retry_count < retry_config.read_retries => + { + retry_count += 1; + tokio::time::sleep(poll_retry_delay(&retry_config, retry_count)).await; + continue; + } + Ok(Err(error)) => return Err(sql_error(&request_id, error)), + Ok(Ok(poll_info)) => poll_info, + }; + if let Some(delay) = MIN_POLL_INTERVAL.checked_sub(started.elapsed()) { + tokio::time::sleep(delay).await; + } + return Ok(poll_info); + } + } + + async fn open_result_endpoint( + &self, + endpoint: FlightEndpoint, + default_namespace_path: &[String], + ) -> Result { + let request_id = uuid::Uuid::new_v4().to_string(); + let read_timeout = resolve_timeout( + self.client_config.timeout_config.read_timeout, + "LANCE_CLIENT_READ_TIMEOUT", + Some(DEFAULT_READ_TIMEOUT), + )? + .unwrap(); + 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_error(&request_id, err))?; + Ok(ResultEndpointStream { + stream, + request_id, + read_timeout, + }) + } + + async fn cancel( + &self, + info: FlightInfo, + default_namespace_path: &[String], + unresolved_attempt: Arc, + ) -> Result { + let request_id = uuid::Uuid::new_v4().to_string(); + let read_timeout = resolve_timeout( + self.client_config.timeout_config.read_timeout, + "LANCE_CLIENT_READ_TIMEOUT", + Some(DEFAULT_READ_TIMEOUT), + )? + .unwrap(); + 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 dispatched = Arc::new(AtomicBool::new(false)); + let mut attempt = CancelAttempt::new(dispatched.clone(), unresolved_attempt); + let mut client = FlightServiceClient::with_interceptor( + connection.channel.clone(), + move |request: tonic::Request<()>| { + dispatched.store(true, Ordering::SeqCst); + Ok(request) + }, + ) + .max_decoding_message_size(MAX_SQL_MESSAGE_SIZE); + let action = Action::new( + "CancelFlightInfo", + CancelFlightInfoRequest::new(info).encode_to_vec(), + ); + let mut request = tonic::Request::new(action); + *request.metadata_mut() = metadata; + let result = tokio::time::timeout(read_timeout, async { + let response = client + .do_action(request) + .await + .map_err(|status| FlightError::Tonic(Box::new(status)))?; + let response = response + .into_inner() + .message() + .await + .map_err(|status| FlightError::Tonic(Box::new(status)))? + .ok_or_else(|| { + FlightError::protocol("Received no response for cancel_flight_info call") + })?; + CancelFlightInfoResult::decode(response.body) + .map_err(|err| FlightError::DecodeError(err.to_string())) + }) + .await + .map_err(|_| sql_error(&request_id, "SQL query cancellation timed out"))?; + let result = match result { + Ok(result) => result, + Err(FlightError::Tonic(status)) if status.code() == tonic::Code::NotFound => { + attempt.resolve(); + return Ok(CancelOutcome::NotFound(request_id)); + } + Err(FlightError::Tonic(status)) if !cancellation_status_is_ambiguous(status.code()) => { + attempt.resolve(); + return Err(sql_error(&request_id, status)); + } + Err(error) => return Err(sql_error(&request_id, error)), + }; + let status = CancelStatus::try_from(result.status) + .map_err(|_| sql_error(&request_id, "SQL query returned an invalid cancel status"))?; + if status != CancelStatus::Unspecified { + attempt.resolve(); + } + Ok(CancelOutcome::Status(status)) + } + + async fn client_with_headers( + &self, + default_namespace_path: &[String], + request_id: &str, + ) -> Result { + let connection = self.connection(request_id).await?; + let headers = self.headers(default_namespace_path, request_id).await?; + client_with_headers(connection.client.clone(), &headers) + } + + async fn connection(&self, request_id: &str) -> Result<&SqlConnection> { + self.client + .get_or_try_init(|| async { + let target = resolve_sql_host_override( + self.host_override.as_deref(), + self.sql_host_override.as_deref(), + )?; + let channel = connect_channel(&target, &self.client_config, request_id).await?; + let client = FlightServiceClient::new(channel.clone()) + .max_decoding_message_size(MAX_SQL_MESSAGE_SIZE); + Ok::<_, Error>(SqlConnection { channel, client }) + }) + .await + } + + async fn headers( + &self, + default_namespace_path: &[String], + request_id: &str, + ) -> Result { + let mut headers = HeaderMap::new(); + merge_headers(&mut headers, &self.client_config.extra_headers)?; + if let Some(provider) = &self.client_config.header_provider { + merge_headers(&mut headers, &provider.get_headers().await?)?; + } + + let has_authorization = headers.contains_key("authorization"); + let has_api_key = headers.contains_key("x-api-key"); + if has_authorization && has_api_key { + return Err(Error::InvalidInput { + message: "SQL accepts either authorization or x-api-key, not both".to_string(), + }); + } + if !has_authorization && !has_api_key { + if self.api_key.is_empty() { + return Err(Error::InvalidInput { + message: "SQL authentication credentials are required".to_string(), + }); + } + insert_header(&mut headers, "x-api-key", &self.api_key)?; + } + + insert_header(&mut headers, "database", &self.database)?; + if let Some(database_prefix) = &self.database_prefix { + insert_header(&mut headers, "x-lancedb-database-prefix", database_prefix)?; + } + let namespace_path = if default_namespace_path.is_empty() { + "public".to_string() + } else { + default_namespace_path.join("$") + }; + insert_header(&mut headers, "namespace-path", &namespace_path)?; + insert_header(&mut headers, "x-request-id", request_id)?; + if let Some(user_id) = self.client_config.resolve_user_id() { + insert_header(&mut headers, "x-lancedb-user-id", &user_id)?; + } + Ok(headers) + } +} + +struct QueryRegistry { + queries: StdMutex>>, +} + +impl QueryRegistry { + fn new() -> Self { + Self { + queries: StdMutex::new(HashMap::new()), + } + } + + fn insert(&self, id: Uuid, query: Arc) { + self.remove_expired(); + self.queries.lock().unwrap().insert(id, query); + } + + fn get(&self, id: Uuid) -> Option> { + self.remove_expired(); + let query = self.queries.lock().unwrap().get(&id).cloned(); + if let Some(query) = &query { + query.touch(); + } + query + } + + fn remove_expired(&self) { + self.queries + .lock() + .unwrap() + .retain(|_, query| !query.registry_expired(Arc::strong_count(query) == 1)); + } +} + +struct RemoteQuery { + id: Uuid, + client: Arc, + default_namespace_path: Vec, + state: Mutex, + poll_gate: Mutex<()>, + cancel_gate: Mutex<()>, + state_changed: Notify, + cancelled: Notify, + expires_at: StdMutex>>, + terminal_at: OnceLock, + last_accessed: StdMutex, + lifecycle: StdMutex, + cancel_request_uncertain: Arc, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum QueryLifecycle { + Running, + Ready, + Cancelling, + Completed, + Cancelled, +} + +impl RemoteQuery { + fn new( + id: Uuid, + client: Arc, + default_namespace_path: Vec, + poll_info: PollInfo, + ) -> Result { + let expires_at = query_expiration(&poll_info)?; + let terminal_at = OnceLock::new(); + let lifecycle = if poll_info.flight_descriptor.is_none() { + let _ = terminal_at.set(Instant::now()); + QueryLifecycle::Ready + } else { + QueryLifecycle::Running + }; + Ok(Self { + id, + client, + default_namespace_path, + state: Mutex::new(poll_info), + poll_gate: Mutex::new(()), + cancel_gate: Mutex::new(()), + state_changed: Notify::new(), + cancelled: Notify::new(), + expires_at: StdMutex::new(expires_at), + terminal_at, + last_accessed: StdMutex::new(Instant::now()), + lifecycle: StdMutex::new(lifecycle), + cancel_request_uncertain: Arc::new(AtomicBool::new(false)), + }) + } + + fn registry_expired(&self, abandoned: bool) -> bool { + if let Some(finished) = self.terminal_at.get() { + return finished.elapsed() >= TERMINAL_QUERY_RETENTION; + } + self.expires_at + .lock() + .unwrap() + .is_some_and(|expires_at| expires_at <= chrono::Utc::now()) + || (abandoned + && self.last_accessed.lock().unwrap().elapsed() >= ABANDONED_QUERY_RETENTION) + } + + fn mark_terminal(&self) { + let _ = self.terminal_at.set(Instant::now()); + } + + fn mark_ready(&self) { + let mut lifecycle = self.lifecycle.lock().unwrap(); + if *lifecycle == QueryLifecycle::Running { + *lifecycle = QueryLifecycle::Ready; + } + drop(lifecycle); + self.mark_terminal(); + } + + fn mark_cancelled(&self) -> bool { + self.cancel_request_uncertain.store(false, Ordering::SeqCst); + let mut lifecycle = self.lifecycle.lock().unwrap(); + if matches!( + *lifecycle, + QueryLifecycle::Cancelled | QueryLifecycle::Completed + ) { + return false; + } + *lifecycle = QueryLifecycle::Cancelled; + drop(lifecycle); + self.mark_terminal(); + self.cancelled.notify_waiters(); + self.state_changed.notify_waiters(); + true + } + + fn mark_cancelling(&self) { + self.cancel_request_uncertain.store(false, Ordering::SeqCst); + let mut lifecycle = self.lifecycle.lock().unwrap(); + if matches!(*lifecycle, QueryLifecycle::Running | QueryLifecycle::Ready) { + *lifecycle = QueryLifecycle::Cancelling; + drop(lifecycle); + self.cancelled.notify_waiters(); + self.state_changed.notify_waiters(); + } + } + + async fn restore_after_rejected_cancellation(&self) { + self.cancel_request_uncertain.store(false, Ordering::SeqCst); + let running = self.state.lock().await.flight_descriptor.is_some(); + let mut lifecycle = self.lifecycle.lock().unwrap(); + if *lifecycle == QueryLifecycle::Cancelling { + *lifecycle = if running { + QueryLifecycle::Running + } else { + QueryLifecycle::Ready + }; + drop(lifecycle); + self.state_changed.notify_waiters(); + } + } + + fn mark_result_completed(&self) -> Result<()> { + let mut lifecycle = self.lifecycle.lock().unwrap(); + if matches!( + *lifecycle, + QueryLifecycle::Cancelling | QueryLifecycle::Cancelled + ) { + return Err(self.cancelled_error()); + } + *lifecycle = QueryLifecycle::Completed; + Ok(()) + } + + fn lifecycle(&self) -> QueryLifecycle { + *self.lifecycle.lock().unwrap() + } + + fn is_cancellation_requested(&self) -> bool { + matches!( + self.lifecycle(), + QueryLifecycle::Cancelling | QueryLifecycle::Cancelled + ) + } + + fn cancelled_error(&self) -> Error { + Error::JobCancelled { + job_id: Some(self.id.to_string()), + } + } + + async fn wait_for_cancellation(&self) { + loop { + let cancelled = self.cancelled.notified(); + if self.is_cancellation_requested() { + return; + } + cancelled.await; + } + } + + fn touch(&self) { + *self.last_accessed.lock().unwrap() = Instant::now(); + } + + async fn poll_next_state(&self, descriptor: FlightDescriptor) -> Result { + self.touch(); + if self.is_cancellation_requested() { + return Err(self.cancelled_error()); + } + let _poll_guard = tokio::select! { + biased; + _ = self.wait_for_cancellation() => return Err(self.cancelled_error()), + poll_guard = self.poll_gate.lock() => poll_guard, + }; + let latest = self.state.lock().await.clone(); + if latest.flight_descriptor.as_ref() != Some(&descriptor) { + return Ok(latest); + } + let updated = tokio::select! { + biased; + _ = self.wait_for_cancellation() => return Err(self.cancelled_error()), + result = self.client.poll_continuation( + descriptor.clone(), + &self.default_namespace_path, + ) => match result { + Err(_) if self.is_cancellation_requested() => { + return Err(self.cancelled_error()); + } + result => result?, + }, + }; + self.update_state(&descriptor, updated).await + } + + async fn prepare_result(self: &Arc) -> Result { + loop { + if self.is_cancellation_requested() { + return Err(self.cancelled_error()); + } + let state = self.state.lock().await.clone(); + if let Some(info) = state.info { + if let Some(endpoint) = info.endpoint.first().cloned() { + let mut endpoint_stream = tokio::select! { + biased; + _ = self.wait_for_cancellation() => return Err(self.cancelled_error()), + result = self.client.open_result_endpoint( + endpoint, + &self.default_namespace_path, + ) => result?, + }; + let buffered_batch = tokio::select! { + biased; + _ = self.wait_for_cancellation() => return Err(self.cancelled_error()), + result = endpoint_stream.next_batch() => result?, + }; + let schema = buffered_batch + .as_ref() + .map(RecordBatch::schema) + .or_else(|| endpoint_stream.stream.schema().cloned()) + .ok_or_else(|| Error::Runtime { + message: "SQL result endpoint did not include a schema".to_string(), + })?; + return Ok(PreparedSqlResult { + schema, + next_endpoint: 1, + endpoint_stream: buffered_batch.is_some().then_some(endpoint_stream), + buffered_batch, + }); + } + if state.flight_descriptor.is_none() { + let schema = if info.schema.is_empty() { + Arc::new(Schema::empty()) + } else { + let request_id = uuid::Uuid::new_v4().to_string(); + Arc::new( + info.try_decode_schema() + .map_err(|err| sql_error(&request_id, err))?, + ) + }; + return Ok(PreparedSqlResult { + schema, + next_endpoint: 0, + endpoint_stream: None, + buffered_batch: None, + }); + } + } else if state.flight_descriptor.is_none() { + return Err(Error::Runtime { + message: "Completed SQL query did not include result information".to_string(), + }); + } + let descriptor = state.flight_descriptor.ok_or_else(|| Error::Runtime { + message: "Completed SQL query did not include result information".to_string(), + })?; + self.poll_next_state(descriptor).await?; + } + } + + async fn run_result_stream( + self: Arc, + mut prepared: PreparedSqlResult, + sender: mpsc::Sender>, + ) -> Result<()> { + if let Some(batch) = prepared.buffered_batch.take() + && !self + .send_result_batch(&sender, &prepared.schema, batch) + .await? + { + return Ok(()); + } + loop { + if self.is_cancellation_requested() { + return Err(self.cancelled_error()); + } + if let Some(endpoint_stream) = prepared.endpoint_stream.as_mut() { + let batch = tokio::select! { + biased; + _ = sender.closed() => return Ok(()), + _ = self.wait_for_cancellation() => return Err(self.cancelled_error()), + result = endpoint_stream.next_batch() => result?, + }; + if let Some(batch) = batch { + if !self + .send_result_batch(&sender, &prepared.schema, batch) + .await? + { + return Ok(()); + } + } else { + prepared.endpoint_stream = None; + } + continue; + } + + let state = self.state.lock().await.clone(); + let endpoints = state + .info + .as_ref() + .map(|info| info.endpoint.as_slice()) + .unwrap_or_default(); + if prepared.next_endpoint > endpoints.len() { + return Err(Error::Runtime { + message: "SQL service removed a previously advertised result endpoint" + .to_string(), + }); + } + if let Some(endpoint) = endpoints.get(prepared.next_endpoint).cloned() { + prepared.next_endpoint += 1; + prepared.endpoint_stream = Some(tokio::select! { + biased; + _ = sender.closed() => return Ok(()), + _ = self.wait_for_cancellation() => return Err(self.cancelled_error()), + result = self.client.open_result_endpoint( + endpoint, + &self.default_namespace_path, + ) => result?, + }); + continue; + } + if let Some(descriptor) = state.flight_descriptor { + tokio::select! { + biased; + _ = sender.closed() => return Ok(()), + _ = self.wait_for_cancellation() => return Err(self.cancelled_error()), + result = self.poll_next_state(descriptor) => result?, + }; + continue; + } + self.mark_result_completed()?; + return Ok(()); + } + } + + async fn send_result_batch( + &self, + sender: &mpsc::Sender>, + schema: &SchemaRef, + batch: RecordBatch, + ) -> Result { + if batch.schema().as_ref() != schema.as_ref() { + return Err(Error::Runtime { + message: "SQL result endpoint returned a different schema".to_string(), + }); + } + tokio::select! { + biased; + _ = self.wait_for_cancellation() => Err(self.cancelled_error()), + result = sender.send(Ok(batch)) => Ok(result.is_ok()), + } + } + + async fn update_state( + &self, + descriptor: &FlightDescriptor, + updated: PollInfo, + ) -> Result { + self.touch(); + let expires_at = query_expiration(&updated)?; + let mut state = self.state.lock().await; + if state.flight_descriptor.as_ref() == Some(descriptor) { + if updated.flight_descriptor.is_none() { + self.mark_ready(); + } + *self.expires_at.lock().unwrap() = expires_at; + *state = updated; + self.state_changed.notify_waiters(); + } + Ok(state.clone()) + } +} + +impl RemoteQuery { + async fn describe(&self) -> Result { + let timeout = self.client.overall_timeout()?; + with_overall_timeout(timeout, "SQL query description", self.describe_inner()).await + } + + async fn describe_inner(&self) -> Result { + self.touch(); + if self.is_cancellation_requested() { + let state = self.state.lock().await.clone(); + return query_description(self.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(), + ), + 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()); + }; + let latest = self.state.lock().await.clone(); + if latest.flight_descriptor.as_ref() != Some(&descriptor) { + latest + } else { + let updated = tokio::select! { + biased; + _ = self.wait_for_cancellation() => return query_description( + self.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?, + }, + }; + if let Some(updated) = updated { + self.update_state(&descriptor, updated).await? + } else { + latest + } + } + } else { + state + }; + query_description(self.id, &state, self.lifecycle()) + } + + async fn cancel(&self) -> Result<()> { + let timeout = self.client.overall_timeout()?; + with_overall_timeout(timeout, "SQL query cancellation", self.cancel_inner()).await + } + + async fn cancel_inner(&self) -> Result<()> { + self.touch(); + let _cancel_guard = self.cancel_gate.lock().await; + if matches!( + self.lifecycle(), + QueryLifecycle::Cancelled | QueryLifecycle::Completed + ) { + return Ok(()); + } + loop { + let notified = self.state_changed.notified(); + let state = self.state.lock().await.clone(); + if let Some(info) = state.info { + let previously_uncertain = self.cancel_request_uncertain.load(Ordering::SeqCst); + let outcome = match self + .client + .cancel( + info, + &self.default_namespace_path, + self.cancel_request_uncertain.clone(), + ) + .await + { + Ok(outcome) => outcome, + Err(_) + if matches!( + self.lifecycle(), + QueryLifecycle::Cancelled | QueryLifecycle::Completed + ) => + { + return Ok(()); + } + Err(error) => return Err(error), + }; + if matches!( + self.lifecycle(), + QueryLifecycle::Cancelled | QueryLifecycle::Completed + ) { + return Ok(()); + } + let status = match outcome { + CancelOutcome::Status(status) => status, + CancelOutcome::NotFound(_) + if self.lifecycle() == QueryLifecycle::Cancelling => + { + self.mark_cancelled(); + return Ok(()); + } + CancelOutcome::NotFound(request_id) => { + let message = if previously_uncertain { + "SQL query cancellation outcome is unknown because a prior request may have reached the service and the target was not found on retry" + } else { + "SQL query cancellation target was not found" + }; + return Err(sql_error(&request_id, message)); + } + }; + return match status { + CancelStatus::Cancelled => { + self.mark_cancelled(); + Ok(()) + } + CancelStatus::Cancelling => { + self.mark_cancelling(); + Ok(()) + } + CancelStatus::NotCancellable => { + self.restore_after_rejected_cancellation().await; + Err(Error::NotSupported { + message: "The SQL query is not cancellable".to_string(), + }) + } + CancelStatus::Unspecified => Err(Error::Runtime { + message: "The SQL service returned an unspecified cancellation status" + .to_string(), + }), + }; + } + let Some(descriptor) = state.flight_descriptor else { + return Ok(()); + }; + + tokio::select! { + poll_guard = self.poll_gate.lock() => { + let _poll_guard = poll_guard; + if self.state.lock().await.flight_descriptor.as_ref() != Some(&descriptor) { + continue; + } + let updated = self.client.poll_continuation( + descriptor.clone(), + &self.default_namespace_path, + ).await?; + self.update_state(&descriptor, updated).await?; + } + _ = notified => {} + } + } + } +} + +struct RemoteQueryHandle { + query: Arc, + result_started: AtomicBool, +} + +impl RemoteQueryHandle { + fn new(query: Arc) -> Self { + Self { + query, + result_started: AtomicBool::new(false), + } + } +} + +#[async_trait::async_trait] +impl QueryHandle for RemoteQueryHandle { + fn id(&self) -> Uuid { + self.query.touch(); + self.query.id + } + + async fn describe(&self) -> Result { + self.query.describe().await + } + + async fn reader(&self) -> Result { + let timeout = self.query.client.overall_timeout()?; + if self + .result_started + .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) + .is_err() + { + return Err(Error::Runtime { + message: "SQL query results can only be consumed once".to_string(), + }); + } + let result_start = ResultStartGuard::new(&self.result_started); + let started = Instant::now(); + let prepared = + with_overall_timeout(timeout, "SQL query result", self.query.prepare_result()).await?; + let remaining_timeout = timeout.map(|timeout| timeout.saturating_sub(started.elapsed())); + let schema = prepared.schema.clone(); + let (sender, receiver) = mpsc::channel(2); + let error_sender = sender.clone(); + let query = self.query.clone(); + tokio::spawn(async move { + let result = with_overall_timeout( + remaining_timeout, + "SQL query result", + query.run_result_stream(prepared, sender), + ) + .await; + if let Err(error) = result { + let _ = error_sender.send(Err(error)).await; + } + }); + let stream = futures::stream::unfold(receiver, |mut receiver| async move { + receiver.recv().await.map(|item| (item, receiver)) + }); + result_start.commit(); + Ok(Box::pin(SimpleRecordBatchStream::new(stream, schema))) + } + + async fn cancel(&self) -> Result<()> { + self.query.cancel().await + } +} + +fn query_description( + id: Uuid, + poll_info: &PollInfo, + lifecycle: QueryLifecycle, +) -> Result { + let expires_at = query_expiration(poll_info)?; + Ok(QueryDescription { + id, + status: match lifecycle { + QueryLifecycle::Cancelling => QueryStatus::Cancelling, + QueryLifecycle::Cancelled => QueryStatus::Cancelled, + QueryLifecycle::Running if poll_info.flight_descriptor.is_some() => { + QueryStatus::Running + } + QueryLifecycle::Running | QueryLifecycle::Ready | QueryLifecycle::Completed => { + QueryStatus::Finished + } + }, + progress: poll_info.progress, + expires_at, + }) +} + +fn query_expiration(poll_info: &PollInfo) -> Result>> { + poll_info + .expiration_time + .as_ref() + .map(|timestamp| { + u32::try_from(timestamp.nanos) + .ok() + .and_then(|nanos| chrono::DateTime::from_timestamp(timestamp.seconds, nanos)) + .ok_or_else(|| Error::Runtime { + message: "SQL service returned an invalid query expiration time".to_string(), + }) + }) + .transpose() +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct SqlTarget { + uri: String, + tls: bool, +} + +fn resolve_sql_host_override( + host_override: Option<&str>, + sql_host_override: Option<&str>, +) -> Result { + if let Some(uri) = sql_host_override { + return normalize_sql_host_override(uri); + } + let host_override = host_override.ok_or_else(|| Error::InvalidInput { + message: "sql_host_override is required when the SQL service endpoint cannot be derived from host_override".to_string(), + })?; + let parsed = url::Url::parse(host_override).map_err(|err| Error::InvalidInput { + message: format!("Invalid host_override: {err}"), + })?; + if parsed.scheme() != "http" { + return Err(Error::InvalidInput { + message: "sql_host_override is required for TLS or non-HTTP host overrides".to_string(), + }); + } + validate_endpoint_url(&parsed, "host_override")?; + let port = match parsed.port().or(explicit_port(host_override)) { + Some(u16::MAX) => { + return Err(Error::InvalidInput { + message: "sql_host_override is required when host_override uses port 65535" + .to_string(), + }); + } + Some(port) => port + 1, + None => DEFAULT_SQL_PORT, + }; + Ok(SqlTarget { + uri: endpoint_uri("http", parsed.host_str().unwrap(), port), + tls: false, + }) +} + +fn normalize_sql_host_override(uri: &str) -> Result { + let parsed = url::Url::parse(uri).map_err(|err| Error::InvalidInput { + message: format!("Invalid sql_host_override: {err}"), + })?; + validate_endpoint_url(&parsed, "sql_host_override")?; + let tls = match parsed.scheme().to_ascii_lowercase().as_str() { + "grpc" | "grpc+tcp" | "http" => false, + "grpc+tls" | "grpcs" | "https" => true, + _ => { + return Err(Error::InvalidInput { + message: + "sql_host_override must use grpc, grpc+tcp, grpc+tls, grpcs, http, or https" + .to_string(), + }); + } + }; + let port = parsed.port().or(explicit_port(uri)).unwrap_or(if tls { + DEFAULT_SQL_TLS_PORT + } else { + DEFAULT_SQL_PORT + }); + if port == 0 { + return Err(Error::InvalidInput { + message: "sql_host_override port must be greater than zero".to_string(), + }); + } + Ok(SqlTarget { + uri: endpoint_uri( + if tls { "https" } else { "http" }, + parsed.host_str().unwrap(), + port, + ), + tls, + }) +} + +fn explicit_port(uri: &str) -> Option { + let authority = uri.split_once("://")?.1.split(['/', '?', '#']).next()?; + let suffix = if authority.starts_with('[') { + authority.split_once(']')?.1.strip_prefix(':')? + } else { + authority.rsplit_once(':')?.1 + }; + suffix.parse().ok() +} + +fn validate_endpoint_url(parsed: &url::Url, name: &str) -> Result<()> { + if parsed.host_str().is_none() { + return Err(Error::InvalidInput { + message: format!("{name} must include a hostname"), + }); + } + if !parsed.username().is_empty() || parsed.password().is_some() { + return Err(Error::InvalidInput { + message: format!("{name} must not include user information"), + }); + } + if !matches!(parsed.path(), "" | "/") || parsed.query().is_some() || parsed.fragment().is_some() + { + return Err(Error::InvalidInput { + message: format!("{name} must not include a path, query, or fragment"), + }); + } + Ok(()) +} + +fn endpoint_uri(scheme: &str, host: &str, port: u16) -> String { + if host.contains(':') { + let host = host + .strip_prefix('[') + .and_then(|host| host.strip_suffix(']')) + .unwrap_or(host); + format!("{scheme}://[{host}]:{port}") + } else { + format!("{scheme}://{host}:{port}") + } +} + +async fn connect_channel( + target: &SqlTarget, + config: &ClientConfig, + request_id: &str, +) -> Result { + let connect_timeout = resolve_timeout( + config.timeout_config.connect_timeout, + "LANCE_CLIENT_CONNECT_TIMEOUT", + Some(DEFAULT_CONNECT_TIMEOUT), + )? + .unwrap(); + let mut endpoint = Endpoint::from_shared(target.uri.clone()) + .map_err(|err| sql_error(request_id, err))? + .connect_timeout(connect_timeout); + if target.tls { + endpoint = endpoint + .tls_config(tls_config(config.tls_config.as_ref())?) + .map_err(|err| sql_error(request_id, err))?; + } + tokio::time::timeout(connect_timeout, endpoint.connect()) + .await + .map_err(|_| sql_error(request_id, "SQL connection timed out"))? + .map_err(|err| sql_error(request_id, err)) +} + +fn tls_config(config: Option<&TlsConfig>) -> Result { + let mut tls = ClientTlsConfig::new().with_enabled_roots(); + if let Some(config) = config { + if !config.assert_hostname { + return Err(Error::InvalidInput { + message: "SQL cannot disable TLS hostname verification".to_string(), + }); + } + if let Some(path) = &config.ssl_ca_cert { + let pem = fs::read(path).map_err(|err| Error::InvalidInput { + message: format!("Failed to read SQL CA certificate {path}: {err}"), + })?; + tls = tls.ca_certificate(Certificate::from_pem(pem)); + } + match (&config.cert_file, &config.key_file) { + (Some(cert), Some(key)) => { + let cert_pem = fs::read(cert).map_err(|err| Error::InvalidInput { + message: format!("Failed to read SQL client certificate {cert}: {err}"), + })?; + let key_pem = fs::read(key).map_err(|err| Error::InvalidInput { + message: format!("Failed to read SQL client key {key}: {err}"), + })?; + tls = tls.identity(Identity::from_pem(cert_pem, key_pem)); + } + (None, None) => {} + _ => { + return Err(Error::InvalidInput { + message: "SQL mTLS requires both cert_file and key_file".to_string(), + }); + } + } + } + Ok(tls) +} + +fn client_with_headers( + client: FlightServiceClient, + headers: &HeaderMap, +) -> Result { + let mut client = FlightClient::new_from_inner(client); + for (key, value) in headers { + let value = value.to_str().map_err(|err| Error::InvalidInput { + message: format!("Invalid SQL metadata value for {key:?}: {err}"), + })?; + client + .add_header(key.as_str(), value) + .map_err(|err| Error::InvalidInput { + message: format!("Invalid SQL metadata header {key:?}: {err}"), + })?; + } + Ok(client) +} + +fn merge_headers(destination: &mut HeaderMap, source: &HashMap) -> Result<()> { + for (key, value) in source { + insert_header(destination, key, value)?; + } + Ok(()) +} + +fn insert_header(headers: &mut HeaderMap, key: &str, value: &str) -> Result<()> { + let key = HeaderName::from_bytes(key.as_bytes()).map_err(|err| Error::InvalidInput { + message: format!("Invalid SQL metadata key {key:?}: {err}"), + })?; + let value = HeaderValue::try_from(value).map_err(|err| Error::InvalidInput { + message: format!("Invalid SQL metadata value for {key:?}: {err}"), + })?; + headers.insert(key, value); + Ok(()) +} + +fn validate_namespace_path(path: &[String]) -> Result<()> { + for component in path { + if component.is_empty() + || !component.is_ascii() + || component.contains('$') + || component.bytes().any(|byte| !(0x20..=0x7e).contains(&byte)) + { + return Err(Error::InvalidInput { + message: "default_namespace_path components must be non-empty printable ASCII strings without '$'".to_string(), + }); + } + } + Ok(()) +} + +fn poll_retry_delay(config: &ResolvedRetryConfig, retry_count: u8) -> Duration { + let exponent = i32::from(retry_count.saturating_sub(1).min(16)); + let backoff = config.backoff_factor * 2.0_f32.powi(exponent); + let jitter = rand::random::() * config.backoff_jitter; + Duration::from_secs_f32((backoff + jitter).clamp(MIN_POLL_INTERVAL.as_secs_f32(), 60.0)) +} + +fn cancellation_status_is_ambiguous(code: tonic::Code) -> bool { + matches!( + code, + tonic::Code::Cancelled + | tonic::Code::Unknown + | tonic::Code::DeadlineExceeded + | tonic::Code::Internal + | tonic::Code::Unavailable + | tonic::Code::DataLoss + ) +} + +fn resolve_timeout( + configured: Option, + env_name: &str, + default: Option, +) -> Result> { + if configured.is_some() { + return Ok(configured); + } + match std::env::var(env_name) { + Ok(value) => value + .parse::() + .map(Duration::from_secs) + .map(Some) + .map_err(|_| Error::InvalidInput { + message: format!("Invalid value for {env_name} environment variable: {value:?}"), + }), + Err(_) => Ok(default), + } +} + +async fn with_overall_timeout( + timeout: Option, + operation: &str, + future: impl std::future::Future>, +) -> Result { + match timeout { + Some(timeout) => { + tokio::time::timeout(timeout, future) + .await + .map_err(|_| Error::Runtime { + message: format!("{operation} timed out"), + })? + } + None => future.await, + } +} + +fn sql_error(request_id: &str, error: impl std::fmt::Display) -> Error { + Error::Runtime { + message: format!("SQL error (request_id={request_id}): {error}"), + } +} + +#[cfg(test)] +#[path = "sql_test.rs"] +mod tests; diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs new file mode 100644 index 000000000..a05a11259 --- /dev/null +++ b/rust/lancedb/src/remote/sql_test.rs @@ -0,0 +1,1040 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::sync::atomic::AtomicUsize; + +use arrow_array::builder::StringDictionaryBuilder; +use arrow_array::{Array, Int64Array, StringArray, types::Int32Type}; +use arrow_flight::encode::FlightDataEncoderBuilder; +use arrow_flight::flight_service_server::{FlightService, FlightServiceServer}; +use arrow_flight::sql::{Any, CommandStatementQuery}; +use arrow_flight::{ + Action, ActionType, CancelFlightInfoResult, Criteria, Empty, FlightData, FlightEndpoint, + FlightInfo, HandshakeRequest, HandshakeResponse, PollInfo, PutResult, SchemaResult, Ticket, +}; +use arrow_schema::{DataType, Field, Schema}; +use futures::stream::BoxStream; +use futures::{StreamExt, TryStreamExt}; +use tonic::{Request, Response, Status, Streaming}; + +use super::*; +use crate::remote::client::HeaderProvider; + +#[derive(Debug, Default)] +struct DelayedHeaderProvider { + delay_next: AtomicBool, +} + +#[async_trait::async_trait] +impl HeaderProvider for DelayedHeaderProvider { + async fn get_headers(&self) -> Result> { + if self.delay_next.swap(false, Ordering::SeqCst) { + tokio::time::sleep(Duration::from_millis(1_100)).await; + } + Ok(HashMap::new()) + } +} + +fn assert_overall_timeout(result: Result, operation: &str) { + match result { + Err(Error::Runtime { message }) => { + assert_eq!(message, format!("SQL query {operation} timed out")); + } + _ => panic!("SQL query {operation} did not honor the overall timeout"), + } +} + +async fn collect_result(query: &Query) -> Result> { + query.reader().await?.try_collect().await +} + +#[derive(Debug)] +struct CapturedHeaders { + database: String, + namespace_path: String, + request_id: String, + api_key: String, + database_prefix: String, +} + +#[derive(Clone)] +struct TestSqlService { + query_count: Arc, + do_get_count: Arc, + cancel_count: Arc, + cancel_denied_count: Arc, + cancel_timeout_count: Arc, + cancel_unspecified_count: Arc, + cancelling_response_count: Arc, + incremental_finished: Arc, + first_continuation_count: Arc, + transient_poll_failures: Arc, + headers: Arc>>, + result: RecordBatch, + large_result: RecordBatch, + dictionary_result: RecordBatch, +} + +impl Default for TestSqlService { + fn default() -> Self { + let schema = Arc::new(Schema::new(vec![Field::new( + "value", + DataType::Int64, + false, + )])); + let result = + RecordBatch::try_new(schema, vec![Arc::new(Int64Array::from(vec![42_i64]))]).unwrap(); + let large_schema = Arc::new(Schema::new(vec![Field::new( + "value", + DataType::Utf8, + false, + )])); + let large_result = RecordBatch::try_new( + large_schema, + vec![Arc::new(StringArray::from(vec![ + "x".repeat(5 * 1024 * 1024), + ]))], + ) + .unwrap(); + let mut dictionary_builder = StringDictionaryBuilder::::new(); + dictionary_builder.append("dictionary value").unwrap(); + let dictionary = dictionary_builder.finish(); + let dictionary_schema = Arc::new(Schema::new(vec![Field::new( + "value", + dictionary.data_type().clone(), + false, + )])); + let dictionary_result = + RecordBatch::try_new(dictionary_schema, vec![Arc::new(dictionary)]).unwrap(); + Self { + query_count: Arc::new(AtomicUsize::new(0)), + do_get_count: Arc::new(AtomicUsize::new(0)), + cancel_count: Arc::new(AtomicUsize::new(0)), + cancel_denied_count: Arc::new(AtomicUsize::new(0)), + cancel_timeout_count: Arc::new(AtomicUsize::new(0)), + cancel_unspecified_count: Arc::new(AtomicUsize::new(0)), + cancelling_response_count: Arc::new(AtomicUsize::new(0)), + incremental_finished: Arc::new(AtomicBool::new(false)), + first_continuation_count: Arc::new(AtomicUsize::new(0)), + transient_poll_failures: Arc::new(AtomicUsize::new(0)), + headers: Arc::new(std::sync::Mutex::new(Vec::new())), + result, + large_result, + dictionary_result, + } + } +} + +#[tonic::async_trait] +impl FlightService for TestSqlService { + type HandshakeStream = BoxStream<'static, std::result::Result>; + type ListFlightsStream = BoxStream<'static, std::result::Result>; + type DoGetStream = BoxStream<'static, std::result::Result>; + type DoPutStream = BoxStream<'static, std::result::Result>; + type DoActionStream = BoxStream<'static, std::result::Result>; + type ListActionsStream = BoxStream<'static, std::result::Result>; + type DoExchangeStream = BoxStream<'static, std::result::Result>; + + async fn handshake( + &self, + _request: Request>, + ) -> std::result::Result, Status> { + Err(Status::unimplemented("handshake")) + } + + async fn list_flights( + &self, + _request: Request, + ) -> std::result::Result, Status> { + Err(Status::unimplemented("list_flights")) + } + + async fn get_flight_info( + &self, + _request: Request, + ) -> std::result::Result, Status> { + Err(Status::unimplemented("get_flight_info")) + } + + async fn poll_flight_info( + &self, + request: Request, + ) -> std::result::Result, Status> { + let metadata = request.metadata(); + let header = |name| { + metadata + .get(name) + .and_then(|value| value.to_str().ok()) + .unwrap() + .to_string() + }; + self.headers.lock().unwrap().push(CapturedHeaders { + database: header("database"), + namespace_path: header("namespace-path"), + request_id: header("x-request-id"), + api_key: header("x-api-key"), + database_prefix: header("x-lancedb-database-prefix"), + }); + + let command = Any::decode(request.get_ref().cmd.as_ref()) + .ok() + .and_then(|any| any.unpack::().ok().flatten()); + let (query, stage) = if let Some(command) = command { + self.query_count.fetch_add(1, Ordering::SeqCst); + (command.query, 0_u8) + } else { + let continuation = std::str::from_utf8(request.get_ref().cmd.as_ref()) + .map_err(|_| Status::invalid_argument("invalid continuation"))?; + let mut parts = continuation.splitn(3, ':'); + if parts.next() != Some("poll") { + return Err(Status::invalid_argument("invalid continuation")); + } + let stage = parts + .next() + .and_then(|stage| stage.parse().ok()) + .ok_or_else(|| Status::invalid_argument("invalid continuation"))?; + if stage == 1 { + self.first_continuation_count.fetch_add(1, Ordering::SeqCst); + } + let query = parts + .next() + .ok_or_else(|| Status::invalid_argument("invalid continuation"))?; + (query.to_string(), stage) + }; + if (query == "SELECT slow" || query == "SELECT cancelling") && stage > 0 { + tokio::time::sleep(Duration::from_millis(250)).await; + } + if query == "SELECT no info" && stage == 1 { + tokio::time::sleep(Duration::from_millis(100)).await; + } + if query == "SELECT incremental" && stage == 1 { + tokio::time::sleep(Duration::from_millis(250)).await; + self.incremental_finished.store(true, Ordering::SeqCst); + } + if stage == 1 + && (query == "SELECT fail" + || (query == "SELECT retry" + && self.transient_poll_failures.fetch_add(1, Ordering::SeqCst) == 0)) + { + return Err(Status::unavailable("transient polling failure")); + } + let complete = if query == "SELECT no info" { + stage >= 2 + } else { + stage >= 1 + }; + + let first_ticket = if query == "SELECT incremental" { + format!("{query}:first") + } 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"), + ); + if query == "SELECT incremental" && stage > 0 { + info = info.with_endpoint( + FlightEndpoint::new() + .with_ticket(Ticket::new(format!("{query}:second"))) + .with_location("grpc://127.0.0.1:1"), + ); + } + if query != "SELECT empty" { + let schema = if query == "SELECT large message" { + self.large_result.schema_ref() + } else if query == "SELECT dictionary" { + self.dictionary_result.schema_ref() + } else { + self.result.schema_ref() + }; + info = info.try_with_schema(schema).unwrap(); + } + Ok(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, + })) + } + + async fn get_schema( + &self, + _request: Request, + ) -> std::result::Result, Status> { + Err(Status::unimplemented("get_schema")) + } + + async fn do_get( + &self, + request: Request, + ) -> std::result::Result::DoGetStream>, Status> { + self.do_get_count.fetch_add(1, Ordering::SeqCst); + let ticket = request.get_ref().ticket.as_ref(); + let empty = ticket == b"SELECT empty"; + let slow = ticket == b"SELECT slow get"; + let large = ticket == b"SELECT large message"; + let result = if large { + self.large_result.clone() + } else if ticket == b"SELECT dictionary" { + self.dictionary_result.clone() + } else { + self.result.clone() + }; + let schema = result.schema(); + let input = futures::stream::once(async move { + if slow { + tokio::time::sleep(Duration::from_millis(250)).await; + } + (!empty).then_some(Ok(result)) + }) + .filter_map(futures::future::ready); + let mut encoder = FlightDataEncoderBuilder::new().with_schema(schema); + if large { + encoder = encoder.with_max_flight_data_size(8 * 1024 * 1024); + } + let stream = encoder.build(input).map_err(Status::from); + Ok(Response::new(Box::pin(stream))) + } + + async fn do_put( + &self, + _request: Request>, + ) -> std::result::Result, Status> { + Err(Status::unimplemented("do_put")) + } + + async fn do_action( + &self, + request: Request, + ) -> std::result::Result, Status> { + if request.get_ref().r#type != "CancelFlightInfo" { + return Err(Status::invalid_argument("unexpected action")); + } + self.cancel_count.fetch_add(1, Ordering::SeqCst); + let cancel_request = CancelFlightInfoRequest::decode(request.get_ref().body.clone()) + .map_err(|_| Status::invalid_argument("invalid cancellation request"))?; + let query = cancel_request + .info + .and_then(|info| info.endpoint.into_iter().next()) + .and_then(|endpoint| endpoint.ticket) + .and_then(|ticket| String::from_utf8(ticket.ticket.to_vec()).ok()) + .ok_or_else(|| Status::invalid_argument("cancellation request had no ticket"))?; + if query == "SELECT cancel race" { + tokio::time::sleep(Duration::from_millis(250)).await; + } + if query == "SELECT cancel timeout" { + if self.cancel_timeout_count.fetch_add(1, Ordering::SeqCst) == 0 { + tokio::time::sleep(Duration::from_millis(250)).await; + } else { + return Err(Status::not_found("query cancellation completed")); + } + } + if query == "SELECT cancel missing" { + return Err(Status::not_found("query was not found")); + } + if query == "SELECT cancel denied" { + if self.cancel_denied_count.fetch_add(1, Ordering::SeqCst) == 0 { + return Err(Status::permission_denied("cancellation is not allowed")); + } + return Err(Status::not_found("query was not found")); + } + if query == "SELECT cancel unspecified" + && self.cancel_unspecified_count.fetch_add(1, Ordering::SeqCst) > 0 + { + return Err(Status::not_found("query cancellation completed")); + } + let status = if query == "SELECT cancel unspecified" { + CancelStatus::Unspecified + } else if query == "SELECT cancelling" { + if self + .cancelling_response_count + .fetch_add(1, Ordering::SeqCst) + == 0 + { + CancelStatus::Cancelling + } else { + return Err(Status::not_found("query cancellation completed")); + } + } else if query == "SELECT cancel race" { + CancelStatus::NotCancellable + } else { + CancelStatus::Cancelled + }; + let response = arrow_flight::Result { + body: CancelFlightInfoResult::new(status).encode_to_vec().into(), + }; + Ok(Response::new(Box::pin(futures::stream::iter([Ok( + response, + )])))) + } + + async fn list_actions( + &self, + _request: Request, + ) -> std::result::Result, Status> { + Err(Status::unimplemented("list_actions")) + } + + async fn do_exchange( + &self, + _request: Request>, + ) -> std::result::Result, Status> { + Err(Status::unimplemented("do_exchange")) + } +} + +#[tokio::test] +async fn submits_polls_fetches_cancels_and_reuses_client() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap(); + drop(listener); + + let service = TestSqlService::default(); + let query_count = service.query_count.clone(); + let do_get_count = service.do_get_count.clone(); + let cancel_count = service.cancel_count.clone(); + let incremental_finished = service.incremental_finished.clone(); + let first_continuation_count = service.first_continuation_count.clone(); + let headers = service.headers.clone(); + let expected = service.result.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_shutdown(address, async { + let _ = shutdown_rx.await; + }), + ); + let mut ready = false; + for _ in 0..100 { + if tokio::net::TcpStream::connect(address).await.is_ok() { + ready = true; + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + assert!(ready, "SQL test server did not start"); + + let mut client_config = ClientConfig::default(); + client_config.retry_config.read_retries = Some(1); + client_config.retry_config.backoff_factor = Some(0.0); + client_config.retry_config.backoff_jitter = Some(0.0); + client_config + .extra_headers + .insert("x-static-secret".to_string(), "static-secret".to_string()); + let header_provider = Arc::new(DelayedHeaderProvider::default()); + client_config.header_provider = Some(header_provider.clone()); + let client = SqlClient::new( + "analytics".to_string(), + Some("tenant/production".to_string()), + "test-key".to_string(), + None, + Some(format!("grpc://{address}")), + client_config, + ); + assert_eq!(client.initialized_client_count().await, 0); + assert!(!format!("{client:?}").contains("test-key")); + assert!(!format!("{client:?}").contains("static-secret")); + + let mut timeout_client_config = ClientConfig::default(); + timeout_client_config.timeout_config.timeout = Some(Duration::from_millis(50)); + let timeout_header_provider = Arc::new(DelayedHeaderProvider::default()); + timeout_client_config.header_provider = Some(timeout_header_provider.clone()); + let timeout_client = SqlClient::new( + "analytics".to_string(), + Some("tenant/production".to_string()), + "test-key".to_string(), + None, + Some(format!("grpc://{address}")), + timeout_client_config, + ); + timeout_header_provider + .delay_next + .store(true, Ordering::SeqCst); + assert_overall_timeout( + timeout_client + .submit("SELECT overall timeout", &["public".to_string()]) + .await, + "submission", + ); + let timeout_query = timeout_client + .submit("SELECT overall timeout", &["public".to_string()]) + .await + .unwrap(); + timeout_header_provider + .delay_next + .store(true, Ordering::SeqCst); + assert_overall_timeout( + timeout_client.describe(timeout_query.id()).await, + "description", + ); + timeout_header_provider + .delay_next + .store(true, Ordering::SeqCst); + assert_overall_timeout(collect_result(&timeout_query).await, "result"); + timeout_header_provider + .delay_next + .store(true, Ordering::SeqCst); + assert_overall_timeout(timeout_query.cancel().await, "cancellation"); + timeout_query.cancel().await.unwrap(); + + let pre_dispatch_timeout = timeout_client + .submit("SELECT cancel missing", &["public".to_string()]) + .await + .unwrap(); + timeout_header_provider + .delay_next + .store(true, Ordering::SeqCst); + assert_overall_timeout(pre_dispatch_timeout.cancel().await, "cancellation"); + assert!(pre_dispatch_timeout.cancel().await.is_err()); + assert_ne!( + pre_dispatch_timeout.describe().await.unwrap().status, + QueryStatus::Cancelled + ); + + let rejected_cancel = timeout_client + .submit("SELECT cancel denied", &["public".to_string()]) + .await + .unwrap(); + assert!(rejected_cancel.cancel().await.is_err()); + assert!(rejected_cancel.cancel().await.is_err()); + assert_ne!( + rejected_cancel.describe().await.unwrap().status, + QueryStatus::Cancelled + ); + + let unspecified_cancel = timeout_client + .submit("SELECT cancel unspecified", &["public".to_string()]) + .await + .unwrap(); + assert!(unspecified_cancel.cancel().await.is_err()); + assert!(unspecified_cancel.cancel().await.is_err()); + assert_ne!( + unspecified_cancel.describe().await.unwrap().status, + QueryStatus::Cancelled + ); + assert_eq!( + collect_result(&unspecified_cancel).await.unwrap(), + vec![expected.clone()] + ); + + let uncertain_cancel = timeout_client + .submit("SELECT cancel timeout", &["public".to_string()]) + .await + .unwrap(); + assert_overall_timeout(uncertain_cancel.cancel().await, "cancellation"); + assert!(uncertain_cancel.cancel().await.is_err()); + assert_ne!( + uncertain_cancel.describe().await.unwrap().status, + QueryStatus::Cancelled + ); + assert_eq!( + collect_result(&uncertain_cancel).await.unwrap(), + vec![expected.clone()] + ); + + let first = client + .submit("SELECT 'super-secret'", &["public".to_string()]) + .await + .unwrap(); + assert_eq!(first.id().get_version_num(), 7); + assert!(!first.id().to_string().contains("super-secret")); + header_provider.delay_next.store(true, Ordering::SeqCst); + let describe_started = Instant::now(); + let first_description = client.describe(first.id()).await.unwrap(); + assert!(describe_started.elapsed() >= Duration::from_millis(1_100)); + assert_eq!(first_description.status, QueryStatus::Finished); + assert_eq!(first_description.progress, Some(1.0)); + let first_result = collect_result(&first).await.unwrap(); + assert!(first.reader().await.is_err()); + + let incremental = client + .submit("SELECT incremental", &["public".to_string()]) + .await + .unwrap(); + let mut incremental_result = incremental.reader().await.unwrap(); + let first_incremental_batch = + tokio::time::timeout(Duration::from_millis(100), incremental_result.try_next()) + .await + .expect("the first partial result must arrive before query completion") + .unwrap() + .unwrap(); + assert_eq!(first_incremental_batch, expected); + assert!(!incremental_finished.load(Ordering::SeqCst)); + let remaining_incremental_batches = incremental_result.try_collect::>().await.unwrap(); + assert_eq!(remaining_incremental_batches, vec![expected.clone()]); + assert!(incremental_finished.load(Ordering::SeqCst)); + + let interrupted_result = Arc::new( + client + .submit("SELECT no info", &["public".to_string()]) + .await + .unwrap(), + ); + let continuation_count_before = first_continuation_count.load(Ordering::SeqCst); + let interrupted_result_task = { + let interrupted_result = interrupted_result.clone(); + tokio::spawn(async move { interrupted_result.reader().await }) + }; + tokio::time::timeout(Duration::from_millis(100), async { + while first_continuation_count.load(Ordering::SeqCst) == continuation_count_before { + tokio::task::yield_now().await; + } + }) + .await + .expect("result preparation must start polling"); + interrupted_result_task.abort(); + assert!( + interrupted_result_task + .await + .is_err_and(|error| error.is_cancelled()) + ); + assert_eq!( + collect_result(&interrupted_result).await.unwrap(), + vec![expected.clone()], + "cancelling result preparation must release the one-shot result claim", + ); + + let dropped_reader = client + .submit("SELECT slow", &["public".to_string()]) + .await + .unwrap(); + let tracked_dropped_reader = client.queries.get(dropped_reader.id()).unwrap(); + let continuation_count_before = first_continuation_count.load(Ordering::SeqCst); + let dropped_result_stream = dropped_reader.reader().await.unwrap(); + tokio::time::timeout(Duration::from_millis(100), async { + while first_continuation_count.load(Ordering::SeqCst) == continuation_count_before { + tokio::task::yield_now().await; + } + }) + .await + .expect("the result producer must start continuation polling"); + assert!(Arc::strong_count(&tracked_dropped_reader) >= 4); + drop(dropped_result_stream); + tokio::time::timeout(Duration::from_millis(100), async { + while Arc::strong_count(&tracked_dropped_reader) != 3 { + tokio::task::yield_now().await; + } + }) + .await + .expect("dropping a result reader must stop its producer"); + + let staged = client + .submit("SELECT no info", &["public".to_string()]) + .await + .unwrap(); + let staged_running = client.describe(staged.id()).await.unwrap(); + assert_eq!(staged_running.status, QueryStatus::Running); + let staged_finished = client.describe(staged.id()).await.unwrap(); + assert_eq!(staged_finished.status, QueryStatus::Finished); + + let empty = client + .submit("SELECT empty", &["public".to_string()]) + .await + .unwrap(); + let empty_result = empty.reader().await.unwrap(); + assert_eq!(empty_result.schema(), expected.schema()); + let empty_result = empty_result.try_collect::>().await.unwrap(); + + let large = client + .submit("SELECT large message", &["public".to_string()]) + .await + .unwrap(); + let large_result = collect_result(&large).await.unwrap(); + assert_eq!(large_result.len(), 1); + assert_eq!(large_result[0].num_rows(), 1); + assert_eq!( + large_result[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0) + .len(), + 5 * 1024 * 1024, + ); + + let dictionary = client + .submit("SELECT dictionary", &["public".to_string()]) + .await + .unwrap(); + let dictionary_result = collect_result(&dictionary).await.unwrap(); + assert_eq!(dictionary_result.len(), 1); + assert_eq!( + dictionary_result[0].schema().field(0).data_type(), + &DataType::Utf8, + ); + assert_eq!( + dictionary_result[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .value(0), + "dictionary value", + ); + + let cancelled = client + .submit( + "SELECT cancelled", + &["events".to_string(), "raw".to_string()], + ) + .await + .unwrap(); + cancelled.cancel().await.unwrap(); + assert_eq!( + cancelled.describe().await.unwrap().status, + QueryStatus::Cancelled + ); + assert!(matches!( + cancelled.reader().await, + Err(Error::JobCancelled { .. }) + )); + + let slow = Arc::new( + client + .submit("SELECT slow", &["public".to_string()]) + .await + .unwrap(), + ); + let result_task = { + let slow = slow.clone(); + tokio::spawn(async move { collect_result(&slow).await }) + }; + tokio::time::sleep(Duration::from_millis(25)).await; + tokio::time::timeout(Duration::from_millis(150), slow.cancel()) + .await + .expect("cancellation must not wait for result polling") + .unwrap(); + assert!(matches!( + tokio::time::timeout(Duration::from_millis(150), result_task) + .await + .expect("cancellation must wake result polling") + .unwrap(), + Err(Error::JobCancelled { .. }) + )); + let cancel_count_after_slow = cancel_count.load(Ordering::SeqCst); + slow.cancel().await.unwrap(); + assert_eq!( + cancel_count.load(Ordering::SeqCst), + cancel_count_after_slow, + "a confirmed cancellation must not be sent again", + ); + + let slow_get = Arc::new( + client + .submit("SELECT slow get", &["public".to_string()]) + .await + .unwrap(), + ); + let do_get_count_before_slow = do_get_count.load(Ordering::SeqCst); + let slow_get_result_task = { + let slow_get = slow_get.clone(); + tokio::spawn(async move { collect_result(&slow_get).await }) + }; + while do_get_count.load(Ordering::SeqCst) == do_get_count_before_slow { + tokio::task::yield_now().await; + } + slow_get.cancel().await.unwrap(); + assert_eq!( + slow_get.describe().await.unwrap().status, + QueryStatus::Cancelled + ); + assert!(matches!( + tokio::time::timeout(Duration::from_millis(150), slow_get_result_task) + .await + .expect("cancellation must wake result fetching") + .unwrap(), + Err(Error::JobCancelled { .. }) + )); + assert!(slow_get.reader().await.is_err()); + + let restored = Arc::new( + RemoteQuery::new( + Uuid::now_v7(), + client.inner.clone(), + vec!["public".to_string()], + PollInfo { + flight_descriptor: Some(FlightDescriptor::new_cmd("restored")), + ..Default::default() + }, + ) + .unwrap(), + ); + let mut restored_waiter = { + let restored = restored.clone(); + tokio::spawn(async move { restored.wait_for_cancellation().await }) + }; + tokio::task::yield_now().await; + restored.mark_cancelling(); + restored.restore_after_rejected_cancellation().await; + assert_eq!(restored.lifecycle(), QueryLifecycle::Running); + assert!( + tokio::time::timeout(Duration::from_millis(25), &mut restored_waiter) + .await + .is_err(), + "a stale cancellation notification must not complete the waiter", + ); + restored.mark_cancelling(); + tokio::time::timeout(Duration::from_millis(100), restored_waiter) + .await + .expect("a current cancellation must complete the waiter") + .unwrap(); + + let cancelling = Arc::new( + client + .submit("SELECT cancelling", &["public".to_string()]) + .await + .unwrap(), + ); + let cancelling_result_task = { + let cancelling = cancelling.clone(); + tokio::spawn(async move { collect_result(&cancelling).await }) + }; + tokio::time::sleep(Duration::from_millis(25)).await; + cancelling.cancel().await.unwrap(); + assert_eq!( + cancelling.describe().await.unwrap().status, + QueryStatus::Cancelling + ); + assert!(matches!( + tokio::time::timeout(Duration::from_millis(150), cancelling_result_task) + .await + .expect("an accepted cancellation must wake result polling") + .unwrap(), + Err(Error::JobCancelled { .. }) + )); + cancelling.cancel().await.unwrap(); + assert_eq!( + cancelling.describe().await.unwrap().status, + QueryStatus::Cancelled + ); + + let cancel_race = Arc::new( + client + .submit("SELECT cancel race", &["public".to_string()]) + .await + .unwrap(), + ); + let cancel_count_before_race = cancel_count.load(Ordering::SeqCst); + let cancel_race_task = { + let cancel_race = cancel_race.clone(); + tokio::spawn(async move { cancel_race.cancel().await }) + }; + while cancel_count.load(Ordering::SeqCst) == cancel_count_before_race { + tokio::task::yield_now().await; + } + let cancel_race_result = collect_result(&cancel_race).await.unwrap(); + tokio::time::timeout(Duration::from_millis(500), cancel_race_task) + .await + .expect("completed result must make in-flight cancellation a no-op") + .unwrap() + .unwrap(); + assert_eq!( + cancel_race.describe().await.unwrap().status, + QueryStatus::Finished + ); + assert_eq!(cancel_race_result, vec![expected.clone()]); + assert!(cancel_race.reader().await.is_err()); + + let no_info = Arc::new( + client + .submit("SELECT no info", &["public".to_string()]) + .await + .unwrap(), + ); + let continuation_count_before = first_continuation_count.load(Ordering::SeqCst); + let no_info_result_task = { + let no_info = no_info.clone(); + tokio::spawn(async move { collect_result(&no_info).await }) + }; + tokio::time::sleep(Duration::from_millis(10)).await; + tokio::time::timeout(Duration::from_secs(1), no_info.cancel()) + .await + .expect("cancellation should wait for cancellable query information") + .unwrap(); + assert!(matches!( + no_info_result_task.await.unwrap(), + Err(Error::JobCancelled { .. }) + )); + assert_eq!( + first_continuation_count.load(Ordering::SeqCst), + continuation_count_before + 1, + "result and cancel must share one continuation poll", + ); + + let retried = client + .submit("SELECT retry", &["public".to_string()]) + .await + .unwrap(); + assert_eq!( + collect_result(&retried).await.unwrap(), + vec![expected.clone()] + ); + + let failed = client + .submit("SELECT fail", &["public".to_string()]) + .await + .unwrap(); + assert!(collect_result(&failed).await.is_err()); + + let registry = QueryRegistry::new(); + for descriptor in ["active-one", "active-two"] { + let id = Uuid::now_v7(); + let query = Arc::new( + RemoteQuery::new( + id, + client.inner.clone(), + vec!["public".to_string()], + PollInfo { + flight_descriptor: Some(FlightDescriptor::new_cmd(descriptor)), + ..Default::default() + }, + ) + .unwrap(), + ); + registry.insert(id, query.clone()); + assert!(Arc::ptr_eq(®istry.get(id).unwrap(), &query)); + } + + let expired_id = Uuid::now_v7(); + let expired_query = Arc::new( + RemoteQuery::new( + expired_id, + client.inner.clone(), + vec!["public".to_string()], + PollInfo { + flight_descriptor: Some(FlightDescriptor::new_cmd("expired")), + expiration_time: Some(Default::default()), + ..Default::default() + }, + ) + .unwrap(), + ); + registry.insert(expired_id, expired_query); + assert!(registry.get(expired_id).is_none()); + + let stale_id = Uuid::now_v7(); + let stale_query = Arc::new( + RemoteQuery::new( + stale_id, + client.inner.clone(), + vec!["public".to_string()], + PollInfo { + flight_descriptor: Some(FlightDescriptor::new_cmd("stale")), + ..Default::default() + }, + ) + .unwrap(), + ); + *stale_query.last_accessed.lock().unwrap() = Instant::now() - ABANDONED_QUERY_RETENTION; + registry.insert(stale_id, stale_query.clone()); + drop(stale_query); + assert!(registry.get(stale_id).is_none()); + + assert_eq!(client.initialized_client_count().await, 1); + assert_eq!(query_count.load(Ordering::SeqCst), 21); + assert_eq!(do_get_count.load(Ordering::SeqCst), 17); + assert_eq!(cancel_count.load(Ordering::SeqCst), 15); + assert_eq!(first_result, vec![expected.clone()]); + assert!(empty_result.is_empty()); + assert!(client.describe(Uuid::nil()).await.is_err()); + { + let headers = headers.lock().unwrap(); + assert_eq!(headers[0].database, "analytics"); + assert_eq!(headers[0].namespace_path, "public"); + assert_eq!(headers[0].api_key, "test-key"); + assert_eq!(headers[0].database_prefix, "tenant/production"); + assert!( + headers + .iter() + .any(|header| header.namespace_path == "events$raw") + ); + assert!( + headers + .windows(2) + .all(|headers| headers[0].request_id != headers[1].request_id) + ); + } + let _ = shutdown_tx.send(()); + server.await.unwrap().unwrap(); +} + +#[test] +fn normalizes_supported_uris() { + assert_eq!( + normalize_sql_host_override("grpc://localhost").unwrap(), + SqlTarget { + uri: "http://localhost:10025".to_string(), + tls: false, + } + ); + assert_eq!( + normalize_sql_host_override("grpcs://example.com").unwrap(), + SqlTarget { + uri: "https://example.com:10026".to_string(), + tls: true, + } + ); + assert_eq!( + normalize_sql_host_override("grpc://[::1]:10025").unwrap(), + SqlTarget { + uri: "http://[::1]:10025".to_string(), + tls: false, + } + ); + assert_eq!( + normalize_sql_host_override("https://example.com:443").unwrap(), + SqlTarget { + uri: "https://example.com:443".to_string(), + tls: true, + } + ); +} + +#[test] +fn derives_plaintext_endpoint_from_host_override() { + assert_eq!( + resolve_sql_host_override(Some("http://localhost:10024"), None).unwrap(), + SqlTarget { + uri: "http://localhost:10025".to_string(), + tls: false, + } + ); + assert_eq!( + resolve_sql_host_override(Some("http://localhost:80"), None).unwrap(), + SqlTarget { + uri: "http://localhost:81".to_string(), + tls: false, + } + ); +} + +#[test] +fn rejects_unsafe_or_ambiguous_endpoints() { + assert!(normalize_sql_host_override("ftp://localhost").is_err()); + assert!(normalize_sql_host_override("grpc://user@localhost").is_err()); + assert!(normalize_sql_host_override("grpc://localhost/path").is_err()); + assert!(resolve_sql_host_override(Some("https://localhost"), None).is_err()); +} + +#[test] +fn validates_namespace_components() { + assert!(validate_namespace_path(&[]).is_ok()); + assert!(validate_namespace_path(&["events".into(), "raw".into()]).is_ok()); + assert!(validate_namespace_path(&["events$raw".into()]).is_err()); + assert!(validate_namespace_path(&["".into()]).is_err()); + assert!(validate_namespace_path(&["café".into()]).is_err()); +} + +#[test] +fn validates_metadata_with_header_map() { + let mut headers = HeaderMap::new(); + insert_header(&mut headers, "X-Custom-Header", "value").unwrap(); + assert_eq!(headers.get("x-custom-header").unwrap(), "value"); + assert!(insert_header(&mut headers, "bad header", "value").is_err()); + assert!(insert_header(&mut headers, "valid-header", "bad\nvalue").is_err()); +} diff --git a/rust/lancedb/src/sql.rs b/rust/lancedb/src/sql.rs new file mode 100644 index 000000000..7c040c51b --- /dev/null +++ b/rust/lancedb/src/sql.rs @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Handles to SQL queries running on a remote database. + +use std::{fmt, sync::Arc}; + +use async_trait::async_trait; +use chrono::{DateTime, Utc}; +use uuid::Uuid; + +use crate::{Result, arrow::SendableRecordBatchStream}; + +/// The externally visible lifecycle state of a submitted SQL query. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum QueryStatus { + /// The server is still executing the query. + Running, + /// The server has made the complete result available. + Finished, + /// The server accepted cancellation but has not confirmed it yet. + Cancelling, + /// The server confirmed cancellation. + Cancelled, +} + +impl fmt::Display for QueryStatus { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::Running => "running", + Self::Finished => "finished", + Self::Cancelling => "cancelling", + Self::Cancelled => "cancelled", + }) + } +} + +/// A point-in-time description of a submitted SQL query. +#[derive(Clone, Debug, PartialEq)] +pub struct QueryDescription { + /// The stable, connection-scoped identifier assigned when the query was submitted. + pub id: Uuid, + /// The server-visible lifecycle state. + pub status: QueryStatus, + /// Server-reported completion progress, when known. Values are in `[0.0, 1.0]`, + /// with `1.0` meaning complete. + pub progress: Option, + /// When the server may stop accepting this query's continuation token. + pub expires_at: Option>, +} + +#[async_trait] +pub(crate) trait QueryHandle: Send + Sync { + fn id(&self) -> Uuid; + async fn describe(&self) -> Result; + async fn reader(&self) -> Result; + async fn cancel(&self) -> Result<()>; +} + +/// A handle to a submitted SQL query. +/// +/// The handle can be inspected, opened as an Arrow reader, or cancelled. +/// Dropping it does not cancel the server-side query. +/// Identifier lookup is scoped to the connection that submitted the query and +/// is not a durable resume mechanism. +pub struct Query { + handle: Arc, +} + +impl std::fmt::Debug for Query { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("Query") + .field("id", &self.id()) + .finish() + } +} + +impl Query { + #[cfg(feature = "remote")] + pub(crate) fn new(handle: Arc) -> Self { + Self { handle } + } + + /// Return the stable, connection-scoped identifier for this query. + pub fn id(&self) -> Uuid { + self.handle.id() + } + + /// Get a point-in-time description of the query. + pub async fn describe(&self) -> Result { + self.handle.describe().await + } + + /// Wait for the initial result stream and return its Arrow record batches. + /// + /// The stream can begin yielding partial results before query execution is + /// complete. It continues polling for newly available result endpoints + /// until the query finishes and all endpoints have been consumed. + /// + /// Results are single-consumer. Calling this method more than once on the + /// same handle returns an error. + pub async fn reader(&self) -> Result { + self.handle.reader().await + } + + /// Request cancellation of the query. + pub async fn cancel(&self) -> Result<()> { + self.handle.cancel().await + } +} + +#[cfg(test)] +mod tests { + use super::QueryStatus; + + #[test] + fn query_status_display_is_stable() { + assert_eq!(QueryStatus::Running.to_string(), "running"); + assert_eq!(QueryStatus::Finished.to_string(), "finished"); + assert_eq!(QueryStatus::Cancelling.to_string(), "cancelling"); + assert_eq!(QueryStatus::Cancelled.to_string(), "cancelled"); + } +} From aab23eb39ee4e1a2d5898484f35a863d4c8e7036 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Thu, 3 Sep 2026 22:23:53 -0700 Subject: [PATCH 176/206] feat: support nullable named function outputs (#4123) Supports fully nullable named Function outputs while preserving the distinction between a valid all-null struct and a null/unassigned result. ## Concrete example This UDF contract is now valid: ```python @udf( input_schema=pa.schema([ pa.field("text", pa.string(), nullable=False), ]), output_schema=pa.schema([ pa.field( "embedding", pa.list_(pa.float32(), list_size=1024), nullable=True, ), pa.field("embedding_failure_reason", pa.string(), nullable=True), pa.field("embedding_failure_code", pa.int32(), nullable=True), ]), ) def embed(text): ... ``` A successful row can return: ```text embedding = [0.12, ...] embedding_failure_reason = NULL embedding_failure_code = NULL ``` If remote inference still fails after retries, it can return: ```text embedding = NULL embedding_failure_reason = "HTTP 429: rate limited" embedding_failure_code = 429 ``` An all-null but valid result struct is also assigned; it is not mistaken for unfinished work. ## Binding shapes - Mapping the result to one output column stores the `StructArray` directly, including its parent validity bitmap. - Flattening the result into top-level columns stores the parent validity in a reserved internal nullable Boolean assignment column that is not part of the UDF result mapping. - An outer null struct remains unassigned/skipped. A valid struct remains assigned regardless of which child fields are null. - Scalar Function outputs remain non-nullable. The contract is preserved through Python registration, Rust application planning, persisted `FunctionBinding` metadata, schema revalidation, and Enterprise execution. --- docs/src/python/python.md | 2 + python/python/lancedb/__init__.py | 1 + python/python/lancedb/functions.py | 28 ++- .../tests/test_first_class_function_slice2.py | 37 +++ rust/lancedb/src/function.rs | 18 +- rust/lancedb/src/table/computed_columns.rs | 217 ++++++++++++++++-- 6 files changed, 270 insertions(+), 33 deletions(-) diff --git a/docs/src/python/python.md b/docs/src/python/python.md index f2bc72b3a..b0d1bb426 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -147,6 +147,8 @@ listing a storage directory. ::: lancedb.functions.OutputMapping +::: lancedb.functions.AssignmentMapping + ::: lancedb.functions.FunctionBinding ::: lancedb.functions.RefreshColumnResult diff --git a/python/python/lancedb/__init__.py b/python/python/lancedb/__init__.py index af325a29b..cb9b57be3 100644 --- a/python/python/lancedb/__init__.py +++ b/python/python/lancedb/__init__.py @@ -26,6 +26,7 @@ from .sql import AsyncQuery as AsyncSqlQuery from .sql import Query as SqlQuery from .sql import QueryDescription from .functions import ( + AssignmentMapping as AssignmentMapping, FunctionArtifactRequest as FunctionArtifactRequest, FunctionApplication as FunctionApplication, FunctionBinding as FunctionBinding, diff --git a/python/python/lancedb/functions.py b/python/python/lancedb/functions.py index 2815f7f17..d3fa6da81 100644 --- a/python/python/lancedb/functions.py +++ b/python/python/lancedb/functions.py @@ -470,11 +470,7 @@ class InputBinding(_RemoteValue): class OutputMapping(_RemoteValue): - """One stable result-field mapping. - - Assignment state is outside the Slice 1 client contract. During the NULL - transition Lance exposes no public cell-flag identifier to persist here. - """ + """One stable result-field mapping.""" result_field: str output_name: str @@ -484,6 +480,13 @@ class OutputMapping(_RemoteValue): nullable: bool +class AssignmentMapping(_RemoteValue): + """Internal physical column preserving flattened struct validity.""" + + output_name: str + output_field_id: _Int32 + + class FunctionBinding(_RemoteValue): """Immutable Function binding persisted by the Enterprise table service.""" @@ -491,6 +494,7 @@ class FunctionBinding(_RemoteValue): function: FunctionVersionRef inputs: tuple[InputBinding, ...] outputs: tuple[OutputMapping, ...] + assignment: Optional[AssignmentMapping] = None input_schema: Optional[Mapping[str, Any]] = None output_schema: Optional[Mapping[str, Any]] = None @@ -911,8 +915,6 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp if not fields: raise ValueError("named-struct Function output must contain at least one field") - if any(field.nullable for field in fields): - raise ValueError("Function output fields must be non-nullable") for field in fields: _validate_exact_arrow_field(field) names = [field.name for field in fields] @@ -924,7 +926,7 @@ def _function_output(output: pa.DataType | pa.Field | pa.Schema) -> FunctionOutp FunctionResultField( name=field.name, arrow_type=_canonical_arrow_field(field), - nullable=False, + nullable=field.nullable, ) for field in fields ), @@ -1307,8 +1309,9 @@ def udf( Input and output signatures are inferred from supported annotations. For Arrow types annotations cannot express precisely, pass ``input_schema`` - and ``output_schema`` together. Nullable outputs are rejected because V1 - uses physical NULL to represent unassigned computed-column rows. + and ``output_schema`` together. Scalar outputs must be non-nullable. Every + named-struct field may be nullable; Enterprise preserves the struct's + validity when the result is expanded into sibling columns. Parameters ---------- @@ -1320,8 +1323,8 @@ def udf( Explicit input fields in the exact order of the callable parameters. Must be provided together with ``output_schema``. output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional - Explicit scalar or named-struct output. Must be non-nullable and be - provided together with ``input_schema``. + Explicit scalar or named-struct output. Scalar outputs must be + non-nullable. Must be provided together with ``input_schema``. pip : sequence of str, optional Pip requirements for the remote environment. conda : sequence of str, optional @@ -1387,6 +1390,7 @@ def udf( __all__ = [ + "AssignmentMapping", "ApplicationInput", "FunctionApplication", "FunctionArtifact", diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index d8a9aeebf..4816019d6 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -850,6 +850,43 @@ def test_named_struct_function_can_include_a_blob_result_field(): ] +def test_named_struct_function_preserves_nullable_result_fields(): + @udf( + input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), + output_schema=pa.schema( + [ + pa.field("result", pa.int64(), nullable=True), + pa.field("failure_code", pa.int32(), nullable=False), + ] + ), + ) + def nullable_result(value): + return {"result": value, "failure_code": 0} + + output = nullable_result.registration_request.signature.output + assert [(field.name, field.nullable) for field in output.fields] == [ + ("result", True), + ("failure_code", False), + ] + + @udf( + input_schema=pa.schema([pa.field("value", pa.int64(), nullable=False)]), + output_schema=pa.schema( + [ + pa.field("result", pa.int64(), nullable=True), + pa.field("failure_code", pa.int32(), nullable=True), + ] + ), + ) + def all_nullable(value): + return {"result": value, "failure_code": None} + + assert all( + field.nullable + for field in all_nullable.registration_request.signature.output.fields + ) + + def test_metadata_marked_blob_field_uses_the_semantic_type(): extension = lancedb.blob("image", nullable=False).type storage = ( diff --git a/rust/lancedb/src/function.rs b/rust/lancedb/src/function.rs index 79693c031..e67d763ac 100644 --- a/rust/lancedb/src/function.rs +++ b/rust/lancedb/src/function.rs @@ -582,8 +582,8 @@ pub struct InputBinding { /// Ordered result-field to table-field mapping for a Function binding. /// -/// Assignment state is not part of the Slice 1 client contract. During the -/// NULL transition there is no public Lance cell-flag identifier to persist. +/// `nullable` describes the logical Function result. Physical computed-column +/// fields remain nullable while unassigned. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct OutputMapping { pub result_field: String, @@ -594,6 +594,14 @@ pub struct OutputMapping { pub nullable: bool, } +/// Internal physical column preserving the parent validity of a flattened +/// named-struct result. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct AssignmentMapping { + pub output_name: String, + pub output_field_id: i32, +} + /// Immutable Function binding persisted by the Enterprise table service. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FunctionBinding { @@ -601,6 +609,8 @@ pub struct FunctionBinding { function: FunctionVersionRef, inputs: Vec, outputs: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + assignment: Option, /// Exact Arrow schema presented to the Function, encoded with the Lance /// Namespace Arrow JSON representation. #[serde(default, skip_serializing_if = "Option::is_none")] @@ -627,6 +637,10 @@ impl FunctionBinding { &self.outputs } + pub fn assignment(&self) -> Option<&AssignmentMapping> { + self.assignment.as_ref() + } + pub fn input_schema(&self) -> Option<&Value> { self.input_schema.as_ref() } diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 085876a81..0fcc5485d 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -60,6 +60,10 @@ pub const FUNCTION_BINDING_ID_META_KEY: &str = "computed_column.function.binding /// Field metadata key holding this sibling's ordered Function output ordinal. pub const FUNCTION_OUTPUT_ORDINAL_META_KEY: &str = "computed_column.function.output_ordinal"; +/// Reserved Function output ordinal for an internal flattened-result +/// assignment column. +pub const FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL: u32 = u32::MAX; + /// Schema metadata key holding all immutable Function bindings. pub const FUNCTION_BINDINGS_META_KEY: &str = "lancedb::function_bindings"; @@ -312,22 +316,29 @@ pub(crate) fn ensure_supported_function_metadata(schema: &ArrowSchema) -> Result binding_id ), })?; - let output = binding - .outputs() - .get(output_ordinal as usize) - .ok_or_else(|| Error::InvalidInput { - message: format!( - "Function output '{}' has invalid ordinal {}", - field.name(), - output_ordinal - ), - })?; - if output.output_name != field.name().as_str() { + let destination = if output_ordinal == FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL { + binding + .assignment() + .map(|assignment| assignment.output_name.as_str()) + } else { + binding + .outputs() + .get(output_ordinal as usize) + .map(|output| output.output_name.as_str()) + } + .ok_or_else(|| Error::InvalidInput { + message: format!( + "Function output '{}' has invalid ordinal {}", + field.name(), + output_ordinal + ), + })?; + if destination != field.name().as_str() { return Err(Error::InvalidInput { message: format!( "Function output '{}' does not match binding destination '{}'", field.name(), - output.output_name + destination ), }); } @@ -498,6 +509,7 @@ fn ensure_known_binding_shape(value: &Value) -> Result<()> { "function", "inputs", "outputs", + "assignment", "input_schema", "output_schema", ], @@ -546,6 +558,13 @@ fn ensure_known_binding_shape(value: &Value) -> Result<()> { "output mapping", )?; } + if let Some(assignment) = object.get("assignment") { + reject_unknown_object_fields( + assignment, + &["output_name", "output_field_id"], + "assignment mapping", + )?; + } Ok(()) } @@ -865,7 +884,7 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding output.output_name )) })?; - if field.name() != &output.output_name || !field.is_nullable() || output.nullable { + if field.name() != &output.output_name || !field.is_nullable() { return Err(invalid_function(format!( "Function output '{}' no longer matches binding '{}'", output.output_name, @@ -926,6 +945,61 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding output_fields.push(json.fields.into_iter().next().unwrap()); } } + if let Some(assignment) = binding.assignment() { + if binding + .outputs() + .iter() + .any(|output| output.result_field == WHOLE_RESULT_FIELD) + { + return Err(invalid_function(format!( + "Function binding '{}' cannot attach an assignment column to a whole result", + binding.binding_id() + ))); + } + let field = schema + .field_with_name(&assignment.output_name) + .map_err(|_| { + invalid_function(format!( + "Function binding '{}' assignment column '{}' is missing", + binding.binding_id(), + assignment.output_name + )) + })?; + let metadata = field.metadata(); + if field.data_type() != &DataType::Boolean + || !field.is_nullable() + || metadata.get(COMPUTED_COLUMN_META_KEY).map(String::as_str) != Some("true") + || metadata.get(KIND_META_KEY).map(String::as_str) != Some(FUNCTION_KIND) + || metadata + .get(FUNCTION_BINDING_ID_META_KEY) + .map(String::as_str) + != Some(binding.binding_id()) + || metadata + .get(FUNCTION_OUTPUT_ORDINAL_META_KEY) + .and_then(|value| value.parse::().ok()) + != Some(FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL) + { + return Err(invalid_function(format!( + "Function binding '{}' assignment column no longer matches its declaration", + binding.binding_id() + ))); + } + let json = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ + ArrowField::new(assignment.output_name.clone(), DataType::Boolean, true), + ])) + .map_err(|e| invalid_function(format!("invalid Function assignment schema: {e}")))?; + output_fields.push(json.fields.into_iter().next().unwrap()); + } else if binding.outputs().iter().all(|output| output.nullable) + && binding + .outputs() + .iter() + .all(|output| output.result_field != WHOLE_RESULT_FIELD) + { + return Err(invalid_function(format!( + "Function binding '{}' has no flattened-result assignment column", + binding.binding_id() + ))); + } let output_schema = JsonArrowSchema::new(output_fields); let output_schema = serde_json::to_value(output_schema).map_err(|e| { invalid_function(format!( @@ -1081,11 +1155,6 @@ pub(crate) fn plan_function_application( "named-struct Function result field names must be unique", )); } - if output.fields.iter().any(|field| field.nullable) { - return Err(invalid_function( - "Function logical outputs must be non-nullable during NULL assignment", - )); - } let unknown = application .columns() .keys() @@ -1107,7 +1176,9 @@ pub(crate) fn plan_function_application( let fields = output .fields .iter() - .map(|field| function_output_field(&field.name, false, &field.arrow_type)) + .map(|field| { + function_output_field(&field.name, field.nullable, &field.arrow_type) + }) .collect::>>()?; let mut data_type = JsonArrowDataType::new("struct".to_string()); data_type.fields = Some(fields); @@ -2858,6 +2929,17 @@ mod tests { &inputs, )); } + if let Some(assignment) = binding.assignment() { + fields.push( + ArrowField::new(&assignment.output_name, DataType::Boolean, true).with_metadata( + function_computed_column_metadata( + binding.binding_id(), + FUNCTION_ASSIGNMENT_OUTPUT_ORDINAL, + &inputs, + ), + ), + ); + } ArrowSchema::new(fields) } @@ -2875,6 +2957,74 @@ mod tests { .unwrap(); } + #[test] + fn test_binding_preserves_all_nullable_outputs_with_an_assignment_column() { + let mut raw_binding: Value = serde_json::from_str(include_str!( + "../../tests/fixtures/first_class_functions/v1/remote_function_binding.json" + )) + .unwrap(); + raw_binding["outputs"][0]["nullable"] = Value::Bool(true); + raw_binding["outputs"][1]["nullable"] = Value::Bool(true); + let without_assignment: FunctionBinding = + serde_json::from_value(raw_binding.clone()).unwrap(); + let error = ensure_binding_matches_schema( + &valid_function_binding_schema(true, true, &without_assignment), + &without_assignment, + ) + .unwrap_err(); + assert!( + error + .to_string() + .contains("flattened-result assignment column") + ); + + raw_binding["assignment"] = serde_json::json!({ + "output_name": "__function_assignment_fb_01K3TEXT", + "output_field_id": -1, + }); + raw_binding["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_binding).unwrap(); + ensure_binding_matches_schema( + &valid_function_binding_schema(true, true, &binding), + &binding, + ) + .unwrap(); + + let schema = ArrowSchema::new_with_metadata( + valid_function_binding_schema(true, true, &binding) + .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(); + + let mut metadata: Value = + serde_json::from_str(schema.metadata().get(FUNCTION_BINDINGS_META_KEY).unwrap()) + .unwrap(); + metadata["bindings"][0]["assignment"]["future"] = Value::Bool(true); + let future_schema = ArrowSchema::new_with_metadata( + schema.fields().to_vec(), + HashMap::from([( + FUNCTION_BINDINGS_META_KEY.to_string(), + serde_json::to_string(&metadata).unwrap(), + )]), + ); + assert!(matches!( + ensure_supported_function_metadata(&future_schema), + Err(Error::NotSupported { .. }) + )); + } + #[test] fn test_nullable_function_input_cannot_bind_to_non_nullable_parameter() { let mut raw_binding: Value = serde_json::from_str(include_str!( @@ -3094,6 +3244,35 @@ mod tests { ); } + #[test] + fn test_named_struct_plan_preserves_nullable_result_fields() { + let mut value = serde_json::to_value(named_struct_application("{}")).unwrap(); + value["output"]["fields"][0]["nullable"] = Value::Bool(true); + value["output"]["fields"][1]["nullable"] = Value::Bool(true); + let application = FunctionApplication::from_json(&value.to_string()).unwrap(); + + let expanded = + plan_function_application(&function_input_schema(), &application, None).unwrap(); + assert!( + expanded + .output_schema + .fields + .iter() + .all(|field| field.nullable) + ); + + let whole = + plan_function_application(&function_input_schema(), &application, Some("features")) + .unwrap(); + let fields = whole.output_schema.fields[0] + .r#type + .fields + .as_ref() + .unwrap(); + assert!(fields[0].nullable); + assert!(fields[1].nullable); + } + #[test] fn test_blob_function_plans_semantic_input_and_scalar_output() { let schema = ArrowSchema::new(vec![crate::blob("image", false)]); From 8c9c5c5a5f98b789d1f7a6a0943c37e6e144d14d Mon Sep 17 00:00:00 2001 From: Drew Date: Thu, 3 Sep 2026 23:52:15 -0700 Subject: [PATCH 177/206] fix: stop enabling stable row ids on blob table create (#4126) This PR stops blob table create from implicitly enabling stable row ids. A blob schema still selects Lance file format 2.2, but row id behavior stays with the table config. Compact then fetch with a `_rowid` captured before compaction is still not supported on a default table. That needs `take` to remap row addresses through blob reuse rather than making stable row ids a blob-table default. BREAKING CHANGE: blob create no longer enables stable row ids. A blob schemastill selects Lance file format 2.2. Fetch uses `_rowid` on HEAD. Held ids survive compact only when the table has stable row ids. ## Testing * `cargo fmt --all` * `ruff format .` * `ruff check .` * `cargo clippy --quiet --features remote --tests --examples -p lancedb` * `cargo test --quiet --features remote -p lancedb --test blob_integration` * `python/.venv/bin/pytest python/python/tests/test_blob.py -q` --- python/python/lancedb/table.py | 9 ++ python/python/tests/test_blob.py | 57 +++++++++++- rust/lancedb/src/blob.rs | 56 +++++++++++- rust/lancedb/src/database/listing.rs | 3 +- rust/lancedb/src/database/namespace.rs | 3 +- rust/lancedb/src/table.rs | 9 ++ rust/lancedb/tests/blob_integration.rs | 115 +++++++++++++++++++------ 7 files changed, 217 insertions(+), 35 deletions(-) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index e397272fc..127ad3722 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1793,6 +1793,9 @@ class Table(ABC): The result has the same length and order as ``row_ids``. Null blobs produce null slots; valid empty blobs produce ``b""``. + ``_rowid`` values stay valid after compaction when the table has stable + row ids. + Convenience for small payloads. For large values use :meth:`fetch_blob_files`. """ @@ -1810,6 +1813,9 @@ class Table(ABC): The result has the same length and order as ``requests``; null blobs produce null slots and empty ranges on non-null blobs produce ``b""``. + ``_rowid`` values stay valid after compaction when the table has stable + row ids. + Row IDs can be obtained from a query with ``with_row_id(True)``. This API is currently supported only by local tables. """ @@ -1825,6 +1831,9 @@ class Table(ABC): ``_rowid`` or a ``_lance_row_id`` field on the blob descriptor. Null rows are ``None``. Remote tables require LanceDB Cloud server 0.5.0 or newer. + + ``_rowid`` values stay valid after compaction when the table has stable + row ids. """ @abstractmethod diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index c9694277c..1f158fb49 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -66,6 +66,25 @@ def _row_ids_by_id(table): return dict(zip(hits["id"].to_pylist(), hits["_rowid"].to_pylist())) +def _assert_missing_blob_row_ids(exc_info): + message = str(exc_info.value) + assert "row ids" in message + assert "rowaddr" not in message + assert "fragment" not in message + + +def _assert_fetch_apis_reject_missing_row_ids(table, row_ids): + with pytest.raises(ValueError) as exc_info: + table.fetch_blobs("image", row_ids) + _assert_missing_blob_row_ids(exc_info) + with pytest.raises(ValueError) as exc_info: + table.fetch_blob_files("image", row_ids) + _assert_missing_blob_row_ids(exc_info) + with pytest.raises(ValueError) as exc_info: + table.fetch_blob_ranges("image", [(row_id, 0, 1) for row_id in row_ids]) + _assert_missing_blob_row_ids(exc_info) + + def test_blob_factory_declares_v2_field(): field = lancedb.blob("image") assert isinstance(field.type, pa.ExtensionType) @@ -691,6 +710,25 @@ def test_fetch_blobs_accepts_query_result(): assert {blobs[i].as_py() for i in range(len(blobs))} == {b"gamma"} +def test_fetch_blobs_after_compact_with_stable_row_ids(tmp_path): + db = lancedb.connect( + tmp_path, storage_options={"new_table_enable_stable_row_ids": "true"} + ) + schema = pa.schema([pa.field("id", pa.int64()), lancedb.blob("image")]) + table = db.create_table("t", schema=schema) + table.add([{"id": 1, "image": b"frag-one"}]) + table.add([{"id": 2, "image": b"frag-two"}]) + by_id = _row_ids_by_id(table) + ids = [by_id[1], by_id[2]] + + table.optimize() + + blobs = table.fetch_blobs("image", ids) + assert blobs.to_pylist() == [b"frag-one", b"frag-two"] + ranges = table.fetch_blob_ranges("image", [(ids[0], 5, 3), (ids[1], 5, 3)]) + assert ranges.to_pylist() == [b"one", b"two"] + + def test_fetch_blobs_preserves_null_and_empty_values(): table = _blob_table( "nulls", @@ -739,8 +777,25 @@ def test_fetch_blob_ranges_validates_requests(): with pytest.raises(ValueError, match="offset \\+ length overflowed"): table.fetch_blob_ranges("image", [(row_id, 2**64 - 1, 1)]) - with pytest.raises(ValueError, match="row IDs"): + with pytest.raises(ValueError) as exc_info: table.fetch_blob_ranges("image", [(2**64 - 1, 0, 1)]) + _assert_missing_blob_row_ids(exc_info) + + +def test_fetch_blob_apis_reject_missing_fragment_row_addr(): + table = _blob_table("missing_frag", [{"id": 1, "image": b"x"}]) + live = _row_ids_by_id(table)[1] + _assert_fetch_apis_reject_missing_row_ids(table, [1 << 32, live]) + + +def test_fetch_blob_apis_reject_deleted_row_ids(): + table = _blob_table( + "deleted_rows", + [{"id": 1, "image": b"one"}, {"id": 2, "image": b"two"}], + ) + by_id = _row_ids_by_id(table) + table.delete("id = 2") + _assert_fetch_apis_reject_missing_row_ids(table, [by_id[2], by_id[1]]) def test_fetch_blob_ranges_empty_requests_returns_empty_array(): diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index d59123ec3..6a0d968b0 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -7,7 +7,9 @@ //! raw `Binary` / `LargeBinary` into the blob struct layout. Queries return //! small descriptors, not bytes. //! -//! Blob tables require Lance file format >= 2.2 and stable row ids at create. +//! Blob tables require Lance file format >= 2.2. `_rowid` values stay valid +//! after compaction when the table has stable row ids. Overwrite is a new +//! create and does not keep the previous table's stable row id setting. use std::ops::Range; use std::sync::Arc; @@ -324,6 +326,7 @@ pub(crate) fn blob_column_names(schema: &Schema) -> Vec { } /// Bumps storage format to at least [`LanceFileVersion::V2_2`] for blob schemas. +/// Leaves `enable_stable_row_ids` unchanged. pub(crate) fn ensure_blob_storage_version(schema: &Schema, params: &mut WriteParams) { if !has_blob_columns(schema) { return; @@ -385,6 +388,30 @@ fn ensure_all_row_ids_resolved(column: &str, requested: usize, resolved: usize) } } +/// Lance take reports a missing physical row address as NotSupported or InvalidInput. +fn map_blob_take_error(column: &str, requested: usize, err: lance::Error) -> Error { + let missing_row_addr = match &err { + lance::Error::NotSupported { source, .. } => { + source.to_string().contains("must not target deleted rows") + } + lance::Error::InvalidInput { source, .. } => source + .to_string() + .contains("belongs to non-existent fragment"), + _ => false, + }; + + if missing_row_addr { + Error::InvalidInput { + message: format!( + "blob read for column '{column}' requested {requested} row ids but some \ + do not exist in the table; pass row ids collected from this table" + ), + } + } else { + err.into() + } +} + /// Materialize blob-local ranges (same length and order as `requests`, nulls preserved). pub(crate) async fn take_blob_ranges_aligned( dataset: &Arc, @@ -405,7 +432,8 @@ pub(crate) async fn take_blob_ranges_aligned( .with_row_ids(lance_requests) .preserve_order(true) .execute() - .await?; + .await + .map_err(|err| map_blob_take_error(column, requests.len(), err))?; ensure_all_row_ids_resolved(column, requests.len(), payloads.len())?; let mut builder = LargeBinaryBuilder::new(); @@ -434,7 +462,8 @@ pub(crate) async fn take_blobs_aligned( .with_row_ids(row_ids.to_vec()) .preserve_order(true) .execute() - .await?; + .await + .map_err(|err| map_blob_take_error(column, row_ids.len(), err))?; ensure_all_row_ids_resolved(column, row_ids.len(), payloads.len())?; let mut builder = LargeBinaryBuilder::new(); @@ -458,7 +487,10 @@ pub(crate) async fn take_blob_files_aligned( return Ok(Vec::new()); } - let handles = dataset.take_blobs(row_ids, column).await?; + let handles = dataset + .take_blobs(row_ids, column) + .await + .map_err(|err| map_blob_take_error(column, row_ids.len(), err))?; ensure_all_row_ids_resolved(column, row_ids.len(), handles.len())?; Ok(handles .into_iter() @@ -504,6 +536,21 @@ mod tests { params.data_storage_version.unwrap().resolve(), ConcreteFileVersion::V2_2 ); + assert!(!params.enable_stable_row_ids); + } + + #[test] + fn storage_version_leaves_stable_row_ids_enabled() { + let mut params = WriteParams { + enable_stable_row_ids: true, + ..Default::default() + }; + ensure_blob_storage_version(&blob_schema(), &mut params); + assert!(params.enable_stable_row_ids); + assert_eq!( + params.data_storage_version.unwrap().resolve(), + ConcreteFileVersion::V2_2 + ); } #[test] @@ -576,5 +623,6 @@ mod tests { let mut params = WriteParams::default(); ensure_blob_storage_version(&schema, &mut params); assert!(params.data_storage_version.is_none()); + assert!(!params.enable_stable_row_ids); } } diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index c22b73dd7..c6d834c5a 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -18,7 +18,7 @@ use lance_table::io::commit::commit_handler_from_url; use object_store::local::LocalFileSystem; use snafu::ResultExt; -use crate::blob::{ensure_blob_storage_version, has_blob_columns}; +use crate::blob::ensure_blob_storage_version; use crate::connection::ConnectRequest; use crate::database::ReadConsistency; use crate::database::namespace::LanceNamespaceDatabase; @@ -827,7 +827,6 @@ impl ListingDatabase { if let Some(enable_stable_row_ids) = overrides .enable_stable_row_ids .or(self.new_table_config.enable_stable_row_ids) - .or(has_blob_columns(&data_schema).then_some(true)) { write_params.enable_stable_row_ids = enable_stable_row_ids; } diff --git a/rust/lancedb/src/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index 5ca720e85..78641a8b3 100644 --- a/rust/lancedb/src/database/namespace.rs +++ b/rust/lancedb/src/database/namespace.rs @@ -23,7 +23,7 @@ use lance_namespace_impls::ConnectBuilder; use lance_table::io::commit::CommitHandler; use lance_table::io::commit::external_manifest::ExternalManifestCommitHandler; -use crate::blob::{ensure_blob_storage_version, has_blob_columns}; +use crate::blob::ensure_blob_storage_version; use crate::connection::NamespaceClientPushdownOperation; use crate::database::ReadConsistency; use crate::database::listing::{NewTableConfig, take_request_creation_overrides}; @@ -217,7 +217,6 @@ impl LanceNamespaceDatabase { if let Some(enable_stable_row_ids) = overrides .enable_stable_row_ids .or(self.new_table_config.enable_stable_row_ids) - .or(has_blob_columns(data_schema.as_ref()).then_some(true)) { params.enable_stable_row_ids = enable_stable_row_ids; } diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 33b6ea8ce..44e12d8ad 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1192,6 +1192,9 @@ impl Table { /// valid empty blobs contain empty byte strings. Prefer /// [`Self::fetch_blob_files`] for large selections. /// + /// `_rowid` values stay valid after compaction when the table has stable + /// row ids. + /// /// ``` /// use arrow_array::UInt64Array; /// use futures::TryStreamExt; @@ -1233,6 +1236,9 @@ impl Table { /// the requests. Null blobs produce null output slots; empty ranges on /// non-null blobs produce empty byte strings. /// + /// `_rowid` values stay valid after compaction when the table has stable + /// row ids. + /// /// ``` /// use lancedb::blob::BlobRangeRequest; /// @@ -1271,6 +1277,9 @@ impl Table { /// Same length and order as `row_ids`. Null rows are `None`. Bytes are not /// read from disk until a call to [`BlobFile::read`]. /// + /// `_rowid` values stay valid after compaction when the table has stable + /// row ids. + /// /// ``` /// # use lancedb::Table; /// # async fn lazy_read(table: &Table, row_ids: &[u64]) -> Result<(), Box> { diff --git a/rust/lancedb/tests/blob_integration.rs b/rust/lancedb/tests/blob_integration.rs index 7b709b645..b884a48f7 100644 --- a/rust/lancedb/tests/blob_integration.rs +++ b/rust/lancedb/tests/blob_integration.rs @@ -111,7 +111,7 @@ async fn query_image_struct(table: &Table) -> StructArray { } #[tokio::test] -async fn declaring_blob_column_bumps_format_and_enables_stable_row_ids() -> Result<()> { +async fn declaring_blob_column_uses_v2_2_and_default_row_ids() -> Result<()> { let tmp = tempdir().unwrap(); let db = connect(tmp.path().to_str().unwrap()).execute().await?; let table = db @@ -120,12 +120,12 @@ async fn declaring_blob_column_bumps_format_and_enables_stable_row_ids() -> Resu .await?; assert!(supports_blob_v2(storage_format_version(&table).await)); - assert!(uses_stable_row_ids(&table).await); + assert!(!uses_stable_row_ids(&table).await); Ok(()) } #[tokio::test] -async fn explicit_stable_row_id_setting_wins_over_blob_default() -> Result<()> { +async fn blob_create_honors_disabled_stable_row_ids() -> Result<()> { let tmp = tempdir().unwrap(); let db = connect(tmp.path().to_str().unwrap()).execute().await?; let table = db @@ -179,7 +179,7 @@ async fn creating_with_blob_data_bumps_format() -> Result<()> { let table = db.create_table("t", batch).execute().await?; assert!(supports_blob_v2(storage_format_version(&table).await)); - assert!(uses_stable_row_ids(&table).await); + assert!(!uses_stable_row_ids(&table).await); assert_eq!(table.count_rows(None).await?, 1); Ok(()) } @@ -277,7 +277,7 @@ async fn add_rejects_uncoercible_blob_input() -> Result<()> { } #[tokio::test] -async fn connection_level_stable_row_id_setting_wins_over_blob_default() -> Result<()> { +async fn connection_disables_stable_row_ids_on_blob_create() -> Result<()> { let tmp = tempdir().unwrap(); let db = connect(tmp.path().to_str().unwrap()) .storage_option(OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS, "false") @@ -294,7 +294,7 @@ async fn connection_level_stable_row_id_setting_wins_over_blob_default() -> Resu } #[tokio::test] -async fn namespace_create_applies_blob_defaults() -> Result<()> { +async fn namespace_blob_create_uses_v2_2_and_default_row_ids() -> Result<()> { let tmp = tempdir().unwrap(); let mut properties = std::collections::HashMap::new(); properties.insert("root".to_string(), tmp.path().to_str().unwrap().to_string()); @@ -304,6 +304,23 @@ async fn namespace_create_applies_blob_defaults() -> Result<()> { .execute() .await?; + assert!(supports_blob_v2(storage_format_version(&table).await)); + assert!(!uses_stable_row_ids(&table).await); + Ok(()) +} + +#[tokio::test] +async fn namespace_create_honors_enabled_stable_row_ids() -> Result<()> { + let tmp = tempdir().unwrap(); + let mut properties = std::collections::HashMap::new(); + properties.insert("root".to_string(), tmp.path().to_str().unwrap().to_string()); + let db = connect_namespace("dir", properties).execute().await?; + let table = db + .create_empty_table("t", blob_table_schema()) + .storage_option(OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS, "true") + .execute() + .await?; + assert!(supports_blob_v2(storage_format_version(&table).await)); assert!(uses_stable_row_ids(&table).await); Ok(()) @@ -430,6 +447,35 @@ async fn collect_id_rowid(table: &Table) -> Result> { .collect()) } +fn assert_missing_blob_row_ids(err: &Error) { + assert!(matches!(err, Error::InvalidInput { .. }), "got {err:?}"); + let message = err.to_string(); + assert!(message.contains("row ids"), "{message}"); + assert!(!message.contains("rowaddr"), "{message}"); + assert!(!message.contains("fragment"), "{message}"); +} + +async fn assert_fetch_apis_reject_missing_row_ids(table: &Table, row_ids: &[u64]) -> Result<()> { + let err = table.fetch_blobs("image", row_ids).await.unwrap_err(); + assert_missing_blob_row_ids(&err); + + let err = table.fetch_blob_files("image", row_ids).await.unwrap_err(); + assert_missing_blob_row_ids(&err); + + let err = table + .fetch_blob_ranges( + "image", + row_ids + .iter() + .copied() + .map(|row_id| BlobRangeRequest::new(row_id, 0, 1)), + ) + .await + .unwrap_err(); + assert_missing_blob_row_ids(&err); + Ok(()) +} + #[tokio::test] async fn fetch_blobs_round_trips_bytes() -> Result<()> { let tmp = tempdir().unwrap(); @@ -482,7 +528,7 @@ async fn fetch_blobs_round_trips_nested_blob_column() -> Result<()> { let table = db.create_table("t", batch).execute().await?; assert!(supports_blob_v2(storage_format_version(&table).await)); - assert!(uses_stable_row_ids(&table).await); + assert!(!uses_stable_row_ids(&table).await); let ids = collect_row_ids(&table).await?; let bytes = table.fetch_blobs("info.blob", &ids).await?; @@ -656,8 +702,7 @@ async fn fetch_blob_ranges_validates_requests() -> Result<()> { .fetch_blob_ranges("image", [BlobRangeRequest::new(u64::MAX, 0, 1)]) .await .unwrap_err(); - assert!(matches!(&err, Error::InvalidInput { .. }), "got {err:?}"); - assert!(err.to_string().contains("row IDs")); + assert_missing_blob_row_ids(&err); Ok(()) } @@ -690,7 +735,21 @@ async fn fetch_blobs_out_of_range_id_errors_without_panic() -> Result<()> { let table = create_inline_blob_table(&db, "t", &[1], &[Some(b"x".as_slice())]).await?; let err = table.fetch_blobs("image", &[u64::MAX]).await.unwrap_err(); - assert!(err.to_string().contains("row IDs")); + assert_missing_blob_row_ids(&err); + Ok(()) +} + +#[tokio::test] +async fn fetch_blob_files_rejects_missing_fragment_row_addr() -> Result<()> { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()).execute().await?; + let table = create_inline_blob_table(&db, "t", &[1], &[Some(b"x".as_slice())]).await?; + + let err = table + .fetch_blob_files("image", &[1u64 << 32]) + .await + .unwrap_err(); + assert_missing_blob_row_ids(&err); Ok(()) } @@ -700,24 +759,25 @@ async fn fetch_blob_apis_reject_mixed_valid_and_missing_row_ids() -> Result<()> let db = connect(tmp.path().to_str().unwrap()).execute().await?; let table = create_inline_blob_table(&db, "t", &[1], &[Some(b"x".as_slice())]).await?; let row_id = collect_row_ids(&table).await?[0]; - let row_ids = [u64::MAX, row_id]; + let missing_row_addr = 1u64 << 32; + let row_ids = [missing_row_addr, row_id]; + assert_fetch_apis_reject_missing_row_ids(&table, &row_ids).await +} - let err = table.fetch_blobs("image", &row_ids).await.unwrap_err(); - assert!(matches!(&err, Error::InvalidInput { .. }), "got {err:?}"); - assert!(err.to_string().contains("row IDs")); +#[tokio::test] +async fn fetch_blob_apis_reject_deleted_row_ids() -> Result<()> { + let tmp = tempdir().unwrap(); + let db = connect(tmp.path().to_str().unwrap()).execute().await?; + let table = + create_inline_blob_table(&db, "t", &[1, 2], &[Some(b"one".as_slice()), Some(b"two")]) + .await?; + let pairs = collect_id_rowid(&table).await?; + let deleted_row_addr = pairs.iter().find(|(id, _)| *id == 2).unwrap().1; + let live_row_addr = pairs.iter().find(|(id, _)| *id == 1).unwrap().1; - let err = table.fetch_blob_files("image", &row_ids).await.unwrap_err(); - assert!(matches!(&err, Error::InvalidInput { .. }), "got {err:?}"); - assert!(err.to_string().contains("row IDs")); + table.delete("id = 2").await?; - let requests = row_ids.map(|row_id| BlobRangeRequest::new(row_id, 0, 1)); - let err = table - .fetch_blob_ranges("image", requests) - .await - .unwrap_err(); - assert!(matches!(&err, Error::InvalidInput { .. }), "got {err:?}"); - assert!(err.to_string().contains("row IDs")); - Ok(()) + assert_fetch_apis_reject_missing_row_ids(&table, &[deleted_row_addr, live_row_addr]).await } #[tokio::test] @@ -920,7 +980,10 @@ async fn fetch_blobs_after_delete() -> Result<()> { #[tokio::test] async fn fetch_blobs_with_precompaction_row_ids_survives_compaction() -> Result<()> { let tmp = tempdir().unwrap(); - let db = connect(tmp.path().to_str().unwrap()).execute().await?; + let db = connect(tmp.path().to_str().unwrap()) + .storage_option(OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS, "true") + .execute() + .await?; let table = create_inline_blob_table(&db, "t", &[1], &[Some(b"frag-one".as_slice())]).await?; table .add(binary_input_batch(&[2], &[Some(b"frag-two".as_slice())])) From 21f11b4463f383e2f71f72b39c0b8cdb89fcf47d Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sat, 5 Sep 2026 16:24:23 -0700 Subject: [PATCH 178/206] feat!: replace get_job/job_history with describe_job/query_job_events (#4130) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 1M-row column refresh over 200 fragments produced no visible result, and the client could only ever say `"running"`. Everything needed to diagnose it already existed server-side — the job registry records a `claim`/`claim_complete` pair per fragment carrying `rows_processed` — but none of it was reachable. ## Before Four ways to ask about a job, none of which told you much. ```python job = table.refresh_column_async("embedding") job.status() # "running". That was the entire debug surface. db.get_job(job_id) # state, and a spec. No result, no progress. db.job_history(job_id) # raw record batches, no limit, no filter db.job(job_id) # a handle that knew nothing ``` ## After Open a job the way you open a table; the handle answers everything. ```python job = db.open_job(job_id) # raises JobNotFoundError if there is no such job ``` ```python >>> print(job) Job( id='job-1', state='failed', job_type='refresh_column', creation_ms=1757000000000, spec={ "column": "embedding", "num_workers": 4 }, failure=JobFailureInfo(phase='execute', message='worker died', retryable=True), ) ``` Individual fields are there too — `job.state`, `job.job_type`, `job.creation_ms`, `job.spec`, `job.result`, `job.failure` — and `job.result` carries `rows_assigned` / `rows_failed` as soon as the job succeeds, with no `wait()` required. Per-fragment progress *while it is still running*: ```python done = job.events(filter="state = 'claim_complete'", limit=10_000) done.column("rows_processed").to_pylist() # [5000, 5000, ...] ``` The handle an async action returns is the same object, one `refresh()` away: ```python job = table.refresh_column_async("embedding") job.refresh() job.state, job.result ``` TypeScript is the same experience, down to `console.log`: ```ts const job = await db.openJob(jobId); // rejects if there is no such job console.log(job); // same multi-line layout job.state; job.jobType; job.spec; job.result; job.failure; const done = await job.events({ filter: "state = 'claim_complete'", limit: 10_000 }); ``` ## Why each piece matters - **A result without waiting.** `rows_assigned` / `rows_failed` used to live only on the terminal result, so a job that never terminated reported nothing at all. - **`limit`.** The server caps event rows at 1000 and truncates without saying so, which silently hid most of a 200-fragment job's history. - **`filter`.** `claim_complete` rows carry per-claim `rows_processed` — the only progress signal that exists mid-flight. - **Events outlive the worker.** They live in the job registry, not in pod logs that vanish with the pod. - **One place to ask.** `open_job` replaces `describe_job`, `query_job_events` and `job`, so a question about a job has one answer instead of one per calling location. - **A missing job is an error, not a `None`.** The common case is a job id copied out of a log, where absence is the surprise worth raising — and it matches `open_table`. - **Printing is the debug surface.** Every field on its own line, JSON payloads keeping their structure. An unrefreshed handle stays on one line, because there is nothing to lay out. - **In-process jobs say so.** A local refresh reports `state` and leaves the rest null rather than inventing fields it has no record for. `list_jobs` and `cancel_job` stay as they were: one lists, the other is a one-shot action that should not need a describe first. ## Breaking All shipped in 0.38.0. No deprecated aliases. | Was | Now | | --- | --- | | `Connection.get_job` → `describe_job` | `Connection.open_job` returns a populated `Job`, or raises | | `Connection.job_history` → `query_job_events` | `job.events(...)` | | `Connection.job` | `Connection.open_job` | | Python events → `List[pa.RecordBatch]` | `pa.Table` | | `JobDescription.spec_json` / `.result_json` | internal; use `job.spec` / `job.result` | Node's `Job` is now a TypeScript class wrapping the native handle, so it returns an Arrow table and parsed values like Python does. New `Error::JobNotFound` / `JobNotFoundError`; the three job exceptions are now in the Python API reference. --- docs/src/js/classes/Connection.md | 86 ++----- docs/src/js/classes/Job.md | 171 +++++++++++++- docs/src/js/globals.md | 2 +- docs/src/js/interfaces/JobDescription.md | 66 ------ docs/src/js/interfaces/JobEventsOptions.md | 29 +++ docs/src/js/interfaces/JobInfo.md | 2 +- docs/src/python/python.md | 12 + nodejs/__test__/remote.test.ts | 77 +++++- nodejs/lancedb/connection.ts | 48 +--- nodejs/lancedb/index.ts | 10 +- nodejs/lancedb/job.ts | 188 +++++++++++++++ nodejs/lancedb/table.ts | 20 +- nodejs/src/connection.rs | 53 +---- nodejs/src/job.rs | 124 +++++++--- python/python/lancedb/_lancedb.pyi | 25 +- python/python/lancedb/db.py | 87 ++----- python/python/lancedb/exceptions.py | 6 + python/python/lancedb/job.py | 224 ++++++++++++++++++ python/python/lancedb/remote/db.py | 29 +-- python/python/tests/test_remote_db.py | 132 +++++++++-- python/src/connection.rs | 43 +--- python/src/error.rs | 6 + python/src/job.rs | 135 ++++++++++- rust/lancedb/src/connection.rs | 50 ++-- rust/lancedb/src/database.rs | 33 ++- rust/lancedb/src/error.rs | 2 + rust/lancedb/src/job.rs | 259 ++++++++++++++++++++- rust/lancedb/src/remote/db.rs | 208 ++++++++++------- rust/lancedb/src/remote/job.rs | 60 ++++- rust/lancedb/src/remote/table.rs | 77 ++++++ 30 files changed, 1679 insertions(+), 585 deletions(-) delete mode 100644 docs/src/js/interfaces/JobDescription.md create mode 100644 docs/src/js/interfaces/JobEventsOptions.md create mode 100644 nodejs/lancedb/job.ts diff --git a/docs/src/js/classes/Connection.md b/docs/src/js/classes/Connection.md index 1c5abd89f..18c1deb3b 100644 --- a/docs/src/js/classes/Connection.md +++ b/docs/src/js/classes/Connection.md @@ -448,26 +448,6 @@ on the returned job to know when cleanup has finished. *** -### getJob() - -```ts -abstract getJob(jobId): Promise -``` - -Describe a single server-side job by id. - -Resolves to `null` when the server has no such job. - -#### Parameters - -* **jobId**: `string` - -#### Returns - -`Promise`<`null` \| [`JobDescription`](../interfaces/JobDescription.md)> - -*** - ### isOpen() ```ts @@ -482,48 +462,6 @@ Return true if the connection has not been closed *** -### job() - -```ts -abstract job(jobId): Job -``` - -A [Job](Job.md) handle for a server-side job by id. - -The handle is constructed without a server round trip; an unknown id -surfaces when the handle is used. Dropping the handle has no effect on -the job itself. - -#### Parameters - -* **jobId**: `string` - -#### Returns - -[`Job`](Job.md) - -*** - -### jobHistory() - -```ts -abstract jobHistory(jobId?): Promise> -``` - -The lifecycle event history of a server-side job, as an Arrow table. - -Lists history across all jobs when `jobId` is omitted. - -#### Parameters - -* **jobId?**: `string` - -#### Returns - -`Promise`<`Table`<`any`>> - -*** - ### listJobs() ```ts @@ -648,6 +586,30 @@ A page of table names and an *** +### openJob() + +```ts +abstract openJob(jobId): Promise +``` + +Open a server-side job by id, returning a handle with its record already +populated. Rejects when the server has no such job, the way +[Connection.openTable](Connection.md#opentable) does for a missing table. + +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. + +#### Parameters + +* **jobId**: `string` + +#### Returns + +`Promise`<[`Job`](Job.md)> + +*** + ### openMaterializedView() ```ts diff --git a/docs/src/js/classes/Job.md b/docs/src/js/classes/Job.md index 9f723e9e8..cfbe454ec 100644 --- a/docs/src/js/classes/Job.md +++ b/docs/src/js/classes/Job.md @@ -8,19 +8,46 @@ A handle to an operation that may still be running. -## Constructors +The operation may already be complete when the handle is created. -### new Job() +The detail getters read what the handle last observed. Submitting an +operation returns only a job id, so populating them eagerly would cost an +extra round trip on every call: + +- [Job.refresh](Job.md#refresh) and [Job.status](Job.md#status) fetch the whole record. +- [Job.wait](Job.md#wait) records the terminal state it establishes, but not the + rest of the record. +- Everything is null until one of those runs. + +## Accessors + +### creationMs ```ts -new Job(): Job +get creationMs(): null | number ``` +When the job was created, in milliseconds since the epoch. + #### Returns -[`Job`](Job.md) +`null` \| `number` -## Accessors +*** + +### failure + +```ts +get failure(): null | JobFailureInfo +``` + +Why the job failed, when it failed and the server reports a reason. + +#### Returns + +`null` \| [`JobFailureInfo`](../interfaces/JobFailureInfo.md) + +*** ### id @@ -28,8 +55,69 @@ new Job(): Job get id(): null | string ``` -Identifies the operation on the server that is running it. Operations -that run in this process have no server id. The value is opaque. +Identifies the operation on the server that is running it. + +Operations that run in this process have no server id. The value is +opaque: parsing it or storing it to resume the job later is not supported. + +#### Returns + +`null` \| `string` + +*** + +### jobType + +```ts +get jobType(): null | string +``` + +The job's type, as the server names it. Null for an in-process job, which +has no server-side record. + +#### Returns + +`null` \| `string` + +*** + +### result + +```ts +get result(): any +``` + +The job-type-specific terminal result. Null until the job succeeds, so a +job that never terminates reports its progress through [Job.events](Job.md#events) +instead. + +#### Returns + +`any` + +*** + +### spec + +```ts +get spec(): any +``` + +The job-type-specific specification it was submitted with. + +#### Returns + +`any` + +*** + +### state + +```ts +get state(): null | string +``` + +The last observed lifecycle state, without contacting the backend. #### Returns @@ -51,18 +139,61 @@ Request cancellation. Cancelling a finished operation is a no-op. *** +### events() + +```ts +events(options?): Promise> +``` + +This job's recorded lifecycle events. + +Where the getters above report a terminal result only once the job reaches +one, events are written as the job runs and outlive the workers that +produced them. A distributed job records a `claim`/`claim_complete` pair +per unit of work, each carrying `rows_processed`, so a job that never +finishes still accounts for what it did. + +The server caps results at 1000 rows by default and 10,000 at most, and +truncates without saying so, so pass `limit` for a job that emits an event +per fragment. `filter` is a SQL-like expression over the `state`, +`updated_by`, `emitted_from`, `emitted_by`, and `claim_entity` columns. + +#### Parameters + +* **options?**: [`JobEventsOptions`](../interfaces/JobEventsOptions.md) + +#### Returns + +`Promise`<`Table`<`any`>> + +*** + +### refresh() + +```ts +refresh(): Promise +``` + +Ask the backend for this job's current state, and for a server-side job +its full record, then cache it for the getters above. + +#### Returns + +`Promise`<`void`> + +*** + ### status() ```ts status(): Promise ``` -The operation's current lifecycle state: "running", "finished", -"failed", or "cancelled". +The operation's current lifecycle state: "running", "finished", "failed", +or "cancelled". -A point snapshot; unlike [Job.wait](Job.md#wait) it does not block or reject -on a terminal failure state. States a newer server reports that this -client version does not know pass through as-is. +A point snapshot; unlike [Job.wait](Job.md#wait) it does not block or reject on a +terminal failure state. Also refreshes the getters above. #### Returns @@ -70,6 +201,22 @@ client version does not know pass through as-is. *** +### toString() + +```ts +toString(): string +``` + +Every field the handle currently knows, one per line, with the JSON +payloads indented -- a refresh job's spec and result are the point of +printing it. + +#### Returns + +`string` + +*** + ### wait() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index beb9cbeff..eb0fc7d5a 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -96,7 +96,7 @@ - [IvfFlatOptions](interfaces/IvfFlatOptions.md) - [IvfPqOptions](interfaces/IvfPqOptions.md) - [IvfRqOptions](interfaces/IvfRqOptions.md) -- [JobDescription](interfaces/JobDescription.md) +- [JobEventsOptions](interfaces/JobEventsOptions.md) - [JobFailureInfo](interfaces/JobFailureInfo.md) - [JobInfo](interfaces/JobInfo.md) - [ListNamespacesOptions](interfaces/ListNamespacesOptions.md) diff --git a/docs/src/js/interfaces/JobDescription.md b/docs/src/js/interfaces/JobDescription.md deleted file mode 100644 index 5118bf5d6..000000000 --- a/docs/src/js/interfaces/JobDescription.md +++ /dev/null @@ -1,66 +0,0 @@ -[**@lancedb/lancedb**](../README.md) • **Docs** - -*** - -[@lancedb/lancedb](../globals.md) / JobDescription - -# Interface: JobDescription - -A described job from `Connection.getJob`. - -## Properties - -### creationMs - -```ts -creationMs: number; -``` - -When the job was created, in milliseconds since the epoch. - -*** - -### failure? - -```ts -optional failure: JobFailureInfo; -``` - -Why the job failed, when the job is failed and the server reports a -reason. - -*** - -### jobId - -```ts -jobId: string; -``` - -*** - -### jobType - -```ts -jobType: string; -``` - -*** - -### specJson? - -```ts -optional specJson: string; -``` - -The job-type-specific specification as a JSON string, when present. - -*** - -### state - -```ts -state: string; -``` - -Lifecycle state: "running", "finished", "failed", or "cancelled". diff --git a/docs/src/js/interfaces/JobEventsOptions.md b/docs/src/js/interfaces/JobEventsOptions.md new file mode 100644 index 000000000..24831f4f1 --- /dev/null +++ b/docs/src/js/interfaces/JobEventsOptions.md @@ -0,0 +1,29 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / JobEventsOptions + +# Interface: JobEventsOptions + +Which of a job's events [Job.events](../classes/Job.md#events) returns. + +## Properties + +### filter? + +```ts +optional filter: string; +``` + +SQL-like filter over the event columns. + +*** + +### limit? + +```ts +optional limit: number; +``` + +Maximum event rows to return, up to the server maximum of 10,000. diff --git a/docs/src/js/interfaces/JobInfo.md b/docs/src/js/interfaces/JobInfo.md index 3596fc968..01a7ceefc 100644 --- a/docs/src/js/interfaces/JobInfo.md +++ b/docs/src/js/interfaces/JobInfo.md @@ -26,7 +26,7 @@ When the job was created, in milliseconds since the epoch. jobId: string; ``` -The job id -- what `Connection.getJob` and `Connection.cancelJob` +The job id -- what `Connection.openJob` and `Connection.cancelJob` accept. *** diff --git a/docs/src/python/python.md b/docs/src/python/python.md index b0d1bb426..28e774473 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -157,6 +157,12 @@ listing a storage directory. ::: lancedb.job.AsyncJob +::: lancedb.job.JobInfo + +::: lancedb.job.JobDescription + +::: lancedb.job.JobFailureInfo + ::: lancedb.sql.Query ::: lancedb.sql.AsyncQuery @@ -310,6 +316,12 @@ still work. Queries return descriptors. Call ::: lancedb.exceptions.MissingColumnError +::: lancedb.exceptions.JobNotFoundError + +::: lancedb.exceptions.JobFailedError + +::: lancedb.exceptions.JobCancelledError + ## Integrations ## Pydantic diff --git a/nodejs/__test__/remote.test.ts b/nodejs/__test__/remote.test.ts index 708559b7b..519f0eb5f 100644 --- a/nodejs/__test__/remote.test.ts +++ b/nodejs/__test__/remote.test.ts @@ -939,6 +939,7 @@ describe("remote connection jobs surface", () => { const { tableFromArrays, tableToIPC } = await import("apache-arrow"); const eventsTable = tableFromArrays({ state: ["created", "succeeded"] }); const eventsBody = Buffer.from(tableToIPC(eventsTable, "stream")); + const queryEventsPayloads: Record[] = []; await withMockDatabase( (req, res) => { @@ -967,6 +968,16 @@ describe("remote connection jobs surface", () => { ); } } else if (req.url === "/v1/jobs/describe") { + if (payload["job_id"] === "job-2") { + res + .writeHead(200, { "Content-Type": "application/json" }) + .end( + '{"job_id": "job-2", "job_type": "refresh_column", ' + + '"job_state": "DONE", "creation_ms": 2000, ' + + '"result": {"rows_assigned": 1000000}}', + ); + return; + } if (payload["job_id"] !== "job-1") { res.writeHead(404).end("no such job"); return; @@ -988,6 +999,7 @@ describe("remote connection jobs surface", () => { .writeHead(200, { "Content-Type": "application/json" }) .end('{"job_id": "job-1"}'); } else if (req.url === "/v1/jobs/query_events") { + queryEventsPayloads.push(payload); res .writeHead(200, { "Content-Type": "application/vnd.apache.arrow.stream", @@ -1004,22 +1016,65 @@ describe("remote connection jobs surface", () => { expect(jobs[0].state).toEqual("running"); expect(jobs[1].state).toEqual("finished"); - const description = await db.getJob("job-1"); - expect(description?.state).toEqual("failed"); - expect(JSON.parse(description?.specJson ?? "")).toEqual({ - column: "vec", - }); - expect(description?.failure?.message).toEqual("worker died"); - expect(await db.getJob("missing")).toBeNull(); - expect(await db.cancelJob("job-1")).toBe(true); expect(await db.cancelJob("missing")).toBe(false); - const history = await db.jobHistory("job-1"); - expect(history.numRows).toEqual(2); + // Opening a job hands back a populated handle; a missing one rejects. + await expect(db.openJob("missing")).rejects.toThrow("not found"); + const finished = await db.openJob("job-2"); + expect(finished.state).toEqual("finished"); + expect(finished.result).toEqual({ + // biome-ignore lint/style/useNamingConvention: snake_case mandated by the server wire format + rows_assigned: 1000000, + }); - const job = db.job("job-1"); + const job = await db.openJob("job-1"); expect(job.id).toEqual("job-1"); + + // openJob already populated the handle; refresh() re-reads it. + expect(job.state).toEqual("failed"); + await job.refresh(); + expect(job.state).toEqual("failed"); + expect(job.jobType).toEqual("create_index"); + expect(job.creationMs).toEqual(1000); + expect(job.spec).toEqual({ column: "vec" }); + expect(job.result).toBeNull(); + expect(job.failure?.message).toEqual("worker died"); + + // The handle reaches its own events, supplying its job id. + const jobEvents = await job.events({ + limit: 500, + filter: "state = 'claim_complete'", + }); + expect(jobEvents.numRows).toEqual(2); + expect(queryEventsPayloads.pop()).toEqual({ + // biome-ignore lint/style/useNamingConvention: snake_case mandated by the server wire format + job_id: "job-1", + limit: 500, + filter: "state = 'claim_complete'", + }); + + // Printing lays every known field out on its own line, with the JSON + // payloads indented rather than crammed onto one line. + expect(`${job}`).toEqual( + [ + "Job(", + ' id="job-1",', + ' state="failed",', + ' jobType="create_index",', + " creationMs=1000,", + " spec={", + ' "column": "vec"', + " },", + " failure={", + ' "phase": "execute",', + ' "message": "worker died",', + ' "retryable": true', + " },", + ")", + ].join("\n"), + ); + expect(await job.status()).toEqual("failed"); await expect(job.wait()).rejects.toThrow("worker died"); }, diff --git a/nodejs/lancedb/connection.ts b/nodejs/lancedb/connection.ts index 263a338ab..094819ec1 100644 --- a/nodejs/lancedb/connection.ts +++ b/nodejs/lancedb/connection.ts @@ -1,7 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -import { tableFromIPC } from "apache-arrow"; import { Data, SchemaLike, @@ -16,6 +15,7 @@ import { makeEmptyTable, } from "./arrow"; import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry"; +import { Job } from "./job"; import { MaterializedView, MaterializedViewSelect, @@ -27,8 +27,6 @@ import type { CreateNamespaceResponse, DescribeNamespaceResponse, DropNamespaceResponse, - Job, - JobDescription, JobInfo, ListNamespacesResponse, ListTablesResponse, @@ -557,24 +555,19 @@ export abstract class Connection { ): Promise; /** - * A {@link Job} handle for a server-side job by id. + * Open a server-side job by id, returning a handle with its record already + * populated. Rejects when the server has no such job, the way + * {@link Connection.openTable} does for a missing table. * - * The handle is constructed without a server round trip; an unknown id - * surfaces when the handle is used. Dropping the handle has no effect on - * the job itself. + * The returned {@link Job} answers for its own state, specification, + * result, failure and event history, so there is no separate + * connection-level call for any of them. */ - abstract job(jobId: string): Job; + abstract openJob(jobId: string): Promise; /** List server-side jobs across the database's tables. */ abstract listJobs(): Promise; - /** - * Describe a single server-side job by id. - * - * Resolves to `null` when the server has no such job. - */ - abstract getJob(jobId: string): Promise; - /** * Request cancellation of a server-side job by id. * @@ -582,13 +575,6 @@ export abstract class Connection { * such job exists. Cancelling an already-terminal job is a no-op success. */ abstract cancelJob(jobId: string): Promise; - - /** - * The lifecycle event history of a server-side job, as an Arrow table. - * - * Lists history across all jobs when `jobId` is omitted. - */ - abstract jobHistory(jobId?: string): Promise; } /** @hideconstructor */ @@ -869,7 +855,7 @@ export class LocalConnection extends Connection { } async dropTableAsync(name: string, namespacePath?: string[]): Promise { - return this.inner.dropTableAsync(name, namespacePath ?? []); + return new Job(await this.inner.dropTableAsync(name, namespacePath ?? [])); } async dropAllTables(namespacePath?: string[]): Promise { @@ -928,29 +914,17 @@ export class LocalConnection extends Connection { ); } - job(jobId: string): Job { - return this.inner.job(jobId); + async openJob(jobId: string): Promise { + return new Job(await this.inner.openJob(jobId)); } async listJobs(): Promise { return this.inner.listJobs(); } - async getJob(jobId: string): Promise { - return this.inner.getJob(jobId); - } - async cancelJob(jobId: string): Promise { return this.inner.cancelJob(jobId); } - - async jobHistory(jobId?: string): Promise { - const buf = await this.inner.jobHistory(jobId); - if (buf.length === 0) { - return new ArrowTable(); - } - return tableFromIPC(buf); - } } /** diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 34d7ce4d9..4f8ff77e5 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -94,13 +94,9 @@ export { RenameTableOptions, } from "./connection"; -export { - Job, - JobDescription, - JobFailureInfo, - JobInfo, - Session, -} from "./native.js"; +export { JobFailureInfo, JobInfo, Session } from "./native.js"; + +export { Job, JobEventsOptions } from "./job"; export { AutoQuery, diff --git a/nodejs/lancedb/job.ts b/nodejs/lancedb/job.ts new file mode 100644 index 000000000..0baa0f571 --- /dev/null +++ b/nodejs/lancedb/job.ts @@ -0,0 +1,188 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { Table as ArrowTable, tableFromIPC } from "apache-arrow"; +import { JobFailureInfo, Job as NativeJob } from "./native"; + +/** Which of a job's events {@link Job.events} returns. */ +export interface JobEventsOptions { + /** Maximum event rows to return, up to the server maximum of 10,000. */ + limit?: number; + /** SQL-like filter over the event columns. */ + filter?: string; +} + +/** + * A handle to an operation that may still be running. + * + * The operation may already be complete when the handle is created. + * + * The detail getters read what the handle last observed. Submitting an + * operation returns only a job id, so populating them eagerly would cost an + * extra round trip on every call: + * + * - {@link Job.refresh} and {@link Job.status} fetch the whole record. + * - {@link Job.wait} records the terminal state it establishes, but not the + * rest of the record. + * - Everything is null until one of those runs. + * + * @hideconstructor + */ +export class Job { + private readonly inner: NativeJob; + + constructor(inner: NativeJob) { + this.inner = inner; + } + + /** + * Identifies the operation on the server that is running it. + * + * Operations that run in this process have no server id. The value is + * opaque: parsing it or storing it to resume the job later is not supported. + */ + get id(): string | null { + return this.inner.id ?? null; + } + + /** The last observed lifecycle state, without contacting the backend. */ + get state(): string | null { + return this.inner.state ?? null; + } + + /** + * The job's type, as the server names it. Null for an in-process job, which + * has no server-side record. + */ + get jobType(): string | null { + return this.inner.jobType ?? null; + } + + /** When the job was created, in milliseconds since the epoch. */ + get creationMs(): number | null { + return this.inner.creationMs ?? null; + } + + /** The job-type-specific specification it was submitted with. */ + // biome-ignore lint/suspicious/noExplicitAny: shape varies by job type + get spec(): any | null { + return parseJson(this.inner.specJson); + } + + /** + * The job-type-specific terminal result. Null until the job succeeds, so a + * job that never terminates reports its progress through {@link Job.events} + * instead. + */ + // biome-ignore lint/suspicious/noExplicitAny: shape varies by job type + get result(): any | null { + return parseJson(this.inner.resultJson); + } + + /** Why the job failed, when it failed and the server reports a reason. */ + get failure(): JobFailureInfo | null { + return this.inner.failure ?? null; + } + + /** + * The operation's current lifecycle state: "running", "finished", "failed", + * or "cancelled". + * + * A point snapshot; unlike {@link Job.wait} it does not block or reject on a + * terminal failure state. Also refreshes the getters above. + */ + async status(): Promise { + return this.inner.status(); + } + + /** Wait until the operation reaches a terminal state. */ + async wait(): Promise { + return this.inner.wait(); + } + + /** Request cancellation. Cancelling a finished operation is a no-op. */ + async cancel(): Promise { + return this.inner.cancel(); + } + + /** + * Ask the backend for this job's current state, and for a server-side job + * its full record, then cache it for the getters above. + */ + async refresh(): Promise { + return this.inner.refresh(); + } + + /** + * This job's recorded lifecycle events. + * + * Where the getters above report a terminal result only once the job reaches + * one, events are written as the job runs and outlive the workers that + * produced them. A distributed job records a `claim`/`claim_complete` pair + * per unit of work, each carrying `rows_processed`, so a job that never + * finishes still accounts for what it did. + * + * The server caps results at 1000 rows by default and 10,000 at most, and + * truncates without saying so, so pass `limit` for a job that emits an event + * per fragment. `filter` is a SQL-like expression over the `state`, + * `updated_by`, `emitted_from`, `emitted_by`, and `claim_entity` columns. + */ + async events(options?: JobEventsOptions): Promise { + const buf = await this.inner.events(options?.limit, options?.filter); + if (buf.length === 0) { + return new ArrowTable(); + } + return tableFromIPC(buf); + } + + /** + * Every field the handle currently knows, one per line, with the JSON + * payloads indented -- a refresh job's spec and result are the point of + * printing it. + */ + toString(): string { + if (this.state === null) { + const known = this.id === null ? "" : `id=${JSON.stringify(this.id)}, `; + return `Job(${known}not refreshed)`; + } + const fields: string[] = []; + if (this.id !== null) { + fields.push(`id=${JSON.stringify(this.id)}`); + } + fields.push(`state=${JSON.stringify(this.state)}`); + if (this.jobType !== null) { + fields.push(`jobType=${JSON.stringify(this.jobType)}`); + } + if (this.creationMs !== null) { + fields.push(`creationMs=${this.creationMs}`); + } + for (const [name, value] of [ + ["spec", this.spec], + ["result", this.result], + ] as const) { + if (value !== null) { + fields.push(`${name}=${indentJson(value)}`); + } + } + if (this.failure !== null) { + fields.push(`failure=${indentJson(this.failure)}`); + } + return `Job(${fields.map((field) => `\n${REPR_INDENT}${field},`).join("")}\n)`; + } + + [Symbol.for("nodejs.util.inspect.custom")](): string { + return this.toString(); + } +} + +const REPR_INDENT = " "; + +// biome-ignore lint/suspicious/noExplicitAny: shape varies by job type +function indentJson(value: any): string { + return JSON.stringify(value, null, 4).replace(/\n/g, `\n${REPR_INDENT}`); +} + +// biome-ignore lint/suspicious/noExplicitAny: shape varies by job type +function parseJson(raw: string | null | undefined): any | null { + return raw === null || raw === undefined ? null : JSON.parse(raw); +} diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 28591f51c..06f8cd991 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -19,6 +19,7 @@ import { import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry"; import { IndexOptions } from "./indices"; +import { Job } from "./job"; import { MergeInsertBuilder } from "./merge"; import { AddColumnsResult, @@ -30,7 +31,6 @@ import { DropColumnsResult, IndexConfig, IndexStatistics, - Job, LsmStats, Branches as NativeBranches, OptimizeStats, @@ -1124,13 +1124,15 @@ export class LocalTable extends Table { ): Promise { // biome-ignore lint/suspicious/noExplicitAny: skip const nativeIndex = (options?.config as any)?.inner; - return await this.inner.createIndexAsync( - nativeIndex, - column, - options?.replace, - options?.waitTimeoutSeconds, - options?.name, - options?.train, + return new Job( + await this.inner.createIndexAsync( + nativeIndex, + column, + options?.replace, + options?.waitTimeoutSeconds, + options?.name, + options?.train, + ), ); } @@ -1313,7 +1315,7 @@ export class LocalTable extends Table { } async refreshColumnAsync(column: string): Promise { - return await this.inner.refreshColumnAsync(column); + return new Job(await this.inner.refreshColumnAsync(column)); } async refreshMaterializedView( diff --git a/nodejs/src/connection.rs b/nodejs/src/connection.rs index 5cf676256..586238359 100644 --- a/nodejs/src/connection.rs +++ b/nodejs/src/connection.rs @@ -442,13 +442,15 @@ impl Connection { self.get_inner()?.drop_all_tables(&ns).await.default_error() } - /// A `Job` handle for a server-side job by id. + /// Open a server-side job by id, returning a handle with its record + /// already populated. Rejects when the server has no such job. /// - /// The handle is constructed without a server round trip; an unknown id - /// surfaces when the handle is used. - #[napi] - pub fn job(&self, job_id: String) -> napi::Result { - let job = self.get_inner()?.job(job_id).default_error()?; + /// The returned handle answers for its own state, specification, result, + /// failure and event history, so there is no separate connection-level + /// call for any of them. + #[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)) } @@ -459,17 +461,6 @@ impl Connection { Ok(jobs.into_iter().map(Into::into).collect()) } - /// Describe a single server-side job by id. `null` when the server has - /// no such job. - #[napi(catch_unwind)] - pub async fn get_job( - &self, - job_id: String, - ) -> napi::Result> { - let description = self.get_inner()?.get_job(&job_id).await.default_error()?; - Ok(description.map(Into::into)) - } - /// Request cancellation of a server-side job by id. Returns true if the /// server accepted the cancellation, false if no such job exists. #[napi(catch_unwind)] @@ -477,34 +468,6 @@ impl Connection { self.get_inner()?.cancel_job(&job_id).await.default_error() } - /// The lifecycle event history of a server-side job (all jobs when - /// `job_id` is null), as an Arrow IPC stream buffer. Empty when there is - /// no history. - #[napi(catch_unwind)] - pub async fn job_history(&self, job_id: Option) -> napi::Result { - let batches = self - .get_inner()? - .job_history(job_id.as_deref()) - .await - .default_error()?; - let Some(first) = batches.first() else { - return Ok(Buffer::from(Vec::::new())); - }; - let mut out = Vec::new(); - let mut writer = arrow_ipc::writer::StreamWriter::try_new(&mut out, &first.schema()) - .map_err(|e| napi::Error::from_reason(e.to_string()))?; - for batch in &batches { - writer - .write(batch) - .map_err(|e| napi::Error::from_reason(e.to_string()))?; - } - writer - .finish() - .map_err(|e| napi::Error::from_reason(e.to_string()))?; - drop(writer); - Ok(Buffer::from(out)) - } - #[napi(catch_unwind)] /// Describe a namespace and return its properties. pub async fn describe_namespace( diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 14013fd27..9c6559dfd 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -3,6 +3,9 @@ use std::sync::Arc; +use arrow_array::RecordBatch; +use lancedb::job::JobEventsRequest; +use napi::bindgen_prelude::Buffer; use napi_derive::napi; use crate::error::NapiErrorExt; @@ -55,12 +58,98 @@ impl Job { pub async fn cancel(&self) -> napi::Result<()> { self.inner.cancel().await.default_error() } + + /// Ask the backend for this job's current state, and for a server-side job + /// its full record, then cache it for the getters below. + /// + /// They are all null until this runs, because submitting an operation + /// returns only a job id. {@link Job.status} fetches the whole record too; + /// {@link Job.wait} records only the terminal state it establishes. + #[napi(catch_unwind)] + pub async fn refresh(&self) -> napi::Result<()> { + self.inner.refresh().await.default_error() + } + + /// The last observed lifecycle state, without contacting the backend. + #[napi(getter)] + pub fn state(&self) -> Option { + self.inner.state() + } + + /// The job's type, as the server names it. Null for an in-process job, + /// which has no server-side record. + #[napi(getter)] + pub fn job_type(&self) -> Option { + self.inner.job_type() + } + + /// When the job was created, in milliseconds since the epoch. + #[napi(getter)] + pub fn creation_ms(&self) -> Option { + self.inner.creation_ms() + } + + /// The job-type-specific specification as a JSON string, when present. + #[napi(getter)] + pub fn spec_json(&self) -> Option { + self.inner.spec().map(|spec| spec.to_string()) + } + + /// The job-type-specific terminal result as a JSON string. Null until the + /// job succeeds, so a job that never terminates reports its progress + /// through {@link Job.events} instead. + #[napi(getter)] + pub fn result_json(&self) -> Option { + self.inner.result().map(|result| result.to_string()) + } + + /// 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, + retryable: failure.retryable, + }) + } + + /// This job's recorded lifecycle events, as an Arrow IPC stream buffer. + /// The TypeScript wrapper turns it into an Arrow table. + #[napi(catch_unwind)] + pub async fn events(&self, limit: Option, filter: Option) -> napi::Result { + let batches = self + .inner + .events(JobEventsRequest { limit, filter }) + .await + .default_error()?; + batches_to_ipc_buffer(&batches) + } +} + +/// Serialise Arrow batches as a single IPC stream for the TypeScript layer. +pub(crate) fn batches_to_ipc_buffer(batches: &[RecordBatch]) -> napi::Result { + let Some(first) = batches.first() else { + return Ok(Buffer::from(Vec::::new())); + }; + let mut out = Vec::new(); + let mut writer = arrow_ipc::writer::StreamWriter::try_new(&mut out, &first.schema()) + .map_err(|e| napi::Error::from_reason(e.to_string()))?; + for batch in batches { + writer + .write(batch) + .map_err(|e| napi::Error::from_reason(e.to_string()))?; + } + writer + .finish() + .map_err(|e| napi::Error::from_reason(e.to_string()))?; + drop(writer); + Ok(Buffer::from(out)) } /// A row from `Connection.listJobs`: one server-side job. #[napi(object)] pub struct JobInfo { - /// The job id -- what `Connection.getJob` and `Connection.cancelJob` + /// The job id -- what `Connection.openJob` and `Connection.cancelJob` /// accept. pub job_id: String, /// The table the job runs against, without URI or namespace. @@ -91,36 +180,3 @@ pub struct JobFailureInfo { pub message: Option, pub retryable: Option, } - -/// A described job from `Connection.getJob`. -#[napi(object)] -pub struct JobDescription { - pub job_id: String, - pub job_type: String, - /// Lifecycle state: "running", "finished", "failed", or "cancelled". - pub state: String, - /// When the job was created, in milliseconds since the epoch. - pub creation_ms: i64, - /// The job-type-specific specification as a JSON string, when present. - pub spec_json: Option, - /// Why the job failed, when the job is failed and the server reports a - /// reason. - pub failure: Option, -} - -impl From for JobDescription { - fn from(description: lancedb::database::JobDescription) -> Self { - Self { - job_id: description.job_id, - job_type: description.job_type, - state: description.state, - creation_ms: description.creation_ms, - spec_json: (!description.spec.is_null()).then(|| description.spec.to_string()), - failure: description.failure.map(|failure| JobFailureInfo { - phase: failure.phase, - message: failure.message, - retryable: failure.retryable, - }), - } - } -} diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 3ea8d15c7..0f7b110ac 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -148,17 +148,13 @@ class Connection(object): start_after: Optional[str], limit: Optional[int], ) -> list[str]: ... # Deprecated: Use list_tables instead - def job(self, job_id: str) -> Job: ... + async def open_job(self, job_id: str) -> Job: ... async def create_function_async(self, request_json: str) -> Job: ... async def get_function(self, name: str, version: str) -> str: ... async def list_functions(self) -> List[str]: ... async def drop_function(self, name: str, version: str) -> bool: ... async def list_jobs(self) -> List[JobInfo]: ... - async def get_job(self, job_id: str) -> Optional[JobDescription]: ... async def cancel_job(self, job_id: str) -> bool: ... - async def job_history( - self, job_id: Optional[str] = None - ) -> List[pa.RecordBatch]: ... async def execute_query_async( self, query: str, @@ -244,9 +240,20 @@ class BlobFile: class Job: @property def id(self) -> Optional[str]: ... + @property + def _state(self) -> Optional[str]: ... + @property + def _description(self) -> Optional[JobDescription]: ... async def status(self) -> str: ... async def wait(self) -> Optional[str]: ... async def cancel(self) -> None: ... + async def refresh(self) -> None: ... + async def events( + self, + *, + limit: Optional[int] = None, + filter: Optional[str] = None, + ) -> pa.Table: ... class JobInfo: @property @@ -278,7 +285,13 @@ class JobDescription: @property def creation_ms(self) -> int: ... @property - def spec_json(self) -> Optional[str]: ... + def _spec_json(self) -> Optional[str]: ... + @property + def _result_json(self) -> Optional[str]: ... + @property + def spec(self) -> Optional[Any]: ... + @property + def result(self) -> Optional[Any]: ... @property def failure(self) -> Optional[JobFailureInfo]: ... diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 82dfa22f1..88718e968 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -76,7 +76,7 @@ if TYPE_CHECKING: from .pydantic import LanceModel from ._lancedb import Connection as LanceDbConnection - from ._lancedb import JobDescription, JobInfo + from ._lancedb import JobInfo from .common import DATA, URI from .embeddings import EmbeddingFunctionConfig from ._lancedb import Session @@ -745,26 +745,23 @@ class DBConnection(EnforceOverrides): "Function catalog operations are not supported for this connection type" ) - def job(self, job_id: str) -> Job: - """A [Job][lancedb.job.Job] handle for a server-side job by id. + def open_job(self, job_id: str) -> Job: + """Open a server-side job by id, returning a handle with its record + already populated. - The handle is constructed without a server round trip; an unknown id - surfaces when the handle is used. Dropping the handle has no effect - on the job itself. + The returned [Job][lancedb.job.Job] answers for its own state, + specification, result, failure and event history, so there is no + separate connection-level call for any of them. + + Raises `JobNotFoundError` when the server has no such job, the way + `open_table` does for a missing table. """ - raise NotImplementedError("job is not supported for this connection type") + raise NotImplementedError("open_job is not supported for this connection type") def list_jobs(self) -> List[JobInfo]: """List server-side jobs across the database's tables.""" raise NotImplementedError("list_jobs is not supported for this connection type") - def get_job(self, job_id: str) -> Optional[JobDescription]: - """Describe a single server-side job by id. - - Returns None when the server has no such job. - """ - raise NotImplementedError("get_job is not supported for this connection type") - def cancel_job(self, job_id: str) -> bool: """Request cancellation of a server-side job by id. @@ -776,15 +773,6 @@ class DBConnection(EnforceOverrides): "cancel_job is not supported for this connection type" ) - def job_history(self, job_id: Optional[str] = None) -> List[pa.RecordBatch]: - """The lifecycle event history of a server-side job, as Arrow batches. - - Lists history across all jobs when `job_id` is None. - """ - raise NotImplementedError( - "job_history is not supported for this connection type" - ) - def execute_query( self, query: str, @@ -1462,14 +1450,11 @@ class LanceDBConnection(DBConnection): ) @override - def job(self, job_id: str) -> Job: - """A [Job][lancedb.job.Job] handle for a server-side job by id. - - The handle is constructed without a server round trip; an unknown id - surfaces when the handle is used. Dropping the handle has no effect - on the job itself. + def open_job(self, job_id: str) -> Job: + """Open a server-side job by id. See + [DBConnection.open_job][lancedb.db.DBConnection.open_job]. """ - return Job(self._conn.job(job_id)) + return Job(LOOP.run(self._conn.open_job(job_id))) @override def create_function_async(self, definition: UdfDefinition) -> Job[FunctionVersion]: @@ -1493,14 +1478,6 @@ class LanceDBConnection(DBConnection): """List server-side jobs across the database's tables.""" return LOOP.run(self._conn.list_jobs()) - @override - def get_job(self, job_id: str) -> Optional[JobDescription]: - """Describe a single server-side job by id. - - Returns None when the server has no such job. - """ - return LOOP.run(self._conn.get_job(job_id)) - @override def cancel_job(self, job_id: str) -> bool: """Request cancellation of a server-side job by id. @@ -1511,14 +1488,6 @@ class LanceDBConnection(DBConnection): """ return LOOP.run(self._conn.cancel_job(job_id)) - @override - def job_history(self, job_id: Optional[str] = None) -> List[pa.RecordBatch]: - """The lifecycle event history of a server-side job, as Arrow batches. - - Lists history across all jobs when `job_id` is None. - """ - return LOOP.run(self._conn.job_history(job_id)) - @override def namespace_client(self) -> LanceNamespace: """Get the equivalent namespace client for this connection. @@ -2289,15 +2258,11 @@ class AsyncConnection(object): namespace_path = [] await self._inner.drop_all_tables(namespace_path=namespace_path) - def job(self, job_id: str) -> AsyncJob: - """An [AsyncJob][lancedb.job.AsyncJob] handle for a server-side job - by id. - - The handle is constructed without a server round trip; an unknown id - surfaces when the handle is used. Dropping the handle has no effect - on the job itself. + async def open_job(self, job_id: str) -> AsyncJob: + """Open a server-side job by id. See + [DBConnection.open_job][lancedb.db.DBConnection.open_job]. """ - return AsyncJob(self._inner.job(job_id)) + return AsyncJob(await self._inner.open_job(job_id)) async def create_function_async( self, definition: UdfDefinition @@ -2337,13 +2302,6 @@ class AsyncConnection(object): """List server-side jobs across the database's tables.""" return await self._inner.list_jobs() - async def get_job(self, job_id: str) -> Optional[JobDescription]: - """Describe a single server-side job by id. - - Returns None when the server has no such job. - """ - return await self._inner.get_job(job_id) - async def cancel_job(self, job_id: str) -> bool: """Request cancellation of a server-side job by id. @@ -2353,13 +2311,6 @@ class AsyncConnection(object): """ return await self._inner.cancel_job(job_id) - async def job_history(self, job_id: Optional[str] = None) -> List[pa.RecordBatch]: - """The lifecycle event history of a server-side job, as Arrow batches. - - Lists history across all jobs when `job_id` is None. - """ - return await self._inner.job_history(job_id) - async def execute_query( self, query: str, diff --git a/python/python/lancedb/exceptions.py b/python/python/lancedb/exceptions.py index daa98ee6e..67f15cabe 100644 --- a/python/python/lancedb/exceptions.py +++ b/python/python/lancedb/exceptions.py @@ -35,3 +35,9 @@ class JobCancelledError(RuntimeError): """Exception raised when an asynchronous job was cancelled.""" pass + + +class JobNotFoundError(ValueError): + """Exception raised when opening a job the server does not have.""" + + pass diff --git a/python/python/lancedb/job.py b/python/python/lancedb/job.py index f688768cb..e57fde0ea 100644 --- a/python/python/lancedb/job.py +++ b/python/python/lancedb/job.py @@ -4,15 +4,27 @@ """Handles to operations a server may run asynchronously.""" import asyncio +import json from datetime import timedelta from typing import Any, Callable, Generic, Optional, TypeVar, cast +import pyarrow as pa + from lancedb.background_loop import LOOP from . import _lancedb +from ._lancedb import JobDescription, JobFailureInfo, JobInfo T = TypeVar("T") +__all__ = [ + "AsyncJob", + "Job", + "JobDescription", + "JobFailureInfo", + "JobInfo", +] + class AsyncJob(Generic[T]): """A handle to an operation that may still be running. @@ -78,6 +90,149 @@ class AsyncJob(Generic[T]): return await self._inner.cancel() + async def refresh(self) -> None: + """Ask the backend for this job's current state, and for a server-side + job its full record, then cache it for the properties below. + + The properties are all `None` until this runs, because submitting an + operation returns only a job id. `status` fetches the whole record too; + `wait` records only the terminal state it establishes. + """ + if self._inner is None: + return + await self._inner.refresh() + + @property + def state(self) -> Optional[str]: + """The last observed lifecycle state, without contacting the backend. + + `None` until the handle has talked to it. See :meth:`AsyncJob.refresh`. + """ + if self._inner is None: + return "finished" + return self._inner._state + + @property + def job_type(self) -> Optional[str]: + """The job's type, as the server names it. + + `None` for an in-process job, which has no server-side record. + """ + return self._field("job_type") + + @property + def creation_ms(self) -> Optional[int]: + """When the job was created, in milliseconds since the epoch.""" + return self._field("creation_ms") + + @property + def spec(self) -> Optional[Any]: + """The job-type-specific specification it was submitted with.""" + return self._field("spec") + + @property + def result(self) -> Optional[Any]: + """The job-type-specific terminal result, as reported data rather than + the typed model :meth:`AsyncJob.wait` returns. + + `None` until the job succeeds, so a job that never terminates reports + its progress through :meth:`AsyncJob.events` instead. + """ + return self._field("result") + + @property + def failure(self) -> Optional[JobFailureInfo]: + """Why the job failed, when it failed and the server reports a reason.""" + return self._field("failure") + + @property + def _spec_json(self) -> Optional[str]: + return self._field("_spec_json") + + @property + def _result_json(self) -> Optional[str]: + return self._field("_result_json") + + def _field(self, name: str) -> Optional[Any]: + 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 events( + self, + *, + limit: Optional[int] = None, + filter: Optional[str] = None, + ) -> "pa.Table": + """This job's recorded lifecycle events. + + Where the properties above report a terminal result only once the job + reaches one, events are written as the job runs and outlive the workers + that produced them. A distributed job records a `claim`/`claim_complete` + pair per unit of work, each carrying `rows_processed`, so a job that + never finishes still accounts for what it did. + + Parameters + ---------- + limit: int, optional + Maximum event rows to return. The server caps results at 1000 by + default and 10,000 at most, and truncates without saying so, so + pass this for a job that emits an event per fragment. + filter: str, optional + SQL-like expression over the `state`, `updated_by`, `emitted_from`, + `emitted_by`, and `claim_entity` columns, such as + ``state = 'claim_complete'``. + """ + if self._inner is None: + raise NotImplementedError( + "job event history is only available for server-side jobs" + ) + return await self._inner.events(limit=limit, filter=filter) + + def __repr__(self) -> str: + return _job_repr("AsyncJob", self) + + +_REPR_INDENT = " " * 4 + + +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) + + +def _job_repr(kind: str, job: Any) -> str: + """Render every field the handle currently knows, omitting the rest. + + One field per line, with the JSON payloads indented, because a refresh + job's spec and result are the point of printing it. + """ + 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 "" + 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}") + for name in ("job_type", "creation_ms"): + value = getattr(job, name) + if value is not None: + fields.append(f"{name}={value!r}") + 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}") + body = "".join(f"\n{_REPR_INDENT}{field}," for field in fields) + return f"{kind}({body}\n)" + class Job(Generic[T]): """Synchronous counterpart of `AsyncJob` with the same result type.""" @@ -122,6 +277,75 @@ class Job(Generic[T]): return LOOP.run(self._inner.cancel()) + def refresh(self) -> None: + """Ask the backend for this job's current state and record. + + See :meth:`AsyncJob.refresh`. + """ + if self._inner is None: + return + LOOP.run(self._inner.refresh()) + + @property + def state(self) -> Optional[str]: + """The last observed lifecycle state. See :attr:`AsyncJob.state`.""" + return self._inner.state if self._inner is not None else "finished" + + @property + def job_type(self) -> Optional[str]: + """The job's type. See :attr:`AsyncJob.job_type`.""" + return self._field("job_type") + + @property + def creation_ms(self) -> Optional[int]: + """When the job was created. See :attr:`AsyncJob.creation_ms`.""" + return self._field("creation_ms") + + @property + def spec(self) -> Optional[Any]: + """The job's specification. See :attr:`AsyncJob.spec`.""" + return self._field("spec") + + @property + def result(self) -> Optional[Any]: + """The job's terminal result. See :attr:`AsyncJob.result`.""" + return self._field("result") + + @property + def failure(self) -> Optional[JobFailureInfo]: + """Why the job failed. See :attr:`AsyncJob.failure`.""" + return self._field("failure") + + @property + def _spec_json(self) -> Optional[str]: + return self._field("_spec_json") + + @property + def _result_json(self) -> Optional[str]: + return self._field("_result_json") + + def _field(self, name: str) -> Optional[Any]: + return getattr(self._inner, name) if self._inner is not None else None + + def events( + self, + *, + limit: Optional[int] = None, + filter: Optional[str] = None, + ) -> "pa.Table": + """This job's recorded lifecycle events. + + See :meth:`AsyncJob.events`. + """ + if self._inner is None: + raise NotImplementedError( + "job event history is only available for server-side jobs" + ) + return LOOP.run(self._inner.events(limit=limit, filter=filter)) + + def __repr__(self) -> str: + return _job_repr("Job", self) + def _typed_job( inner: "_lancedb.Job", result_decoder: Callable[[str], T] diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index 1c0dd3afa..5b6828b04 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -31,7 +31,7 @@ from ..sql import QueryDescription from ..materialized_view import MaterializedView, SelectArg if TYPE_CHECKING: - from .._lancedb import JobDescription, JobInfo + from .._lancedb import JobInfo from ..embeddings import EmbeddingFunctionConfig from lance_namespace import ( LanceNamespace, @@ -739,14 +739,11 @@ class RemoteDBConnection(DBConnection): ) @override - def job(self, job_id: str) -> Job: - """A [Job][lancedb.job.Job] handle for a server-side job by id. - - The handle is constructed without a server round trip; an unknown id - surfaces when the handle is used. Dropping the handle has no effect - on the job itself. + def open_job(self, job_id: str) -> Job: + """Open a server-side job by id. See + [DBConnection.open_job][lancedb.db.DBConnection.open_job]. """ - return Job(self._conn.job(job_id)) + return Job(LOOP.run(self._conn.open_job(job_id))) @override def create_function_async(self, definition: UdfDefinition) -> Job[FunctionVersion]: @@ -769,14 +766,6 @@ class RemoteDBConnection(DBConnection): """List server-side jobs across the database's tables.""" return LOOP.run(self._conn.list_jobs()) - @override - def get_job(self, job_id: str) -> Optional["JobDescription"]: - """Describe a single server-side job by id. - - Returns None when the server has no such job. - """ - return LOOP.run(self._conn.get_job(job_id)) - @override def cancel_job(self, job_id: str) -> bool: """Request cancellation of a server-side job by id. @@ -787,14 +776,6 @@ class RemoteDBConnection(DBConnection): """ return LOOP.run(self._conn.cancel_job(job_id)) - @override - def job_history(self, job_id: Optional[str] = None) -> List[pa.RecordBatch]: - """The lifecycle event history of a server-side job, as Arrow batches. - - Lists history across all jobs when `job_id` is None. - """ - return LOOP.run(self._conn.job_history(job_id)) - @override def execute_query_async( self, diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index add995de1..1e5a71e9a 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -2467,7 +2467,7 @@ def test_remote_blob_byte_apis_not_supported_on_old_server(): def test_remote_connection_jobs_surface(): - from lancedb.exceptions import JobFailedError + from lancedb.exceptions import JobFailedError, JobNotFoundError schema = pa.schema([("state", pa.string())]) batch = pa.record_batch([pa.array(["created", "done"])], schema=schema) @@ -2475,6 +2475,7 @@ def test_remote_connection_jobs_surface(): with pa.ipc.new_stream(sink, schema) as writer: writer.write_batch(batch) events_body = sink.getvalue().to_pybytes() + query_events_payloads = [] def handler(request): content_len = int(request.headers.get("Content-Length", 0)) @@ -2512,6 +2513,22 @@ def test_remote_connection_jobs_surface(): request.end_headers() request.wfile.write(json.dumps(rsp).encode()) elif request.path == "/v1/jobs/describe": + if payload["job_id"] == "job-2": + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + dict( + job_id="job-2", + job_type="refresh_column", + job_state="DONE", + creation_ms=2000, + result=dict(rows_assigned=1000000, rows_failed=0), + ) + ).encode() + ) + return if payload["job_id"] != "job-1": request.send_response(404) request.end_headers() @@ -2543,7 +2560,7 @@ def test_remote_connection_jobs_surface(): request.end_headers() request.wfile.write(b'{"job_id": "job-1"}') elif request.path == "/v1/jobs/query_events": - assert payload["job_id"] == "job-1" + query_events_payloads.append(payload) request.send_response(200) request.send_header("Content-Type", "application/vnd.apache.arrow.stream") request.end_headers() @@ -2559,24 +2576,109 @@ def test_remote_connection_jobs_surface(): assert jobs[0].table == "t1" assert jobs[1].state == "finished" - description = db.get_job("job-1") - assert description.job_type == "create_index" - assert description.state == "failed" - assert json.loads(description.spec_json) == {"column": "vec"} - assert description.failure.message == "worker died" - assert description.failure.retryable is True - assert db.get_job("missing") is None - assert db.cancel_job("job-1") is True assert db.cancel_job("missing") is False - batches = db.job_history("job-1") - assert len(batches) == 1 - assert batches[0].num_rows == 2 - assert batches[0].column("state").to_pylist() == ["created", "done"] + # Opening a job hands back a populated handle; a missing one fails. + with pytest.raises(JobNotFoundError, match="missing"): + db.open_job("missing") + finished = db.open_job("job-2") + assert finished.state == "finished" + assert finished.result == {"rows_assigned": 1000000, "rows_failed": 0} - job = db.job("job-1") + job = db.open_job("job-1") assert job.id == "job-1" + # Opening already populated the handle. + assert job.state == "failed" + assert job.spec == {"column": "vec"} + assert job.failure.message == "worker died" assert job.status() == "failed" with pytest.raises(JobFailedError, match="worker died"): job.wait(timeout=timedelta(seconds=5)) + + +def test_remote_job_handle_reports_its_own_detail(): + schema = pa.schema([("state", pa.string())]) + batch = pa.record_batch([pa.array(["claim_complete"])], schema=schema) + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, schema) as writer: + writer.write_batch(batch) + events_body = sink.getvalue().to_pybytes() + event_payloads = [] + + def handler(request): + content_len = int(request.headers.get("Content-Length", 0)) + body = request.rfile.read(content_len) if content_len > 0 else b"" + payload = json.loads(body) if body else {} + if request.path == "/v1/jobs/describe": + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + dict( + job_id="job-1", + job_type="refresh_column", + job_state="DONE", + creation_ms=2000, + spec=dict(column="vec"), + result=dict(rows_assigned=1000000), + ) + ).encode() + ) + elif request.path == "/v1/jobs/query_events": + event_payloads.append(payload) + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + request.end_headers() + request.wfile.write(events_body) + else: + request.send_response(404) + request.end_headers() + + with mock_lancedb_connection(handler) as db: + job = db.open_job("job-1") + + # Opening populates the handle in the same round trip. + assert job.state == "finished" + job.refresh() + assert job.job_type == "refresh_column" + assert job.creation_ms == 2000 + assert job.spec == {"column": "vec"} + assert job.result == {"rows_assigned": 1000000} + assert job.failure is None + # The JSON payloads stay reachable, but as internal APIs. + 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(", + " id='job-1',", + " state='finished',", + " job_type='refresh_column',", + " creation_ms=2000,", + " spec={", + ' "column": "vec"', + " },", + " result={", + ' "rows_assigned": 1000000', + " },", + ")", + ] + ) + # Nothing it does not know shows up. + assert "failure" not in repr(job) + + events = job.events(filter="state = 'claim_complete'", limit=500) + assert isinstance(events, pa.Table) + assert events.column("state").to_pylist() == ["claim_complete"] + # The handle supplies job_id; the caller only narrows the query. + assert event_payloads[-1] == { + "job_id": "job-1", + "limit": 500, + "filter": "state = 'claim_complete'", + } diff --git a/python/src/connection.rs b/python/src/connection.rs index 882fdfd29..2d613966a 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -13,11 +13,7 @@ use crate::{ runtime::future_into_py, table::Table, }; -use arrow::{ - datatypes::Schema, - ffi_stream::ArrowArrayStreamReader, - pyarrow::{FromPyArrow, ToPyArrow}, -}; +use arrow::{datatypes::Schema, ffi_stream::ArrowArrayStreamReader, pyarrow::FromPyArrow}; use lancedb::{ connection::Connection as LanceConnection, connection::NamespaceClientPushdownOperation, @@ -28,7 +24,7 @@ use pyo3::{ Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python, exceptions::{PyRuntimeError, PyValueError}, pyclass, pyfunction, pymethods, - types::{PyAnyMethods, PyDict, PyDictMethods, PyList, PyListMethods}, + types::{PyAnyMethods, PyDict, PyDictMethods, PyList}, }; #[pyclass] @@ -644,9 +640,12 @@ impl Connection { }) } - pub fn job(&self, job_id: String) -> PyResult { - let inner = self.get_inner()?.clone(); - Ok(crate::job::Job::new(inner.job(job_id).infer_error()?)) + pub fn open_job(self_: PyRef<'_, Self>, job_id: String) -> PyResult> { + 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)) + }) } pub fn create_function_async( @@ -716,38 +715,12 @@ impl Connection { }) } - pub fn get_job(self_: PyRef<'_, Self>, job_id: String) -> PyResult> { - let inner = self_.get_inner()?.clone(); - future_into_py(self_.py(), async move { - let description = inner.get_job(&job_id).await.infer_error()?; - Ok(description.map(crate::job::JobDescription::from)) - }) - } - pub fn cancel_job(self_: PyRef<'_, Self>, job_id: String) -> PyResult> { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { inner.cancel_job(&job_id).await.infer_error() }) } - - #[pyo3(signature = (job_id=None))] - pub fn job_history( - self_: PyRef<'_, Self>, - job_id: Option, - ) -> PyResult> { - let inner = self_.get_inner()?.clone(); - future_into_py(self_.py(), async move { - let batches = inner.job_history(job_id.as_deref()).await.infer_error()?; - Python::attach(|py| { - let list = PyList::empty(py); - for batch in batches { - list.append(batch.to_pyarrow(py)?)?; - } - Ok(list.unbind()) - }) - }) - } } #[pyfunction] diff --git a/python/src/error.rs b/python/src/error.rs index b66afe47b..aa13a8e87 100644 --- a/python/src/error.rs +++ b/python/src/error.rs @@ -114,6 +114,12 @@ impl PythonErrorExt for std::result::Result { .getattr(intern!(py, "JobCancelledError"))?; Err(PyErr::from_value(cls.call1((err.to_string(),))?)) }), + LanceError::JobNotFound { .. } => Python::attach(|py| { + let cls = py + .import(intern!(py, "lancedb.exceptions"))? + .getattr(intern!(py, "JobNotFoundError"))?; + Err(PyErr::from_value(cls.call1((err.to_string(),))?)) + }), _ => self.runtime_error(), }, } diff --git a/python/src/job.rs b/python/src/job.rs index 688cba7f9..4922c701a 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -4,11 +4,50 @@ use std::sync::Arc; use crate::runtime::future_into_py; -use pyo3::{Bound, PyAny, PyRef, PyResult, pyclass, pymethods}; +use arrow::{ + datatypes::Schema, + pyarrow::{IntoPyArrow, Table as PyArrowTable}, +}; +use lancedb::job::JobEventsRequest; +use pyo3::{ + Bound, PyAny, PyRef, PyResult, Python, + exceptions::PyValueError, + pyclass, pymethods, + types::{PyAnyMethods, PyDict, PyDictMethods}, +}; use serde::Serialize; use crate::error::PythonErrorExt; +const REPR_INDENT: &str = " "; + +/// Parse a stored JSON payload into Python data. The bindings carry these as +/// strings because that is what crosses the boundary cheaply; the public +/// Python surface is the parsed form. +fn parse_json_payload<'py>( + py: Python<'py>, + raw: Option<&str>, +) -> PyResult>> { + match raw { + None => Ok(None), + Some(raw) => Ok(Some(py.import("json")?.call_method1("loads", (raw,))?)), + } +} + +/// A payload rendered as indented JSON, aligned under the field that holds it. +fn pretty_json_payload(py: Python<'_>, raw: Option<&str>) -> PyResult> { + let Some(parsed) = parse_json_payload(py, raw)? else { + return Ok(None); + }; + let kwargs = PyDict::new(py); + kwargs.set_item("indent", 4)?; + let rendered: String = py + .import("json")? + .call_method("dumps", (parsed,), Some(&kwargs))? + .extract()?; + Ok(Some(rendered.replace('\n', &format!("\n{REPR_INDENT}")))) +} + #[pyclass] pub struct Job { inner: Arc, String>>>, @@ -67,6 +106,48 @@ impl Job { Ok(()) }) } + + pub fn refresh(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.inner.clone(); + future_into_py(self_.py(), async move { + inner.refresh().await.infer_error()?; + Ok(()) + }) + } + + /// The last observed lifecycle state, without contacting the backend. + #[getter] + pub fn _state(&self) -> Option { + self.inner.state() + } + + /// The last observed server-side record. `None` for an in-process job. + #[getter] + pub fn _description(&self) -> Option { + self.inner.description().map(JobDescription::from) + } + + #[pyo3(signature = (*, limit=None, filter=None))] + pub fn events( + self_: PyRef<'_, Self>, + limit: Option, + filter: Option, + ) -> PyResult> { + let inner = self_.inner.clone(); + let request = JobEventsRequest { limit, filter }; + future_into_py(self_.py(), async move { + let batches = inner.events(request).await.infer_error()?; + Python::attach(|py| { + let schema = batches + .first() + .map(|batch| batch.schema()) + .unwrap_or_else(|| Arc::new(Schema::empty())); + let table = PyArrowTable::try_new(batches, schema) + .map_err(|err| PyValueError::new_err(err.to_string()))?; + table.into_pyarrow(py).map(|table| table.unbind()) + }) + }) + } } /// A row from `Connection.list_jobs`: one server-side job. @@ -121,7 +202,7 @@ impl JobFailureInfo { } } -/// A described job from `Connection.get_job`. +/// The server-side record behind a `Job` handle. #[pyclass(get_all, skip_from_py_object)] #[derive(Clone)] pub struct JobDescription { @@ -129,17 +210,49 @@ pub struct JobDescription { job_type: String, state: String, creation_ms: i64, - spec_json: Option, + /// Internal: the wire form behind the `spec` property. + _spec_json: Option, + /// Internal: the wire form behind the `result` property. + _result_json: Option, failure: Option, } #[pymethods] impl JobDescription { - fn __repr__(&self) -> String { - format!( - "JobDescription(job_id={:?}, job_type={:?}, state={:?}, creation_ms={})", - self.job_id, self.job_type, self.state, self.creation_ms - ) + /// The job-type-specific specification it was submitted with. + #[getter] + fn spec<'py>(&self, py: Python<'py>) -> PyResult>> { + parse_json_payload(py, self._spec_json.as_deref()) + } + + /// The job-type-specific terminal result. `None` until the job succeeds. + #[getter] + fn result<'py>(&self, py: Python<'py>) -> PyResult>> { + parse_json_payload(py, self._result_json.as_deref()) + } + + fn __repr__(&self, py: Python<'_>) -> PyResult { + let mut fields = vec![ + format!("job_id={:?}", self.job_id), + format!("job_type={:?}", self.job_type), + format!("state={:?}", self.state), + format!("creation_ms={}", self.creation_ms), + ]; + // Lay the payloads out as indented JSON, the same way the `Job` repr + // does, so the two agree on how the same data looks. + for (name, payload) in [("spec", &self._spec_json), ("result", &self._result_json)] { + if let Some(rendered) = pretty_json_payload(py, payload.as_deref())? { + fields.push(format!("{name}={rendered}")); + } + } + if let Some(failure) = &self.failure { + fields.push(format!("failure={}", failure.__repr__())); + } + let body = fields + .iter() + .map(|field| format!("\n{REPR_INDENT}{field},")) + .collect::(); + Ok(format!("JobDescription({body}\n)")) } } @@ -150,7 +263,11 @@ impl From for JobDescription { job_type: description.job_type, state: description.state, creation_ms: description.creation_ms, - spec_json: (!description.spec.is_null()).then(|| description.spec.to_string()), + _spec_json: (!description.spec.is_null()).then(|| description.spec.to_string()), + _result_json: description + .result + .filter(|result| !result.is_null()) + .map(|result| result.to_string()), failure: description.failure.map(|failure| JobFailureInfo { phase: failure.phase, message: failure.message, diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index f04f04ce2..6ec4a6ec1 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, JobDescription, JobInfo, OpenTableRequest, - ReadConsistency, TableNamesRequest, + CloneTableRequest, Database, DatabaseOptions, JobInfo, OpenTableRequest, ReadConsistency, + TableNamesRequest, }; use crate::embeddings::{EmbeddingRegistry, MemoryRegistry}; use crate::error::{Error, Result}; @@ -670,14 +670,34 @@ impl Connection { self.internal.read_consistency().await } - /// A [`crate::job::Job`] handle for a server-side job by id, suitable for - /// waiting on or cancelling the job. + /// Open a server-side job by id, returning a handle with its record + /// already populated. Fails with [`crate::Error::JobNotFound`] when the + /// server has no such job, the way [`Connection::open_table`] does for a + /// missing table. /// - /// The handle is constructed without a server round trip; an unknown id - /// surfaces when the handle is used. Only server-backed databases support - /// job handles by id. - pub fn job(&self, job_id: impl AsRef) -> Result { - self.internal.job(job_id.as_ref()) + /// This is the one way in: the returned [`crate::job::Job`] answers for + /// its own state, specification, result, failure and event history, so + /// there is no separate connection-level call for any of them. + /// + /// # Example + /// + /// ```no_run + /// # use lancedb::job::JobEventsRequest; + /// # async fn open_job( + /// # connection: &lancedb::Connection, + /// # job_id: &str, + /// # ) -> Result<(), Box> { + /// let job = connection.open_job(job_id).await?; + /// println!("{:?} {:?}", job.state(), job.result()); + /// let done = job + /// .events(JobEventsRequest::default().filter("state = 'claim_complete'")) + /// .await?; + /// println!("{} completions", done.iter().map(|b| b.num_rows()).sum::()); + /// # Ok(()) + /// # } + /// ``` + pub async fn open_job(&self, job_id: impl AsRef) -> Result { + self.internal.open_job(job_id.as_ref()).await } /// List server-side jobs across the database's tables. @@ -685,24 +705,12 @@ impl Connection { self.internal.list_jobs().await } - /// Describe a single server-side job by id. `None` when the server has no - /// such job. - pub async fn get_job(&self, job_id: impl AsRef) -> Result> { - self.internal.get_job(job_id.as_ref()).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 { self.internal.cancel_job(job_id.as_ref()).await } - /// The lifecycle event history of a server-side job (all jobs when - /// `job_id` is `None`), as recorded Arrow batches. - pub async fn job_history(&self, job_id: Option<&str>) -> Result> { - self.internal.job_history(job_id).await - } - /// Drop a table in the database. /// /// # Arguments diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 532ea3658..843170030 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -18,8 +18,6 @@ use std::collections::HashMap; use std::sync::Arc; use std::time::Duration; -use arrow_array::RecordBatch; - use lance::dataset::ReadParams; use lance_namespace::LanceNamespace; use lance_namespace::models::{ @@ -206,8 +204,8 @@ pub enum ReadConsistency { /// compaction, column refresh, ...). #[derive(Debug, Clone)] pub struct JobInfo { - /// The job id -- what [`Database::get_job`] and [`Database::cancel_job`] - /// accept. + /// The job id -- what [`Database::open_job`] and + /// [`Database::cancel_job`] accept. pub job_id: String, /// The table the job runs against, without URI or namespace. pub table: String, @@ -218,8 +216,8 @@ pub struct JobInfo { pub created_at_millis: i64, } -/// A described job from [`Database::get_job`]: lifecycle state plus the -/// job-type-specific specification. +/// The server-side record behind a [`crate::job::Job`] handle: lifecycle +/// state plus the job-type-specific specification and result. #[derive(Debug, Clone)] pub struct JobDescription { pub job_id: String, @@ -230,6 +228,10 @@ pub struct JobDescription { pub creation_ms: i64, /// The job-type-specific specification. Null when the server omits it. pub spec: serde_json::Value, + /// The job-type-specific terminal result, for job types that define one. + /// `None` until the job succeeds, so a job that never terminates reports + /// its progress through [`crate::job::Job::events`] instead. + pub result: Option, /// Why the job failed, when the job is failed and the server reports a /// reason. pub failure: Option, @@ -315,31 +317,22 @@ pub trait Database: async fn drop_function(&self, _name: &str, _version: &str) -> Result { function_catalog_not_supported() } - /// A [`crate::job::Job`] handle for a server-side job by id, suitable for - /// waiting on or cancelling the job. The handle is constructed without a - /// server round trip; an unknown id surfaces when the handle is used. - fn job(&self, _job_id: &str) -> Result { - job_op_not_supported("job") + /// Open a job by id, returning a handle with its record already + /// populated. Fails with [`crate::Error::JobNotFound`] when the server has + /// no such job. + async fn open_job(&self, _job_id: &str) -> Result { + job_op_not_supported("open_job") } /// List server-side jobs across the database's tables. async fn list_jobs(&self) -> Result> { job_op_not_supported("list_jobs") } - /// Describe a single job by id. `None` when the server has no such job. - async fn get_job(&self, _job_id: &str) -> Result> { - job_op_not_supported("get_job") - } /// 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. async fn cancel_job(&self, _job_id: &str) -> Result { job_op_not_supported("cancel_job") } - /// The lifecycle event history of a job (all jobs when `job_id` is - /// `None`), as recorded Arrow batches. - async fn job_history(&self, _job_id: Option<&str>) -> Result> { - job_op_not_supported("job_history") - } /// Start executing a SQL statement on a remote database. async fn execute_query_async( &self, diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index be4641388..f6a2df9a6 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -102,6 +102,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 }, // 3rd party / external errors #[snafu(display("object_store error: {source}"))] diff --git a/rust/lancedb/src/job.rs b/rust/lancedb/src/job.rs index 22f1a0450..54b46fc11 100644 --- a/rust/lancedb/src/job.rs +++ b/rust/lancedb/src/job.rs @@ -3,16 +3,53 @@ //! Handles to operations a server may run asynchronously. -use std::sync::Arc; +use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard}; +use arrow_array::RecordBatch; use async_trait::async_trait; use serde::{Serialize, de::DeserializeOwned}; use serde_json::Value; use tokio::sync::watch; use tokio::task::{AbortHandle, JoinHandle}; +use crate::database::JobDescription; use crate::error::{Error, JobFailure, Result}; +/// Which of a job's events [`Job::events`] returns. +/// +/// The handle already knows which job to ask about, so this narrows the +/// query rather than naming one. +#[derive(Debug, Clone, Default)] +pub struct JobEventsRequest { + /// Maximum event rows to return. The server applies its own default + /// (1000 rows) and maximum (10,000 rows) when this is `None`, and + /// truncates without saying so, which matters for a job with one event + /// per fragment. + pub limit: Option, + /// SQL-like filter over the event columns `state`, `updated_by`, + /// `emitted_from`, `emitted_by`, and `claim_entity`. For example + /// `state = 'claim_complete'` selects only per-claim completions. + pub filter: Option, +} + +impl JobEventsRequest { + pub fn limit(mut self, limit: u32) -> Self { + self.limit = Some(limit); + self + } + + pub fn filter(mut self, filter: impl Into) -> Self { + self.filter = Some(filter.into()); + self + } +} + +fn job_detail_not_supported(what: &str) -> Result { + Err(Error::NotSupported { + message: format!("{what} is only available for server-side jobs"), + }) +} + /// Backend-specific tracking for an asynchronous operation. #[async_trait] pub(crate) trait JobHandle: Send + Sync { @@ -23,6 +60,15 @@ pub(crate) trait JobHandle: Send + Sync { async fn status(&self) -> Result; async fn wait(&self) -> Result; async fn cancel(&self) -> Result<()>; + /// The job's full server-side record. Backends that run the operation in + /// this process have none and keep the default. + async fn describe(&self) -> Result { + job_detail_not_supported("describing a job") + } + /// The job's recorded lifecycle events. + async fn events(&self, _request: JobEventsRequest) -> Result> { + job_detail_not_supported("job event history") + } } /// A backend-neutral successful terminal result. @@ -85,16 +131,34 @@ enum JobInner { Completed(T), } +/// What a handle last learned about its job. `state` is separate because an +/// in-process job can report one but has no server-side record behind it. +#[derive(Default)] +struct JobCache { + state: Option, + description: Option, +} + /// A handle to an operation that may still be running. /// /// The operation may already be complete when the handle is created. `T` is /// the endpoint's successful terminal result; unit-result operations use the /// default `Job<()>`. +/// +/// The detail accessors ([`Job::state`], [`Job::job_type`], ...) read what the +/// handle last observed. Submitting an operation returns only a job id, so +/// populating them eagerly would cost an extra round trip on every call: +/// +/// - [`Job::refresh`] and [`Job::status`] fetch the whole record. +/// - [`Job::wait`] records the terminal state it establishes, but not the rest +/// of the record; call [`Job::refresh`] for that. +/// - Everything is `None` until one of those runs. pub struct Job where T: Clone + Send + Sync + 'static, { inner: JobInner, + cache: RwLock, } impl std::fmt::Debug for Job @@ -102,18 +166,40 @@ where T: Clone + Send + Sync + 'static, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Job") - .field("id", &self.id()) - .field("done", &matches!(self.inner, JobInner::Completed(_))) - .finish() + let cache = self.cache_read(); + let mut out = f.debug_struct("Job"); + out.field("id", &self.id()) + .field("done", &matches!(self.inner, JobInner::Completed(_))); + if let Some(state) = &cache.state { + out.field("state", state); + } + if let Some(description) = &cache.description { + out.field("job_type", &description.job_type) + .field("creation_ms", &description.creation_ms); + if !description.spec.is_null() { + out.field("spec", &description.spec); + } + if let Some(result) = &description.result { + out.field("result", result); + } + if let Some(failure) = &description.failure { + out.field("failure", failure); + } + } + out.finish() } } impl Job<()> { - /// A job whose operation finished before the handle was created. + /// A job whose operation finished before the handle was created. Its + /// state is known without asking anyone, so the cache starts populated. pub(crate) fn new_done() -> Self { Self { inner: JobInner::Completed(()), + cache: RwLock::new(JobCache { + state: Some("finished".to_string()), + description: None, + }), } } @@ -123,8 +209,21 @@ impl Job<()> { handle, decode: Arc::new(|_| Ok(())), }, + cache: RwLock::default(), } } + + /// A handle whose record the caller has already fetched, so the detail + /// accessors answer without a second round trip. + pub(crate) fn opened(handle: Box, description: JobDescription) -> Self { + let job = Self::new(handle); + { + let mut cache = job.cache_write(); + cache.state = Some(description.state.clone()); + cache.description = Some(description); + } + job + } } impl Job @@ -138,6 +237,7 @@ where handle, decode: Arc::new(TerminalResult::decode::), }, + cache: RwLock::default(), } } } @@ -169,16 +269,124 @@ where } } + fn cache_read(&self) -> RwLockReadGuard<'_, JobCache> { + self.cache.read().unwrap_or_else(|err| err.into_inner()) + } + + fn cache_write(&self) -> RwLockWriteGuard<'_, JobCache> { + self.cache.write().unwrap_or_else(|err| err.into_inner()) + } + + /// Asks the backend for this job's current state, and for a server-side + /// job its full record, then caches the answer for the detail accessors. + /// + /// In-process operations have no server-side record, so only + /// [`Job::state`] is populated for them. + pub async fn refresh(&self) -> Result<()> { + self.refresh_state().await.map(|_| ()) + } + + /// Refreshes and reports the state, which every backend can answer. + async fn refresh_state(&self) -> Result { + let JobInner::Handle { handle, .. } = &self.inner else { + let state = "finished".to_string(); + self.cache_write().state = Some(state.clone()); + return Ok(state); + }; + match handle.describe().await { + Ok(description) => { + let state = description.state.clone(); + let mut cache = self.cache_write(); + cache.state = Some(state.clone()); + cache.description = Some(description); + Ok(state) + } + // An in-process job knows its own state and nothing more. + Err(Error::NotSupported { .. }) => { + let state = handle.status().await?; + self.cache_write().state = Some(state.clone()); + Ok(state) + } + Err(err) => Err(err), + } + } + /// The operation's current lifecycle state: "running", "finished", /// "failed", or "cancelled". /// /// A point snapshot; unlike [`Job::wait`] it does not block, raise on a /// terminal failure state, or retry. States a newer server reports that - /// this client version does not know pass through as-is. + /// this client version does not know pass through as-is. Also refreshes + /// the detail accessors. pub async fn status(&self) -> Result { + self.refresh_state().await + } + + /// The last lifecycle state this handle observed, without contacting the + /// backend. `None` until the handle has. + pub fn state(&self) -> Option { + self.cache_read().state.clone() + } + + /// The whole server-side record this handle last observed. The accessors + /// below read individual fields out of it. `None` for an in-process job, + /// which has no such record. + pub fn description(&self) -> Option { + self.cache_read().description.clone() + } + + /// The job's type, as the server names it. `None` for an in-process job. + pub fn job_type(&self) -> Option { + self.with_description(|description| description.job_type.clone()) + } + + /// When the job was created, in milliseconds since the epoch. `None` for + /// an in-process job. + pub fn creation_ms(&self) -> Option { + self.with_description(|description| description.creation_ms) + } + + /// The job-type-specific specification it was submitted with. + pub fn spec(&self) -> Option { + self.with_description(|description| description.spec.clone()) + .filter(|spec| !spec.is_null()) + } + + /// The job-type-specific terminal result, as reported data rather than the + /// typed model [`Job::wait`] returns. `None` until the job succeeds. + pub fn result(&self) -> Option { + self.with_description(|description| description.result.clone()) + .flatten() + } + + /// Why the job failed, when it failed and the server reports a reason. + pub fn failure(&self) -> Option { + self.with_description(|description| description.failure.clone()) + .flatten() + } + + fn with_description(&self, read: impl FnOnce(&JobDescription) -> R) -> Option { + self.cache_read().description.as_ref().map(read) + } + + /// This job's recorded lifecycle events. + /// + /// Unlike the detail accessors, which report a terminal result only once + /// the job reaches one, events are written as the job runs and outlive the + /// workers that produced them. A distributed job records a + /// `claim`/`claim_complete` pair per unit of work, each carrying + /// `rows_processed`, so a job that never finishes still accounts for what + /// it did. In-process operations keep no event history. + pub async fn events(&self, request: JobEventsRequest) -> Result> { match &self.inner { - JobInner::Handle { handle, .. } => handle.status().await, - JobInner::Completed(_) => Ok("finished".to_string()), + JobInner::Handle { handle, .. } => handle.events(request).await, + // The operation finished before the handle existed, so there is no + // id to query with even when a server ran it. + JobInner::Completed(_) => Err(Error::NotSupported { + message: "this operation completed before its handle was created, so it \ + carries no job id to query events with" + .to_string(), + }), } } @@ -190,8 +398,19 @@ where /// [`crate::Error::JobCancelled`] if it was cancelled. pub async fn wait(&self) -> Result { match &self.inner { - JobInner::Handle { handle, decode } => (decode)(handle.wait().await?), - JobInner::Completed(result) => Ok(result.clone()), + JobInner::Handle { handle, decode } => { + let settled = handle.wait().await; + // Waiting already established a terminal state; record it so + // the detail accessors do not need another round trip for it. + if let Some(state) = terminal_state(&settled) { + self.cache_write().state = Some(state.to_string()); + } + (decode)(settled?) + } + JobInner::Completed(result) => { + self.cache_write().state = Some("finished".to_string()); + Ok(result.clone()) + } } } @@ -224,20 +443,36 @@ where U: Clone + Send + Sync + 'static, F: Fn(T) -> U + Send + Sync + 'static, { - match self.inner { + // The mapped handle tracks the same job, so it inherits what this one + // has already learned about it. + let Self { inner, cache } = self; + match inner { JobInner::Handle { handle, decode } => Job { inner: JobInner::Handle { handle, decode: Arc::new(move |result| Ok(map((decode)(result)?))), }, + cache, }, JobInner::Completed(result) => Job { inner: JobInner::Completed(map(result)), + cache, }, } } } +/// The lifecycle state a settled [`JobHandle::wait`] implies. +fn terminal_state(settled: &Result) -> Option<&'static str> { + match settled { + Ok(_) => Some("finished"), + Err(Error::JobFailed { .. }) => Some("failed"), + Err(Error::JobCancelled { .. }) => Some("cancelled"), + // Anything else is a transport failure, not a verdict on the job. + Err(_) => None, + } +} + /// How an in-process operation ended. Cloneable so every waiter can be given /// the outcome; [`Error`] is not, so failures share one behind an [`Arc`]. #[derive(Clone)] diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 87486a522..32ace368e 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -20,13 +20,13 @@ use lance_namespace::models::{ use crate::Error; use crate::database::{ - CloneTableRequest, CreateTableMode, CreateTableRequest, Database, DatabaseOptions, - JobDescription, JobInfo, OpenTableRequest, ReadConsistency, TableNamesRequest, + CloneTableRequest, CreateTableMode, CreateTableRequest, Database, DatabaseOptions, JobInfo, + OpenTableRequest, ReadConsistency, TableNamesRequest, }; use crate::error::Result; use crate::function::{FunctionRegistrationRequest, FunctionVersion}; use crate::job::Job; -use crate::remote::job::{DescribeJobResponse, RemoteJob, job_state_to_client}; +use crate::remote::job::{RemoteJob, job_state_to_client}; use crate::remote::util::stream_as_body; use crate::table::BaseTable; @@ -671,11 +671,18 @@ impl Database for RemoteDatabase { Ok(response.dropped) } - fn job(&self, job_id: &str) -> Result { - Ok(crate::job::Job::new(Box::new(super::job::RemoteJob::new( - self.client.clone(), - job_id.to_string(), - )))) + async fn open_job(&self, job_id: &str) -> Result { + 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 { + job_id: job_id.to_string(), + }), + Err(err) => Err(err), + } } async fn list_jobs(&self) -> Result> { @@ -712,31 +719,6 @@ impl Database for RemoteDatabase { Ok(out) } - async fn get_job(&self, job_id: &str) -> Result> { - let req = self - .client - .post("/v1/jobs/describe") - .json(&serde_json::json!({ "job_id": job_id })); - let (request_id, rsp) = self.client.send(req).await?; - let rsp = match self.client.check_response(&request_id, rsp).await { - Ok(rsp) => rsp, - Err(Error::Http { - status_code: Some(StatusCode::NOT_FOUND), - .. - }) => return Ok(None), - Err(err) => return Err(err), - }; - let body: DescribeJobResponse = rsp.json().await.err_to_http(request_id)?; - Ok(Some(JobDescription { - job_id: body.job_id, - job_type: body.job_type, - state: job_state_to_client(&body.job_state), - creation_ms: body.creation_ms, - spec: body.spec, - failure: body.failure.map(|reported| reported.into_job_failure()), - })) - } - async fn cancel_job(&self, job_id: &str) -> Result { let req = self .client @@ -753,21 +735,6 @@ impl Database for RemoteDatabase { } } - async fn job_history(&self, job_id: Option<&str>) -> Result> { - let mut body = serde_json::json!({}); - if let Some(job_id) = job_id { - body["job_id"] = serde_json::Value::String(job_id.to_string()); - } - let req = self.client.post("/v1/jobs/query_events").json(&body); - let (request_id, rsp) = self.client.send(req).await?; - let rsp = self.client.check_response(&request_id, rsp).await?; - let bytes = rsp.bytes().await.err_to_http(request_id)?; - let reader = arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(bytes), None)?; - reader - .collect::, _>>() - .map_err(Into::into) - } - async fn execute_query_async( &self, query: &str, @@ -1307,6 +1274,7 @@ mod tests { use crate::{ Connection, Error, database::CreateTableMode, + job::JobEventsRequest, remote::{ARROW_STREAM_CONTENT_TYPE, ClientConfig, HeaderProvider, JSON_CONTENT_TYPE}, }; @@ -2655,7 +2623,7 @@ mod tests { } #[tokio::test] - async fn test_get_job() { + async fn test_open_job() { let conn = Connection::new_with_handler(|request| { assert_eq!(request.method(), &reqwest::Method::POST); assert_eq!(request.url().path(), "/v1/jobs/describe"); @@ -2669,51 +2637,55 @@ mod tests { ) .unwrap() }); - let job = conn.get_job("job-1").await.unwrap().unwrap(); - assert_eq!(job.job_id, "job-1"); - assert_eq!(job.job_type, "create_index"); - assert_eq!(job.state, "failed"); - assert_eq!(job.creation_ms, 1000); - assert_eq!(job.spec["column"], "vec"); - let failure = job.failure.unwrap(); + // Opening populates the handle, so the accessors answer without a + // second round trip. + let job = conn.open_job("job-1").await.unwrap(); + assert_eq!(job.id(), Some("job-1")); + assert_eq!(job.job_type().as_deref(), Some("create_index")); + assert_eq!(job.state().as_deref(), Some("failed")); + assert_eq!(job.creation_ms(), Some(1000)); + assert_eq!(job.spec().unwrap()["column"], "vec"); + assert!(job.result().is_none()); + let failure = job.failure().unwrap(); assert_eq!(failure.phase.as_deref(), Some("execute")); assert_eq!(failure.message.as_deref(), Some("worker died")); assert_eq!(failure.retryable, Some(true)); } #[tokio::test] - async fn test_get_job_missing_is_none() { + async fn test_open_job_reports_the_terminal_result() { let conn = Connection::new_with_handler(|_| { - http::Response::builder() - .status(404) - .body("no such job") - .unwrap() - }); - assert!(conn.get_job("nope").await.unwrap().is_none()); - } - - #[tokio::test] - async fn test_cancel_job() { - let conn = Connection::new_with_handler(|request| { - assert_eq!(request.url().path(), "/v1/jobs/cancel"); http::Response::builder() .status(200) - .body(r#"{"job_id": "job-1"}"#) + .body( + r#"{"job_id": "job-1", "job_type": "refresh_column", "job_state": "DONE", "creation_ms": 1000, "result": {"rows_assigned": 1000000, "rows_failed": 0}}"#, + ) .unwrap() }); - assert!(conn.cancel_job("job-1").await.unwrap()); + let job = conn.open_job("job-1").await.unwrap(); + assert_eq!(job.state().as_deref(), Some("finished")); + let result = job.result().unwrap(); + assert_eq!(result["rows_assigned"], 1_000_000); + assert_eq!(result["rows_failed"], 0); + } + #[tokio::test] + async fn test_open_job_missing_fails() { let conn = Connection::new_with_handler(|_| { http::Response::builder() .status(404) .body("no such job") .unwrap() }); - assert!(!conn.cancel_job("nope").await.unwrap()); + let err = conn.open_job("nope").await.unwrap_err(); + assert!( + matches!(&err, Error::JobNotFound { job_id } if job_id == "nope"), + "{err:?}" + ); } #[tokio::test] - async fn test_job_history_parses_arrow_stream() { + async fn test_job_events_scope_to_that_job() { let schema = Arc::new(Schema::new(vec![Field::new( "state", DataType::Utf8, @@ -2722,29 +2694,91 @@ mod tests { let batch = RecordBatch::try_new( schema.clone(), vec![Arc::new(arrow_array::StringArray::from(vec![ - "created", "done", + "claim_complete", ]))], ) .unwrap(); - let mut body = Vec::new(); + let mut events = Vec::new(); { - let mut writer = arrow_ipc::writer::StreamWriter::try_new(&mut body, &schema).unwrap(); + let mut writer = + arrow_ipc::writer::StreamWriter::try_new(&mut events, &schema).unwrap(); writer.write(&batch).unwrap(); writer.finish().unwrap(); } let conn = Connection::new_with_handler(move |request| { - assert_eq!(request.url().path(), "/v1/jobs/query_events"); - let req_body: serde_json::Value = + let body: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); - assert_eq!(req_body["job_id"], "job-1"); + if request.url().path() == "/v1/jobs/describe" { + return http::Response::builder() + .status(200) + .body( + r#"{"job_id": "job-1", "job_type": "refresh_column", "job_state": "IN_PROGRESS", "creation_ms": 1}"# + .as_bytes() + .to_vec(), + ) + .unwrap(); + } + assert_eq!(request.url().path(), "/v1/jobs/query_events"); + // The handle supplies job_id; the caller only narrows the query. + assert_eq!(body["job_id"], "job-1"); + assert_eq!(body["limit"], 500); + assert_eq!(body["filter"], "state = 'claim_complete'"); http::Response::builder() .status(200) - .body(body.clone()) + .body(events.clone()) .unwrap() }); - let batches = conn.job_history(Some("job-1")).await.unwrap(); + let job = conn.open_job("job-1").await.unwrap(); + let batches = job + .events( + JobEventsRequest::default() + .limit(500) + .filter("state = 'claim_complete'"), + ) + .await + .unwrap(); assert_eq!(batches.len(), 1); - assert_eq!(batches[0].num_rows(), 2); + assert_eq!(batches[0].num_rows(), 1); + } + + #[tokio::test] + async fn test_job_events_keep_the_schema_when_nothing_matches() { + let schema = Arc::new(Schema::new(vec![Field::new( + "state", + DataType::Utf8, + false, + )])); + let mut events = Vec::new(); + { + let mut writer = + arrow_ipc::writer::StreamWriter::try_new(&mut events, &schema).unwrap(); + writer.finish().unwrap(); + } + let conn = Connection::new_with_handler(move |request| { + if request.url().path() == "/v1/jobs/describe" { + return http::Response::builder() + .status(200) + .body( + r#"{"job_id": "job-1", "job_type": "refresh_column", "job_state": "IN_PROGRESS", "creation_ms": 1}"# + .as_bytes() + .to_vec(), + ) + .unwrap(); + } + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + // Only the job id when the caller narrows nothing. + assert_eq!(body, serde_json::json!({ "job_id": "job-1" })); + http::Response::builder() + .status(200) + .body(events.clone()) + .unwrap() + }); + let job = conn.open_job("job-1").await.unwrap(); + let batches = job.events(JobEventsRequest::default()).await.unwrap(); + assert_eq!(batches.len(), 1); + assert_eq!(batches[0].num_rows(), 0); + assert_eq!(batches[0].schema(), schema); } #[tokio::test] @@ -2939,7 +2973,9 @@ mod tests { let polls_ref = polls.clone(); let conn = Connection::new_with_handler(move |request| { assert_eq!(request.url().path(), "/v1/jobs/describe"); - let state = if polls_ref.fetch_add(1, Ordering::SeqCst) == 0 { + // Two in-progress answers: one for the load, one for the first + // status poll. + let state = if polls_ref.fetch_add(1, Ordering::SeqCst) < 2 { "IN_PROGRESS" } else { "DONE" @@ -2952,11 +2988,13 @@ mod tests { )) .unwrap() }); - let job = conn.job("job-1").unwrap(); + let job = conn.open_job("job-1").await.unwrap(); assert_eq!(job.id(), Some("job-1")); + // Opening already answered the state; no extra call needed for it. + assert_eq!(job.state().as_deref(), Some("running")); assert_eq!(job.status().await.unwrap(), "running"); job.wait().await.unwrap(); assert_eq!(job.status().await.unwrap(), "finished"); - assert!(polls.load(Ordering::SeqCst) >= 3); + assert!(polls.load(Ordering::SeqCst) >= 4); } } diff --git a/rust/lancedb/src/remote/job.rs b/rust/lancedb/src/remote/job.rs index 0d41dbb35..c7acc3c05 100644 --- a/rust/lancedb/src/remote/job.rs +++ b/rust/lancedb/src/remote/job.rs @@ -5,13 +5,15 @@ use std::time::Duration; +use arrow_array::RecordBatch; use async_trait::async_trait; use tokio::time::sleep; use serde::Deserialize; +use crate::database::JobDescription; use crate::error::{Error, JobFailure, Result}; -use crate::job::{JobHandle, TerminalResult}; +use crate::job::{JobEventsRequest, JobHandle, TerminalResult}; use crate::remote::client::{HttpSend, RequestResultExt, RestfulLanceDbClient}; /// Delay before the second job-state poll; doubles up to [`MAX_POLL_INTERVAL`]. @@ -86,7 +88,7 @@ pub(super) struct DescribeJobResponse { #[serde(default)] pub(super) spec: serde_json::Value, #[serde(default)] - result: Option, + pub(super) result: Option, #[serde(default)] pub(super) failure: Option, } @@ -110,6 +112,39 @@ impl DescribeJobResponse { fn into_terminal_result(self, request_id: String) -> TerminalResult { TerminalResult::remote(self.result, request_id) } + + /// The public description this wire envelope stands for. + pub(super) fn into_description(self) -> JobDescription { + JobDescription { + job_id: self.job_id, + job_type: self.job_type, + state: JobState::from(self.job_state.as_str()).client_label(), + creation_ms: self.creation_ms, + spec: self.spec, + result: self.result, + failure: self.failure.map(ReportedFailure::into_job_failure), + } + } +} + +/// One `/v1/jobs/query_events` round trip. +pub(super) async fn fetch_job_events( + client: &RestfulLanceDbClient, + body: serde_json::Value, +) -> Result> { + let request = client.post("/v1/jobs/query_events").json(&body); + let (request_id, response) = client.send(request).await?; + let response = client.check_response(&request_id, response).await?; + let bytes = response.bytes().await.err_to_http(request_id)?; + let reader = arrow_ipc::reader::StreamReader::try_new(std::io::Cursor::new(bytes), None)?; + let schema = reader.schema(); + let mut batches = reader.collect::, _>>()?; + // A query that matched nothing still describes the event columns. + // Keep that schema so callers can build a typed empty result. + if batches.is_empty() { + batches.push(RecordBatch::new_empty(schema)); + } + Ok(batches) } pub struct RemoteJob { @@ -123,7 +158,7 @@ impl RemoteJob { } /// One `/v1/jobs/describe` round trip. - async fn describe(&self) -> Result<(String, DescribeJobResponse)> { + async fn fetch_description(&self) -> Result<(String, DescribeJobResponse)> { let request = self .client .post("/v1/jobs/describe") @@ -148,13 +183,28 @@ impl JobHandle for RemoteJob { } async fn status(&self) -> Result { - Ok(self.describe().await?.1.state().client_label()) + Ok(self.fetch_description().await?.1.state().client_label()) + } + + async fn describe(&self) -> Result { + Ok(self.fetch_description().await?.1.into_description()) + } + + async fn events(&self, request: JobEventsRequest) -> Result> { + let mut body = serde_json::json!({ "job_id": self.job_id }); + if let Some(limit) = request.limit { + body["limit"] = serde_json::Value::from(limit); + } + if let Some(filter) = request.filter { + body["filter"] = serde_json::Value::String(filter); + } + fetch_job_events(&self.client, body).await } async fn wait(&self) -> Result { let mut interval = INITIAL_POLL_INTERVAL; loop { - let (request_id, description) = self.describe().await?; + let (request_id, description) = self.fetch_description().await?; match description.state() { JobState::Done => return Ok(description.into_terminal_result(request_id)), JobState::Failed => { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 5faffa8c7..89885061e 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -264,6 +264,17 @@ impl crate::job::JobHandle for FreshnessJob { crate::job::JobHandle::status(&self.inner).await } + async fn describe(&self) -> Result { + crate::job::JobHandle::describe(&self.inner).await + } + + async fn events( + &self, + request: crate::job::JobEventsRequest, + ) -> Result> { + crate::job::JobHandle::events(&self.inner, request).await + } + async fn wait(&self) -> Result { let result = crate::job::JobHandle::wait(&self.inner).await?; let version = self.version.read().await; @@ -7982,6 +7993,72 @@ mod tests { ); } + /// The refresh handle is wrapped for read-freshness tracking, so it has to + /// forward the detail APIs too -- this is the job an operator is holding + /// when a backfill goes quiet. + #[tokio::test] + async fn test_refresh_job_handle_reports_detail_and_events() { + let schema = Arc::new(Schema::new(vec![Field::new( + "state", + DataType::Utf8, + false, + )])); + let batch = RecordBatch::try_new( + schema.clone(), + vec![Arc::new(arrow_array::StringArray::from(vec![ + "claim_complete", + ]))], + ) + .unwrap(); + let mut events = Vec::new(); + { + let mut writer = + arrow_ipc::writer::StreamWriter::try_new(&mut events, &schema).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + } + let table = Table::new_with_handler("my_table", move |request| { + match request.url().path() { + "/v1/table/my_table/backfill_column" => http::Response::builder() + .status(202) + .body(r#"{"job_id": "j-42"}"#.as_bytes().to_vec()) + .unwrap(), + "/v1/jobs/describe" => http::Response::builder() + .status(200) + .body( + r#"{"job_id": "j-42", "job_type": "refresh_column", "job_state": "IN_PROGRESS", "creation_ms": 7, "spec": {"column": "doubled"}}"# + .as_bytes() + .to_vec(), + ) + .unwrap(), + "/v1/jobs/query_events" => { + 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(events.clone()) + .unwrap() + } + other => panic!("unexpected path {other}"), + } + }); + + let job = table.refresh_column_async("doubled").await.unwrap(); + job.refresh().await.unwrap(); + assert_eq!(job.state().as_deref(), Some("running")); + assert_eq!(job.job_type().as_deref(), Some("refresh_column")); + assert_eq!(job.creation_ms(), Some(7)); + assert_eq!(job.spec().unwrap()["column"], "doubled"); + + let batches = job + .events(crate::job::JobEventsRequest::default()) + .await + .unwrap(); + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::(), 1); + } + #[tokio::test] async fn test_refresh_submission_uses_add_columns_version_fence() { let table = Table::new_with_handler("my_table", |request| match request.url().path() { From e5cc7a4d6685a2ffa33a727ec268e7e2c35c6d82 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sat, 5 Sep 2026 23:25:29 +0000 Subject: [PATCH 179/206] =?UTF-8?q?Bump=20version:=200.39.0-beta.1=20?= =?UTF-8?q?=E2=86=92=200.39.0-beta.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index bd1db72ee..63315af84 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.39.0-beta.1" +current_version = "0.39.0-beta.2" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index d0c3dc408..b5a1638a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5474,7 +5474,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.39.0-beta.1" +version = "0.39.0-beta.2" dependencies = [ "ahash", "anyhow", @@ -5565,7 +5565,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.39.0-beta.1" +version = "0.39.0-beta.2" dependencies = [ "arrow-array", "arrow-buffer", @@ -5590,7 +5590,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.39.0-beta.1" +version = "0.39.0-beta.2" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 80245cc15..1148fc00d 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.39.0-beta.1 + 0.39.0-beta.2 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 1b9e68776..97e96b7c8 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.1 + 0.39.0-beta.2 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 01fe2ce85..07fbb76b0 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.1 + 0.39.0-beta.2 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 4968bc7ca..8c43fcb06 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.39.0-beta.1" +version = "0.39.0-beta.2" 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 d7b592fa4..e338330bc 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.39.0-beta.1", + "version": "0.39.0-beta.2", "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 8aad32ca9..76c511628 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.39.0-beta.1", + "version": "0.39.0-beta.2", "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 72fd1b4ec..184d37bb1 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.39.0-beta.1", + "version": "0.39.0-beta.2", "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 0d9c4b92b..23a80c14e 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.39.0-beta.1", + "version": "0.39.0-beta.2", "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 ed5388426..5d725363c 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.39.0-beta.1", + "version": "0.39.0-beta.2", "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 35a650b22..d6060c676 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.39.0-beta.1", + "version": "0.39.0-beta.2", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index b4fedadfa..c658351ab 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.39.0-beta.1", + "version": "0.39.0-beta.2", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 49de9080b..8c5c9fb74 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.39.0-beta.1", + "version": "0.39.0-beta.2", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 850752925..896764ab8 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.39.0-beta.1" +version = "0.39.0-beta.2" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 836bffa4f..18389520a 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.39.0-beta.1" +version = "0.39.0-beta.2" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 1b0f9329ea6a42048cd3cf0ec0cf85ed370b023b Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sun, 6 Sep 2026 01:58:40 -0700 Subject: [PATCH 180/206] fix: compare Function output list children by type only (#4137) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A table whose Function output type contains a list cannot be appended to. That is every embedding column. `add()` re-validates the table's own schema against its bindings before it looks at the incoming data, so the failure does not depend on what you are writing: ``` ValueError: Invalid input, Function output 'udf_text_embedding_384' type no longer matches binding 'fb_...' ``` The check required a list child to be identical to the declaration. Lance rewrites a list item's name and nullability when it writes, so a declared `fixed_size_list` is stored as `fixed_size_list` and never matches again. The server already draws this distinction — `job_executor::function_arrow_type::equivalent` compares list children by type and struct children by identity — which is why declaring the column succeeded in the first place. This brings the client's copy of the check into line so the two agree on what a valid Function column looks like. Struct children still compare by name and nullability, and the list length is still part of the declaration. --- rust/lancedb/src/table/computed_columns.rs | 214 ++++++++++++++++----- 1 file changed, 170 insertions(+), 44 deletions(-) diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 0fcc5485d..21d4f3016 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -759,14 +759,33 @@ fn function_output_field(name: &str, nullable: bool, raw: &str) -> Result bool { - expected.name() == actual.name() - && expected.is_nullable() == actual.is_nullable() - && if expected.is_blob_v2() { +/// Whether two fields describe the same Function output. +/// +/// `compare_identity` covers the field's own name and nullability. Struct +/// children carry both as part of the declaration and compare with it on. List +/// children do not: Lance rewrites a list item's name and nullability when it +/// writes, so a stored `fixed_size_list` comes back as +/// `fixed_size_list` and never matches the declaration again. +/// Comparing those by type alone keeps this agreeing with the server, which +/// draws the same distinction and is what accepted the column when it was +/// declared. +fn function_output_field_matches( + expected: &ArrowField, + actual: &ArrowField, + compare_identity: bool, +) -> bool { + if compare_identity + && (expected.name() != actual.name() || expected.is_nullable() != actual.is_nullable()) + { + return false; + } + match (expected.is_blob_v2(), actual.is_blob_v2()) { + (false, false) => function_output_type_matches(expected.data_type(), actual.data_type()), + (true, true) => { has_supported_blob_v2_layout(expected) && has_supported_blob_v2_layout(actual) - } else { - function_output_type_matches(expected.data_type(), actual.data_type()) } + _ => false, + } } fn function_output_type_matches(expected: &DataType, actual: &DataType) -> bool { @@ -779,33 +798,19 @@ fn function_output_type_matches(expected: &DataType, actual: &DataType) -> bool && expected .iter() .zip(actual) - .all(|(expected, actual)| function_output_field_matches(expected, actual)) + .all(|(expected, actual)| function_output_field_matches(expected, actual, true)) } (DataType::List(expected), DataType::List(actual)) | (DataType::LargeList(expected), DataType::LargeList(actual)) => { - function_output_field_matches(expected, actual) + function_output_field_matches(expected, actual, false) } ( DataType::FixedSizeList(expected, expected_size), DataType::FixedSizeList(actual, actual_size), - ) => expected_size == actual_size && function_output_field_matches(expected, actual), + ) => expected_size == actual_size && function_output_field_matches(expected, actual, false), (DataType::Map(expected, expected_sorted), DataType::Map(actual, actual_sorted)) => { - expected_sorted == actual_sorted && function_output_field_matches(expected, actual) - } - _ => false, - } -} - -fn function_output_type_has_blob(data_type: &DataType) -> bool { - match data_type { - DataType::Struct(fields) => fields - .iter() - .any(|field| field.is_blob_v2() || function_output_type_has_blob(field.data_type())), - DataType::List(field) - | DataType::LargeList(field) - | DataType::FixedSizeList(field, _) - | DataType::Map(field, _) => { - field.is_blob_v2() || function_output_type_has_blob(field.data_type()) + expected_sorted == actual_sorted + && function_output_field_matches(expected, actual, true) } _ => false, } @@ -891,16 +896,13 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding binding.binding_id() ))); } - let (type_matches, has_semantic_blob) = if output.arrow_type == FUNCTION_BLOB_V2_TYPE { - (has_supported_blob_v2_layout(field), true) + let type_matches = if output.arrow_type == FUNCTION_BLOB_V2_TYPE { + has_supported_blob_v2_layout(field) } else { let expected_type = parse_output_arrow_type(&output.arrow_type)?; let expected_type = lance_namespace::schema::convert_json_arrow_type(&expected_type) .map_err(|e| invalid_function(format!("invalid Function output type: {e}")))?; - ( - function_output_type_matches(&expected_type, field.data_type()), - function_output_type_has_blob(&expected_type), - ) + function_output_type_matches(&expected_type, field.data_type()) }; if !type_matches { return Err(invalid_function(format!( @@ -931,19 +933,16 @@ fn ensure_binding_matches_schema(schema: &ArrowSchema, binding: &FunctionBinding binding.binding_id() ))); } - if has_semantic_blob { - output_fields.push(function_output_field( - field.name(), - true, - &output.arrow_type, - )?); - } else { - let json = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ - ArrowField::new(field.name().clone(), field.data_type().clone(), true), - ])) - .map_err(|e| invalid_function(format!("invalid Function output schema: {e}")))?; - output_fields.push(json.fields.into_iter().next().unwrap()); - } + // Rebuild from the declaration rather than from the stored field. The + // stored field carries Lance's write-time normalization, which would + // never round-trip back to the schema the binding recorded -- the same + // reason list children compare by type above. Whether the column on + // disk still matches is settled by that comparison, not here. + output_fields.push(function_output_field( + field.name(), + true, + &output.arrow_type, + )?); } if let Some(assignment) = binding.assignment() { if binding @@ -1815,6 +1814,69 @@ mod tests { assert!(super::validate_declarations(schema, &declarations).is_err()); } + #[test] + fn list_children_match_by_type_but_struct_children_by_identity() { + use arrow_schema::Field as F; + + // Lance rewrites a list item's name and nullability on write, so the + // stored field is no longer identical to what was declared. Comparing + // those by type keeps a table with a vector output usable. + let declared = + DataType::FixedSizeList(Arc::new(F::new("item", DataType::Float32, false)), 4); + let stored = DataType::FixedSizeList(Arc::new(F::new("item", DataType::Float32, true)), 4); + assert!(super::function_output_type_matches(&declared, &stored)); + + let renamed = + DataType::FixedSizeList(Arc::new(F::new("element", DataType::Float32, true)), 4); + assert!(super::function_output_type_matches(&declared, &renamed)); + + // The dimension is still part of the declaration. + let resized = DataType::FixedSizeList(Arc::new(F::new("item", DataType::Float32, true)), 8); + assert!(!super::function_output_type_matches(&declared, &resized)); + + // Struct children keep comparing by name and nullability. + let struct_declared = + DataType::Struct(vec![F::new("changed", DataType::Boolean, false)].into()); + let struct_nullable = + DataType::Struct(vec![F::new("changed", DataType::Boolean, true)].into()); + let struct_renamed = + DataType::Struct(vec![F::new("altered", DataType::Boolean, false)].into()); + assert!(super::function_output_type_matches( + &struct_declared, + &struct_declared + )); + assert!(!super::function_output_type_matches( + &struct_declared, + &struct_nullable + )); + assert!(!super::function_output_type_matches( + &struct_declared, + &struct_renamed + )); + + // A list nested inside a struct gets the list rule. + let nested_declared = DataType::Struct( + vec![F::new( + "tokens", + DataType::List(Arc::new(F::new("item", DataType::Utf8, false))), + true, + )] + .into(), + ); + let nested_stored = DataType::Struct( + vec![F::new( + "tokens", + DataType::List(Arc::new(F::new("item", DataType::Utf8, true))), + true, + )] + .into(), + ); + assert!(super::function_output_type_matches( + &nested_declared, + &nested_stored + )); + } + #[test] fn output_arrow_type_grammar_matches_the_shared_golden() { let golden: serde_json::Value = serde_json::from_str(include_str!( @@ -3289,6 +3351,70 @@ mod tests { assert!(output_schema.field(0).is_blob_v2()); } + #[test] + fn binding_accepts_a_lance_normalized_list_child() { + // The whole guard, not just the type helper: this also reaches the + // output-schema comparison at the end of ensure_binding_matches_schema, + // which used to rebuild the schema from the stored field and so failed + // on exactly the same normalization. + let input = ArrowField::new("value", DataType::Int64, false); + let application = FunctionApplication::from_json( + &serde_json::json!({ + "function": {"name": "embed", "version": "fv_embed"}, + "inputs": [{ + "parameter": "value", + "kind": "column", + "value": {"path": "value"} + }], + "output": { + "kind": "scalar", + "arrow_type": "fixed_size_list", + "nullable": false + } + }) + .to_string(), + ) + .unwrap(); + let plan = plan_function_application( + &ArrowSchema::new(vec![input.clone()]), + &application, + Some("embedding"), + ) + .unwrap(); + let binding = binding_from_plan(&plan); + + // The declaration says the item is non-nullable; Lance rewrites it to + // nullable on write, so this is what the column looks like on disk. + let stored = DataType::FixedSizeList( + Arc::new(ArrowField::new("item", DataType::Float32, true)), + 4, + ); + let output = ArrowField::new("embedding", stored, true).with_metadata( + function_computed_column_metadata(binding.binding_id(), 0, &["value".into()]), + ); + + ensure_binding_matches_schema(&ArrowSchema::new(vec![input.clone(), output]), &binding) + .unwrap(); + + // A different element type is still a mismatch. + let wrong = ArrowField::new( + "embedding", + DataType::FixedSizeList( + Arc::new(ArrowField::new("item", DataType::Float64, true)), + 4, + ), + true, + ) + .with_metadata(function_computed_column_metadata( + binding.binding_id(), + 0, + &["value".into()], + )); + assert!( + ensure_binding_matches_schema(&ArrowSchema::new(vec![input, wrong]), &binding).is_err() + ); + } + #[test] fn test_blob_scalar_binding_accepts_full_logical_layout() { let input = crate::blob("image", false); From c7980dbc40538c946b8055178dd874adc3f44ed7 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 6 Sep 2026 08:59:24 +0000 Subject: [PATCH 181/206] =?UTF-8?q?Bump=20version:=200.39.0-beta.2=20?= =?UTF-8?q?=E2=86=92=200.39.0-beta.3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 63315af84..3ee1dd9c1 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.39.0-beta.2" +current_version = "0.39.0-beta.3" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index b5a1638a0..081a64a5f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5474,7 +5474,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.39.0-beta.2" +version = "0.39.0-beta.3" dependencies = [ "ahash", "anyhow", @@ -5565,7 +5565,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.39.0-beta.2" +version = "0.39.0-beta.3" dependencies = [ "arrow-array", "arrow-buffer", @@ -5590,7 +5590,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.39.0-beta.2" +version = "0.39.0-beta.3" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 1148fc00d..173c444ad 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.39.0-beta.2 + 0.39.0-beta.3 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 97e96b7c8..550d81f5f 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.2 + 0.39.0-beta.3 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 07fbb76b0..b8a34293a 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.2 + 0.39.0-beta.3 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 8c43fcb06..1d0bf8bda 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.39.0-beta.2" +version = "0.39.0-beta.3" 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 e338330bc..35f40bbd1 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.39.0-beta.2", + "version": "0.39.0-beta.3", "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 76c511628..44399c991 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.39.0-beta.2", + "version": "0.39.0-beta.3", "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 184d37bb1..f83601e48 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.39.0-beta.2", + "version": "0.39.0-beta.3", "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 23a80c14e..8fecdcb29 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.39.0-beta.2", + "version": "0.39.0-beta.3", "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 5d725363c..d1a73a67b 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.39.0-beta.2", + "version": "0.39.0-beta.3", "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 d6060c676..1fc109c66 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.39.0-beta.2", + "version": "0.39.0-beta.3", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index c658351ab..b37a0e781 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.39.0-beta.2", + "version": "0.39.0-beta.3", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 8c5c9fb74..534e63a7b 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.39.0-beta.2", + "version": "0.39.0-beta.3", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 896764ab8..8d971bd77 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.39.0-beta.2" +version = "0.39.0-beta.3" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 18389520a..4b4aec1a6 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.39.0-beta.2" +version = "0.39.0-beta.3" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 02ea0dda9fb4589943ff18b39012294a73b249d5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 6 Sep 2026 09:41:24 -0700 Subject: [PATCH 182/206] build(deps-dev): bump the nodejs-deps group across 1 directory with 2 updates (#4134) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps the nodejs-deps group with 2 updates in the /nodejs directory: [@opentelemetry/sdk-metrics](https://github.com/open-telemetry/opentelemetry-js) and [ts-jest](https://github.com/kulshekhar/ts-jest). Updates `@opentelemetry/sdk-metrics` from 2.10.0 to 2.11.0
Release notes

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

v2.11.0

2.11.0

:rocket: Features

  • feat(context-async-hooks): implement attach() on AsyncLocalStorageContextManager #6845 @​pichlermarc
    • On Node.js 25.9+, delegates to AsyncLocalStorage.withScope() returning a native RunScope. On older Node.js, falls back to enterWith() with a manual disposable wrapper.
  • feat(sdk-trace): allow configuring the force flush timeout per call #6929 @​LarryHu0217

:bug: Bug Fixes

  • fix(sdk-metrics): ignore Infinity in exponential histograms #7015 @​mwear

:house: Internal

  • perf(sdk-metrics): reuse a single DataView for exponential histogram bit reads #6998 @​mwear
  • chore(ci): run documentation tests on a weekly schedule #6920 @​LarryHu0217
  • feat(ci): support pre-releases and major version bumps in the release workflow #6768 @​pichlermarc
  • chore(resources): Ensure that multiple uses of serviceInstanceIdDetector.detect() return the same value for service.instance.id
Changelog

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

2.11.0

:rocket: Features

  • feat(context-async-hooks): implement attach() on AsyncLocalStorageContextManager #6845 @​pichlermarc
    • On Node.js 25.9+, delegates to AsyncLocalStorage.withScope() returning a native RunScope. On older Node.js, falls back to enterWith() with a manual disposable wrapper.
  • feat(sdk-trace): allow configuring the force flush timeout per call #6929 @​LarryHu0217

:bug: Bug Fixes

  • fix(sdk-trace-base): avoid a Webpack self-reference error in CommonJS output #6981 @​sansynx
  • fix(sdk-metrics): ignore Infinity in exponential histograms #7015 @​mwear

:house: Internal

  • perf(sdk-metrics): reuse a single DataView for exponential histogram bit reads #6998 @​mwear
  • chore(ci): run documentation tests on a weekly schedule #6920 @​LarryHu0217
  • feat(ci): support pre-releases and major version bumps in the release workflow #6768 @​pichlermarc
  • chore(resources): Ensure that multiple uses of serviceInstanceIdDetector.detect() return the same value for service.instance.id
Commits
  • 0b72a81 chore: prepare next release (#7044)
  • a9c5338 ci: roll prerelease changelog into one final release changelog (#7045)
  • f41805e chore: prepare next release (#7042)
  • b85eb28 chore(instrumentation-http): fix lint errors (#7039)
  • 3f92530 ci: support pre-releases and major version bumps in release workflow (#7035)
  • 82a5831 docs(otlp-exporter-base): document HTTP exporter options (#6735)
  • e086dec Merge commit from fork
  • 59dac70 chore(deps): update jamesives/github-pages-deploy-action action to v4.9.0 (#7...
  • d0ce753 chore: add @​maryliag to maintainers (#7024)
  • 03469a1 chore(deps): update open-telemetry/shared-workflows action to v0.10.0 (#7032)
  • Additional commits viewable in compare view

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

Sourced from ts-jest's releases.

v29.4.12

Please refer to CHANGELOG.md for details.

v29.4.11

Please refer to CHANGELOG.md for details.

v29.4.10

Please refer to CHANGELOG.md for details.

Changelog

Sourced from ts-jest's changelog.

29.4.12 (2026-07-22)

Features

  • compiler: support TypeScript 7 projects through compatibility aliases (#5386)

29.4.11 (2026-05-21)

Bug Fixes

  • preserve Bundler on the CJS path under TypeScript >= 6 (3941818), closes #4198

29.4.10 (2026-05-18)

Bug Fixes

  • pass resolutionMode to ts.resolveModuleName for hybrid module support (b557a85)
  • rebuild Program when consecutive compiles need different module kinds (a82a2b3), closes #4774
  • respect tsconfig moduleResolution instead of forcing Node10 (1bffffc)
  • transformer: transpile mjs files from node_modules for CJS mode (96d025d)
  • transformer: use a consistent comparator in hoist-jest sortStatements (8a8fd2f)
Commits
  • 3f05625 chore(release): 29.4.12
  • df28b27 docs: clarify TypeScript version prerequisites
  • c8a614a docs: mention TypeScript 7 setup in README
  • 06c79d4 fix: address TypeScript 7 review feedback
  • f107460 docs: explain TypeScript 7 compatibility setup
  • 3388227 test(e2e): add TypeScript compatibility matrix
  • 891dc73 fix(compiler): support TypeScript 7 compatibility aliases
  • eb135eb build(deps-dev): bump shell-quote from 1.8.4 to 1.10.0 in /examples
  • d5d80a3 ci: pin google osv scan action at v2.3.5
  • 6bf293f build(deps): bump shell-quote from 1.8.4 to 1.10.0 in /website
  • 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> --- nodejs/pnpm-lock.yaml | 48 +++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/nodejs/pnpm-lock.yaml b/nodejs/pnpm-lock.yaml index f10db2f3f..a03838999 100644 --- a/nodejs/pnpm-lock.yaml +++ b/nodejs/pnpm-lock.yaml @@ -41,7 +41,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.10.0(@opentelemetry/api@1.9.1) + version: 2.11.0(@opentelemetry/api@1.9.1) '@types/axios': specifier: ^0.14.0 version: 0.14.4 @@ -80,7 +80,7 @@ importers: version: 0.2.7 ts-jest: specifier: ^29.1.2 - version: 29.4.9(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4) + version: 29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4) typedoc: specifier: 0.26.4 version: 0.26.4(typescript@5.5.4) @@ -1394,20 +1394,20 @@ packages: resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==} engines: {node: '>=8.0.0'} - '@opentelemetry/core@2.10.0': - resolution: {integrity: sha512-/wNZ8twnEQQA4HoHu22+vcsdru6pWPWxW+7w+FlxT6Id7PE/WIbZmVKkte+PF72e0F2dnImFeHD2syyE1Mw6MQ==} + '@opentelemetry/core@2.11.0': + resolution: {integrity: sha512-7YP44XH0tV6+Mb54x2YGf84i7yi+31MBZlE8JwvozkxyTvXbSp10X7cI7YE49ChJ3shMJoBmCJF3+1QFBJctGA==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.0.0 <1.10.0' - '@opentelemetry/resources@2.10.0': - resolution: {integrity: sha512-q6MMm2zhggzsHVNbabYwut+a6nbuQQe3URUoxaojM/8K1IBfwwPzvxIjNi2/lI1TFe+fMHMW9MWhrtDLEXEnkA==} + '@opentelemetry/resources@2.11.0': + resolution: {integrity: sha512-Ie7+8q8MDF4FAEQCKVMTx3ReUvxiIAgIiiW3c9JdmP8+HMcDy20puT+AHjexnExgnbvBxjQ9fjkFDWrikJ2jQA==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.3.0 <1.10.0' - '@opentelemetry/sdk-metrics@2.10.0': - resolution: {integrity: sha512-t6r1VSvXNtSDnPXU1FbZeetJb7yyovHmgu0wRSoftxtE0g2rSNhQZQUy69sRUCL+iioJpX8SN/S6wq6ZtvLySQ==} + '@opentelemetry/sdk-metrics@2.11.0': + resolution: {integrity: sha512-7GXXcObyHyDUUSG+L+kJoquty01bzm7ivE7+SSgXXJcHuPzGviptxwARmI2c+bnnxjexGQbJnyNlN8HxBP/Y7A==} engines: {node: ^18.19.0 || >=20.6.0} peerDependencies: '@opentelemetry/api': '>=1.9.0 <1.10.0' @@ -1480,6 +1480,7 @@ 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 '@smithy/credential-provider-imds@4.3.1': resolution: {integrity: sha512-0S/acwHnqX4WrjXzhdiDRxsG2s9SC0cpPIK9nZ1R6UOHd+j7uL28+4bHu22urbLk2TVw3fkp6na/+fkUt/pLNQ==} @@ -3238,8 +3239,8 @@ packages: peerDependencies: typescript: '>=4.2.0' - ts-jest@29.4.9: - resolution: {integrity: sha512-LTb9496gYPMCqjeDLdPrKuXtncudeV1yRZnF4Wo5l3SFi0RYEnYRNgMrFIdg+FHvfzjCyQk1cLncWVqiSX+EvQ==} + ts-jest@29.4.12: + resolution: {integrity: sha512-Ov6ClY53Fflh6BGAnY2DlTq1hYDrTycz2PVTXBWFW2CU+9zrEqAp9fWdGXl42EXO5RLSFAcAZ2JFKbP+zBTFfw==} engines: {node: ^14.15.0 || ^16.10.0 || ^18.0.0 || >=20.0.0} hasBin: true peerDependencies: @@ -5110,22 +5111,22 @@ snapshots: '@opentelemetry/api@1.9.1': {} - '@opentelemetry/core@2.10.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/core@2.11.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/resources@2.10.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/resources@2.11.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) + '@opentelemetry/core': 2.11.0(@opentelemetry/api@1.9.1) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/sdk-metrics@2.10.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/sdk-metrics@2.11.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.10.0(@opentelemetry/api@1.9.1) + '@opentelemetry/core': 2.11.0(@opentelemetry/api@1.9.1) + '@opentelemetry/resources': 2.11.0(@opentelemetry/api@1.9.1) '@opentelemetry/semantic-conventions@1.43.0': {} @@ -5574,7 +5575,7 @@ snapshots: globby: 11.1.0 is-glob: 4.0.3 minimatch: 9.0.9 - semver: 7.8.0 + semver: 7.8.5 ts-api-utils: 1.4.3(typescript@5.5.4) optionalDependencies: typescript: 5.5.4 @@ -6426,7 +6427,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.5 transitivePeerDependencies: - supports-color @@ -6705,7 +6706,7 @@ snapshots: jest-util: 29.7.0 natural-compare: 1.4.0 pretty-format: 29.7.0 - semver: 7.8.0 + semver: 7.8.5 transitivePeerDependencies: - supports-color @@ -6828,7 +6829,7 @@ snapshots: make-dir@4.0.0: dependencies: - semver: 7.8.0 + semver: 7.8.5 make-error@1.3.6: {} @@ -7162,8 +7163,7 @@ snapshots: semver@7.8.0: {} - semver@7.8.5: - optional: true + semver@7.8.5: {} sharp@0.35.4(@types/node@22.7.4): dependencies: @@ -7327,7 +7327,7 @@ snapshots: dependencies: typescript: 5.5.4 - ts-jest@29.4.9(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4): + ts-jest@29.4.12(@babel/core@7.29.7)(@jest/transform@29.7.0)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(jest-util@29.7.0)(jest@29.7.0(@types/node@22.7.4))(typescript@5.5.4): dependencies: bs-logger: 0.2.6 fast-json-stable-stringify: 2.1.0 @@ -7336,7 +7336,7 @@ snapshots: json5: 2.2.3 lodash.memoize: 4.1.2 make-error: 1.3.6 - semver: 7.8.0 + semver: 7.8.5 type-fest: 4.41.0 typescript: 5.5.4 yargs-parser: 21.1.1 From a487d4033ea34a657cabc8270b6731f239597600 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Sun, 6 Sep 2026 13:43:35 -0700 Subject: [PATCH 183/206] chore: update lance dependency to v12.0.0-beta.14 (#4141) Update the Rust workspace Lance dependencies and Java lance-core from v12.0.0-beta.11 to [v12.0.0-beta.14](https://github.com/lance-format/lance/releases/tag/v12.0.0-beta.14), refreshing Cargo.lock. Resolve two Clippy diagnostics by making an internal Node.js helper private and using a byte string literal in a remote-table test fixture. Validation: `cargo clippy --quiet --workspace --tests --all-features -- -D warnings`, `cargo fmt --all --quiet`, `git diff --check`, and `pnpm build` in nodejs. --------- Co-authored-by: Jack Ye --- Cargo.lock | 90 ++++++++-------- Cargo.toml | 28 ++--- java/pom.xml | 2 +- nodejs/src/job.rs | 2 +- rust/lancedb/src/remote/table.rs | 2 +- .../src/table/datafusion/blob_coerce.rs | 100 +++++++++++++++++- 6 files changed, 161 insertions(+), 63 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 081a64a5f..2d16a7259 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3526,8 +3526,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4886,8 +4886,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arc-swap", "arrow", @@ -4959,8 +4959,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow-array", "arrow-buffer", @@ -4982,7 +4982,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow-array", "arrow-buffer", @@ -4996,7 +4996,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow-array", "arrow-schema", @@ -5005,8 +5005,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrayref", "crunchy", @@ -5016,8 +5016,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow-array", "arrow-buffer", @@ -5054,8 +5054,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow", "arrow-array", @@ -5085,8 +5085,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow", "arrow-array", @@ -5103,8 +5103,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "proc-macro2", "quote", @@ -5113,8 +5113,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow-arith", "arrow-array", @@ -5147,8 +5147,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow-arith", "arrow-array", @@ -5179,8 +5179,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arc-swap", "arrow", @@ -5244,8 +5244,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow-array", "arrow-schema", @@ -5267,8 +5267,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow", "arrow-array", @@ -5308,8 +5308,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow-array", "arrow-schema", @@ -5323,21 +5323,23 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow", "async-trait", "bytes", "lance-core", "lance-namespace-reqwest-client", + "serde", + "serde_json", "snafu 0.9.0", ] [[package]] name = "lance-namespace-impls" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow", "arrow-ipc", @@ -5376,9 +5378,9 @@ dependencies = [ [[package]] name = "lance-namespace-reqwest-client" -version = "0.11.1" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d06b1fbb5d41f93bc652b61e2872af92e8a6c5f6b4ce8839a8ecfa05365d359" +checksum = "d8d23e54b1634d5bbb434f8dd33dc3c05f6e58d876a9a27b3b4aef58ddbe11af" dependencies = [ "reqwest 0.12.28", "serde", @@ -5390,8 +5392,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow-array", "arrow-buffer", @@ -5405,8 +5407,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow", "arrow-array", @@ -5446,8 +5448,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "arrow-array", "arrow-schema", @@ -5460,8 +5462,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "12.0.0-beta.11" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.11#4a0e26895729feb86d0cb9c09d551bfd619c6472" +version = "12.0.0-beta.14" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 63ebeb75a..5c5b0362d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=12.0.0-beta.11", default-features = false, "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=12.0.0-beta.11", default-features = false, "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=12.0.0-beta.11", default-features = false, "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=12.0.0-beta.11", "tag" = "v12.0.0-beta.11", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=12.0.0-beta.14", default-features = false, "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=12.0.0-beta.14", default-features = false, "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=12.0.0-beta.14", default-features = false, "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index b8a34293a..4359c74cc 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 12.0.0-beta.11 + 12.0.0-beta.14 false 2.30.0 1.7 diff --git a/nodejs/src/job.rs b/nodejs/src/job.rs index 9c6559dfd..214e687b4 100644 --- a/nodejs/src/job.rs +++ b/nodejs/src/job.rs @@ -127,7 +127,7 @@ impl Job { } /// Serialise Arrow batches as a single IPC stream for the TypeScript layer. -pub(crate) fn batches_to_ipc_buffer(batches: &[RecordBatch]) -> napi::Result { +fn batches_to_ipc_buffer(batches: &[RecordBatch]) -> napi::Result { let Some(first) = batches.first() else { return Ok(Buffer::from(Vec::::new())); }; diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 89885061e..5c32e3cdd 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -8021,7 +8021,7 @@ mod tests { match request.url().path() { "/v1/table/my_table/backfill_column" => http::Response::builder() .status(202) - .body(r#"{"job_id": "j-42"}"#.as_bytes().to_vec()) + .body(br#"{"job_id": "j-42"}"#.to_vec()) .unwrap(), "/v1/jobs/describe" => http::Response::builder() .status(200) diff --git a/rust/lancedb/src/table/datafusion/blob_coerce.rs b/rust/lancedb/src/table/datafusion/blob_coerce.rs index 0596e7a2d..3b79ec022 100644 --- a/rust/lancedb/src/table/datafusion/blob_coerce.rs +++ b/rust/lancedb/src/table/datafusion/blob_coerce.rs @@ -5,12 +5,17 @@ //! //! [`super::cast::cast_to_table_schema`] calls [`coerce_blob_expr`]. +use std::fmt; +use std::hash::{Hash, Hasher}; use std::sync::Arc; -use arrow_schema::{DataType, Field, FieldRef, Fields}; +use arrow_array::{Array, BooleanArray, RecordBatch}; +use arrow_schema::{DataType, Field, FieldRef, Fields, Schema}; +use arrow_select::nullif::nullif; use datafusion::functions::core::{get_field, named_struct}; use datafusion_common::ScalarValue; use datafusion_common::config::ConfigOptions; +use datafusion_expr::ColumnarValue; use datafusion_physical_expr::ScalarFunctionExpr; use datafusion_physical_expr::expressions::{CastExpr, Literal}; use datafusion_physical_plan::PhysicalExpr; @@ -133,16 +138,102 @@ pub(super) fn coerce_blob_expr( ns_args.push(value); } - let expr: Arc = Arc::new(ScalarFunctionExpr::new( + let built: Arc = Arc::new(ScalarFunctionExpr::new( &format!("named_struct({})", table_field.name()), named_struct(), ns_args, table_field.clone(), config.clone(), )); + + // `named_struct` always yields a valid struct, so a null input would land + // as a row that set neither `data` nor `uri` -- not an absent blob but a + // malformed one, which Lance rejects on write. + let expr: Arc = Arc::new(AbsentBlobIsNull { + source: input_expr, + built, + field: table_field.clone(), + }); Ok((expr, table_field.clone())) } +/// Carries the source column's nullity onto the struct built for it. +/// +/// This is its own expression rather than a `CASE` because the projection +/// takes its output field from `return_field`, and the generic implementation +/// rebuilds a bare field -- which would drop the `lance.blob.v2` extension +/// metadata and stop the column being recognised as a blob at all. +#[derive(Debug, Clone)] +struct AbsentBlobIsNull { + source: Arc, + built: Arc, + field: FieldRef, +} + +impl fmt::Display for AbsentBlobIsNull { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "absent_blob_is_null({}, {})", self.source, self.built) + } +} + +impl PartialEq for AbsentBlobIsNull { + fn eq(&self, other: &Self) -> bool { + self.source.eq(&other.source) && self.built.eq(&other.built) && self.field == other.field + } +} + +impl Eq for AbsentBlobIsNull {} + +impl Hash for AbsentBlobIsNull { + fn hash(&self, state: &mut H) { + self.source.hash(state); + self.built.hash(state); + self.field.hash(state); + } +} + +impl PhysicalExpr for AbsentBlobIsNull { + fn return_field(&self, _input_schema: &Schema) -> datafusion_common::Result { + Ok(self.field.clone()) + } + + fn nullable(&self, _input_schema: &Schema) -> datafusion_common::Result { + Ok(true) + } + + fn evaluate(&self, batch: &RecordBatch) -> datafusion_common::Result { + let rows = batch.num_rows(); + let built = self.built.evaluate(batch)?.into_array(rows)?; + let source = self.source.evaluate(batch)?.into_array(rows)?; + let Some(nulls) = source.logical_nulls() else { + return Ok(ColumnarValue::Array(built)); + }; + // `nullif` nulls the rows the mask marks true, which is where the + // source had no value. + let absent = BooleanArray::new(!nulls.inner(), None); + Ok(ColumnarValue::Array(nullif(built.as_ref(), &absent)?)) + } + + fn children(&self) -> Vec<&Arc> { + vec![&self.source, &self.built] + } + + fn with_new_children( + self: Arc, + children: Vec>, + ) -> datafusion_common::Result> { + Ok(Arc::new(Self { + source: children[0].clone(), + built: children[1].clone(), + field: self.field.clone(), + })) + } + + fn fmt_sql(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{self}") + } +} + enum BlobInputShape<'a> { Bytes, String, @@ -313,6 +404,11 @@ mod tests { let data = image.column_by_name("data").unwrap(); assert!(!data.is_null(0)); assert!(data.is_null(1)); + // The row itself has to be null, not merely a struct whose children + // are. A present-but-empty struct set neither `data` nor `uri`, which + // Lance rejects as malformed rather than reading as an absent blob. + assert!(!image.is_null(0)); + assert!(image.is_null(1)); } #[tokio::test] From 0111a72dc3ad7eebc52d197bb5447e26ce02df43 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Sun, 6 Sep 2026 20:46:25 +0000 Subject: [PATCH 184/206] =?UTF-8?q?Bump=20version:=200.39.0-beta.3=20?= =?UTF-8?q?=E2=86=92=200.39.0-beta.4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 3ee1dd9c1..215d1bf4a 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.39.0-beta.3" +current_version = "0.39.0-beta.4" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 2d16a7259..2042305e5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5476,7 +5476,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.39.0-beta.3" +version = "0.39.0-beta.4" dependencies = [ "ahash", "anyhow", @@ -5567,7 +5567,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.39.0-beta.3" +version = "0.39.0-beta.4" dependencies = [ "arrow-array", "arrow-buffer", @@ -5592,7 +5592,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.39.0-beta.3" +version = "0.39.0-beta.4" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 173c444ad..96fb7c11a 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.39.0-beta.3 + 0.39.0-beta.4 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 550d81f5f..1b995bff0 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.3 + 0.39.0-beta.4 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 4359c74cc..4eca407af 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.3 + 0.39.0-beta.4 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 1d0bf8bda..b58c97af8 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.39.0-beta.3" +version = "0.39.0-beta.4" 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 35f40bbd1..a8f14f9db 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.39.0-beta.3", + "version": "0.39.0-beta.4", "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 44399c991..0d49b045f 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.39.0-beta.3", + "version": "0.39.0-beta.4", "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 f83601e48..418656624 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.39.0-beta.3", + "version": "0.39.0-beta.4", "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 8fecdcb29..5a46b698f 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.39.0-beta.3", + "version": "0.39.0-beta.4", "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 d1a73a67b..4e6ab2967 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.39.0-beta.3", + "version": "0.39.0-beta.4", "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 1fc109c66..003db2da7 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.39.0-beta.3", + "version": "0.39.0-beta.4", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index b37a0e781..0cc18c6f6 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.39.0-beta.3", + "version": "0.39.0-beta.4", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 534e63a7b..aa571aff6 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.39.0-beta.3", + "version": "0.39.0-beta.4", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 8d971bd77..9b21acb9e 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.39.0-beta.3" +version = "0.39.0-beta.4" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 4b4aec1a6..f206677f4 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.39.0-beta.3" +version = "0.39.0-beta.4" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 1f95398c34a0eac61b15beebde5b2cfa4b88d2e4 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Tue, 8 Sep 2026 04:38:22 -0700 Subject: [PATCH 185/206] feat: function columns on materialized views (#4119) A view could not carry a column it does not compute: the definition planned every output as a SQL expression, and the refresh engine treated any commit it did not make as drift and rebuilt. Servers fill such columns on tables with a separate job, as computed columns bound to a registered function, and want the same column on a view. This lets a declaration add computed columns, placed at their positions in the select list and validated by the existing computed-column contract, with the view created in one commit. Refresh writes those columns NULL on every path and never reads them, so a rewritten row comes back unfilled, and a commit that rewrites only computed columns is recognised as a fill rather than drift, so the next refresh carries on incrementally. A source column a computed column reads without the view projecting it is held as an internal projection, so the select list stays the view's column list. Nothing in the stored definition changes; an older reader fails closed on the schema check. Two smaller changes ride along because the feature needs them: an identity projection keeps its source column's nullability, with the schema check accepting a nullable physical field for a non-null planned one so existing views keep refreshing; and `prepare_declaration` takes `Option` projections, so an empty list declares no projection rather than `SELECT *`. --------- Co-authored-by: Claude Fable 5.1 --- rust/lancedb/src/database/namespace.rs | 5 + rust/lancedb/src/materialized_view.rs | 975 +++++++++++++++++- rust/lancedb/src/materialized_view/refresh.rs | 553 +++++++++- rust/lancedb/src/table.rs | 3 +- rust/lancedb/src/table/computed_columns.rs | 153 ++- 5 files changed, 1647 insertions(+), 42 deletions(-) diff --git a/rust/lancedb/src/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index 78641a8b3..9447b27ea 100644 --- a/rust/lancedb/src/database/namespace.rs +++ b/rust/lancedb/src/database/namespace.rs @@ -3,6 +3,7 @@ //! Namespace-based database implementation that delegates table management to lance-namespace +use lance_datafusion::utils::StreamingWriteSource; use std::collections::{HashMap, HashSet}; use std::sync::{Arc, Mutex}; @@ -304,6 +305,10 @@ impl Database for LanceNamespaceDatabase { } async fn create_table(&self, request: DbCreateTableRequest) -> Result> { + // Refuse a bad declaration before the namespace records a table. + crate::table::computed_columns::ensure_declarations_are_planned( + &request.data.arrow_schema(), + )?; let mut table_id = request.namespace_path.clone(); table_id.push(request.name.clone()); let mut existing_table = None; diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index ec77c1181..80546b4a4 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -27,7 +27,12 @@ use crate::connection::Connection; use crate::database::listing::OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS; use crate::database::{CreateTableRequest, Database, OpenTableRequest}; use crate::embeddings::EmbeddingDefinition; +use crate::function::FunctionBinding; use crate::table::Table; +use crate::table::computed_columns::{ + FUNCTION_BINDINGS_META_KEY, computed_column_from_field, computed_columns, + ensure_declarations_are_planned, function_bindings_metadata, +}; use crate::table::refresh::quote_identifier; use crate::table::{ColumnDefinition, ColumnKind}; use crate::{Error, Result}; @@ -119,6 +124,16 @@ pub struct MaterializedViewDefinition { pub inputs: Vec, } +/// Prefix of the internal columns holding source columns a computed column +/// reads without the view projecting them; see +/// [`PreparedDeclaration::input_column`]. +pub const INPUT_COLUMN_PREFIX: &str = "__input_"; + +/// The internal view column holding a copy of `source_column`. +pub fn input_column_name(source_column: &str) -> String { + format!("{INPUT_COLUMN_PREFIX}{source_column}") +} + /// A view definition as read back from schema metadata. Non-exhaustive so a /// kind added later is additive. #[derive(Debug, Clone, PartialEq, Eq)] @@ -192,7 +207,7 @@ pub(crate) fn plan( source_schema: SchemaRef, source_table: &str, source_namespace: &[String], - projections: &[(String, String)], + projections: Option<&[(String, String)]>, filter: Option<&str>, limit: Option, ) -> Result<(MaterializedViewDefinition, Vec, Lineage)> { @@ -205,17 +220,16 @@ pub(crate) fn plan( }, err => err, })?; - let projections: Vec<(String, String)> = if projections.is_empty() { - source_schema + let projections: Vec<(String, String)> = match projections { + Some(projections) => projections.to_vec(), + // `SELECT *`. A source that is itself a view carries its own + // provenance column; the new view records its own, not a copy. + None => source_schema .fields() .iter() - // A source that is itself a view carries its own provenance - // column; the new view records its own, not a copy. .filter(|f| f.name() != SOURCE_ROW_ID_COLUMN) .map(|f| (f.name().clone(), quote_identifier(f.name()))) - .collect() - } else { - projections.to_vec() + .collect(), }; // A scan takes the cap as i64. Rejecting it here keeps creation and @@ -288,9 +302,16 @@ pub(crate) fn plan( message: e.to_string(), })?; - // Always nullable: what a refresh appends must fit the declared field - // whatever nullability the evaluator reports for a given batch. - let mut field = ArrowField::new(output, data_type, true); + // A projected column keeps its nullability; a computed value is + // nullable whatever the evaluator reports for a given batch. + let nullable = match projected_path(&expr).as_deref() { + Some([column]) => source_schema + .field_with_name(column) + .map(|f| f.is_nullable()) + .unwrap_or(true), + _ => true, + }; + let mut field = ArrowField::new(output, data_type, nullable); // Identity projections keep descriptive field metadata (blob markers); // computed values carry none. Structural declarations never come along. if let Some(source_field) = projected_field(&expr, &source_schema) { @@ -627,6 +648,12 @@ fn project_schema(schema: &ArrowSchema, columns: &[String]) -> SchemaRef { pub struct PreparedDeclaration { schema: SchemaRef, definition: MaterializedViewDefinition, + /// The source schema and the projection lineage, for placing a computed + /// column's inputs; `internal_inputs` counts the projections + /// [`PreparedDeclaration::input_column`] added after the declared ones. + source_schema: SchemaRef, + lineage: Lineage, + internal_inputs: usize, /// The source's own database: the only place /// [`PreparedDeclaration::create`] will put the view, because refresh /// resolves the recorded source coordinate through the view's database. @@ -647,6 +674,196 @@ impl PreparedDeclaration { &self.definition } + /// The schema the view will have: the declared columns in order, any + /// internal projections added by [`PreparedDeclaration::input_column`], + /// then [`SOURCE_ROW_ID_COLUMN`]. + pub fn schema(&self) -> &SchemaRef { + &self.schema + } + + /// The view column that holds `source_column` for a computed column to + /// read: the column the view projects it to, if any, otherwise an + /// internal projection added here, named by [`input_column_name`]. + pub fn input_column(&mut self, source_column: &str) -> Result { + if let Some(output) = self.lineage.get(source_column).and_then(|o| o.first()) { + return Ok(output.clone()); + } + let name = input_column_name(source_column); + let field = self + .source_schema + .field_with_name(source_column) + .map_err(|_| Error::InvalidInput { + message: format!("the source has no column '{source_column}' to read"), + })?; + if self.schema.field_with_name(&name).is_ok() { + return Err(Error::ColumnAlreadyExists { name }); + } + let row_id = self.row_id_index()?; + let mut fields: Vec = self + .schema + .fields() + .iter() + .map(|f| f.as_ref().clone()) + .collect(); + fields.insert( + row_id, + without_declarations(&field.as_ref().clone().with_name(name.clone())), + ); + self.definition.projections.push(ViewProjection { + output: name.clone(), + expression: quote_identifier(source_column), + }); + self.definition.inputs.push(source_column.to_string()); + self.definition.inputs.sort(); + self.definition.inputs.dedup(); + self.lineage + .entry(source_column.to_string()) + .or_default() + .push(name.clone()); + self.internal_inputs += 1; + let mut metadata = self.schema.metadata().clone(); + rewrite_column_definitions(&mut metadata, self.schema.as_ref(), &fields)?; + metadata.insert( + DEFINITION_META_KEY.to_string(), + definition_to_metadata(&self.definition)?, + ); + self.schema = Arc::new(ArrowSchema::new_with_metadata(fields, metadata)); + Ok(name) + } + + /// Add computed columns, each at its position among the declared + /// columns, with the bindings any of them name. + /// + /// Refresh never computes such a column: every row it writes carries + /// NULL there, and the declaration's owner fills it, `refresh_column` + /// for a SQL declaration. A commit that fills only computed columns is + /// the one commit on a view refresh does not treat as drift. Declarations + /// are validated over the assembled schema, and read only columns the + /// view holds (see [`PreparedDeclaration::input_column`]). + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # use std::collections::HashMap; + /// # use arrow_schema::{DataType, Field}; + /// # use lancedb::materialized_view::prepare_declaration; + /// # use lancedb::table::computed_columns::{ + /// # COMPUTED_COLUMN_META_KEY, EXPRESSION_META_KEY, INPUTS_META_KEY, KIND_META_KEY, SQL_KIND, + /// # }; + /// # async fn declare(source: &lancedb::Table) -> Result<(), Box> { + /// let mut prepared = prepare_declaration( + /// source, + /// Some(&[("id".into(), "id".into())]), + /// None, + /// None, + /// ) + /// .await?; + /// // `text` is not projected; the view holds it internally for the column to read. + /// let text = prepared.input_column("text")?; + /// let length = Field::new("length", DataType::Int32, true).with_metadata(HashMap::from([ + /// (COMPUTED_COLUMN_META_KEY.into(), "true".into()), + /// (KIND_META_KEY.into(), SQL_KIND.into()), + /// (EXPRESSION_META_KEY.into(), format!("length({text})")), + /// (INPUTS_META_KEY.into(), format!("[\"{text}\"]")), + /// ])); + /// let view = prepared + /// .with_computed_columns(vec![(1, length)], &[])? + /// .create("lengths") + /// .await?; + /// view.refresh().execute().await?; // rows land with `length` NULL + /// view.table().refresh_column("length").await?; // filled + /// # Ok(()) + /// # } + /// ``` + pub fn with_computed_columns( + mut self, + columns: Vec<(usize, ArrowField)>, + bindings: &[FunctionBinding], + ) -> Result { + let invalid = |message: String| Error::InvalidInput { message }; + if columns.is_empty() { + return Err(invalid("at least one computed column is needed".into())); + } + if !computed_columns(&self.schema).is_empty() { + return Err(invalid( + "computed columns were already declared on this view".into(), + )); + } + if self.definition.projections.is_empty() { + return Err(invalid( + "a view of computed columns alone must read at least one source column".into(), + )); + } + let visible_count = self.visible_count(); + let mut fields: Vec = self + .schema + .fields() + .iter() + .map(|f| f.as_ref().clone()) + .collect(); + let mut columns = columns; + columns.sort_by_key(|(position, _)| *position); + for (inserted, (position, field)) in columns.iter().enumerate() { + let name = field.name().as_str(); + if name == SOURCE_ROW_ID_COLUMN + || name == ROW_ID + || name.starts_with(INPUT_COLUMN_PREFIX) + { + return Err(invalid(format!("view column name '{name}' is reserved"))); + } + if fields.iter().any(|f| f.name() == name) { + return Err(Error::ColumnAlreadyExists { + name: name.to_string(), + }); + } + if !field.is_nullable() { + return Err(invalid(format!( + "computed column '{name}' must be nullable until a refresh fills it" + ))); + } + if computed_column_from_field(field).is_none() { + return Err(invalid(format!( + "column '{name}' does not carry a computed-column declaration" + ))); + } + let limit = visible_count + inserted; + if *position > limit { + return Err(invalid(format!( + "computed column '{name}' is placed at {position}, past the view's {limit} columns" + ))); + } + // Positions index the select list, which counts the computed + // columns already inserted before this one. + fields.insert(*position, field.clone()); + } + let mut metadata = self.schema.metadata().clone(); + if !bindings.is_empty() { + metadata.insert( + FUNCTION_BINDINGS_META_KEY.to_string(), + function_bindings_metadata(bindings)?, + ); + } + rewrite_column_definitions(&mut metadata, self.schema.as_ref(), &fields)?; + let schema = ArrowSchema::new_with_metadata(fields, metadata); + ensure_declarations_are_planned(&schema)?; + self.schema = Arc::new(schema); + Ok(self) + } + + fn row_id_index(&self) -> Result { + self.schema + .index_of(SOURCE_ROW_ID_COLUMN) + .map_err(|e| Error::Runtime { + message: e.to_string(), + }) + } + + /// Columns the declaration lists: everything before the internal + /// projections and the provenance column. + fn visible_count(&self) -> usize { + self.definition.projections.len() - self.internal_inputs + + computed_columns(&self.schema).len() + } + /// Create the view table and verify it, consuming the declaration. /// /// The view goes at the root of the source's own database, where refresh @@ -717,11 +934,49 @@ impl PreparedDeclaration { } } -/// Validate a view declaration against its live source and hold what its -/// creation needs. The declaration is canonicalized through the coordinate a -/// refresh will resolve -- name and namespace both -- so a handle that does -/// not resolve back to itself is rejected. Same creation-time checks as -/// [`Connection::create_materialized_view`]. +/// Column definitions are positional over the view schema: carry each +/// field's entry to its place in `fields`, physical for a field that had none. +fn rewrite_column_definitions( + metadata: &mut HashMap, + previous: &ArrowSchema, + fields: &[ArrowField], +) -> Result<()> { + let Some(raw) = metadata.get(COLUMN_DEFINITIONS_META_KEY).cloned() else { + return Ok(()); + }; + let definitions: Vec = + serde_json::from_str(&raw).map_err(|e| Error::Runtime { + message: format!("unreadable column definitions on the view: {e}"), + })?; + let by_name: HashMap<&str, &ColumnDefinition> = previous + .fields() + .iter() + .zip(&definitions) + .map(|(field, definition)| (field.name().as_str(), definition)) + .collect(); + let rewritten: Vec = fields + .iter() + .map(|field| { + by_name + .get(field.name().as_str()) + .map(|d| (*d).clone()) + .unwrap_or(ColumnDefinition { + kind: ColumnKind::Physical, + }) + }) + .collect(); + metadata.insert( + COLUMN_DEFINITIONS_META_KEY.to_string(), + serde_json::to_string(&rewritten).map_err(|e| Error::Runtime { + message: format!("failed to serialize column definitions: {e}"), + })?, + ); + Ok(()) +} + +/// `projections` of `None` selects every source column, as `SELECT *`; +/// `Some(&[])` declares no projected column, for a view of function +/// columns alone. /// /// ```no_run /// # #![recursion_limit = "256"] @@ -729,7 +984,7 @@ impl PreparedDeclaration { /// # async fn declare(source: &lancedb::Table) -> Result<(), Box> { /// let prepared = prepare_declaration( /// source, -/// &[("id".into(), "id".into()), ("double".into(), "value * 2".into())], +/// Some(&[("id".into(), "id".into()), ("double".into(), "value * 2".into())]), /// Some("value > 0"), /// None, /// ) @@ -740,7 +995,7 @@ impl PreparedDeclaration { /// ``` pub async fn prepare_declaration( source: &Table, - projections: &[(String, String)], + projections: Option<&[(String, String)]>, filter: Option<&str>, limit: Option, ) -> Result { @@ -806,6 +1061,17 @@ pub async fn prepare_declaration( resolved.name(), ) .await?; + // The internal-input prefix belongs to the declaration alone; the + // replan at refresh sees those projections and must accept them. + if let Some(reserved) = projections + .unwrap_or_default() + .iter() + .find(|(output, _)| output.starts_with(INPUT_COLUMN_PREFIX)) + { + return Err(Error::InvalidInput { + message: format!("view column name '{}' is reserved", reserved.0), + }); + } let source_schema = resolved.schema().await?; let source_metadata = source_schema.metadata().clone(); let (definition, mut fields, lineage) = plan( @@ -841,6 +1107,9 @@ pub async fn prepare_declaration( Ok(PreparedDeclaration { schema: Arc::new(ArrowSchema::new_with_metadata(fields, metadata)), definition, + source_schema, + lineage, + internal_inputs: 0, database, }) } @@ -944,7 +1213,7 @@ impl CreateMaterializedViewBuilder { .await?; let prepared = prepare_declaration( &source, - &self.projections, + (!self.projections.is_empty()).then_some(self.projections.as_slice()), self.filter.as_deref(), self.limit, ) @@ -2076,7 +2345,7 @@ mod tests { ("id".to_string(), "id".to_string()), ("double".to_string(), "value * 2".to_string()), ]; - let prepared = prepare_declaration(&source, &projections, Some("value > 0"), None) + let prepared = prepare_declaration(&source, Some(&projections), Some("value > 0"), None) .await .unwrap(); assert_eq!(prepared.definition().source_table, "src"); @@ -2091,7 +2360,7 @@ mod tests { // external creation path cannot skip the check. conn.create_table("plain", batch).execute().await.unwrap(); let plain = conn.open_table("plain").execute().await.unwrap(); - let err = prepare_declaration(&plain, &[], None, None) + let err = prepare_declaration(&plain, None, None, None) .await .unwrap_err(); assert!(err.to_string().contains("stable row ids"), "{err}"); @@ -2113,7 +2382,7 @@ mod tests { .execute() .await .unwrap(); - let err = prepare_declaration(&masquerade, &[], None, None) + let err = prepare_declaration(&masquerade, None, None, None) .await .unwrap_err(); assert!( @@ -2134,7 +2403,7 @@ mod tests { .execute() .await .unwrap(); - let err = prepare_declaration(&custom, &[], None, None) + let err = prepare_declaration(&custom, None, None, None) .await .unwrap_err(); assert!(err.to_string().contains("custom_loc"), "{err}"); @@ -2272,4 +2541,664 @@ mod tests { ); } } + + /// A binding as the server records it: one Utf8 input over `input` + /// bound to a nullable parameter, one Int32 output named `output`, with + /// the exact schemas the durable contract requires. + pub fn test_binding(binding_id: &str, input: &str, output: &str) -> FunctionBinding { + let input_schema = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ + ArrowField::new("text", DataType::Utf8, true), + ])) + .unwrap(); + let output_schema = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ + ArrowField::new(output, DataType::Int32, true), + ])) + .unwrap(); + let input_type = input_schema.fields[0].r#type.r#type.clone(); + let output_type = output_schema.fields[0].r#type.r#type.clone(); + FunctionBinding::from_json( + &serde_json::json!({ + "binding_id": binding_id, + "function": {"name": "embed", "version": "fv_test"}, + "inputs": [{ + "parameter": "text", "field_id": -1, "field_path": input, + "arrow_type": input_type, "nullable": true, + }], + "outputs": [{ + "result_field": "$value", "output_name": output, "output_field_id": -1, + "output_ordinal": 0, "arrow_type": output_type, "nullable": false, + }], + "input_schema": serde_json::to_value(input_schema).unwrap(), + "output_schema": serde_json::to_value(output_schema).unwrap(), + }) + .to_string(), + ) + .unwrap() + } + + /// A computed column as the server declares it on a table: bound to a + /// registered Function. + pub fn computed_field(name: &str, binding_id: &str, input: &str) -> ArrowField { + ArrowField::new(name, DataType::Int32, true).with_metadata( + crate::table::computed_columns::function_computed_column_metadata( + binding_id, + 0, + &[input.to_string()], + ), + ) + } + + pub async fn people(conn: &Connection) -> Table { + let batch = + record_batch!(("id", Int32, [1, 2, 3]), ("name", Utf8, ["a", "b", "c"])).unwrap(); + conn.create_table("people", batch) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap() + } + + /// `people` with both columns non-nullable, for nullability cases. + pub async fn strict_people(conn: &Connection) -> Table { + let schema = Arc::new(ArrowSchema::new(vec![ + ArrowField::new("id", DataType::Int32, false), + ArrowField::new("name", DataType::Utf8, false), + ])); + let batch = arrow_array::RecordBatch::try_new( + schema, + vec![ + Arc::new(arrow_array::Int32Array::from(vec![1, 2, 3])), + Arc::new(arrow_array::StringArray::from(vec!["a", "b", "c"])), + ], + ) + .unwrap(); + conn.create_table("people", batch) + .write_options(stable_row_ids()) + .execute() + .await + .unwrap() + } + + async fn prepared_people(conn: &Connection) -> PreparedDeclaration { + let source = people(conn).await; + prepare_declaration( + &source, + Some(&[ + ("id".to_string(), "id".to_string()), + ("name".to_string(), "name".to_string()), + ]), + None, + None, + ) + .await + .unwrap() + } + + #[tokio::test] + async fn a_computed_column_is_declared_null_with_its_binding() { + let conn = connect("memory://").execute().await.unwrap(); + let view = prepared_people(&conn) + .await + .with_computed_columns( + vec![(2, computed_field("emb", "fb_1", "name"))], + &[test_binding("fb_1", "name", "emb")], + ) + .unwrap() + .create("v") + .await + .unwrap(); + + let schema = view.table().schema().await.unwrap(); + let names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect(); + assert_eq!(names, ["id", "name", "emb", SOURCE_ROW_ID_COLUMN]); + let declared: Vec = computed_columns(&schema) + .into_iter() + .map(|c| c.name) + .collect(); + assert_eq!(declared, ["emb"]); + let bindings = crate::table::computed_columns::function_bindings(&schema).unwrap(); + assert_eq!(bindings.len(), 1); + assert_eq!(bindings[0].binding_id(), "fb_1"); + // The stored definition is the plain select it always was. + let stored: serde_json::Value = + serde_json::from_str(&schema.metadata()[DEFINITION_META_KEY]).unwrap(); + assert_eq!(stored["kind"], SELECT_KIND); + assert_eq!(view.definition().projections.len(), 2); + assert_eq!(view.table().count_rows(None).await.unwrap(), 0); + assert_eq!(conn.open_materialized_view("v").await.unwrap().name(), "v"); + } + + #[tokio::test] + async fn computed_column_declarations_are_validated() { + let conn = connect("memory://").execute().await.unwrap(); + let prepared = prepared_people(&conn).await; + let binding = test_binding("fb_1", "name", "emb"); + let fails = |prepared: PreparedDeclaration, + columns: Vec<(usize, ArrowField)>, + bindings: &[FunctionBinding]| { + prepared + .with_computed_columns(columns, bindings) + .err() + .map(|e| e.to_string()) + .expect("the declaration should be refused") + }; + let emb = |binding_id: &str| computed_field("emb", binding_id, "name"); + + let err = fails( + prepared.clone(), + vec![(2, emb("fb_1").with_nullable(false))], + std::slice::from_ref(&binding), + ); + assert!(err.contains("must be nullable"), "{err}"); + + let plain = ArrowField::new("emb", DataType::Int32, true); + let err = fails( + prepared.clone(), + vec![(2, plain)], + std::slice::from_ref(&binding), + ); + assert!( + err.contains("does not carry a computed-column declaration"), + "{err}" + ); + + // The rest is the computed-column contract: a binding the field does + // not name, an output the binding does not map to this field, an + // input the view does not hold. + let err = fails( + prepared.clone(), + vec![(2, emb("fb_other"))], + std::slice::from_ref(&binding), + ); + assert!(err.contains("does not match binding 'fb_1'"), "{err}"); + let err = fails( + prepared.clone(), + vec![(2, emb("fb_1"))], + &[test_binding("fb_1", "name", "different_output")], + ); + assert!(err.contains("different_output"), "{err}"); + let err = fails( + prepared.clone(), + vec![(2, emb("fb_1"))], + &[test_binding("fb_1", "bio", "emb")], + ); + assert!(err.contains("'bio'"), "{err}"); + + let err = fails( + prepared.clone(), + vec![(2, computed_field("name", "fb_1", "name"))], + &[test_binding("fb_1", "name", "name")], + ); + assert!(err.contains("already exists"), "{err}"); + let err = fails( + prepared.clone(), + vec![(2, computed_field(SOURCE_ROW_ID_COLUMN, "fb_1", "name"))], + &[test_binding("fb_1", "name", SOURCE_ROW_ID_COLUMN)], + ); + assert!(err.contains("reserved"), "{err}"); + let err = fails( + prepared.clone(), + vec![(7, emb("fb_1"))], + std::slice::from_ref(&binding), + ); + assert!( + err.contains("placed at 7, past the view's 2 columns"), + "{err}" + ); + let err = fails(prepared, Vec::new(), std::slice::from_ref(&binding)); + assert!(err.contains("at least one computed column"), "{err}"); + } + + /// A source column a computed column reads without the view projecting + /// it becomes an internal projection before the provenance column, with + /// the source's nullability; a projected column is read from its + /// projection. + #[tokio::test] + async fn an_unprojected_input_becomes_an_internal_projection() { + let conn = connect("memory://").execute().await.unwrap(); + let source = strict_people(&conn).await; + let mut prepared = prepare_declaration( + &source, + Some(&[("key".to_string(), "id".to_string())]), + None, + None, + ) + .await + .unwrap(); + assert_eq!(prepared.input_column("id").unwrap(), "key"); + assert_eq!(prepared.input_column("name").unwrap(), "__input_name"); + assert_eq!(prepared.input_column("name").unwrap(), "__input_name"); + let err = prepared.input_column("missing").unwrap_err().to_string(); + assert!(err.contains("no column 'missing'"), "{err}"); + + let view = prepared + .with_computed_columns( + vec![(1, computed_field("emb", "fb_1", "__input_name"))], + &[test_binding("fb_1", "__input_name", "emb")], + ) + .unwrap() + .create("v") + .await + .unwrap(); + let schema = view.table().schema().await.unwrap(); + let names: Vec<&str> = schema.fields().iter().map(|f| f.name().as_str()).collect(); + assert_eq!(names, ["key", "emb", "__input_name", SOURCE_ROW_ID_COLUMN]); + let input = schema.field_with_name("__input_name").unwrap(); + assert_eq!(input.data_type(), &DataType::Utf8); + assert!( + !input.is_nullable(), + "the copy keeps the source's nullability" + ); + assert!(!schema.field_with_name("key").unwrap().is_nullable()); + let projections: Vec<(&str, &str)> = view + .definition() + .projections + .iter() + .map(|p| (p.output.as_str(), p.expression.as_str())) + .collect(); + assert_eq!(projections, [("key", "id"), ("__input_name", "`name`")]); + assert_eq!(view.definition().inputs, ["id", "name"]); + } + + /// Two outputs of one binding land at consecutive positions: each + /// insertion widens the range the next may take. + #[tokio::test] + async fn sibling_computed_columns_take_consecutive_positions() { + let conn = connect("memory://").execute().await.unwrap(); + let source = people(&conn).await; + let prepared = prepare_declaration( + &source, + Some(&[("id".to_string(), "id".to_string())]), + None, + None, + ) + .await + .unwrap(); + let metadata = |ordinal: u32| { + crate::table::computed_columns::function_computed_column_metadata( + "fb_pair", + ordinal, + &["id".to_string()], + ) + }; + let left = ArrowField::new("left", DataType::Int32, true).with_metadata(metadata(0)); + let right = ArrowField::new("right", DataType::Int32, true).with_metadata(metadata(1)); + let input_schema = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ + ArrowField::new("value", DataType::Int32, true), + ])) + .unwrap(); + let output_schema = lance_namespace::schema::arrow_schema_to_json(&ArrowSchema::new(vec![ + ArrowField::new("left", DataType::Int32, true), + ArrowField::new("right", DataType::Int32, true), + ])) + .unwrap(); + let int = input_schema.fields[0].r#type.r#type.clone(); + let binding = FunctionBinding::from_json( + &serde_json::json!({ + "binding_id": "fb_pair", + "function": {"name": "pair", "version": "fv_test"}, + "inputs": [{"parameter": "value", "field_id": -1, "field_path": "id", + "arrow_type": int, "nullable": true}], + "outputs": [ + {"result_field": "left", "output_name": "left", "output_field_id": -1, + "output_ordinal": 0, "arrow_type": int, "nullable": false}, + {"result_field": "right", "output_name": "right", "output_field_id": -1, + "output_ordinal": 1, "arrow_type": int, "nullable": false}, + ], + "input_schema": serde_json::to_value(input_schema).unwrap(), + "output_schema": serde_json::to_value(output_schema).unwrap(), + }) + .to_string(), + ) + .unwrap(); + let view = prepared + .with_computed_columns(vec![(1, left), (2, right)], &[binding]) + .unwrap() + .create("v") + .await + .unwrap(); + let names: Vec = view + .table() + .schema() + .await + .unwrap() + .fields() + .iter() + .map(|f| f.name().clone()) + .collect(); + assert_eq!(names, ["id", "left", "right", SOURCE_ROW_ID_COLUMN]); + } + + /// A SQL declaration as `add_columns().computed()` records it. + pub fn sql_field( + name: &str, + data_type: DataType, + expression: &str, + inputs: &str, + ) -> ArrowField { + use crate::table::computed_columns::{ + COMPUTED_COLUMN_META_KEY, EXPRESSION_META_KEY, INPUTS_META_KEY, KIND_META_KEY, SQL_KIND, + }; + ArrowField::new(name, data_type, true).with_metadata(HashMap::from([ + (COMPUTED_COLUMN_META_KEY.to_string(), "true".to_string()), + (KIND_META_KEY.to_string(), SQL_KIND.to_string()), + (EXPRESSION_META_KEY.to_string(), expression.to_string()), + (INPUTS_META_KEY.to_string(), inputs.to_string()), + ])) + } + + /// A SQL declaration is re-planned at admission: it must parse against + /// the view, yield the declared type, and read the inputs it declares. + #[tokio::test] + async fn a_sql_declaration_is_planned_at_admission() { + let conn = connect("memory://").execute().await.unwrap(); + let fails = |prepared: PreparedDeclaration, field: ArrowField| { + prepared + .with_computed_columns(vec![(1, field)], &[]) + .err() + .map(|e| e.to_string()) + .expect("the declaration should be refused") + }; + let prepared = prepared_people(&conn).await; + let err = fails( + prepared.clone(), + sql_field("bad", DataType::Int32, "missing + 1", r#"["missing"]"#), + ); + assert!(err.contains("missing"), "{err}"); + let err = fails( + prepared.clone(), + sql_field("wide", DataType::Int64, "id + 1", r#"["id"]"#), + ); + assert!( + err.contains("declared as Int64 but its expression yields Int32"), + "{err}" + ); + let err = fails( + prepared.clone(), + sql_field("lying", DataType::Int32, "id + 1", r#"["name"]"#), + ); + assert!(err.contains("declares inputs"), "{err}"); + + let view = prepared + .with_computed_columns( + vec![(1, sql_field("next", DataType::Int32, "id + 1", r#"["id"]"#))], + &[], + ) + .unwrap() + .create("v") + .await + .unwrap(); + let names: Vec = view + .table() + .schema() + .await + .unwrap() + .fields() + .iter() + .map(|f| f.name().clone()) + .collect(); + assert_eq!(names, ["id", "next", "name", SOURCE_ROW_ID_COLUMN]); + } + + /// Creation persists a declaration only when it re-plans and the data + /// carries no values for it, whichever door created the table. + #[tokio::test] + async fn a_created_table_cannot_carry_computed_values() { + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(ArrowSchema::new(vec![ + ArrowField::new("x", DataType::Int32, false), + sql_field("forged", DataType::Int32, "x + 1", r#"["x"]"#), + ])); + let filled = arrow_array::RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(arrow_array::Int32Array::from(vec![1])), + Arc::new(arrow_array::Int32Array::from(vec![999])), + ], + ) + .unwrap(); + let err = conn + .create_table("forged", filled) + .execute() + .await + .unwrap_err() + .to_string(); + assert!(err.contains("cannot be written directly"), "{err}"); + assert!( + !conn + .table_names() + .execute() + .await + .unwrap() + .contains(&"forged".to_string()) + ); + + let unfilled = arrow_array::RecordBatch::try_new( + schema, + vec![ + Arc::new(arrow_array::Int32Array::from(vec![1])), + Arc::new(arrow_array::Int32Array::new_null(1)), + ], + ) + .unwrap(); + let table = conn + .create_table("declared", unfilled) + .execute() + .await + .unwrap(); + assert_eq!(table.refresh_column("forged").await.unwrap().rows_filled, 1); + + // A declaration with only its marker is broken, not absent. + let half = ArrowField::new("half", DataType::Int32, true).with_metadata(HashMap::from([( + crate::table::computed_columns::COMPUTED_COLUMN_META_KEY.to_string(), + "true".to_string(), + )])); + let batch = arrow_array::RecordBatch::try_new( + Arc::new(ArrowSchema::new(vec![ + ArrowField::new("x", DataType::Int32, false), + half, + ])), + vec![ + Arc::new(arrow_array::Int32Array::from(vec![1])), + Arc::new(arrow_array::Int32Array::from(vec![999])), + ], + ) + .unwrap(); + let err = conn + .create_table("half", batch) + .execute() + .await + .unwrap_err() + .to_string(); + assert!( + err.contains("incomplete computed-column declaration"), + "{err}" + ); + + let bogus = Arc::new(ArrowSchema::new(vec![ + ArrowField::new("x", DataType::Int32, false), + sql_field("bad", DataType::Int32, "missing + 1", r#"["missing"]"#), + ])); + let batch = arrow_array::RecordBatch::new_empty(bogus); + let err = conn + .create_table("bogus", batch) + .execute() + .await + .unwrap_err() + .to_string(); + assert!(err.contains("missing"), "{err}"); + } + + /// The internal-input prefix is reserved for the declaration, like the + /// provenance column, so an alias cannot masquerade as an internal input. + #[tokio::test] + async fn the_internal_input_prefix_is_reserved() { + let conn = connect("memory://").execute().await.unwrap(); + let source = people(&conn).await; + let err = prepare_declaration( + &source, + Some(&[("__input_x".to_string(), "name".to_string())]), + None, + None, + ) + .await + .unwrap_err() + .to_string(); + assert!(err.contains("'__input_x' is reserved"), "{err}"); + } + + /// A computed column may not read another, through any path: a + /// Function bound to a child of a computed struct is refused like a SQL + /// declaration over it. + #[tokio::test] + async fn a_computed_column_cannot_read_a_computed_root() { + let conn = connect("memory://").execute().await.unwrap(); + let prepared = prepared_people(&conn).await; + let payload = sql_field( + "payload", + DataType::Struct(vec![ArrowField::new("value", DataType::Utf8, true)].into()), + "named_struct('value', name)", + r#"["name"]"#, + ); + let err = prepared + .with_computed_columns( + vec![ + (2, payload), + (3, computed_field("emb", "fb_dependent", "payload.value")), + ], + &[test_binding("fb_dependent", "payload.value", "emb")], + ) + .err() + .map(|e| e.to_string()) + .expect("a computed root as a Function input should be refused"); + assert!(err.contains("reads computed column 'payload'"), "{err}"); + } + + /// The root check uses the canonical path parser: a quoted top-level + /// name containing a dot is one root, not two segments. + #[tokio::test] + async fn a_quoted_computed_root_is_still_refused() { + let conn = connect("memory://").execute().await.unwrap(); + let prepared = prepared_people(&conn).await; + let payload = sql_field( + "payload.dot", + DataType::Struct(vec![ArrowField::new("value", DataType::Utf8, true)].into()), + "named_struct('value', name)", + r#"["name"]"#, + ); + let input = "`payload.dot`.value"; + let err = prepared + .with_computed_columns( + vec![ + (2, payload), + (3, computed_field("emb", "fb_dependent", input)), + ], + &[test_binding("fb_dependent", input, "emb")], + ) + .err() + .map(|e| e.to_string()) + .expect("a quoted computed root should be refused"); + assert!(err.contains("reads computed column 'payload.dot'"), "{err}"); + } + + /// Namespace-backed creation admits declarations by the same rule, and + /// refuses before the namespace records the table. + #[tokio::test] + async fn a_namespace_created_table_cannot_carry_computed_values() { + let tmp = tempfile::tempdir().unwrap(); + let mut properties = std::collections::HashMap::new(); + properties.insert("root".to_string(), tmp.path().to_str().unwrap().to_string()); + let conn = crate::connect_namespace("dir", properties) + .execute() + .await + .unwrap(); + let half = ArrowField::new("half", DataType::Int32, true).with_metadata(HashMap::from([( + crate::table::computed_columns::COMPUTED_COLUMN_META_KEY.to_string(), + "true".to_string(), + )])); + let batch = arrow_array::RecordBatch::try_new( + Arc::new(ArrowSchema::new(vec![ + ArrowField::new("id", DataType::Int32, false), + half, + ])), + vec![ + Arc::new(arrow_array::Int32Array::from(vec![1])), + Arc::new(arrow_array::Int32Array::from(vec![999])), + ], + ) + .unwrap(); + let err = conn + .create_table("malformed", batch) + .execute() + .await + .unwrap_err() + .to_string(); + assert!( + err.contains("incomplete computed-column declaration"), + "{err}" + ); + assert!(conn.table_names().execute().await.unwrap().is_empty()); + + let schema = Arc::new(ArrowSchema::new(vec![ + ArrowField::new("id", DataType::Int32, false), + sql_field("next", DataType::Int32, "id + 1", r#"["id"]"#), + ])); + let filled = arrow_array::RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(arrow_array::Int32Array::from(vec![1])), + Arc::new(arrow_array::Int32Array::from(vec![999])), + ], + ) + .unwrap(); + let err = conn + .create_table("forged", filled) + .execute() + .await + .unwrap_err() + .to_string(); + assert!(err.contains("cannot be written directly"), "{err}"); + + let unfilled = arrow_array::RecordBatch::try_new( + schema, + vec![ + Arc::new(arrow_array::Int32Array::from(vec![1])), + Arc::new(arrow_array::Int32Array::new_null(1)), + ], + ) + .unwrap(); + let table = conn + .create_table("declared", unfilled) + .execute() + .await + .unwrap(); + assert_eq!(table.refresh_column("next").await.unwrap().rows_filled, 1); + } + + /// A projected column keeps its nullability; a computed value is + /// nullable. + #[tokio::test] + async fn an_identity_projection_keeps_source_nullability() { + let conn = connect("memory://").execute().await.unwrap(); + let source = strict_people(&conn).await; + let prepared = prepare_declaration( + &source, + Some(&[ + ("id".to_string(), "id".to_string()), + ("n".to_string(), "name".to_string()), + ("next".to_string(), "id + 1".to_string()), + ]), + None, + None, + ) + .await + .unwrap(); + let nullable: Vec = prepared + .schema() + .fields() + .iter() + .map(|f| f.is_nullable()) + .collect(); + assert_eq!(nullable, [false, false, true, false]); + } } diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index efddd1c7b..23bb51566 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -24,8 +24,8 @@ use std::time::{SystemTime, UNIX_EPOCH}; use arrow_array::cast::AsArray; use arrow_array::types::UInt64Type; -use arrow_array::{RecordBatch, UInt64Array}; -use arrow_schema::{Schema as ArrowSchema, SchemaRef}; +use arrow_array::{RecordBatch, UInt64Array, new_null_array}; +use arrow_schema::{FieldRef, Schema as ArrowSchema, SchemaRef}; use datafusion::common::ScalarValue; use datafusion::error::DataFusionError; use datafusion::physical_plan::SendableRecordBatchStream; @@ -34,7 +34,7 @@ use datafusion::prelude::{col, lit}; use futures::{StreamExt, TryStreamExt}; use lance::Dataset; use lance::dataset::mem_wal::DatasetMemWalExt; -use lance::dataset::transaction::{Operation, Transaction}; +use lance::dataset::transaction::{Operation, Transaction, UpdateMode}; use lance::dataset::write::delete::DeleteBuilder; use lance::dataset::write::merge_insert::inserted_rows::{ KeyExistenceFilter, KeyExistenceFilterBuilder, KeyValue, @@ -51,6 +51,9 @@ use super::{ definition_to_metadata, }; use crate::database::OpenTableRequest; +use crate::table::computed_columns::{ + computed_column_from_field, computed_columns, ensure_declarations_are_planned, +}; use crate::table::{NativeTable, NativeTableExt, Table}; use crate::{Error, Result}; @@ -167,30 +170,52 @@ pub(crate) async fn execute_refresh( .map(|p| (p.output.clone(), p.expression.clone())) .collect(); validate_inputs(&source_ds, definition)?; - let (replanned, mut planned_fields, _renames) = super::plan( + let (replanned, planned_fields, _renames) = super::plan( source_schema, &definition.source_table, &definition.source_namespace, - &projections, + Some(&projections), definition.filter.as_deref(), definition.limit, )?; + let mut planned_fields = planned_fields; planned_fields.push(arrow_schema::Field::new( SOURCE_ROW_ID_COLUMN, arrow_schema::DataType::UInt64, false, )); + // A computed column is not planned from the source: refresh writes it + // NULL and its declaration's owner fills it. Its declaration must still + // be complete, and it must be able to hold NULL. let physical = ArrowSchema::from(view_ds.schema()); - let planned_shape: Vec<_> = planned_fields - .iter() - .map(|f| (f.name().clone(), f.data_type().clone(), f.is_nullable())) - .collect(); - let physical_shape: Vec<_> = physical + let mut computed = computed_columns(&physical).into_iter().map(|c| c.name); + if let Some(name) = computed.by_ref().find(|name| { + physical + .field_with_name(name) + .is_ok_and(|f| !f.is_nullable()) + }) { + return Err(Error::Schema { + message: format!( + "computed column '{name}' of view '{}' cannot hold NULL; recreate the view", + view.name() + ), + }); + } + ensure_declarations_are_planned(&physical)?; + let physical_planned: Vec<&FieldRef> = physical .fields() .iter() - .map(|f| (f.name().clone(), f.data_type().clone(), f.is_nullable())) + .filter(|f| computed_column_from_field(f).is_none()) .collect(); - if planned_shape != physical_shape { + // A projected column that became nullable at the source still fits the + // view's nullable field; the reverse would not. + let matches = planned_fields.len() == physical_planned.len() + && planned_fields.iter().zip(&physical_planned).all(|(e, p)| { + e.name() == p.name() + && e.data_type() == p.data_type() + && (p.is_nullable() || !e.is_nullable()) + }); + if !matches { return Err(Error::Schema { message: format!( "the stored definition of view '{}' does not produce this \ @@ -229,11 +254,18 @@ pub(crate) async fn execute_refresh( .get(SOURCE_VERSION_TS_META_KEY) .and_then(|raw| raw.parse().ok()); // The watermark speaks only for the view state its refresh left behind; - // any other commit on the view since then is drift. - let view_intact = metadata + // any other commit on the view since then is drift, except a fill of its + // computed columns, which rewrites nothing refresh certifies. + let recorded_view_version = metadata .get(VIEW_VERSION_META_KEY) - .and_then(|raw| raw.parse::().ok()) - == Some(view_ds.version().version); + .and_then(|raw| raw.parse::().ok()); + let view_intact = match recorded_view_version { + Some(recorded) if recorded == view_ds.version().version => true, + Some(recorded) if recorded < view_ds.version().version => { + only_computed_rewrites_since(&view_ds, recorded).await? + } + _ => false, + }; if !full && watermark == Some(source_version) && view_intact && recorded_ts == Some(source_ts) { return Ok(RefreshMaterializedViewResult { @@ -1090,6 +1122,69 @@ struct RowScope { limit: Option, } +/// Whether every commit on the view after `recorded` is a fill of its +/// computed columns: a column rewrite or data replacement touching only +/// those fields and neither adding nor removing rows. A version whose +/// transaction cannot be read is not proven, so it counts as drift. +async fn only_computed_rewrites_since(view_ds: &Dataset, recorded: u64) -> Result { + // A fill may write any field under a computed column, so the whole + // subtree counts, not only the root. + let physical = ArrowSchema::from(view_ds.schema()); + fn subtree(field: &lance_core::datatypes::Field, ids: &mut Vec) { + ids.push(field.id as u32); + for child in &field.children { + subtree(child, ids); + } + } + let mut computed_fields = Vec::new(); + for column in computed_columns(&physical) { + if let Some(field) = view_ds.schema().field(&column.name) { + subtree(field, &mut computed_fields); + } + } + if computed_fields.is_empty() { + return Ok(false); + } + for version in recorded + 1..=view_ds.version().version { + let Some(transaction) = view_ds.read_transaction_by_version(version).await? else { + return Ok(false); + }; + let fill = match &transaction.operation { + Operation::Update { + removed_fragment_ids, + new_fragments, + fields_modified, + update_mode: Some(UpdateMode::RewriteColumns), + .. + } => { + removed_fragment_ids.is_empty() + && new_fragments.is_empty() + && !fields_modified.is_empty() + && fields_modified + .iter() + .all(|field| computed_fields.contains(field)) + } + // What `refresh_column` commits for a SQL declaration. + Operation::DataReplacement { replacements } => { + !replacements.is_empty() + && replacements.iter().all(|group| { + !group.1.fields.is_empty() + && group + .1 + .fields + .iter() + .all(|field| computed_fields.contains(&(*field as u32))) + }) + } + _ => false, + }; + if !fill { + return Ok(false); + } + } + Ok(true) +} + async fn compute_stream( source: &Dataset, definition: &MaterializedViewDefinition, @@ -1158,6 +1253,10 @@ async fn compute_stream( let batch = batch.map_err(|e| DataFusionError::External(Box::new(e)))?; let mut columns = Vec::with_capacity(out_schema.fields().len()); for field in out_schema.fields() { + if computed_column_from_field(field).is_some() { + columns.push(new_null_array(field.data_type(), batch.num_rows())); + continue; + } let name = if field.name() == SOURCE_ROW_ID_COLUMN { ROW_ID } else { @@ -2768,7 +2867,7 @@ mod tests { let (conn, source) = db_with_source(vec![1]).await; let prepared = crate::materialized_view::prepare_declaration( &source, - &[("x".into(), "x".into()), ("twice".into(), "x * 2".into())], + Some(&[("x".into(), "x".into()), ("twice".into(), "x * 2".into())]), None, None, ) @@ -3132,4 +3231,424 @@ mod tests { let err = view.refresh().execute().await.unwrap_err(); assert!(err.to_string().contains("source table 'src'"), "{err}"); } + + /// A view with a computed column, declared over `people` and refreshed. + async fn refreshed_computed_view(conn: &Connection) -> MaterializedView { + use crate::materialized_view::tests::{computed_field, people, test_binding}; + let source = people(conn).await; + let view = crate::materialized_view::prepare_declaration( + &source, + Some(&[ + ("id".to_string(), "id".to_string()), + ("name".to_string(), "name".to_string()), + ]), + None, + None, + ) + .await + .unwrap() + .with_computed_columns( + vec![(2, computed_field("emb", "fb_1", "name"))], + &[test_binding("fb_1", "name", "emb")], + ) + .unwrap() + .create("v") + .await + .unwrap(); + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Rebuild); + view + } + + async fn unfilled(view: &MaterializedView) -> usize { + view.table() + .count_rows(Some("emb IS NULL".to_string())) + .await + .unwrap() + } + + async fn append_people(conn: &Connection, ids: Vec, names: Vec<&str>) { + let batch = record_batch!(("id", Int32, ids), ("name", Utf8, names)).unwrap(); + conn.open_table("people") + .execute() + .await + .unwrap() + .add(batch) + .execute() + .await + .unwrap(); + } + + /// Commit the fill job's shape on the view: a column rewrite of + /// `fields`, touching no rows. The data is left as it is; what matters + /// here is how the next refresh classifies the commit. + async fn commit_column_rewrite(view: &MaterializedView, fields: &[&str]) { + let native = view.table().as_native().unwrap(); + native.dataset.reload().await.unwrap(); + let dataset = native.dataset.get().await.unwrap().as_ref().clone(); + let fields_modified = fields + .iter() + .map(|name| dataset.schema().field(name).unwrap().id as u32) + .collect(); + let updated_fragments = dataset + .get_fragments() + .iter() + .map(|fragment| fragment.metadata().clone()) + .collect(); + let operation = Operation::Update { + removed_fragment_ids: Vec::new(), + updated_fragments, + new_fragments: Vec::new(), + fields_modified, + compacted_sstables: Vec::new(), + fields_for_preserving_frag_bitmap: Vec::new(), + update_mode: Some(UpdateMode::RewriteColumns), + inserted_rows_filter: None, + updated_fragment_offsets: None, + }; + let read_version = dataset.version().version; + CommitBuilder::new(WriteDestination::Dataset(Arc::new(dataset))) + .execute(Transaction::new(read_version, operation, None)) + .await + .unwrap(); + } + + /// Refresh never computes a computed column: every row it writes, on a + /// rebuild, an append and a rewrite, carries NULL there, and the + /// declaration survives all three. + #[tokio::test] + async fn test_computed_columns_are_written_null_and_kept() { + let conn = connect("memory://").execute().await.unwrap(); + let view = refreshed_computed_view(&conn).await; + assert_eq!(unfilled(&view).await, 3); + + append_people(&conn, vec![4, 5], vec!["d", "e"]).await; + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(unfilled(&view).await, 5); + + conn.open_table("people") + .execute() + .await + .unwrap() + .update() + .column("name", "'z'") + .only_if("id = 1") + .execute() + .await + .unwrap(); + view.refresh().execute().await.unwrap(); + assert_eq!(unfilled(&view).await, 5); + assert_eq!(read(view.table(), "id").await, vec![1, 2, 3, 4, 5]); + + let schema = view.table().schema().await.unwrap(); + assert!( + crate::table::computed_columns::function_bindings(&schema) + .unwrap() + .iter() + .any(|b| b.binding_id() == "fb_1"), + "the binding envelope was lost" + ); + assert!( + computed_column_from_field(schema.field_with_name("emb").unwrap()).is_some(), + "the declaration was lost" + ); + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::NoOp + ); + } + + /// The fill job's commit rewrites only computed columns. It is the one + /// commit on a view that is not drift: the next refresh carries on from + /// its watermark instead of rebuilding, which would null what the fill + /// just wrote. + #[tokio::test] + async fn test_a_computed_column_fill_is_not_drift() { + let conn = connect("memory://").execute().await.unwrap(); + let view = refreshed_computed_view(&conn).await; + + commit_column_rewrite(&view, &["emb"]).await; + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::NoOp + ); + + commit_column_rewrite(&view, &["emb"]).await; + append_people(&conn, vec![4], vec!["d"]).await; + let result = view.refresh().execute().await.unwrap(); + assert_eq!(result.mode, RefreshMode::Incremental); + assert_eq!(result.rows_written, 1); + assert_eq!(read(view.table(), "id").await, vec![1, 2, 3, 4]); + } + + /// A column rewrite that reaches a projected column is drift like any + /// other write: refresh certifies those columns and must recompute them. + #[tokio::test] + async fn test_a_rewrite_of_a_projected_column_is_drift() { + let conn = connect("memory://").execute().await.unwrap(); + let view = refreshed_computed_view(&conn).await; + + commit_column_rewrite(&view, &["emb", "name"]).await; + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::Rebuild + ); + } + + /// The declaration contract is checked before any refresh mutation: a + /// missing binding envelope and a column that lost its declaration both + /// fail closed. + #[tokio::test] + async fn test_a_broken_declaration_is_refused_before_refresh() { + let conn = connect("memory://").execute().await.unwrap(); + let view = refreshed_computed_view(&conn).await; + let native = view.table().as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + dataset + .update_schema_metadata(vec![( + crate::table::computed_columns::FUNCTION_BINDINGS_META_KEY.to_string(), + None, + )]) + .await + .unwrap(); + let err = view.refresh().execute().await.unwrap_err().to_string(); + assert!(err.contains("references missing binding 'fb_1'"), "{err}"); + + let conn = connect("memory://").execute().await.unwrap(); + let view = refreshed_computed_view(&conn).await; + let native = view.table().as_native().unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + dataset + .replace_field_metadata(vec![( + dataset.schema().field("emb").unwrap().id as u32, + HashMap::new(), + )]) + .await + .unwrap(); + let err = view.refresh().execute().await.unwrap_err().to_string(); + assert!(err.contains("does not match binding 'fb_1'"), "{err}"); + } + + /// An input the view does not project is materialized on every refresh + /// path, before the provenance column, with the source's values. + #[tokio::test] + async fn test_internal_inputs_are_materialized_and_refreshed() { + use crate::materialized_view::tests::{computed_field, strict_people, test_binding}; + let conn = connect("memory://").execute().await.unwrap(); + let source = strict_people(&conn).await; + let mut prepared = crate::materialized_view::prepare_declaration( + &source, + Some(&[("id".to_string(), "id".to_string())]), + None, + None, + ) + .await + .unwrap(); + let input = prepared.input_column("name").unwrap(); + let view = prepared + .with_computed_columns( + vec![(1, computed_field("emb", "fb_1", &input))], + &[test_binding("fb_1", &input, "emb")], + ) + .unwrap() + .create("v") + .await + .unwrap(); + let names: Vec = view + .table() + .schema() + .await + .unwrap() + .fields() + .iter() + .map(|f| f.name().clone()) + .collect(); + assert_eq!(names, ["id", "emb", "__input_name", SOURCE_ROW_ID_COLUMN]); + + let unfilled_inputs = || async { + view.table() + .count_rows(Some("__input_name IS NULL".to_string())) + .await + .unwrap() + }; + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::Rebuild + ); + assert_eq!(view.table().count_rows(None).await.unwrap(), 3); + assert_eq!(unfilled_inputs().await, 0); + + let more = arrow_array::RecordBatch::try_new( + source.schema().await.unwrap(), + vec![ + Arc::new(Int32Array::from(vec![4])), + Arc::new(arrow_array::StringArray::from(vec!["d"])), + ], + ) + .unwrap(); + source.add(more).execute().await.unwrap(); + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::Incremental + ); + assert_eq!(unfilled_inputs().await, 0); + assert_eq!( + view.table() + .count_rows(Some("__input_name = 'd'".to_string())) + .await + .unwrap(), + 1 + ); + + source + .update() + .column("name", "'z'") + .only_if("id = 1") + .execute() + .await + .unwrap(); + view.refresh().execute().await.unwrap(); + assert_eq!( + view.table() + .count_rows(Some("__input_name = 'z'".to_string())) + .await + .unwrap(), + 1 + ); + assert_eq!( + unfilled(&view).await, + 4, + "rewritten and new rows are unfilled" + ); + } + + /// A SQL declaration is filled by `refresh_column` on the view, which + /// commits a data replacement; the next refresh continues from its + /// watermark and keeps what the fill wrote, and only rows the view added + /// since come back unfilled. + #[tokio::test] + async fn test_a_sql_fill_is_not_drift() { + use crate::materialized_view::tests::{people, sql_field}; + let conn = connect("memory://").execute().await.unwrap(); + let source = people(&conn).await; + let view = crate::materialized_view::prepare_declaration( + &source, + Some(&[("id".to_string(), "id".to_string())]), + None, + None, + ) + .await + .unwrap() + .with_computed_columns( + vec![( + 1, + sql_field("next", arrow_schema::DataType::Int32, "id + 1", r#"["id"]"#), + )], + &[], + ) + .unwrap() + .create("v") + .await + .unwrap(); + let filled = || async { + view.table() + .count_rows(Some("next = id + 1".to_string())) + .await + .unwrap() + }; + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::Rebuild + ); + assert_eq!( + view.table() + .refresh_column("next") + .await + .unwrap() + .rows_filled, + 3 + ); + assert_eq!(filled().await, 3); + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::NoOp + ); + assert_eq!(filled().await, 3); + + append_people(&conn, vec![4], vec!["d"]).await; + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::Incremental + ); + assert_eq!(filled().await, 3); + assert_eq!( + view.table() + .refresh_column("next") + .await + .unwrap() + .rows_filled, + 1 + ); + assert_eq!(filled().await, 4); + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::NoOp + ); + } + + /// A fill of a nested computed column writes its child fields; that is + /// still a fill, not drift. + #[tokio::test] + async fn test_a_nested_sql_fill_is_not_drift() { + use crate::materialized_view::tests::{people, sql_field}; + let conn = connect("memory://").execute().await.unwrap(); + let source = people(&conn).await; + let payload = sql_field( + "payload", + arrow_schema::DataType::Struct( + vec![arrow_schema::Field::new( + "value", + arrow_schema::DataType::Utf8, + true, + )] + .into(), + ), + "named_struct('value', name)", + r#"["name"]"#, + ); + let view = crate::materialized_view::prepare_declaration( + &source, + Some(&[("name".to_string(), "name".to_string())]), + None, + None, + ) + .await + .unwrap() + .with_computed_columns(vec![(1, payload)], &[]) + .unwrap() + .create("v") + .await + .unwrap(); + view.refresh().execute().await.unwrap(); + assert_eq!( + view.table() + .refresh_column("payload") + .await + .unwrap() + .rows_filled, + 3 + ); + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::NoOp + ); + assert_eq!( + view.table() + .count_rows(Some("payload.value = name".to_string())) + .await + .unwrap(), + 3 + ); + } } diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 44e12d8ad..56d7ce518 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -2804,7 +2804,7 @@ impl NativeTable { namespace_client: Option>, pushdown_operations: HashSet, ) -> Result { - computed_columns::ensure_no_foreign_declarations(batches.arrow_schema().fields())?; + let batches = computed_columns::admit_create_source(batches)?; // Default params uses format v1. let params = params.unwrap_or(WriteParams { ..Default::default() @@ -2904,6 +2904,7 @@ impl NativeTable { pushdown_operations: HashSet, session: Option>, ) -> Result { + let batches = computed_columns::admit_create_source(batches)?; // 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/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index 21d4f3016..f1ec75213 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -21,6 +21,7 @@ //! [`computed_columns`] and [`computed_column_from_field`] read declarations //! back off a schema. +use futures::StreamExt; use std::collections::{BTreeSet, HashMap, HashSet}; use std::sync::Arc; @@ -1338,6 +1339,106 @@ pub(crate) fn ensure_batch_writes_no_computed_values( Ok(()) } +/// Validate every computed-column declaration `schema` carries against the +/// schema itself: every field with declaration metadata is a complete +/// declaration, a SQL declaration re-plans to the field it declares, a +/// Function declaration satisfies the binding contract, and no declaration +/// reads another computed column. What passes here is what `refresh_column` +/// can execute. +pub(crate) fn ensure_declarations_are_planned(schema: &ArrowSchema) -> 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. + for field in schema.fields() { + if field.metadata().keys().any(|k| is_declaration_key(k)) + && computed_column_from_field(field).is_none() + { + return Err(invalid(format!( + "field '{}' carries an incomplete computed-column declaration", + field.name() + ))); + } + } + let declared: HashSet = computed_columns(schema) + .into_iter() + .map(|c| c.name) + .collect(); + for column in computed_columns(schema) { + let field = schema.field_with_name(&column.name)?; + if !field.is_nullable() { + return Err(invalid(format!( + "computed column '{}' must be nullable until a refresh fills it", + column.name + ))); + } + match &column.kind { + ComputedColumnKind::Sql { expression } => { + let others: Vec = schema + .fields() + .iter() + .filter(|f| f.name() != &column.name) + .map(|f| f.as_ref().clone()) + .collect(); + let bound = bind(Arc::new(ArrowSchema::new(others)), &column.name, expression)?; + if let Some(input) = bound.roots.iter().find(|r| declared.contains(*r)) { + return Err(invalid(format!( + "computed column '{}' reads computed column '{input}'", + column.name + ))); + } + if &bound.data_type != field.data_type() { + return Err(invalid(format!( + "computed column '{}' is declared as {} but its expression yields {}", + column.name, + field.data_type(), + bound.data_type + ))); + } + let mut declared_inputs = column.inputs.clone(); + declared_inputs.sort(); + if declared_inputs != bound.inputs { + return Err(invalid(format!( + "computed column '{}' declares inputs {:?} but its expression reads {:?}", + column.name, declared_inputs, bound.inputs + ))); + } + } + ComputedColumnKind::Function { binding_id, .. } => { + // The binding validator resolves each input's leaf; the + // no-computed-input rule is about the root it hangs from. + let bindings = function_bindings(schema)?; + let Some(binding) = bindings.iter().find(|b| b.binding_id() == binding_id) else { + continue; // reported by the binding validator below + }; + // Roots come from the canonical path parser: a quoted + // top-level name may itself contain a dot. + if let Some(input) = binding + .inputs() + .iter() + .filter_map(|input| resolve_field_path(schema, &input.field_path).ok()) + .map(|resolved| resolved.root.name().as_str()) + .find(|r| declared.contains(*r)) + { + return Err(invalid(format!( + "computed column '{}' reads computed column '{input}'", + column.name + ))); + } + } + ComputedColumnKind::Unrecognized { kind } => { + return Err(Error::NotSupported { + message: format!( + "computed column '{}' is defined by '{kind}', which this version \ + of lancedb cannot fill", + column.name + ), + }); + } + } + } + ensure_supported_function_metadata(schema) +} + /// Reject fields carrying declaration metadata that did not come through /// [`plan`]. One authority for creation, overwrite and raw transforms. pub(crate) fn ensure_no_foreign_declarations<'a>( @@ -1796,6 +1897,54 @@ pub(super) async fn add_foreign_kind(table: &crate::Table, name: &str, kind: &st .unwrap(); } +/// Admit a table's initial data: every declaration it carries is validated, +/// and the stream refuses any batch with values in a computed column, whose +/// values come from refresh alone. One boundary for every way a table is +/// created. +pub(crate) fn admit_create_source( + batches: S, +) -> Result> { + let schema = batches.arrow_schema(); + ensure_declarations_are_planned(&schema)?; + let declared = computed_columns(&schema) + .into_iter() + .map(|c| c.name) + .collect(); + Ok(UnfilledDeclarations { + inner: batches, + declared, + }) +} + +/// A write source whose computed columns must arrive unfilled. +pub(crate) struct UnfilledDeclarations { + inner: S, + declared: Vec, +} + +impl lance_datafusion::utils::StreamingWriteSource + for UnfilledDeclarations +{ + fn arrow_schema(&self) -> SchemaRef { + self.inner.arrow_schema() + } + + fn into_stream(self) -> datafusion_physical_plan::SendableRecordBatchStream { + if self.declared.is_empty() { + return self.inner.into_stream(); + } + let schema = self.inner.arrow_schema(); + let declared = self.declared; + let stream = self.inner.into_stream().map(move |batch| { + let batch = batch?; + ensure_batch_writes_no_computed_values(&declared, &batch) + .map_err(|e| datafusion_common::DataFusionError::External(Box::new(e)))?; + Ok(batch) + }); + Box::pin(datafusion_physical_plan::stream::RecordBatchStreamAdapter::new(schema, stream)) + } +} + #[cfg(test)] mod tests { /// The gate's reproducer: the validator applies the same schema-level @@ -2646,6 +2795,8 @@ mod tests { ); } + /// A create carries a declaration only if it re-plans completely; this + /// one lacks its inputs and is refused before its forged value matters. #[tokio::test] async fn test_create_table_cannot_inject_a_declaration() { let conn = connect("memory://").execute().await.unwrap(); @@ -2673,7 +2824,7 @@ mod tests { .await .unwrap_err(); assert!( - matches!(&err, Error::InvalidInput { message } if message.contains("computed()")), + matches!(&err, Error::InvalidInput { message } if message.contains("computed column 'doubled'")), "{err:?}" ); } From 19fb665c764ac1d4057747677e981049c0f64c01 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Tue, 8 Sep 2026 12:03:14 +0000 Subject: [PATCH 186/206] =?UTF-8?q?Bump=20version:=200.39.0-beta.4=20?= =?UTF-8?q?=E2=86=92=200.39.0-beta.5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 215d1bf4a..061f4aa9f 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.39.0-beta.4" +current_version = "0.39.0-beta.5" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 2042305e5..d979cb95f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5476,7 +5476,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.39.0-beta.4" +version = "0.39.0-beta.5" dependencies = [ "ahash", "anyhow", @@ -5567,7 +5567,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.39.0-beta.4" +version = "0.39.0-beta.5" dependencies = [ "arrow-array", "arrow-buffer", @@ -5592,7 +5592,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.39.0-beta.4" +version = "0.39.0-beta.5" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 96fb7c11a..bf853c725 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.39.0-beta.4 + 0.39.0-beta.5 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 1b995bff0..d021cc77a 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.4 + 0.39.0-beta.5 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 4eca407af..8f64bd4d9 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.4 + 0.39.0-beta.5 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index b58c97af8..a58f4f1f6 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.39.0-beta.4" +version = "0.39.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 a8f14f9db..2268f09a9 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.39.0-beta.4", + "version": "0.39.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 0d49b045f..f82f46c85 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.39.0-beta.4", + "version": "0.39.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 418656624..e0ea6eddc 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.39.0-beta.4", + "version": "0.39.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 5a46b698f..aa8e85157 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.39.0-beta.4", + "version": "0.39.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 4e6ab2967..087702133 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.39.0-beta.4", + "version": "0.39.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 003db2da7..2c3282b35 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.39.0-beta.4", + "version": "0.39.0-beta.5", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 0cc18c6f6..301d8f11d 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.39.0-beta.4", + "version": "0.39.0-beta.5", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index aa571aff6..871cdf80b 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.39.0-beta.4", + "version": "0.39.0-beta.5", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index 9b21acb9e..e9ef79b93 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.39.0-beta.4" +version = "0.39.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 f206677f4..a732534a5 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.39.0-beta.4" +version = "0.39.0-beta.5" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 3e3878b223844cd27cdc58a86d200d6c79097feb Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Tue, 8 Sep 2026 05:12:45 -0700 Subject: [PATCH 187/206] chore: update lance dependency to v12.0.0-beta.15 (#4143) Updates the Rust workspace Lance dependencies, Cargo lockfile, and Java lance-core from v12.0.0-beta.14 to [v12.0.0-beta.15](https://github.com/lance-format/lance/releases/tag/v12.0.0-beta.15). No compatibility fixes were required; `cargo clippy --quiet --workspace --tests --all-features -- -D warnings`, `cargo fmt --all --quiet`, and `git diff --check` passed. --------- Co-authored-by: Jack Ye --- Cargo.lock | 84 +++++++++++++------------- Cargo.toml | 28 ++++----- java/pom.xml | 2 +- nodejs/__test__/table.test.ts | 4 +- python/python/tests/test_blob.py | 5 +- python/python/tests/test_namespace.py | 8 ++- python/python/tests/test_query.py | 48 ++++++++++++--- python/python/tests/test_table.py | 20 ++++-- rust/lancedb/src/blob.rs | 18 +++--- rust/lancedb/src/materialized_view.rs | 11 +++- rust/lancedb/src/table.rs | 2 +- rust/lancedb/tests/blob_integration.rs | 12 +++- 12 files changed, 155 insertions(+), 87 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d979cb95f..7c50a92a1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3526,8 +3526,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4886,8 +4886,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arc-swap", "arrow", @@ -4959,8 +4959,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow-array", "arrow-buffer", @@ -4982,7 +4982,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow-array", "arrow-buffer", @@ -4996,7 +4996,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow-array", "arrow-schema", @@ -5005,8 +5005,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrayref", "crunchy", @@ -5016,8 +5016,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow-array", "arrow-buffer", @@ -5054,8 +5054,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow", "arrow-array", @@ -5085,8 +5085,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow", "arrow-array", @@ -5103,8 +5103,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "proc-macro2", "quote", @@ -5113,8 +5113,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow-arith", "arrow-array", @@ -5147,8 +5147,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow-arith", "arrow-array", @@ -5179,8 +5179,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arc-swap", "arrow", @@ -5244,8 +5244,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow-array", "arrow-schema", @@ -5267,8 +5267,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow", "arrow-array", @@ -5308,8 +5308,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow-array", "arrow-schema", @@ -5323,8 +5323,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow", "async-trait", @@ -5338,8 +5338,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow", "arrow-ipc", @@ -5392,8 +5392,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow-array", "arrow-buffer", @@ -5407,8 +5407,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow", "arrow-array", @@ -5448,8 +5448,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "arrow-array", "arrow-schema", @@ -5462,8 +5462,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "12.0.0-beta.14" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.14#a8a101774a1c9647065cc60137094feadbe55296" +version = "12.0.0-beta.15" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 5c5b0362d..e3cba6366 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=12.0.0-beta.14", default-features = false, "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=12.0.0-beta.14", default-features = false, "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=12.0.0-beta.14", default-features = false, "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=12.0.0-beta.14", "tag" = "v12.0.0-beta.14", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=12.0.0-beta.15", default-features = false, "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=12.0.0-beta.15", default-features = false, "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=12.0.0-beta.15", default-features = false, "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index 8f64bd4d9..56a30b983 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 12.0.0-beta.14 + 12.0.0-beta.15 false 2.30.0 1.7 diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index 6f80ca74e..d11169b46 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -281,7 +281,7 @@ describe.each([arrow15, arrow16, arrow17, arrow18])( numIndices: 0, numRows: 3, // Full on-disk size of the two data files, footers and metadata included. - totalBytes: 684, + totalBytes: 550, }); // Index files count toward totalBytes too (only deletion files and @@ -289,7 +289,7 @@ describe.each([arrow15, arrow16, arrow17, arrow18])( await table.createIndex("id", { config: Index.btree() }); const statsWithIndex = await table.stats(); expect(statsWithIndex.numIndices).toBe(1); - expect(statsWithIndex.totalBytes).toBeGreaterThan(684); + expect(statsWithIndex.totalBytes).toBeGreaterThan(550); }); it("should overwrite data if asked", async () => { diff --git a/python/python/tests/test_blob.py b/python/python/tests/test_blob.py index 1f158fb49..298b021df 100644 --- a/python/python/tests/test_blob.py +++ b/python/python/tests/test_blob.py @@ -297,7 +297,10 @@ def test_blob_v2_projection_sources_use_typed_column_name(): def _legacy_v1_table(name): - db = lancedb.connect("memory:///") + # Legacy v1 blob columns are only writable at file version <= 2.1. + db = lancedb.connect( + "memory:///", storage_options={"new_table_data_storage_version": "2.1"} + ) schema = pa.schema( [ pa.field("id", pa.int64()), diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index f8cbfe92c..7f095b71d 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -193,7 +193,13 @@ class TestNamespaceConnection: ), ) - table = db.create_table("blob_table", data, namespace_path=["test_ns"]) + # Legacy v1 blob columns are only writable at file version <= 2.1. + table = db.create_table( + "blob_table", + data, + namespace_path=["test_ns"], + storage_options={"new_table_data_storage_version": "2.1"}, + ) df = table.to_pandas(blob_mode="lazy").sort_values("id") blob = df["blob"].iloc[0] diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 6fbe0689b..e3d55917d 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -40,6 +40,10 @@ from utils import exception_output from importlib.util import find_spec +# Legacy v1 blob columns are only writable at file version <= 2.1. +LEGACY_BLOB_STORAGE_OPTIONS = {"new_table_data_storage_version": "2.1"} + + def _blob_query_data(): return pa.table( { @@ -119,13 +123,17 @@ def _assert_blob_bytes_projection(df): def _blob_query_table(db, name, blob_schema): if blob_schema == "v1": - return db.create_table(name, _blob_query_data()) + return db.create_table( + name, _blob_query_data(), storage_options=LEGACY_BLOB_STORAGE_OPTIONS + ) return _create_blob_v2_query_table(db, name) async def _blob_query_table_async(db, name, blob_schema): if blob_schema == "v1": - return await db.create_table(name, _blob_query_data()) + return await db.create_table( + name, _blob_query_data(), storage_options=LEGACY_BLOB_STORAGE_OPTIONS + ) return await _create_blob_v2_query_table_async(db, name) @@ -275,7 +283,9 @@ async def test_query_to_pandas_kwargs(table, table_async): def test_plain_scan_query_to_pandas_blob_modes(tmp_db, blob_mode): pytest.importorskip("lance") table = tmp_db.create_table( - f"test_query_to_pandas_blob_{blob_mode}", _blob_query_data() + f"test_query_to_pandas_blob_{blob_mode}", + _blob_query_data(), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, ) df = ( @@ -322,7 +332,9 @@ def test_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow( ): pytest.importorskip("lance") table = tmp_db.create_table( - "test_query_to_pandas_blob_no_arrow_collect", _blob_query_data() + "test_query_to_pandas_blob_no_arrow_collect", + _blob_query_data(), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, ) query = table.search().where("id = 1").select(["id", "blob"]) @@ -347,7 +359,9 @@ def test_plain_scan_query_to_pandas_blob_descriptions_flatten_uses_scanner( ): pytest.importorskip("lance") table = tmp_db.create_table( - "test_query_to_pandas_blob_desc_flatten", _blob_query_data() + "test_query_to_pandas_blob_desc_flatten", + _blob_query_data(), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, ) query = table.search().where("id = 1").select(["id", "blob"]) @@ -365,7 +379,11 @@ def test_plain_scan_query_to_pandas_blob_descriptions_flatten_uses_scanner( def test_plain_scan_query_to_pandas_scanner_state(tmp_db): pytest.importorskip("lance") data = _blob_query_data() - table = tmp_db.create_table("test_query_to_pandas_scanner_state", data.slice(0, 2)) + table = tmp_db.create_table( + "test_query_to_pandas_scanner_state", + data.slice(0, 2), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) table.add(data.slice(2, 2)) fragments = table.to_lance().get_fragments() @@ -400,7 +418,9 @@ def test_plain_scan_query_to_pandas_scanner_state(tmp_db): async def test_async_plain_scan_query_to_pandas_blob_projection(tmp_db_async): pytest.importorskip("lance") table = await tmp_db_async.create_table( - "test_async_query_to_pandas_blob_projection", _blob_query_data() + "test_async_query_to_pandas_blob_projection", + _blob_query_data(), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, ) lazy_df = await ( @@ -452,7 +472,9 @@ async def test_async_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow ): pytest.importorskip("lance") table = await tmp_db_async.create_table( - "test_async_query_to_pandas_blob_no_arrow_collect", _blob_query_data() + "test_async_query_to_pandas_blob_no_arrow_collect", + _blob_query_data(), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, ) query = table.query().where("id = 1").select(["id", "blob"]) @@ -474,7 +496,11 @@ async def test_async_plain_scan_query_to_pandas_blob_mode_does_not_collect_arrow def test_vector_query_to_pandas_blob_mode_requires_native_path(tmp_db): pytest.importorskip("lance") - table = tmp_db.create_table("test_vector_query_blob_mode", _blob_query_data()) + table = tmp_db.create_table( + "test_vector_query_blob_mode", + _blob_query_data(), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) with pytest.raises(RuntimeError, match="Lance native pandas conversion"): table.search([1.0, 0.0]).select(["blob", "vector"]).limit(1).to_pandas( @@ -485,7 +511,9 @@ def test_vector_query_to_pandas_blob_mode_requires_native_path(tmp_db): def test_vector_query_to_pandas_blob_descriptions_requires_plain_scan(tmp_db): pytest.importorskip("lance") table = tmp_db.create_table( - "test_vector_query_blob_descriptions", _blob_query_data() + "test_vector_query_blob_descriptions", + _blob_query_data(), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, ) with pytest.raises(RuntimeError, match="plain scan query"): diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 82ad045c8..3e1f6fb37 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -64,15 +64,23 @@ async def _blob_v2_table_async(db: AsyncConnection, name: str): return table +# Legacy v1 blob columns are only writable at file version <= 2.1. +LEGACY_BLOB_STORAGE_OPTIONS = {"new_table_data_storage_version": "2.1"} + + def _blob_table(db: DBConnection, name: str, blob_schema: str): if blob_schema == "v1": - return db.create_table(name, data=_blob_test_data()) + return db.create_table( + name, data=_blob_test_data(), storage_options=LEGACY_BLOB_STORAGE_OPTIONS + ) return _blob_v2_table(db, name) async def _blob_table_async(db: AsyncConnection, name: str, blob_schema: str): if blob_schema == "v1": - return await db.create_table(name, data=_blob_test_data()) + return await db.create_table( + name, data=_blob_test_data(), storage_options=LEGACY_BLOB_STORAGE_OPTIONS + ) return await _blob_v2_table_async(db, name) @@ -147,7 +155,11 @@ def test_table_to_pandas_invalid_blob_mode_non_blob_table(tmp_db: DBConnection): @pytest.mark.parametrize("blob_mode", ["lazy", "bytes", "descriptions"]) def test_table_to_pandas_blob_modes(tmp_db: DBConnection, blob_mode): pytest.importorskip("lance") - table = tmp_db.create_table(f"test_to_pandas_blob_{blob_mode}", _blob_test_data()) + table = tmp_db.create_table( + f"test_to_pandas_blob_{blob_mode}", + _blob_test_data(), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) df = table.to_pandas(blob_mode=blob_mode) @@ -3959,7 +3971,7 @@ def test_stats(mem_db: DBConnection): print(f"{stats=}") assert stats == { # Full on-disk size of the data file, footer and metadata included. - "total_bytes": 633, + "total_bytes": 637, "num_rows": 2, "num_indices": 0, "fragment_stats": { diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index 6a0d968b0..cbc0724c6 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -532,10 +532,11 @@ mod tests { fn storage_version_bumps_to_v2_2() { let mut params = WriteParams::default(); ensure_blob_storage_version(&blob_schema(), &mut params); - assert_eq!( - params.data_storage_version.unwrap().resolve(), - ConcreteFileVersion::V2_2 - ); + let resolved = params + .data_storage_version + .unwrap_or(LanceFileVersion::Stable) + .resolve(); + assert_eq!(resolved, ConcreteFileVersion::V2_2); assert!(!params.enable_stable_row_ids); } @@ -547,10 +548,11 @@ mod tests { }; ensure_blob_storage_version(&blob_schema(), &mut params); assert!(params.enable_stable_row_ids); - assert_eq!( - params.data_storage_version.unwrap().resolve(), - ConcreteFileVersion::V2_2 - ); + let resolved = params + .data_storage_version + .unwrap_or(LanceFileVersion::Stable) + .resolve(); + assert_eq!(resolved, ConcreteFileVersion::V2_2); } #[test] diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index 80546b4a4..98f1338d0 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -1917,7 +1917,16 @@ mod tests { /// declaration buried in a struct child binds as hard as one on top. #[tokio::test] async fn test_nested_projection_metadata_and_declarations() { - let conn = connect("memory://").execute().await.unwrap(); + // The schema below carries the legacy v1 blob marker, which Lance only + // allows writing at file version <= 2.1. + let conn = connect("memory://") + .storage_options([( + crate::database::listing::OPT_NEW_TABLE_STORAGE_VERSION, + "2.1", + )]) + .execute() + .await + .unwrap(); let payload = crate::blob("payload", true).with_metadata(HashMap::from([ ("lance-encoding:blob".to_string(), "true".to_string()), ( diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 56d7ce518..636aaefd0 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -5678,7 +5678,7 @@ mod tests { TableStatistics { num_rows: 250, num_indices: 0, - total_bytes: 8925, + total_bytes: 8969, fragment_stats: FragmentStatistics { num_fragments: 11, num_small_fragments: 11, diff --git a/rust/lancedb/tests/blob_integration.rs b/rust/lancedb/tests/blob_integration.rs index b884a48f7..118ecf5c9 100644 --- a/rust/lancedb/tests/blob_integration.rs +++ b/rust/lancedb/tests/blob_integration.rs @@ -19,6 +19,7 @@ use lancedb::{ connect, connect_namespace, database::listing::{ ListingDatabaseOptions, NewTableConfig, OPT_NEW_TABLE_ENABLE_STABLE_ROW_IDS, + OPT_NEW_TABLE_STORAGE_VERSION, }, query::{ExecutableQuery, QueryBase}, table::{AddDataMode, CompactionOptions, OptimizeAction, OptimizeStats, WriteOptions}, @@ -146,7 +147,10 @@ async fn non_blob_table_keeps_default_format_and_row_id_setting() -> Result<()> let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int64, false)])); let table = db.create_empty_table("t", schema).execute().await?; - assert!(!supports_blob_v2(storage_format_version(&table).await)); + assert_eq!( + storage_format_version(&table).await, + LanceFileVersion::Stable.resolve() + ); assert!(!uses_stable_row_ids(&table).await); Ok(()) } @@ -809,7 +813,11 @@ async fn fetch_blobs_rejects_unknown_column() -> Result<()> { #[tokio::test] async fn fetch_blobs_rejects_legacy_v1_blob_column() -> Result<()> { let tmp = tempdir().unwrap(); - let db = connect(tmp.path().to_str().unwrap()).execute().await?; + // Legacy v1 blob columns are only writable at file version <= 2.1. + let db = connect(tmp.path().to_str().unwrap()) + .storage_options([(OPT_NEW_TABLE_STORAGE_VERSION, "2.1")]) + .execute() + .await?; let legacy = Field::new("image", DataType::LargeBinary, true).with_metadata( std::collections::HashMap::from([("lance-encoding:blob".to_string(), "true".to_string())]), ); From 2e205ac9bbea030e23db06fdb5ff1278b0100596 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Tue, 8 Sep 2026 12:14:12 +0000 Subject: [PATCH 188/206] =?UTF-8?q?Bump=20version:=200.39.0-beta.5=20?= =?UTF-8?q?=E2=86=92=200.39.0-beta.6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index 061f4aa9f..de5f91973 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.39.0-beta.5" +current_version = "0.39.0-beta.6" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 7c50a92a1..a2a8797f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5476,7 +5476,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.39.0-beta.5" +version = "0.39.0-beta.6" dependencies = [ "ahash", "anyhow", @@ -5567,7 +5567,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.39.0-beta.5" +version = "0.39.0-beta.6" dependencies = [ "arrow-array", "arrow-buffer", @@ -5592,7 +5592,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.39.0-beta.5" +version = "0.39.0-beta.6" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index bf853c725..17d14df15 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.39.0-beta.5 + 0.39.0-beta.6 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index d021cc77a..c5c928219 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.5 + 0.39.0-beta.6 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 56a30b983..67363dee4 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.5 + 0.39.0-beta.6 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index a58f4f1f6..c4ef09cda 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.39.0-beta.5" +version = "0.39.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 2268f09a9..7ebfcaacb 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.39.0-beta.5", + "version": "0.39.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 f82f46c85..1e2ad10b3 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.39.0-beta.5", + "version": "0.39.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 e0ea6eddc..d4843f743 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.39.0-beta.5", + "version": "0.39.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 aa8e85157..d4107659a 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.39.0-beta.5", + "version": "0.39.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 087702133..d14af6c09 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.39.0-beta.5", + "version": "0.39.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 2c3282b35..823db7c7c 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.39.0-beta.5", + "version": "0.39.0-beta.6", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 301d8f11d..c2f0b0a80 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.39.0-beta.5", + "version": "0.39.0-beta.6", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 871cdf80b..dae336765 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.39.0-beta.5", + "version": "0.39.0-beta.6", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index e9ef79b93..e0c72df48 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.39.0-beta.5" +version = "0.39.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 a732534a5..c8f17d50c 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.39.0-beta.5" +version = "0.39.0-beta.6" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From c7b051aff7039333a3f61b79217246c27676806a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=BF=97=E8=B0=A6?= <89645338+simpleqt@users.noreply.github.com> Date: Wed, 9 Sep 2026 04:53:38 +0800 Subject: [PATCH 189/206] docs: fix spelling typos across python package docstrings (#4146) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Six files carried spelling typos in user-visible docstrings: - `table.py` (×3) + `remote/table.py`: "The **targetted** vector to search for" → "targeted" - `query.py`: "pa.Array **wouln't** be allowed" → "wouldn't" - `embeddings/gte.py`: "mlx package **insalled**" → "installed" - `rerankers/base.py`: "This is **inteded**" → "intended" - `index.py`: "dimension **divded** by 8" → "divided" Docstrings only. --- python/python/lancedb/embeddings/gte.py | 2 +- python/python/lancedb/index.py | 2 +- python/python/lancedb/query.py | 2 +- python/python/lancedb/remote/table.py | 2 +- python/python/lancedb/rerankers/base.py | 2 +- python/python/lancedb/table.py | 6 +++--- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/python/python/lancedb/embeddings/gte.py b/python/python/lancedb/embeddings/gte.py index 9bad4b54f..10dcaf456 100644 --- a/python/python/lancedb/embeddings/gte.py +++ b/python/python/lancedb/embeddings/gte.py @@ -21,7 +21,7 @@ class GteEmbeddings(TextEmbeddingFunction): An embedding function that uses GTE-LARGE MLX format(for Apple silicon devices only) as well as the standard cpu/gpu version from: https://huggingface.co/thenlper/gte-large. - For Apple users, you will need the mlx package insalled, which can be done with: + For Apple users, you will need the mlx package installed, which can be done with: pip install mlx Parameters diff --git a/python/python/lancedb/index.py b/python/python/lancedb/index.py index 948342887..78ee72e57 100644 --- a/python/python/lancedb/index.py +++ b/python/python/lancedb/index.py @@ -751,7 +751,7 @@ class IvfPq: This value controls how much the vector is compressed during the quantization step. The more sub vectors there are the less the vector is compressed. The default is the dimension of the vector divided by 16. If - the dimension is not evenly divisible by 16 we use the dimension divded by + the dimension is not evenly divisible by 16 we use the dimension divided by 8. The above two cases are highly preferred. Having 8 or 16 values per diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index c76e9e7db..80927093c 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -859,7 +859,7 @@ class Query(pydantic.BaseModel): return query # This tells pydantic to allow custom types (needed for the `vector` query since - # pa.Array wouln't be allowed otherwise) + # pa.Array wouldn't be allowed otherwise) model_config = pydantic.ConfigDict(arbitrary_types_allowed=True) diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 3eb9cbfa1..89b958165 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -720,7 +720,7 @@ class RemoteTable(Table): Parameters ---------- query: list/np.ndarray/str/PIL.Image.Image, default None - The targetted vector to search for. + The targeted vector to search for. - *default None*. Acceptable types are: list, np.ndarray, PIL.Image.Image diff --git a/python/python/lancedb/rerankers/base.py b/python/python/lancedb/rerankers/base.py index 7bc7ff105..4af938a1e 100644 --- a/python/python/lancedb/rerankers/base.py +++ b/python/python/lancedb/rerankers/base.py @@ -175,7 +175,7 @@ class Reranker(ABC): if the results haven't been executed yet or the results in arrow format. query : str or None, The input query. Some rerankers might not need the query to rerank. - In that case, it can be set to None explicitly. This is inteded to + In that case, it can be set to None explicitly. This is intended to be handled by the reranker implementations. deduplicate : bool, optional Whether to deduplicate the results based on the `_rowid` column, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 127ad3722..6b9f450db 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -1619,7 +1619,7 @@ class Table(ABC): Parameters ---------- query: list/np.ndarray/str/PIL.Image.Image, default None - The targetted vector to search for. + The targeted vector to search for. - *default None*. Acceptable types are: list, np.ndarray, PIL.Image.Image @@ -3841,7 +3841,7 @@ class LanceTable(Table): Parameters ---------- query: list/np.ndarray/str/PIL.Image.Image, default None - The targetted vector to search for. + The targeted vector to search for. - *default None*. Acceptable types are: list, np.ndarray, PIL.Image.Image @@ -5814,7 +5814,7 @@ class AsyncTable: Parameters ---------- query: list/np.ndarray/str/PIL.Image.Image, default None - The targetted vector to search for. + The targeted vector to search for. - *default None*. Acceptable types are: list, np.ndarray, PIL.Image.Image From 577fb48376b76d9aa44598a0f1b1f44deff444bc Mon Sep 17 00:00:00 2001 From: Madan Kumar Date: Wed, 9 Sep 2026 04:12:06 +0530 Subject: [PATCH 190/206] fix(python): apply offset when combining async hybrid results (#4028) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #4027 ## Summary `AsyncHybridQuery` (`table.query().nearest_to(...).nearest_to_text(...)`) paginates incorrectly when `.offset()` is used: the second page repeats rows from the first page and silently drops others. `offset()` on a hybrid query pushes the offset down into *both* sub-queries (`HybridQuery::offset` in `python/src/query.rs` forwards to `inner_vec` and `inner_fts`), so each sub-query independently skips its own first `offset` rows before the results are fused. `AsyncHybridQuery.to_batches` then called `_combine_hybrid_results(..., limit=self._inner.get_limit())` without an `offset`, so the reranked table was sliced starting at position 0 and the sub-query limits were never raised to cover the skipped prefix. On the 4-row fixture in `test_hybrid_query.py`, with `_rowid` ordering `[3, 0, 2, 1]`: | query | before | after | | --- | --- | --- | | `.limit(2)` | `[0, 3]` | `[0, 3]` | | `.offset(2).limit(2)` | `[3, 1]` | `[2, 1]` | Row `3` was returned on both pages and row `2` was never returned at all. This is the async counterpart of #3769 (`Fixes #3765`), which fixed the same bug in the synchronous `LanceHybridQueryBuilder`. #3765 explicitly deferred the async path; this PR closes that gap and reuses the `offset` parameter that #3769 already added to `_combine_hybrid_results`. The synchronous path is unaffected — it was fixed in #3769. ## Changes `python/python/lancedb/query.py`, `AsyncHybridQuery.to_batches`: - Each sub-query now fetches `limit + offset` rows and its own offset is reset to 0, so the fused result contains the full prefix the window is sliced out of. - The combined, reranked table is sliced with `offset=` instead of always starting at 0. Both halves are needed: raising the sub-query limits without the final slice still returns page 1, and slicing without raising the limits still misses rows. `nodejs` has no equivalent hybrid combine path, so there is no SDK parity gap here. ## Test plan - [x] New regression test `test_async_hybrid_query_offset` in `python/python/tests/test_hybrid_query.py`, mirroring the sync `test_hybrid_query_offset`. It asserts the offset window is a suffix of the un-offset result *and* that page 1 + page 2 together cover every row exactly once (a row-count-only assertion would pass even with duplicates). - [x] `pytest python/tests/test_hybrid_query.py` — 16 passed - [x] `pytest python/tests/test_rerankers.py` — 9 passed, 11 skipped - [x] `pytest python/tests/test_query.py` — 86 passed - [x] `pytest --doctest-modules python/lancedb/query.py` — 13 passed - [x] `ruff format --check` / `ruff check` — clean --- ## Scope, after review @lancedb-gatekeeper raised three points. Two were mine and are fixed in `04d07c2`; the third is deliberately left alone and I'd like a maintainer's call on it. **Fixed — effective limit was read from the FTS child only.** `HybridQuery::get_limit()` (`python/src/query.rs:1159`) returns `self.inner_fts.inner.current_request().limit`, so an FTS-first hybrid with no explicit `.limit()` yielded `None`, skipped the widening branch and passed `limit=None` to the combiner — returning the union of both candidate lists instead of the documented default of 10. The limit is now derived from both children with a `DEFAULT_HYBRID_LIMIT = 10` fallback, so construction order no longer matters. **Fixed — `explain_plan()` / `analyze_plan()` described a different query than the one that ran.** Both built their children straight from `self._inner`, bypassing the limit/offset rewrite in `to_batches`, and reported `skip=2, fetch=2` while execution used `skip=0, fetch=4`. Child preparation now lives in one `_create_child_queries()` helper used by all three. > **Visible change to `explain_plan()` output:** because the plan is now built from the real execution children, which carry `with_row_id()`, the two `ProjectionExec` lines gain a `_rowid` column. The doctest is updated to match. This is the diagnostic becoming truthful rather than the assertion being weakened — it is still an exact-match comparison. **Not fixed here — RRF candidate-pool invariance.** Widening each sub-query to `limit + offset` does change the candidate pool between page requests, so the fused ranking can shift and pagination can still repeat rows. That's a real problem, but it is exactly what the merged sync path does today: ```python # LanceHybridQueryBuilder (sync), merged in #3769 sub_query_limit = self._limit + (self._offset or 0) ``` Making the pool invariant means choosing a contract — a fixed candidate pool, or an explicit cursor — and that ought to apply to sync and async together rather than letting the two paths diverge. I've asked in the review thread which way you'd prefer, and I'm happy to do it here or in a follow-up covering both paths. So, to be precise about what this PR delivers: it makes `.offset()` take effect on the async hybrid path and makes the diagnostics honest. It does not make hybrid pagination stable across pages under reranking — that needs the contract decision above. --- python/python/lancedb/query.py | 73 +++++++++++++++----- python/python/tests/test_hybrid_query.py | 87 ++++++++++++++++++++++++ 2 files changed, 144 insertions(+), 16 deletions(-) diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 80927093c..cef89e63c 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -78,6 +78,10 @@ if TYPE_CHECKING: T = TypeVar("T", bound="LanceModel") AnalyzePlanDistributedMetrics = Literal["aggregate", "per_worker", "full"] +# Number of rows a hybrid query returns when no limit was set on it. This +# mirrors the default the Rust query builder applies to its sub-queries. +DEFAULT_HYBRID_LIMIT = 10 + @runtime_checkable class _LanceScanner(Protocol): @@ -3893,14 +3897,54 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): return self + def _create_child_queries( + self, + ) -> Tuple["AsyncFTSQuery", "AsyncVectorQuery", int, int]: + """Build the sub-queries that make up this hybrid query. + + Execution, `explain_plan` and `analyze_plan` all go through here so that + the plans that are reported are the plans that actually run. + + Returns the two sub-queries along with the effective limit and offset of + the hybrid query itself. + """ + fts_query = AsyncFTSQuery(self._inner.to_fts_query(), self._table) + vec_query = AsyncVectorQuery(self._inner.to_vector_query(), self._table) + + fts_req = fts_query._inner.to_query_request() + vec_req = vec_query._inner.to_query_request() + + # Only one of the two sub-queries carries the limit when it was never + # set explicitly: nearest_to()/nearest_to_text() build the sibling query + # from scratch, and that is where the default gets filled in. Which one + # that is depends on the order the hybrid query was built in, so look at + # both rather than at a single side. + limit = fts_req.limit if fts_req.limit is not None else vec_req.limit + if limit is None: + limit = DEFAULT_HYBRID_LIMIT + offset = fts_req.offset or vec_req.offset or 0 + + fts_query.with_row_id() + vec_query.with_row_id() + + # offset() pushes the offset down into both sub-queries, which would make + # each of them skip its own first `offset` rows. The window has to be + # taken out of the combined, reranked results instead, so fetch the + # skipped prefix here too and slice it off afterwards. + fts_query.limit(limit + offset) + vec_query.limit(limit + offset) + fts_query.offset(0) + vec_query.offset(0) + + return fts_query, vec_query, limit, offset + async def to_batches( self, *, max_batch_length: Optional[int] = None, timeout: Optional[timedelta] = None, ) -> AsyncRecordBatchReader: - fts_query = AsyncFTSQuery(self._inner.to_fts_query(), self._table) - vec_query = AsyncVectorQuery(self._inner.to_vector_query(), self._table) + fts_query, vec_query, limit, offset = self._create_child_queries() req = fts_query._inner.to_query_request() blob_auto_row_id = False @@ -3920,9 +3964,6 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): self._blob_auto_row_id = blob_auto_row_id self._blob_paths = blob_paths - fts_query.with_row_id() - vec_query.with_row_id() - fts_results, vector_results = await asyncio.gather( fts_query.to_arrow(timeout=timeout), vec_query.to_arrow(timeout=timeout), @@ -3934,8 +3975,9 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): norm=self._norm, fts_query=fts_query.get_query(), reranker=self._reranker, - limit=self._inner.get_limit(), + limit=limit, with_row_ids=True, + offset=offset, ) if ( not self._user_requested_row_id() @@ -3964,14 +4006,14 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): ... print(plan) >>> asyncio.run(doctest_example()) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE RRFReranker(K=60) - ProjectionExec: expr=[vector@0 as vector, text@3 as text, _distance@2 as _distance] + ProjectionExec: expr=[vector@0 as vector, text@3 as text, _distance@2 as _distance, _rowid@1 as _rowid] LanceRead: uri=..., projection=[text], source=stream(_rowid) GlobalLimitExec: skip=0, fetch=10 FilterExec: _distance@2 IS NOT NULL SortExec: TopK(fetch=10), expr=[_distance@2 ASC NULLS LAST, _rowid@1 ASC NULLS LAST], preserve_partitioning=[false] KNNVectorDistance: metric=l2 LanceRead: uri=..., projection=[vector], ... - ProjectionExec: expr=[vector@2 as vector, text@3 as text, _score@1 as _score] + ProjectionExec: expr=[vector@2 as vector, text@3 as text, _score@1 as _score, _rowid@0 as _rowid] LanceRead: uri=..., projection=[vector, text], source=stream(_rowid) GlobalLimitExec: skip=0, fetch=10 MatchQuery: column=text, query=[hello] @@ -3986,8 +4028,9 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): plan : str """ # noqa: E501 - vector_plan = await self._inner.to_vector_query().explain_plan(verbose) - fts_plan = await self._inner.to_fts_query().explain_plan(verbose) + fts_query, vec_query, _, _ = self._create_child_queries() + vector_plan = await vec_query.explain_plan(verbose) + fts_plan = await fts_query.explain_plan(verbose) # Indent sub-plans under the reranker indented_vector = "\n".join(" " + line for line in vector_plan.splitlines()) indented_fts = "\n".join(" " + line for line in fts_plan.splitlines()) @@ -4014,14 +4057,12 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase): ------- plan : str """ + fts_query, vec_query, _, _ = self._create_child_queries() + results = ["Vector Search Query:"] - results.append( - await self._inner.to_vector_query().analyze_plan(distributed_metrics) - ) + results.append(await vec_query.analyze_plan(distributed_metrics)) results.append("FTS Search Query:") - results.append( - await self._inner.to_fts_query().analyze_plan(distributed_metrics) - ) + results.append(await fts_query.analyze_plan(distributed_metrics)) return "\n".join(results) diff --git a/python/python/tests/test_hybrid_query.py b/python/python/tests/test_hybrid_query.py index 5e9b45ecb..61b8001cf 100644 --- a/python/python/tests/test_hybrid_query.py +++ b/python/python/tests/test_hybrid_query.py @@ -203,6 +203,93 @@ async def test_async_hybrid_query_default_limit(table: AsyncTable): assert texts.count("a") == 1 +@pytest.mark.asyncio +async def test_async_hybrid_query_offset(table: AsyncTable): + # The offset window of a hybrid query must be a suffix of the same query + # run without an offset. Skipping the first rows of each sub-query instead + # of the first rows of the fused result silently changes which rows land in + # the window. + full = await ( + table.query() + .nearest_to([0.0, 0.4]) + .nearest_to_text("dog") + .limit(4) + .with_row_id() + .to_arrow() + ) + assert len(full) == 4 + + second_page = await ( + table.query() + .nearest_to([0.0, 0.4]) + .nearest_to_text("dog") + .offset(2) + .limit(2) + .with_row_id() + .to_arrow() + ) + assert second_page["_rowid"].to_pylist() == full["_rowid"].to_pylist()[2:] + + first_page = await ( + table.query() + .nearest_to([0.0, 0.4]) + .nearest_to_text("dog") + .limit(2) + .with_row_id() + .to_arrow() + ) + # Paging through the result must visit every row exactly once: no row + # repeated from the previous page and none dropped between the two. + paged = first_page["_rowid"].to_pylist() + second_page["_rowid"].to_pylist() + assert sorted(paged) == sorted(full["_rowid"].to_pylist()) + + +@pytest.mark.asyncio +async def test_async_hybrid_query_fts_first_default_limit(table: AsyncTable): + # nearest_to() and nearest_to_text() build their new sibling sub-query from + # scratch, and that is the sub-query the default limit ends up on. So the + # side that carries the limit depends on the order the hybrid query was + # built in, and looking at only one side loses the limit for half the ways + # a hybrid query can be written. Without a limit the combined results are + # not truncated at all and the whole union of both candidate lists is + # returned. + await table.add([{"text": "dog", "vector": [50.0 + i, 50.0]} for i in range(10)]) + + result = await ( + table.query().nearest_to_text("dog").nearest_to([0.1, 0.1]).to_arrow() + ) + assert len(result) == 10 + + offset_result = await ( + table.query().nearest_to_text("dog").nearest_to([0.1, 0.1]).offset(2).to_arrow() + ) + assert len(offset_result) == 10 + + +@pytest.mark.asyncio +async def test_async_hybrid_query_explain_plan_matches_execution(table: AsyncTable): + # Paging rewrites the sub-queries: each one fetches limit + offset rows with + # no offset of its own, and the window is sliced out after fusion. The plans + # have to be built from those rewritten sub-queries, otherwise explain_plan + # and analyze_plan describe a query that is never run. + query = ( + table.query().nearest_to([0.0, 0.4]).nearest_to_text("dog").offset(2).limit(2) + ) + await query.to_arrow() + + plan = await query.explain_plan() + assert [ + line.strip() for line in plan.splitlines() if "GlobalLimitExec" in line + ] == [ + "GlobalLimitExec: skip=0, fetch=4", + "GlobalLimitExec: skip=0, fetch=4", + ] + + analyzed = await query.analyze_plan() + assert analyzed.count("skip=0, fetch=4") == 2 + assert "skip=2" not in analyzed + + def test_hybrid_query_offset(sync_table: Table): # The offset window of a hybrid query must be a suffix of the same query # run without an offset -- it must not be silently ignored. From 1da5876870e4766621d903fb4ce9e656d1261124 Mon Sep 17 00:00:00 2001 From: Will Jones Date: Wed, 9 Sep 2026 00:33:04 -0700 Subject: [PATCH 191/206] ci: add spell checking (#4148) Adds [typos](https://github.com/crate-ci/typos) as a CI check and pre-commit hook, the same way Lance does it, so misspellings like the ones fixed in #4146 get caught automatically going forward. This also fixes the misspellings `typos` found across the repo (Rust, Python, TypeScript source, comments, and generated docs), and adds a small `.typos.toml` with `extend-words` entries for terms that are correct but look like typos: `AKS` (Azure Kubernetes Service), `RabitQ` (a real quantization algorithm name), `mmaped` (the actual name of a `candle-core` API we call), and `Writeable` (from Python's `_typeshed.WriteableBuffer`). Third-party license files are excluded. Fixes #4147 Co-authored-by: Claude Sonnet 5 --- .github/workflows/typos.yml | 20 +++++++++++++++++++ .pre-commit-config.yaml | 4 ++++ .typos.toml | 19 ++++++++++++++++++ docs/openapi.yml | 2 +- docs/src/js/classes/MergeInsertBuilder.md | 2 +- docs/src/js/classes/Table.md | 2 +- docs/src/js/interfaces/HnswPqOptions.md | 2 +- docs/src/js/interfaces/IndexOptions.md | 2 +- docs/src/js/interfaces/IvfPqOptions.md | 2 +- nodejs/__test__/table.test.ts | 4 ++-- nodejs/lancedb/arrow.ts | 4 ++-- nodejs/lancedb/indices.ts | 6 +++--- nodejs/lancedb/merge.ts | 2 +- nodejs/lancedb/sanitize.ts | 2 +- nodejs/lancedb/table.ts | 2 +- .../python/lancedb/embeddings/instructor.py | 2 +- python/python/lancedb/table.py | 2 +- python/python/tests/test_embeddings.py | 10 +++++----- python/python/tests/test_fts.py | 18 +++++++++++++---- python/python/tests/test_rerankers.py | 2 +- python/python/tests/test_table.py | 2 +- python/src/query.rs | 2 +- rust/lancedb/src/arrow.rs | 2 +- rust/lancedb/src/connection.rs | 2 +- rust/lancedb/src/database/listing.rs | 18 ++++++++--------- rust/lancedb/src/database/namespace.rs | 6 +++--- rust/lancedb/src/index/vector.rs | 2 +- rust/lancedb/src/query.rs | 2 +- rust/lancedb/src/table.rs | 4 ++-- rust/lancedb/src/table/dataset.rs | 2 +- rust/lancedb/src/table/merge.rs | 2 +- rust/lancedb/src/table/merge/lsm.rs | 2 +- 32 files changed, 104 insertions(+), 51 deletions(-) create mode 100644 .github/workflows/typos.yml create mode 100644 .typos.toml diff --git a/.github/workflows/typos.yml b/.github/workflows/typos.yml new file mode 100644 index 000000000..70e96efe5 --- /dev/null +++ b/.github/workflows/typos.yml @@ -0,0 +1,20 @@ +name: Typo checker +on: + push: + branches: + - main + pull_request: + +permissions: + contents: read + +jobs: + run: + name: Spell Check with Typos + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v6 + + - name: Check spelling of the entire repository + uses: crate-ci/typos@6802cc60d4e7f78b9d5454f6cf3935c042d5e1e3 # v1.26.0 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7c98a344c..6b863aebb 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -10,6 +10,10 @@ repos: rev: v0.9.9 hooks: - id: ruff + - repo: https://github.com/crate-ci/typos + rev: v1.26.0 + hooks: + - id: typos # - repo: https://github.com/RobertCraigie/pyright-python # rev: v1.1.395 # hooks: diff --git a/.typos.toml b/.typos.toml new file mode 100644 index 000000000..7d1e4b14b --- /dev/null +++ b/.typos.toml @@ -0,0 +1,19 @@ +[default] +extend-ignore-re = ["(?Rm)^.*(#|//)\\s*spellchecker:disable-line$"] + +[default.extend-words] +# Azure Kubernetes Service, mentioned in rust/lancedb/src/remote/oauth.rs. +AKS = "AKS" +# RabitQ is the name of a vector quantization algorithm, not a typo of "Rabbit". +Rabit = "Rabit" +# `VarBuilder::from_mmaped_safetensors` is the real (if oddly-spelled) name of +# the candle-core API we call in rust/lancedb/src/embeddings/sentence_transformers.rs. +mmaped = "mmaped" +# `WriteableBuffer` is the real name of a type from Python's `_typeshed` stubs, +# used in python/python/lancedb/_blob.py. +Writeable = "Writeable" + +[files] +extend-exclude = [ + "*_THIRD_PARTY_LICENSES.*", +] diff --git a/docs/openapi.yml b/docs/openapi.yml index c4cb19754..e619aa038 100644 --- a/docs/openapi.yml +++ b/docs/openapi.yml @@ -155,7 +155,7 @@ paths: vector: type: FixedSizeList description: | - The targetted vector to search for. Required. + The targeted vector to search for. Required. vector_column: type: string description: | diff --git a/docs/src/js/classes/MergeInsertBuilder.md b/docs/src/js/classes/MergeInsertBuilder.md index beb6cdfce..81349a0bc 100644 --- a/docs/src/js/classes/MergeInsertBuilder.md +++ b/docs/src/js/classes/MergeInsertBuilder.md @@ -141,7 +141,7 @@ Currently this causes multiple copies of the row to be created but that behavior is subject to change. An optional condition may be specified. If it is, then only -matched rows that satisfy the condtion will be updated. Any +matched rows that satisfy the condition will be updated. Any rows that do not satisfy the condition will be left as they are. Failing to satisfy the condition does not cause a "matched row" to become a "not matched" row. diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 894d7a464..3847f3a39 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1266,7 +1266,7 @@ value is 0") Note: if your condition is something like "some_id_column == 7" and you are updating many rows (with different ids) then you will get better performance with a single [`merge_insert`] call instead of -repeatedly calilng this method. +repeatedly calling this method. ##### Parameters diff --git a/docs/src/js/interfaces/HnswPqOptions.md b/docs/src/js/interfaces/HnswPqOptions.md index 65e6ea0fb..6d42ed28f 100644 --- a/docs/src/js/interfaces/HnswPqOptions.md +++ b/docs/src/js/interfaces/HnswPqOptions.md @@ -118,7 +118,7 @@ Number of sub-vectors of PQ. This value controls how much the vector is compressed during the quantization step. The more sub vectors there are the less the vector is compressed. The default is the dimension of the vector divided by 16. If the dimension is not evenly divisible -by 16 we use the dimension divded by 8. +by 16 we use the dimension divided by 8. The above two cases are highly preferred. Having 8 or 16 values per subvector allows us to use efficient SIMD instructions. diff --git a/docs/src/js/interfaces/IndexOptions.md b/docs/src/js/interfaces/IndexOptions.md index 82764601d..eb1a10c8f 100644 --- a/docs/src/js/interfaces/IndexOptions.md +++ b/docs/src/js/interfaces/IndexOptions.md @@ -16,7 +16,7 @@ optional config: Index; Advanced index configuration -This option allows you to specify a specfic index to create and also +This option allows you to specify a specific index to create and also allows you to pass in configuration for training the index. See the static methods on Index for details on the various index types. diff --git a/docs/src/js/interfaces/IvfPqOptions.md b/docs/src/js/interfaces/IvfPqOptions.md index 7b47c8e53..7109e448c 100644 --- a/docs/src/js/interfaces/IvfPqOptions.md +++ b/docs/src/js/interfaces/IvfPqOptions.md @@ -112,7 +112,7 @@ Number of sub-vectors of PQ. This value controls how much the vector is compressed during the quantization step. The more sub vectors there are the less the vector is compressed. The default is the dimension of the vector divided by 16. If the dimension is not evenly divisible -by 16 we use the dimension divded by 8. +by 16 we use the dimension divided by 8. The above two cases are highly preferred. Having 8 or 16 values per subvector allows us to use efficient SIMD instructions. diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index d11169b46..e8b97bf77 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -3252,7 +3252,7 @@ describe.each([arrow15, arrow16, arrow17, arrow18])( const db = await connect(tmpDir.name); const data = [ { text: "fa", vector: [0.1, 0.2, 0.3] }, - { text: "fo", vector: [0.4, 0.5, 0.6] }, + { text: "fo", vector: [0.4, 0.5, 0.6] }, // spellchecker:disable-line { text: "fob", vector: [0.4, 0.5, 0.6] }, { text: "focus", vector: [0.4, 0.5, 0.6] }, { text: "foo", vector: [0.4, 0.5, 0.6] }, @@ -3277,7 +3277,7 @@ describe.each([arrow15, arrow16, arrow17, arrow18])( const resultSet = new Set(fuzzyResults.map((r) => r.text)); expect(resultSet.has("foo")).toBe(true); expect(resultSet.has("fob")).toBe(true); - expect(resultSet.has("fo")).toBe(true); + expect(resultSet.has("fo")).toBe(true); // spellchecker:disable-line expect(resultSet.has("food")).toBe(true); const prefixResults = await table diff --git a/nodejs/lancedb/arrow.ts b/nodejs/lancedb/arrow.ts index 1b6b98cc9..119887704 100644 --- a/nodejs/lancedb/arrow.ts +++ b/nodejs/lancedb/arrow.ts @@ -600,7 +600,7 @@ function makeVector( } if (values.length === 0) { throw Error( - "makeVector requires at least one value or the type must be specfied", + "makeVector requires at least one value or the type must be specified", ); } const sampleValue = values.find((val) => val !== null && val !== undefined); @@ -858,7 +858,7 @@ async function applyEmbeddings( * customized by the `embeddingDataType` property of the embedding function. * * If a schema is provided in `makeTableOptions` then it should include the - * embedding columns. If no schema is provded then embedding columns will + * embedding columns. If no schema is provided then embedding columns will * be placed at the end of the table, after all of the input columns. */ export async function convertToTable( diff --git a/nodejs/lancedb/indices.ts b/nodejs/lancedb/indices.ts index dbeebf433..bc9e19300 100644 --- a/nodejs/lancedb/indices.ts +++ b/nodejs/lancedb/indices.ts @@ -26,7 +26,7 @@ export interface IvfPqOptions { * This value controls how much the vector is compressed during the quantization step. * The more sub vectors there are the less the vector is compressed. The default is * the dimension of the vector divided by 16. If the dimension is not evenly divisible - * by 16 we use the dimension divded by 8. + * by 16 we use the dimension divided by 8. * * The above two cases are highly preferred. Having 8 or 16 values per subvector allows * us to use efficient SIMD instructions. @@ -228,7 +228,7 @@ export interface HnswPqOptions { * This value controls how much the vector is compressed during the quantization step. * The more sub vectors there are the less the vector is compressed. The default is * the dimension of the vector divided by 16. If the dimension is not evenly divisible - * by 16 we use the dimension divded by 8. + * by 16 we use the dimension divided by 8. * * The above two cases are highly preferred. Having 8 or 16 values per subvector allows * us to use efficient SIMD instructions. @@ -825,7 +825,7 @@ export interface IndexOptions { /** * Advanced index configuration * - * This option allows you to specify a specfic index to create and also + * This option allows you to specify a specific index to create and also * allows you to pass in configuration for training the index. * * See the static methods on Index for details on the various index types. diff --git a/nodejs/lancedb/merge.ts b/nodejs/lancedb/merge.ts index 30bde7281..5f1d8704a 100644 --- a/nodejs/lancedb/merge.ts +++ b/nodejs/lancedb/merge.ts @@ -27,7 +27,7 @@ export class MergeInsertBuilder { * but that behavior is subject to change. * * An optional condition may be specified. If it is, then only - * matched rows that satisfy the condtion will be updated. Any + * matched rows that satisfy the condition will be updated. Any * rows that do not satisfy the condition will be left as they * are. Failing to satisfy the condition does not cause a * "matched row" to become a "not matched" row. diff --git a/nodejs/lancedb/sanitize.ts b/nodejs/lancedb/sanitize.ts index 454c82247..3e5d583c4 100644 --- a/nodejs/lancedb/sanitize.ts +++ b/nodejs/lancedb/sanitize.ts @@ -3,7 +3,7 @@ // The utilities in this file help sanitize data from the user's arrow // library into the types expected by vectordb's arrow library. Node -// generally allows for mulitple versions of the same library (and sometimes +// generally allows for multiple versions of the same library (and sometimes // even multiple copies of the same version) to be installed at the same // time. However, arrow-js uses instanceof which expected that the input // comes from the exact same library instance. This is not always the case diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 06f8cd991..d1fb8acd8 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -313,7 +313,7 @@ export abstract class Table { * Note: if your condition is something like "some_id_column == 7" and * you are updating many rows (with different ids) then you will get * better performance with a single [`merge_insert`] call instead of - * repeatedly calilng this method. + * repeatedly calling this method. * @param {Map | Record} updates - the * columns to update * @returns {Promise} A promise that resolves to an object diff --git a/python/python/lancedb/embeddings/instructor.py b/python/python/lancedb/embeddings/instructor.py index 37ae1c296..a7a2b7e96 100644 --- a/python/python/lancedb/embeddings/instructor.py +++ b/python/python/lancedb/embeddings/instructor.py @@ -60,7 +60,7 @@ class InstructorEmbeddingFunction(TextEmbeddingFunction): import lancedb from lancedb.pydantic import LanceModel, Vector - from lancedb.embeddings import get_registry, InstuctorEmbeddingFunction + from lancedb.embeddings import get_registry, InstructorEmbeddingFunction instructor = get_registry().get("instructor").create( source_instruction="represent the document for retrieval", diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 6b9f450db..72362acad 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -5638,7 +5638,7 @@ class AsyncTable: if fill_value is None: fill_value = 0.0 - # _santitize_data is an old code path, but we will use it until the + # _sanitize_data is an old code path, but we will use it until the # new code path is ready. if mode == "overwrite": # For overwrite, apply the same preprocessing as create_table diff --git a/python/python/tests/test_embeddings.py b/python/python/tests/test_embeddings.py index 9850669eb..a57a495ee 100644 --- a/python/python/tests/test_embeddings.py +++ b/python/python/tests/test_embeddings.py @@ -327,8 +327,8 @@ def test_embedding_function_with_pandas(tmp_path): ) -> List[np.array]: return [np.random.randn(self.ndims()).tolist() for _ in range(len(texts))] - registery = get_registry() - func = registery.get("mock-embedding").create() + registry = get_registry() + func = registry.get("mock-embedding").create() class TestSchema(LanceModel): text: str = func.SourceField() @@ -394,9 +394,9 @@ def test_multiple_embeddings_for_pandas(tmp_path): ) -> List[np.array]: return [np.random.randn(self.ndims()).tolist() for _ in range(len(texts))] - registery = get_registry() - func1 = registery.get("mock-embedding").create() - func2 = registery.get("mock-embedding2").create() + registry = get_registry() + func1 = registry.get("mock-embedding").create() + func2 = registry.get("mock-embedding2").create() class TestSchema(LanceModel): text: str = func1.SourceField() diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index e5129dd9c..e7b0a83ce 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -1011,8 +1011,13 @@ def test_fts_ngram(mem_db: DBConnection): assert set(r["text"] for r in results) == {"lance database", "lance is cool"} results = ( - table.search("nce", query_type="fts").limit(10).to_list() - ) # spellchecker:disable-line + table.search( + "nce", # spellchecker:disable-line + query_type="fts", + ) + .limit(10) + .to_list() + ) assert len(results) == 2 assert set(r["text"] for r in results) == {"lance database", "lance is cool"} @@ -1034,8 +1039,13 @@ def test_fts_ngram(mem_db: DBConnection): assert set(r["text"] for r in results) == {"lance database", "lance is cool"} results = ( - table.search("nce", query_type="fts").limit(10).to_list() - ) # spellchecker:disable-line + table.search( + "nce", # spellchecker:disable-line + query_type="fts", + ) + .limit(10) + .to_list() + ) assert len(results) == 0 results = table.search("la", query_type="fts").limit(10).to_list() diff --git a/python/python/tests/test_rerankers.py b/python/python/tests/test_rerankers.py index 372a6b0f7..4430fa98f 100644 --- a/python/python/tests/test_rerankers.py +++ b/python/python/tests/test_rerankers.py @@ -81,7 +81,7 @@ def get_test_table(tmp_path): "but his son was mortal", "there hasn't been a good battlefield game since 2142", "I wish they would make another one", - "campains are not as good as they used to be", + "campaigns are not as good as they used to be", "Multiplayer and open world games have destroyed the single player experience", "Maybe the future is console games", "I don't know", diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index 3e1f6fb37..b85486412 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -3354,7 +3354,7 @@ def test_empty_query(mem_db: DBConnection): # None is the same as default df = table.search().select(["id"]).limit(None).to_arrow() assert df.num_rows == 100 - # invalid limist is the same as None, wihch is the same as default + # invalid limist is the same as None, which is the same as default df = table.search().select(["id"]).limit(-1).to_arrow() assert df.num_rows == 100 # valid limit should work diff --git a/python/src/query.rs b/python/src/query.rs index ef71939f2..2398376d5 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -334,7 +334,7 @@ pub struct PyQueryRequest { pub column: Option, pub query_vector: Option, pub minimum_nprobes: Option, - // None means user did not set it and default shoud be used (currenty 20) + // None means user did not set it and default should be used (currently 20) // Some(0) means user set it to None and there is no limit pub maximum_nprobes: Option, pub lower_bound: Option, diff --git a/rust/lancedb/src/arrow.rs b/rust/lancedb/src/arrow.rs index c40459b40..8cb7dbda7 100644 --- a/rust/lancedb/src/arrow.rs +++ b/rust/lancedb/src/arrow.rs @@ -163,7 +163,7 @@ pub struct PolarsDataFrameRecordBatchReader { impl PolarsDataFrameRecordBatchReader { /// Creates a new `PolarsDataFrameRecordBatchReader` from a given Polars DataFrame. /// If the input dataframe does not have aligned chunks, this function undergoes - /// the costly operation of reallocating each series as a single contigous chunk. + /// the costly operation of reallocating each series as a single contiguous chunk. pub fn new(mut df: DataFrame) -> Result { df.align_chunks(); let arrow_schema = diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index 6ec4a6ec1..df7da3d62 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -827,7 +827,7 @@ impl Connection { pub struct ConnectRequest { /// Database URI /// - /// ### Accpeted URI formats + /// ### Accepted URI formats /// /// - `/path/to/database` - local database on file system. /// - `s3://bucket/path/to/database` or `gs://bucket/path/to/database` - database on cloud object store diff --git a/rust/lancedb/src/database/listing.rs b/rust/lancedb/src/database/listing.rs index c6d834c5a..59b075e4f 100644 --- a/rust/lancedb/src/database/listing.rs +++ b/rust/lancedb/src/database/listing.rs @@ -512,7 +512,7 @@ impl ListingDatabase { // iter thru the query params and extract the commit store param let mut engine = None; let mut mirrored_store = None; - let mut filtered_querys = vec![]; + let mut filtered_queries = vec![]; // WARNING: specifying engine is NOT a publicly supported feature in lancedb yet // THE API WILL CHANGE @@ -528,13 +528,13 @@ impl ListingDatabase { mirrored_store = Some(value.to_string()); } else { // to owned so we can modify the url - filtered_querys.push((key.to_string(), value.to_string())); + filtered_queries.push((key.to_string(), value.to_string())); } } // Filter out the commit store query param -- it's a lancedb param url.query_pairs_mut().clear(); - url.query_pairs_mut().extend_pairs(filtered_querys); + url.query_pairs_mut().extend_pairs(filtered_queries); // Take a copy of the query string so we can propagate it to lance. // `query_pairs_mut()` leaves the URL with `Some("")` even when no // pairs survive (or none existed in the first place), so an empty @@ -896,11 +896,11 @@ impl Database for ListingDatabase { } async fn read_consistency(&self) -> Result { - if let Some(read_consistency_inverval) = self.read_consistency_interval { - if read_consistency_inverval.is_zero() { + if let Some(interval) = self.read_consistency_interval { + if interval.is_zero() { Ok(ReadConsistency::Strong) } else { - Ok(ReadConsistency::Eventual(read_consistency_inverval)) + Ok(ReadConsistency::Eventual(interval)) } } else { Ok(ReadConsistency::Manual) @@ -3043,15 +3043,15 @@ mod tests { /// across platforms — see the `file://` test below). fn capture_query_like_connect(input_uri: &str) -> Option { let mut url = url::Url::parse(input_uri).unwrap(); - let mut filtered_querys = Vec::new(); + let mut filtered_queries = Vec::new(); for (key, value) in url.query_pairs() { if key == ENGINE || key == MIRRORED_STORE { continue; } - filtered_querys.push((key.to_string(), value.to_string())); + filtered_queries.push((key.to_string(), value.to_string())); } url.query_pairs_mut().clear(); - url.query_pairs_mut().extend_pairs(filtered_querys); + url.query_pairs_mut().extend_pairs(filtered_queries); url.query().filter(|q| !q.is_empty()).map(|s| s.to_string()) } diff --git a/rust/lancedb/src/database/namespace.rs b/rust/lancedb/src/database/namespace.rs index 9447b27ea..6bca29476 100644 --- a/rust/lancedb/src/database/namespace.rs +++ b/rust/lancedb/src/database/namespace.rs @@ -251,11 +251,11 @@ impl Database for LanceNamespaceDatabase { } async fn read_consistency(&self) -> Result { - if let Some(read_consistency_inverval) = self.read_consistency_interval { - if read_consistency_inverval.is_zero() { + if let Some(interval) = self.read_consistency_interval { + if interval.is_zero() { Ok(ReadConsistency::Strong) } else { - Ok(ReadConsistency::Eventual(read_consistency_inverval)) + Ok(ReadConsistency::Eventual(interval)) } } else { Ok(ReadConsistency::Manual) diff --git a/rust/lancedb/src/index/vector.rs b/rust/lancedb/src/index/vector.rs index 29e01a49b..bce77a610 100644 --- a/rust/lancedb/src/index/vector.rs +++ b/rust/lancedb/src/index/vector.rs @@ -125,7 +125,7 @@ macro_rules! impl_pq_params_setter { /// This value controls how much the vector is compressed during the quantization step. /// The more sub vectors there are the less the vector is compressed. The default is /// the dimension of the vector divided by 16. If the dimension is not evenly divisible - /// by 16 we use the dimension divded by 8. + /// by 16 we use the dimension divided by 8. /// /// The above two cases are highly preferred. Having 8 or 16 values per subvector allows /// us to use efficient SIMD instructions. diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 5b889cada..ab1bdfc4a 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -1299,7 +1299,7 @@ impl VectorQuery { /// This can be useful when there is a narrow filter to allow these queries to /// spend more time searching and avoid potential false negatives. /// - /// Set to None to search all partitions, if needed, to satsify the limit + /// Set to None to search all partitions, if needed, to satisfy the limit pub fn maximum_nprobes(mut self, maximum_nprobes: Option) -> Result { if let Some(maximum_nprobes) = maximum_nprobes { if maximum_nprobes == 0 { diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 636aaefd0..7f139c4cb 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -240,7 +240,7 @@ enum BadVectorHandling { /// An error is returned #[default] Error, - /// The offending row is droppped + /// The offending row is dropped Drop, /// The invalid/missing items are replaced by fill_value Fill(f32), @@ -1326,7 +1326,7 @@ impl Table { /// Note: if your condition is something like "some_id_column == 7" and /// you are updating many rows (with different ids) then you will get /// better performance with a single [`merge_insert`] call instead of - /// repeatedly calilng this method. + /// repeatedly calling this method. pub fn update(&self) -> UpdateBuilder { UpdateBuilder::new(self.inner.clone()) } diff --git a/rust/lancedb/src/table/dataset.rs b/rust/lancedb/src/table/dataset.rs index 5e3733b85..af9fc2563 100644 --- a/rust/lancedb/src/table/dataset.rs +++ b/rust/lancedb/src/table/dataset.rs @@ -52,7 +52,7 @@ enum ConsistencyMode { /// refresh_window = min(3s, TTL/4) /// /// | t < TTL - refresh_window | t < TTL | t >= TTL | - /// | Return value | Background refresh & return value | syncronous refresh | + /// | Return value | Background refresh & return value | synchronous refresh | Eventual(BackgroundCache, Error>), } diff --git a/rust/lancedb/src/table/merge.rs b/rust/lancedb/src/table/merge.rs index ef2af8fe0..8f5585829 100644 --- a/rust/lancedb/src/table/merge.rs +++ b/rust/lancedb/src/table/merge.rs @@ -103,7 +103,7 @@ impl MergeInsertBuilder { /// but that behavior is subject to change. /// /// An optional condition may be specified. If it is, then only - /// matched rows that satisfy the condtion will be updated. Any + /// matched rows that satisfy the condition will be updated. Any /// rows that do not satisfy the condition will be left as they /// are. Failing to satisfy the condition does not cause a /// "matched row" to become a "not matched" row. diff --git a/rust/lancedb/src/table/merge/lsm.rs b/rust/lancedb/src/table/merge/lsm.rs index a06507ba0..1a1f0b28c 100644 --- a/rust/lancedb/src/table/merge/lsm.rs +++ b/rust/lancedb/src/table/merge/lsm.rs @@ -904,7 +904,7 @@ fn unsharded_shard_id() -> Uuid { /// Build a [`ShardWriterConfig`] from the persisted `writer_config_defaults`. /// -/// Unknown or unparseable keys are ignored; absent keys keep the +/// Unknown or unparsable keys are ignored; absent keys keep the /// [`ShardWriterConfig`] default. The shard id is set by `mem_wal_writer`. fn shard_writer_config_from_defaults(defaults: &HashMap) -> ShardWriterConfig { let mut config = ShardWriterConfig::default().with_shard_spec_id(SHARDING_SPEC_ID); From bc4497b21a87c3d9c1d7a523fa6450cd1446d587 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Thu, 10 Sep 2026 00:32:31 -0700 Subject: [PATCH 192/206] chore: update lance dependency to v12.0.0-beta.16 (#4156) Updates the Rust workspace Lance dependencies, Cargo lockfile, and Java lance-core from v12.0.0-beta.15 to [v12.0.0-beta.16](https://github.com/lance-format/lance/releases/tag/v12.0.0-beta.16). No compatibility fixes were required; `cargo clippy --quiet --workspace --tests --all-features -- -D warnings`, `cargo fmt --all --quiet`, and `git diff --check` passed. --- Cargo.lock | 84 ++++++++++++++++++++++++++-------------------------- Cargo.toml | 28 +++++++++--------- java/pom.xml | 2 +- 3 files changed, 57 insertions(+), 57 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a2a8797f8..b8b1f9148 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3526,8 +3526,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4886,8 +4886,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arc-swap", "arrow", @@ -4959,8 +4959,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow-array", "arrow-buffer", @@ -4982,7 +4982,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow-array", "arrow-buffer", @@ -4996,7 +4996,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow-array", "arrow-schema", @@ -5005,8 +5005,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrayref", "crunchy", @@ -5016,8 +5016,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow-array", "arrow-buffer", @@ -5054,8 +5054,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow", "arrow-array", @@ -5085,8 +5085,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow", "arrow-array", @@ -5103,8 +5103,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "proc-macro2", "quote", @@ -5113,8 +5113,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow-arith", "arrow-array", @@ -5147,8 +5147,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow-arith", "arrow-array", @@ -5179,8 +5179,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arc-swap", "arrow", @@ -5244,8 +5244,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow-array", "arrow-schema", @@ -5267,8 +5267,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow", "arrow-array", @@ -5308,8 +5308,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow-array", "arrow-schema", @@ -5323,8 +5323,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow", "async-trait", @@ -5338,8 +5338,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow", "arrow-ipc", @@ -5392,8 +5392,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow-array", "arrow-buffer", @@ -5407,8 +5407,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow", "arrow-array", @@ -5448,8 +5448,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "arrow-array", "arrow-schema", @@ -5462,8 +5462,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "12.0.0-beta.15" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.15#271a155ba505fd8e1094c095d4ce356707e93866" +version = "12.0.0-beta.16" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index e3cba6366..a0a908489 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=12.0.0-beta.15", default-features = false, "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=12.0.0-beta.15", default-features = false, "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=12.0.0-beta.15", default-features = false, "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=12.0.0-beta.15", "tag" = "v12.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=12.0.0-beta.16", default-features = false, "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=12.0.0-beta.16", default-features = false, "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=12.0.0-beta.16", default-features = false, "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index 67363dee4..b3dbe413c 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 12.0.0-beta.15 + 12.0.0-beta.16 false 2.30.0 1.7 From 13f9dd630bcfad01911ebadb831f9d097b5b50ac Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 10 Sep 2026 10:15:08 -0700 Subject: [PATCH 193/206] build(deps): bump prost from 0.14.3 to 0.14.4 in the rust-minor-patch group (#4135) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bumps the rust-minor-patch group with 1 update: [prost](https://github.com/tokio-rs/prost). Updates `prost` from 0.14.3 to 0.14.4
Changelog

Sourced from prost's changelog.

Prost version 0.14.4

PROST! is a Protocol Buffers implementation for the Rust Language. prost generates simple, idiomatic Rust code from proto2 and proto3 files.

🚀 Features

  • (prost-derive) Make is_valid a constant function (#1401)
  • Increase MSRV to 1.85 (#1428)

🐛 Bug Fixes

  • Use Display instead of Debug for generated enumeration attributes (#1419)
  • (prost-derive) Return error for invalid enumeration default identifiers (#1426)
  • (build) Grab binary path from cargo (#1429)
  • (build) Fix C++ build on GCC 15 (#1395)

📚 Documentation

  • Add example for decode_length_delimiter (#1311)
  • Update protobuf-src example to avoid unsafe set_var

🧪 Testing

  • Test derive Eq behavior (#1422)
  • (groups) Actually construct NestedGroup (#1363)

💼 Dependencies

  • (deps) Update criterion requirement from 0.7 to 0.8 (#1374)
  • (deps) Remove getrandom@0.4.1 from build-dependencies (#1400)
  • (deps) Update rand requirement from 0.9 to 0.10 (#1397)
  • (deps) Bump actions/upload-artifact from 6 to 7 (#1409)
  • (deps) Update cargo clippy to 1.89 (#1433)
  • (deps) Update cargo clippy to 1.91 (#1435)
  • (deps) Update and improve nix devshell (#1393)

🎨 Styling

  • Prevent needless borrow (#1404)
  • Use std::hint::black_box() (#1403)
  • Use variables directly in format!() (#1432)
  • Remove explicit .into_iter() (#1434)
  • Run clippy on benches (#1405)
Commits

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=prost&package-manager=cargo&previous-version=0.14.3&new-version=0.14.4)](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> --- Cargo.lock | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b8b1f9148..3afa04044 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7703,9 +7703,9 @@ dependencies = [ [[package]] name = "prost" -version = "0.14.3" +version = "0.14.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2ea70524a2f82d518bce41317d0fae74151505651af45faf1ffbd6fd33f0568" +checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1" dependencies = [ "bytes", "prost-derive", @@ -7732,9 +7732,9 @@ dependencies = [ [[package]] name = "prost-derive" -version = "0.14.3" +version = "0.14.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27c6023962132f4b30eb4c172c91ce92d933da334c59c23cddee82358ddafb0b" +checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" dependencies = [ "anyhow", "itertools 0.14.0", From e0bd4b5fa1afdb10d2d551e867ae7d5304179c38 Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Fri, 11 Sep 2026 09:59:19 -0700 Subject: [PATCH 194/206] chore: update lance dependency to v12.0.0-beta.17 (#4162) Update the Rust workspace Lance dependencies and Java lance-core to [v12.0.0-beta.17](https://github.com/lance-format/lance/releases/tag/v12.0.0-beta.17). Align object_store to 0.14.1 for compatibility with Lance and refresh the Cargo lockfile, including the required reqsign updates. Validation passed: `cargo clippy --quiet --workspace --tests --all-features -- -D warnings` and `cargo fmt --all --quiet`. --- Cargo.lock | 489 ++++++++++++++++++++++++++------------------------- Cargo.toml | 30 ++-- java/pom.xml | 2 +- 3 files changed, 266 insertions(+), 255 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3afa04044..209ee4942 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -141,7 +141,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -152,7 +152,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -581,6 +581,16 @@ dependencies = [ "loom", ] +[[package]] +name = "asyncband" +version = "0.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94a214ba60d6231afd0e805e3c27c45a1626d9debaa5a5061c45a1ea1b2f1ed0" +dependencies = [ + "hashbrown 0.17.1", + "slab", +] + [[package]] name = "atoi" version = "2.0.0" @@ -937,7 +947,7 @@ dependencies = [ "http 1.5.0", "http-body 1.1.0", "http-body-util", - "md-5 0.11.0", + "md-5", "pin-project-lite", "sha1 0.11.0", "sha2 0.11.0", @@ -1767,7 +1777,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" dependencies = [ "clap_builder", - "clap_derive", ] [[package]] @@ -1776,22 +1785,8 @@ version = "4.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" dependencies = [ - "anstream", "anstyle", "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" -dependencies = [ - "heck 0.5.0", - "proc-macro2", - "quote", - "syn 2.0.117", ] [[package]] @@ -1827,7 +1822,7 @@ version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2230,16 +2225,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "ctor" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "424e0138278faeb2b401f174ad17e715c829512d74f3d1e81eb43365c2e0590e" -dependencies = [ - "ctor-proc-macro", - "dtor", -] - [[package]] name = "ctor" version = "1.0.12" @@ -2250,12 +2235,6 @@ dependencies = [ "linktime-proc-macro", ] -[[package]] -name = "ctor-proc-macro" -version = "0.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52560adf09603e58c9a7ee1fe1dcb95a16927b17c127f0ac02d6e768a0e25bc1" - [[package]] name = "ctutils" version = "0.4.2" @@ -2392,7 +2371,7 @@ dependencies = [ "indexmap 2.14.0", "itertools 0.14.0", "log", - "object_store", + "object_store 0.13.2", "parking_lot", "sqlparser 0.62.0", "tempfile", @@ -2421,7 +2400,7 @@ dependencies = [ "futures", "itertools 0.14.0", "log", - "object_store", + "object_store 0.13.2", "parking_lot", "tokio", ] @@ -2446,7 +2425,7 @@ dependencies = [ "futures", "itertools 0.14.0", "log", - "object_store", + "object_store 0.13.2", ] [[package]] @@ -2466,7 +2445,7 @@ dependencies = [ "itertools 0.14.0", "libc", "log", - "object_store", + "object_store 0.13.2", "sqlparser 0.62.0", "tokio", "uuid", @@ -2507,7 +2486,7 @@ dependencies = [ "glob", "itertools 0.14.0", "log", - "object_store", + "object_store 0.13.2", "parking_lot", "rand 0.9.5", "tokio", @@ -2534,7 +2513,7 @@ dependencies = [ "datafusion-session", "futures", "itertools 0.14.0", - "object_store", + "object_store 0.13.2", "tokio", ] @@ -2556,7 +2535,7 @@ dependencies = [ "datafusion-physical-plan", "datafusion-session", "futures", - "object_store", + "object_store 0.13.2", "regex", "tokio", ] @@ -2579,7 +2558,7 @@ dependencies = [ "datafusion-physical-plan", "datafusion-session", "futures", - "object_store", + "object_store 0.13.2", "tokio", "tokio-stream", ] @@ -2605,7 +2584,7 @@ dependencies = [ "datafusion-physical-expr-common", "futures", "log", - "object_store", + "object_store 0.13.2", "parking_lot", "rand 0.9.5", "tempfile", @@ -2669,7 +2648,7 @@ dependencies = [ "hex", "itertools 0.14.0", "log", - "md-5 0.11.0", + "md-5", "memchr", "num-traits", "rand 0.9.5", @@ -3105,7 +3084,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.61.2", + "windows-sys 0.59.0", ] [[package]] @@ -3137,21 +3116,6 @@ dependencies = [ "litrs", ] -[[package]] -name = "dtor" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "404d02eeb088a82cfd873006cb713fe411306c7d182c344905e101fb1167d301" -dependencies = [ - "dtor-proc-macro", -] - -[[package]] -name = "dtor-proc-macro" -version = "0.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f678cf4a922c215c63e0de95eb1ff08a958a81d47e485cf9da1e27bf6305cfa5" - [[package]] name = "dunce" version = "1.0.5" @@ -3328,7 +3292,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3526,8 +3490,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4085,18 +4049,21 @@ dependencies = [ [[package]] name = "hf-xet" -version = "1.5.2" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "430b33fa84f92796d4d263070b6c0d3ca219df7b9a0e1853ee431029b1612bcd" +checksum = "c237ef4fb0ce1962a5117f8bd8c74454b41629826a9df17d14a1840ca18f0754" dependencies = [ + "anyhow", "async-trait", "bytes", "http 1.5.0", "more-asserts", "serde", + "serde_json", "thiserror 2.0.18", "tokio", "tokio-util", + "tokio_with_wasm", "tracing", "uuid", "xet-client", @@ -4333,7 +4300,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2 0.6.3", + "socket2 0.5.10", "system-configuration", "tokio", "tower-service", @@ -4632,7 +4599,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -4677,6 +4644,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" @@ -4886,8 +4862,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arc-swap", "arrow", @@ -4935,7 +4911,7 @@ dependencies = [ "lance-tokenizer", "log", "moka", - "object_store", + "object_store 0.14.1", "permutation", "pin-project", "prost", @@ -4959,8 +4935,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow-array", "arrow-buffer", @@ -4982,7 +4958,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow-array", "arrow-buffer", @@ -4996,7 +4972,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow-array", "arrow-schema", @@ -5005,8 +4981,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrayref", "crunchy", @@ -5016,8 +4992,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow-array", "arrow-buffer", @@ -5036,7 +5012,7 @@ dependencies = [ "log", "moka", "num_cpus", - "object_store", + "object_store 0.14.1", "pin-project", "prost", "quick_cache", @@ -5054,8 +5030,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow", "arrow-array", @@ -5085,8 +5061,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow", "arrow-array", @@ -5103,8 +5079,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "proc-macro2", "quote", @@ -5113,8 +5089,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow-arith", "arrow-array", @@ -5147,8 +5123,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow-arith", "arrow-array", @@ -5169,7 +5145,7 @@ dependencies = [ "lance-io", "log", "num-traits", - "object_store", + "object_store 0.14.1", "prost", "prost-build", "prost-types", @@ -5179,8 +5155,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arc-swap", "arrow", @@ -5224,7 +5200,7 @@ dependencies = [ "log", "ndarray", "num-traits", - "object_store", + "object_store 0.14.1", "prost", "prost-build", "prost-types", @@ -5244,8 +5220,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow-array", "arrow-schema", @@ -5267,8 +5243,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow", "arrow-array", @@ -5287,7 +5263,7 @@ dependencies = [ "log", "metrics", "moka", - "object_store", + "object_store 0.14.1", "object_store_opendal", "opendal", "path_abs", @@ -5308,8 +5284,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow-array", "arrow-schema", @@ -5323,8 +5299,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow", "async-trait", @@ -5338,8 +5314,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow", "arrow-ipc", @@ -5361,7 +5337,7 @@ dependencies = [ "lance-namespace", "lance-table", "log", - "object_store", + "object_store 0.14.1", "quick-xml 0.40.1", "rand 0.9.5", "reqwest 0.12.28", @@ -5392,8 +5368,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow-array", "arrow-buffer", @@ -5407,8 +5383,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow", "arrow-array", @@ -5429,7 +5405,7 @@ dependencies = [ "lance-io", "lance-select", "log", - "object_store", + "object_store 0.14.1", "prost", "prost-build", "prost-types", @@ -5448,8 +5424,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "arrow-array", "arrow-schema", @@ -5462,8 +5438,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "12.0.0-beta.16" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.16#f7df098f5860cf9b3ac5339e7a641430cfbc6351" +version = "12.0.0-beta.17" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" dependencies = [ "frostem", "icu_segmenter", @@ -5536,7 +5512,7 @@ dependencies = [ "metrics-util", "moka", "num-traits", - "object_store", + "object_store 0.14.1", "pin-project", "polars", "polars-arrow", @@ -5956,16 +5932,6 @@ dependencies = [ "thread-tree", ] -[[package]] -name = "md-5" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" -dependencies = [ - "cfg-if 1.0.4", - "digest 0.10.7", -] - [[package]] name = "md-5" version = "0.11.0" @@ -5978,10 +5944,11 @@ dependencies = [ [[package]] name = "mea" -version = "0.6.3" +version = "0.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6747f54621d156e1b47eb6b25f39a941b9fc347f98f67d25d8881ff99e8ed832" +checksum = "c709842c4ce65cb91e2666ad5319dfc1efc3af0d34f02075eddca9000d9f8afb" dependencies = [ + "hashbrown 0.17.1", "slab", ] @@ -6187,7 +6154,7 @@ checksum = "58c5f4d5375213fdb7be2655e152386e82f026f9a5ba36a75556e11359aafe09" dependencies = [ "bitflags 2.11.1", "chrono", - "ctor 1.0.12", + "ctor", "futures", "libc", "napi-build", @@ -6212,7 +6179,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fa55ea69990c90b888e9e77044410e304ce7f35de599dc6d0b5c1923d2e59af" dependencies = [ "convert_case", - "ctor 1.0.12", + "ctor", "napi-derive-backend", "proc-macro2", "quote", @@ -6276,6 +6243,18 @@ dependencies = [ "libc", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.11.1", + "cfg-if 1.0.4", + "cfg_aliases", + "libc", +] + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -6325,7 +6304,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]] @@ -6470,9 +6449,37 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "622acbc9100d3c10e2ee15804b0caa40e55c933d5aa53814cd520805b7958a49" dependencies = [ "async-trait", + "bytes", + "chrono", + "futures-channel", + "futures-core", + "futures-util", + "http 1.5.0", + "humantime", + "itertools 0.14.0", + "parking_lot", + "percent-encoding", + "thiserror 2.0.18", + "tokio", + "tracing", + "url", + "walkdir", + "wasm-bindgen-futures", + "web-time", +] + +[[package]] +name = "object_store" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d354792e39fa5f0009e47623cf8b15b099bf9a652fa55c6f817fe28ac84fea50" +dependencies = [ + "async-trait", + "aws-lc-rs", "base64 0.22.1", "bytes", "chrono", + "crc-fast", "form_urlencoded", "futures-channel", "futures-core", @@ -6482,14 +6489,14 @@ dependencies = [ "httparse", "humantime", "hyper 1.9.0", - "itertools 0.14.0", - "md-5 0.10.6", + "itertools 0.15.0", + "md-5", + "nix 0.31.3", "parking_lot", "percent-encoding", - "quick-xml 0.39.4", + "quick-xml 0.41.0", "rand 0.10.1", - "reqwest 0.12.28", - "ring", + "reqwest 0.13.4", "rustls-pki-types", "serde", "serde_json", @@ -6501,20 +6508,21 @@ dependencies = [ "walkdir", "wasm-bindgen-futures", "web-time", + "windows-sys 0.61.2", ] [[package]] name = "object_store_opendal" -version = "0.58.0" +version = "0.60.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88f165780495c17aa3ce86846600504198c3fffd99073521552751c2430fa6ac" +checksum = "f0206382328a82a28b549e5b2d18b6b9384ac1d82fa1f3c63da06f5ee6f7f054" dependencies = [ "async-trait", + "asyncband", "bytes", "chrono", "futures", - "mea", - "object_store", + "object_store 0.14.1", "opendal", "pin-project", "tokio", @@ -6568,11 +6576,11 @@ checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] name = "opendal" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f20562cc7447fcc915fc5c23df305a412ea80a733c9f2fd9e2d267e2815be6d" +checksum = "f950151f9587a51a7bed70a15fa0cff464eae96e41ae7499f97067bdafdf43eb" dependencies = [ - "ctor 1.0.12", + "ctor", "opendal-core", "opendal-http-transport-reqwest", "opendal-layer-concurrent-limit", @@ -6591,19 +6599,19 @@ dependencies = [ [[package]] name = "opendal-core" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec75551ff4cf3e57da98979f6a937aaa9ddb3915bf68cc17d03df733be6646ed" +checksum = "a43405d217dfdfb543f58847336d3af672897dd1939bb7dcf314b63cf364f1c9" dependencies = [ "anyhow", + "asyncband", "base64 0.23.1", "bytes", "futures", "http 1.5.0", "jiff", "log", - "md-5 0.11.0", - "mea", + "md-5", "percent-encoding", "quick-xml 0.41.0", "reqsign-core", @@ -6617,9 +6625,9 @@ dependencies = [ [[package]] name = "opendal-http-transport-reqwest" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ad4d4f19c3ce01126a30611f8e544eaa217104a278c889ac17c9374fe4f9e4ef" +checksum = "401999057db611e592f883fcf2cbd6754ff37af587deaadd07b8c1398b2b6b06" dependencies = [ "bytes", "futures", @@ -6631,21 +6639,21 @@ dependencies = [ [[package]] name = "opendal-layer-concurrent-limit" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "249ac5b0aa5a7a6c3737342d10456067937f9c9a6f3f02544271f7908ab91081" +checksum = "fba1dd0742261925fc0eb910773ec39cbc1336c55d41e13b19f3af970ad5a126" dependencies = [ + "asyncband", "futures", "http 1.5.0", - "mea", "opendal-core", ] [[package]] name = "opendal-layer-logging" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c75411ab00f77851ff086b686c1e9ca8175ac18c15afa2cb75b9036436cb06c" +checksum = "d0fd963f9d32dd276521479d7f1f3a265d669b03a75f2062a4570a26b1b17421" dependencies = [ "log", "opendal-core", @@ -6653,9 +6661,9 @@ dependencies = [ [[package]] name = "opendal-layer-retry" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80b7738bd5f233ad8da39af9b9316b9b7a4eaddd91e8e32a1e19b7030688121d" +checksum = "06306202c97c54fb41bdbbdcb854c8798823f0022ae7aac7a40c8a1023aa83a6" dependencies = [ "backon", "log", @@ -6664,9 +6672,9 @@ dependencies = [ [[package]] name = "opendal-layer-timeout" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a704141924500f3803c05ed871b53305d2a2f11cb5ef20160c3ee688a1857f66" +checksum = "6bd334cbd0a0bc934146733e74a80a5faf8db8e014781a25f6d9d80d7b87c981" dependencies = [ "opendal-core", "tokio", @@ -6674,9 +6682,9 @@ dependencies = [ [[package]] name = "opendal-service-azblob" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3310fbbb48f111c6f590473c2cd15e1b7f8e384444b0d4e328f0464c864d767" +checksum = "ba0d2662ddf0de1f838db5dc48fafb8212ed1a5c7980bc164aa67809696c309c" dependencies = [ "base64 0.23.1", "bytes", @@ -6695,15 +6703,15 @@ dependencies = [ [[package]] name = "opendal-service-azdls" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e3c406729935fe214ce574d68681a1ff7e0b322548f14094912bdbfe50e5c53" +checksum = "9064ed464286bffbea5955d470082a1e72b9b89f1e8f7a61b9e303c55ec08e4f" dependencies = [ + "asyncband", "base64 0.23.1", "bytes", "http 1.5.0", "log", - "mea", "opendal-core", "opendal-service-azure-common", "quick-xml 0.41.0", @@ -6716,9 +6724,9 @@ dependencies = [ [[package]] name = "opendal-service-azure-common" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7348c88edf15af435b7be930077746b569fac5e738c1bf6a363b675e7317c9df" +checksum = "6348e3c0d7ff77a9b05c5b7f3d744ed395c2b2511812d3b37a934218002248f8" dependencies = [ "http 1.5.0", "opendal-core", @@ -6726,9 +6734,9 @@ dependencies = [ [[package]] name = "opendal-service-cos" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d533d4582105d269c8aebeee5f0e8bcf960f41b8aab6197df7012254d9f39bf0" +checksum = "49a652eadc76b94f9cffa497b3de5250dff53cce394d2974c00dde62c4e4cd81" dependencies = [ "bytes", "http 1.5.0", @@ -6743,9 +6751,9 @@ dependencies = [ [[package]] name = "opendal-service-gcs" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "007f3fba63c21e516c956b891e96ff9892d8175662bfb781cdada9d3766a11e6" +checksum = "1ccbf8450652bfe7b3ae69b7decce090c95c120ad565048f9a5a77dac2917a19" dependencies = [ "async-trait", "bytes", @@ -6760,13 +6768,14 @@ dependencies = [ "serde", "serde_json", "tokio", + "uuid", ] [[package]] name = "opendal-service-goosefs" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60871e6386f04d831e6a5bdbc032af4a91aeba49963252d0ef456a2cf36a9b78" +checksum = "4b53d8c3e1db3176add7aff9ad2637c907409bac19e025ee8e9c072c0061d9c5" dependencies = [ "bytes", "goosefs-sdk", @@ -6778,10 +6787,11 @@ dependencies = [ [[package]] name = "opendal-service-hf" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b41fd41eb7ed03c5e66cefda61e8e117808ffd2908f2916737cb020a6beb02c7" +checksum = "5c17b59cf22bd2da9f751b8e66db595d5fe546b4c6b6ff0fb84c7bfd27455d7a" dependencies = [ + "asyncband", "bytes", "hf-xet", "http 1.5.0", @@ -6794,9 +6804,9 @@ dependencies = [ [[package]] name = "opendal-service-oss" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd528ec2d49c5ca69e674ffed7b3e0686fb9cfcfea0596870de381467fda4f1b" +checksum = "284373c4a1143d8efaa7d010c1db05856d33a7cad475aaee8405dbcb0660cd96" dependencies = [ "bytes", "http 1.5.0", @@ -6811,16 +6821,16 @@ dependencies = [ [[package]] name = "opendal-service-s3" -version = "0.58.1" +version = "0.59.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58e80cdf192d7eff05feed747894d64f81905ac4eaf132edf7ea270abdd2d663" +checksum = "388b1d39b62535c62803754ebef89808859558697366dbedd0299345887ba461" dependencies = [ "base64 0.23.1", "bytes", "crc-fast", "http 1.5.0", "log", - "md-5 0.11.0", + "md-5", "opendal-core", "quick-xml 0.41.0", "reqsign-aws-v4", @@ -7633,7 +7643,7 @@ dependencies = [ "inferno", "libc", "log", - "nix", + "nix 0.26.4", "once_cell", "smallvec", "spin 0.10.1", @@ -7655,7 +7665,7 @@ dependencies = [ "inferno", "libc", "log", - "nix", + "nix 0.26.4", "once_cell", "smallvec", "spin 0.10.1", @@ -7915,16 +7925,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "quick-xml" -version = "0.39.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdcc8dd4e2f670d309a5f0e83fe36dfdc05af317008fea29144da1a2ac858e5e" -dependencies = [ - "memchr", - "serde", -] - [[package]] name = "quick-xml" version = "0.40.1" @@ -7969,7 +7969,7 @@ dependencies = [ "quinn-udp", "rustc-hash", "rustls 0.23.40", - "socket2 0.6.3", + "socket2 0.5.10", "thiserror 2.0.18", "tokio", "tracing", @@ -8007,7 +8007,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2 0.6.3", + "socket2 0.5.10", "tracing", "windows-sys 0.60.2", ] @@ -8382,9 +8382,9 @@ dependencies = [ [[package]] name = "reqsign-aws-core" -version = "3.0.3" +version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4af084e1f3cbf3e67e0c972765399bce54ecec804cceba46b39a8331f3c1bff" +checksum = "bac4749b7dfa7bfaccd01eb03e9dc795ed37e3f20d6f0f38e2c67ee85ad6bc86" dependencies = [ "bytes", "form_urlencoded", @@ -8403,9 +8403,9 @@ dependencies = [ [[package]] name = "reqsign-aws-v4" -version = "3.1.0" +version = "3.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4ac5b3b7cefa28933792b439186459f77f19f9b6edbeab41b8b187150361a206" +checksum = "ff250f0fd0b913fbd565e405acc553da0f13bde30bfb5403178c9d0313cdc15f" dependencies = [ "bytes", "http 1.5.0", @@ -8439,9 +8439,9 @@ dependencies = [ [[package]] name = "reqsign-core" -version = "3.2.1" +version = "3.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c07dd510b1e1b9b241883e483358147fb2ed2d497a7b39b065ba61eb93deceb0" +checksum = "ff052daffb0599681c50f85c59e7236438976efe991ab864edd9f3b235501a0f" dependencies = [ "anyhow", "base64 0.23.1", @@ -8452,6 +8452,7 @@ dependencies = [ "http 1.5.0", "jiff", "log", + "mea", "percent-encoding", "rsa", "serde", @@ -8463,9 +8464,9 @@ dependencies = [ [[package]] name = "reqsign-file-read-tokio" -version = "3.0.4" +version = "3.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "663d9d55abd0df0830ef0ae43708297cc1371cf4e8ca91f3ac813c309cca8c98" +checksum = "b3235df90a6bca681aa47dd86f2393d122a6d77042aa8a7c81e218cd45c5bfc0" dependencies = [ "anyhow", "reqsign-core", @@ -8474,10 +8475,11 @@ dependencies = [ [[package]] name = "reqsign-google" -version = "3.0.4" +version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4080a227f82a09f68540ecd028622065d7ac4c0bcb8727a25bdcfc0526235792" +checksum = "272a5813571885c1455ffe106f0c768577e6ce69313446d4476e8d41dcf6ac5a" dependencies = [ + "bytes", "form_urlencoded", "http 1.5.0", "log", @@ -8561,6 +8563,7 @@ dependencies = [ "bytes", "futures-core", "futures-util", + "h2 0.4.16", "http 1.5.0", "http-body 1.1.0", "http-body-util", @@ -8787,7 +8790,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -8858,7 +8861,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -9255,7 +9258,6 @@ dependencies = [ "cfg-if 1.0.4", "cpufeatures 0.2.17", "digest 0.10.7", - "sha2-asm", ] [[package]] @@ -9269,15 +9271,6 @@ dependencies = [ "digest 0.11.3", ] -[[package]] -name = "sha2-asm" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b845214d6175804686b2bd482bcffe96651bb2d1200742b712003504a2dac1ab" -dependencies = [ - "cc", -] - [[package]] name = "sharded-slab" version = "0.1.7" @@ -9450,7 +9443,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -9557,7 +9550,7 @@ dependencies = [ "cfg-if 1.0.4", "libc", "psm", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -9849,7 +9842,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -10134,6 +10127,30 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio_with_wasm" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34e40fbbbd95441133fe9483f522db15dbfd26dc636164ebd8f2dd28759a6aa6" +dependencies = [ + "js-sys", + "tokio", + "tokio_with_wasm_proc", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "tokio_with_wasm_proc" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d01145a2c788d6aae4cd653afec1e8332534d7d783d01897cefcafe4428de992" +dependencies = [ + "quote", + "syn 2.0.117", +] + [[package]] name = "toml_datetime" version = "1.1.1+spec-1.1.0" @@ -10829,7 +10846,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.52.0", ] [[package]] @@ -11263,20 +11280,18 @@ dependencies = [ [[package]] name = "xet-client" -version = "1.5.2" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e1e496dcbe6a09017acdfaf48e1a646735e7ff5b2a49e2c7e081cca77a59bc8" +checksum = "c3b8da8cc70aa2e3c500c0400e012df82c656ab9fca47f9f939fffc5afd89aca" dependencies = [ "anyhow", "async-trait", "base64 0.22.1", "bytes", - "clap", "crc32fast", "futures", "http 1.5.0", "hyper 1.9.0", - "lazy_static", "more-asserts", "rand 0.10.1", "redb", @@ -11290,8 +11305,8 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tokio-retry", + "tokio_with_wasm", "tracing", - "tracing-subscriber", "url", "urlencoding", "web-time", @@ -11301,24 +11316,21 @@ dependencies = [ [[package]] name = "xet-core-structures" -version = "1.5.2" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb838aa8eb67d730af301584cf003caad407487606058292a6750711b603fbee" +checksum = "73503c223783dccc864abde22115e09d12f190448a0baf58ab2c54bc709e2f99" dependencies = [ "async-trait", "base64 0.22.1", "blake3", "bytemuck", "bytes", - "clap", "countio", - "csv", "futures", "futures-util", "getrandom 0.4.2", "heapify", "itertools 0.14.0", - "lazy_static", "lz4_flex", "more-asserts", "rand 0.10.1", @@ -11326,7 +11338,6 @@ dependencies = [ "safe-transmute", "serde", "static_assertions", - "tempfile", "thiserror 2.0.18", "tokio", "tokio-util", @@ -11338,32 +11349,31 @@ dependencies = [ [[package]] name = "xet-data" -version = "1.5.2" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67fd409bef621411a9d9013798540bb8036cb2678f03ab39af89a5e88034ed8c" +checksum = "c89052ec5dec2187cad30b86af92cc24fd61c4a57a795f1ff7ff5f38d49184eb" dependencies = [ "anyhow", "async-trait", "bytes", "chrono", - "clap", "gearhash", "http 1.5.0", "itertools 0.14.0", - "lazy_static", "more-asserts", "rand 0.10.1", "serde", "serde_json", - "sha2 0.10.9", + "sha2 0.11.0", "tempfile", "thiserror 2.0.18", "tokio", "tokio-util", + "tokio_with_wasm", "tracing", "url", "uuid", - "walkdir", + "web-time", "xet-client", "xet-core-structures", "xet-runtime", @@ -11371,9 +11381,9 @@ dependencies = [ [[package]] name = "xet-runtime" -version = "1.5.2" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15d8f121c33866f7648b737abe70d0e2dd9c0af4ffdd7219207531d0283aa63d" +checksum = "af5c60d5eed38ab4c576f4421bae835e7bd07631fb381705605529d2015c106b" dependencies = [ "anyhow", "async-trait", @@ -11381,13 +11391,12 @@ dependencies = [ "chrono", "colored", "const-str", - "ctor 0.6.3", + "ctor", "dirs", "futures", "git-version", "humantime", "konst", - "lazy_static", "libc", "more-asserts", "oneshot", @@ -11401,9 +11410,11 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tokio-util", + "tokio_with_wasm", "tracing", "tracing-appender", "tracing-subscriber", + "web-time", "whoami", "winapi", ] diff --git a/Cargo.toml b/Cargo.toml index a0a908489..2b16a6bf0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=12.0.0-beta.16", default-features = false, "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=12.0.0-beta.16", default-features = false, "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=12.0.0-beta.16", default-features = false, "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=12.0.0-beta.16", "tag" = "v12.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=12.0.0-beta.17", default-features = false, "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=12.0.0-beta.17", default-features = false, "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=12.0.0-beta.17", default-features = false, "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow @@ -60,7 +60,7 @@ log = "0.4" metrics = "0.24" metrics-util = "0.19" moka = { version = "0.12", features = ["future"] } -object_store = "0.13.2" +object_store = "0.14.1" pin-project = "1.0.7" rand = "0.9" snafu = "0.8" diff --git a/java/pom.xml b/java/pom.xml index b3dbe413c..7cbb819d9 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 12.0.0-beta.16 + 12.0.0-beta.17 false 2.30.0 1.7 From 6702e3fec1a2de38aa9e1c04fb69bcd93bfd210a Mon Sep 17 00:00:00 2001 From: Drew Date: Fri, 11 Sep 2026 14:46:27 -0700 Subject: [PATCH 195/206] feat(node): add blob v2 fetch and field helpers (#4155) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit this PR blob v2 field helpers and reads to the Node SDK. `blob()` marks a field as blob v2 and lets you set the storage thresholds. Inputs can be bytes, a URI, or a data/uri struct. Queries return descriptors. `fetchBlobs()` reads the bytes by row ID, and `fetchBlobFiles()` gives you lazy handles for full or range reads. `blobColumns()` lists the blob fields, including nested ones. Fetch uses the table’s current checkout. It preserves order, duplicates, and nulls. Holding row IDs across compaction still requires stable row IDs. ```javascript const db = await connect("./data"); const video = await readFile("clip.mp4"); const table = await db.createTable( "videos", [{ id: 1n, video }], { schema: new Schema([ new Field("id", new Int64()), blob("video"), ]), }, ); const rows = await table.query().select(["id"]).withRowId().toArray(); const rowIds = rows.map((row) => row._rowid as bigint); const bytes = await table.fetchBlobs("video", rowIds); const [handle] = await table.fetchBlobFiles("video", rowIds); const header = await handle!.readRange(0n, 65536n); ``` ### Testing - cover input validation, thresholds, nested fields, fetch ordering, nulls, and range reads. --- docs/src/js/classes/BlobFile.md | 62 ++++++ docs/src/js/classes/Table.md | 62 ++++++ docs/src/js/functions/blob.md | 55 +++++ docs/src/js/functions/isBlobField.md | 22 ++ docs/src/js/globals.md | 4 + docs/src/js/type-aliases/BlobOptions.md | 48 +++++ nodejs/__test__/blob.test.ts | 185 ++++++++++++++++ nodejs/__test__/table.test.ts | 271 ++++++++++++++++++++++++ nodejs/lancedb/arrow.ts | 103 ++++++++- nodejs/lancedb/blob.ts | 236 +++++++++++++++++++++ nodejs/lancedb/index.ts | 3 + nodejs/lancedb/table.ts | 91 ++++++-- nodejs/src/blob.rs | 95 +++++++++ nodejs/src/lib.rs | 1 + nodejs/src/table.rs | 39 ++++ 15 files changed, 1260 insertions(+), 17 deletions(-) create mode 100644 docs/src/js/classes/BlobFile.md create mode 100644 docs/src/js/functions/blob.md create mode 100644 docs/src/js/functions/isBlobField.md create mode 100644 docs/src/js/type-aliases/BlobOptions.md create mode 100644 nodejs/__test__/blob.test.ts create mode 100644 nodejs/lancedb/blob.ts create mode 100644 nodejs/src/blob.rs diff --git a/docs/src/js/classes/BlobFile.md b/docs/src/js/classes/BlobFile.md new file mode 100644 index 000000000..84a596d1a --- /dev/null +++ b/docs/src/js/classes/BlobFile.md @@ -0,0 +1,62 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / BlobFile + +# Class: BlobFile + +A lazy handle to blob bytes. Create one with [Table.fetchBlobFiles](Table.md#fetchblobfiles). + +## Methods + +### read() + +```ts +read(): Promise +``` + +Reads from the cursor to the end and advances the cursor. + +A second call returns an empty buffer. [BlobFile.readRange](BlobFile.md#readrange) does +not move the cursor. + +#### Returns + +`Promise`<`Buffer`> + +*** + +### readRange() + +```ts +readRange(start, end): Promise +``` + +Reads the half-open byte range `[start, end)`. + +Fails when `end` is past the blob size. Does not move the cursor. + +#### Parameters + +* **start**: `bigint` + +* **end**: `bigint` + +#### Returns + +`Promise`<`Buffer`> + +*** + +### size() + +```ts +size(): bigint +``` + +Returns the blob size in bytes. + +#### Returns + +`bigint` diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 3847f3a39..ef6e9535a 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -137,6 +137,20 @@ containing the new version number of the table after altering the columns. *** +### blobColumns() + +```ts +abstract blobColumns(): Promise +``` + +Blob v2 columns, including nested dotted paths. + +#### Returns + +`Promise`<`string`[]> + +*** + ### branches() ```ts @@ -499,6 +513,54 @@ Drop an index from the table. *** +### fetchBlobFiles() + +```ts +abstract fetchBlobFiles(column, rowIds): Promise<(null | BlobFile)[]> +``` + +Opens lazy blob handles for `column` at the given row IDs using the +table's current checkout. + +Preserves input order, duplicates, and nulls. Use this for large payloads. +See [Table.fetchBlobs](Table.md#fetchblobs) for row-ID validity across versions. + +#### Parameters + +* **column**: `string` + +* **rowIds**: readonly (`number` \| `bigint`)[] + +#### Returns + +`Promise`<(`null` \| [`BlobFile`](BlobFile.md))[]> + +*** + +### fetchBlobs() + +```ts +abstract fetchBlobs(column, rowIds): Promise<(null | Buffer)[]> +``` + +Bytes for `column` at row IDs from [Query.withRowId](Query.md#withrowid). + +Reads the table's current checkout. IDs from another version can fail after +compaction unless stable row ids are enabled. Results keep input order and +duplicates. Null blobs are `null`. Empty blobs are empty buffers. + +#### Parameters + +* **column**: `string` + +* **rowIds**: readonly (`number` \| `bigint`)[] + +#### Returns + +`Promise`<(`null` \| `Buffer`)[]> + +*** + ### flushLsm() ```ts diff --git a/docs/src/js/functions/blob.md b/docs/src/js/functions/blob.md new file mode 100644 index 000000000..20a734cd4 --- /dev/null +++ b/docs/src/js/functions/blob.md @@ -0,0 +1,55 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / blob + +# Function: blob() + +```ts +function blob(name, options): Field +``` + +Declares a `lance.blob.v2` column. + +Query results are descriptors, not payload bytes. Use [Table.fetchBlobs](../classes/Table.md#fetchblobs) +or [Table.fetchBlobFiles](../classes/Table.md#fetchblobfiles) to read bytes. + +## Parameters + +* **name**: `string` + +* **options**: [`BlobOptions`](../type-aliases/BlobOptions.md) = `{}` + +## Returns + +`Field` + +## Example + +```ts +import { readFile } from "node:fs/promises"; +import { Field, Int64, Schema } from "apache-arrow"; +import { blob, connect } from "@lancedb/lancedb"; + +const db = await connect("./data"); +const video = await readFile("clip.mp4"); +const table = await db.createTable( + "videos", + [{ id: 1n, video }], + { + schema: new Schema([ + new Field("id", new Int64()), + blob("video"), + ]), + }, +); + +const rows = await table.query().select(["id"]).withRowId().toArray(); +const rowIds = rows.map((row) => row._rowid as bigint); +const bytes = await table.fetchBlobs("video", rowIds); + +const [handle] = await table.fetchBlobFiles("video", rowIds); +const size = handle!.size(); +const header = await handle!.readRange(0n, size < 65536n ? size : 65536n); +``` diff --git a/docs/src/js/functions/isBlobField.md b/docs/src/js/functions/isBlobField.md new file mode 100644 index 000000000..944309f90 --- /dev/null +++ b/docs/src/js/functions/isBlobField.md @@ -0,0 +1,22 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / isBlobField + +# Function: isBlobField() + +```ts +function isBlobField(field): boolean +``` + +Checks for the `lance.blob.v2` extension marker. Does not validate the +field's storage type. + +## Parameters + +* **field**: `Field`<`any`> + +## Returns + +`boolean` diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index eb0fc7d5a..4a5effaae 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -19,6 +19,7 @@ ## Classes - [AutoQuery](classes/AutoQuery.md) +- [BlobFile](classes/BlobFile.md) - [BooleanQuery](classes/BooleanQuery.md) - [BoostQuery](classes/BoostQuery.md) - [BranchContents](classes/BranchContents.md) @@ -143,6 +144,7 @@ - [AnalyzePlanDistributedMetrics](type-aliases/AnalyzePlanDistributedMetrics.md) - [BaseTokenizer](type-aliases/BaseTokenizer.md) +- [BlobOptions](type-aliases/BlobOptions.md) - [Data](type-aliases/Data.md) - [DataLike](type-aliases/DataLike.md) - [FieldLike](type-aliases/FieldLike.md) @@ -158,9 +160,11 @@ ## Functions - [RecordBatchIterator](functions/RecordBatchIterator.md) +- [blob](functions/blob.md) - [connect](functions/connect.md) - [connectNamespace](functions/connectNamespace.md) - [instrumentLanceDbMetrics](functions/instrumentLanceDbMetrics.md) +- [isBlobField](functions/isBlobField.md) - [makeArrowTable](functions/makeArrowTable.md) - [packBits](functions/packBits.md) - [permutationBuilder](functions/permutationBuilder.md) diff --git a/docs/src/js/type-aliases/BlobOptions.md b/docs/src/js/type-aliases/BlobOptions.md new file mode 100644 index 000000000..41dbe92c2 --- /dev/null +++ b/docs/src/js/type-aliases/BlobOptions.md @@ -0,0 +1,48 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / BlobOptions + +# Type Alias: BlobOptions + +```ts +type BlobOptions: object; +``` + +## Type declaration + +### dedicatedSizeThreshold? + +```ts +optional dedicatedSizeThreshold: number; +``` + +Max payload bytes stored in a packed sidecar before a dedicated file. Must +be a positive safe integer. + +### inlineSizeThreshold? + +```ts +optional inlineSizeThreshold: number; +``` + +Max payload bytes kept inline in the data file. Zero is allowed. Must be a +safe integer. + +### nullable? + +```ts +optional nullable: boolean; +``` + +Defaults to true. + +### packFileSizeThreshold? + +```ts +optional packFileSizeThreshold: number; +``` + +Max bytes in one packed sidecar before starting another. Must be a positive +safe integer. diff --git a/nodejs/__test__/blob.test.ts b/nodejs/__test__/blob.test.ts new file mode 100644 index 000000000..e8e9357e3 --- /dev/null +++ b/nodejs/__test__/blob.test.ts @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { Field, Int64, List, Schema, Struct, Utf8 } from "apache-arrow"; +import { makeArrowTable } from "../lancedb/arrow"; +import { BlobFile, blob, coerceBlobValue, isBlobField } from "../lancedb/blob"; + +describe("blob()", () => { + it("marks the field as lance.blob.v2", () => { + const field = blob("image", { nullable: false }); + expect(field.nullable).toBe(false); + expect(isBlobField(field)).toBe(true); + expect(field.metadata.get("ARROW:extension:name")).toBe("lance.blob.v2"); + }); + + it("writes encoding thresholds as field metadata", () => { + const field = blob("video", { + inlineSizeThreshold: 1024, + dedicatedSizeThreshold: 2 * 1024 * 1024, + packFileSizeThreshold: 64 * 1024 * 1024, + }); + expect( + field.metadata.get("lance-encoding:blob-inline-size-threshold"), + ).toBe("1024"); + expect( + field.metadata.get("lance-encoding:blob-dedicated-size-threshold"), + ).toBe(String(2 * 1024 * 1024)); + expect( + field.metadata.get("lance-encoding:blob-pack-file-size-threshold"), + ).toBe(String(64 * 1024 * 1024)); + }); + + it("rejects invalid thresholds", () => { + expect(() => blob("image", { inlineSizeThreshold: -1 })).toThrow( + /inlineSizeThreshold must be non-negative/, + ); + expect(() => blob("image", { dedicatedSizeThreshold: 0 })).toThrow( + /dedicatedSizeThreshold must be positive/, + ); + expect(() => blob("image", { packFileSizeThreshold: 1.5 })).toThrow( + /packFileSizeThreshold must be a safe integer/, + ); + expect(() => + blob("image", { dedicatedSizeThreshold: Number.MAX_SAFE_INTEGER + 1 }), + ).toThrow(/dedicatedSizeThreshold must be a safe integer/); + }); +}); + +describe("coerceBlobValue", () => { + it.each([ + ["Buffer", Buffer.from("x"), { data: Buffer.from("x"), uri: null }], + [ + "Uint8Array", + new Uint8Array([120]), + { data: new Uint8Array([120]), uri: null }, + ], + ["URI string", "s3://bucket/key", { data: null, uri: "s3://bucket/key" }], + [ + "data struct", + { data: Buffer.from("y") }, + { data: Buffer.from("y"), uri: null }, + ], + [ + "uri struct", + { uri: "s3://bucket/key" }, + { data: null, uri: "s3://bucket/key" }, + ], + ["null", null, null], + ])("accepts %s", (_name, input, expected) => { + expect(coerceBlobValue(input)).toEqual(expected); + }); + + it.each([ + ["empty URI", "", /uri cannot be empty/], + ["object without data or uri", { position: 0 }, /data' or 'uri/], + [ + "Int16Array", + new Int16Array([1]), + /Blob data must be Buffer or Uint8Array/, + ], + [ + "both data and uri", + { data: Buffer.from("y"), uri: "s3://bucket/key" }, + /exactly one of 'data' or 'uri'/, + ], + [ + "neither data nor uri", + { data: null, uri: null }, + /exactly one of 'data' or 'uri'/, + ], + ])("rejects %s", (_name, input, message) => { + expect(() => coerceBlobValue(input)).toThrow(message); + }); +}); + +describe("BlobFile", () => { + it("rejects constructing BlobFile without a native handle", () => { + expect(() => new (BlobFile as unknown as { new (): BlobFile })()).toThrow( + /fetchBlobFiles/, + ); + }); +}); + +describe("makeArrowTable blob columns", () => { + it("coerces Buffer input onto a blob field", () => { + const schema = new Schema([ + new Field("id", new Int64(), true), + blob("image"), + ]); + const table = makeArrowTable([{ id: 1n, image: Buffer.from("hello") }], { + schema, + }); + expect(isBlobField(table.schema.fields[1])).toBe(true); + const image = table.getChild("image")!; + expect(image.nullCount).toBe(0); + expect(image.getChild("uri")!.get(0)).toBeNull(); + expect(image.getChild("data")!.nullCount).toBe(0); + expect(Buffer.from(image.getChild("data")!.get(0)!).toString()).toBe( + "hello", + ); + }); + + it("coerces Buffer elements inside a list and keeps null slots", () => { + const schema = new Schema([ + new Field("id", new Int64(), true), + new Field("images", new List(blob("image")), true), + ]); + const table = makeArrowTable( + [ + { id: 1n, images: [Buffer.from("a"), Buffer.from("bb")] }, + { id: 2n, images: null }, + { id: 3n, images: [Buffer.from("c"), null] }, + { id: 4n, images: [] }, + ], + { schema }, + ); + const images = table.getChild("images")!; + expect(images.nullCount).toBe(1); + const rows = images.toArray(); + expect(rows[1]).toBeNull(); + expect(Array.from(rows[3] as Iterable)).toHaveLength(0); + const first = Array.from(rows[0] as Iterable<{ data: Uint8Array | null }>); + expect(Buffer.from(first[0].data!).toString()).toBe("a"); + expect(Buffer.from(first[1].data!).toString()).toBe("bb"); + const third = Array.from( + rows[2] as Iterable<{ data: Uint8Array | null } | null>, + ); + expect(Buffer.from(third[0]!.data!).toString()).toBe("c"); + expect(third[1]).toBeNull(); + }); + + it("coerces Buffer fields inside list structs", () => { + const schema = new Schema([ + new Field("id", new Int64(), true), + new Field( + "items", + new List( + new Field( + "item", + new Struct([new Field("name", new Utf8(), true), blob("image")]), + true, + ), + ), + true, + ), + ]); + const table = makeArrowTable( + [ + { + id: 1n, + items: [{ name: "one", image: Buffer.from("alpha") }], + }, + ], + { schema }, + ); + const items = Array.from( + table.getChild("items")!.toArray()[0] as Iterable<{ + name: string; + image: { data: Uint8Array | null }; + }>, + ); + expect(items[0].name).toBe("one"); + expect(Buffer.from(items[0].image.data!).toString()).toBe("alpha"); + }); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index e8b97bf77..cae01d9d5 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -18,6 +18,7 @@ import { Query, Table, VectorQuery, + blob, connect, tokenize, } from "../lancedb"; @@ -2401,6 +2402,276 @@ describe("when dealing with versioning", () => { }); }); +describe("when dealing with blob columns", () => { + let tmpDir: tmp.DirResult; + beforeEach(() => { + tmpDir = tmp.dirSync({ unsafeCleanup: true }); + }); + afterEach(() => { + tmpDir.removeCallback(); + }); + + it("discovers blob columns", async () => { + const { table } = await openBlobTable(); + expect(await table.blobColumns()).toEqual(["image"]); + }); + + it("preserves order, duplicates, and nulls", async () => { + const { table, rowIds } = await openBlobTable(); + const [alphaId, betaId, nullId] = rowIds; + const bytes = await table.fetchBlobs("image", [ + betaId, + alphaId, + betaId, + nullId, + ]); + expect(bytes.map((b) => (b == null ? null : b.toString()))).toEqual([ + "beta", + "alpha", + "beta", + null, + ]); + const files = await table.fetchBlobFiles("image", [ + betaId, + nullId, + alphaId, + ]); + expect(files.map((f) => f == null)).toEqual([false, true, false]); + }); + + it("reads full blob contents", async () => { + const { table, rowIds, alpha, beta } = await openBlobTable(); + const bytes = await table.fetchBlobs("image", rowIds); + expect(bytes[0]!.equals(alpha)).toBe(true); + expect(bytes[1]!.equals(beta)).toBe(true); + const files = await table.fetchBlobFiles("image", rowIds); + expect(files[0]!.size()).toBe(BigInt(alpha.length)); + expect(Buffer.from(await files[0]!.read()).toString()).toBe("alpha"); + expect(Buffer.from(await files[1]!.read()).toString()).toBe("beta"); + }); + + it("reads a half-open range", async () => { + const { table, rowIds } = await openBlobTable(); + const files = await table.fetchBlobFiles("image", rowIds); + expect(Buffer.from(await files[0]!.readRange(0n, 2n)).toString()).toBe( + "al", + ); + }); + + it("readRange does not move the cursor", async () => { + const { table, rowIds, alpha } = await openBlobTable(); + const [handle] = await table.fetchBlobFiles("image", rowIds); + expect((await handle!.readRange(1n, 3n)).toString()).toBe("lp"); + expect(await handle!.read()).toEqual(alpha); + expect(await handle!.read()).toEqual(Buffer.alloc(0)); + }); + + it("fails when readRange end is past the blob size", async () => { + const { table, rowIds, alpha } = await openBlobTable(); + const files = await table.fetchBlobFiles("image", rowIds); + await expect( + files[0]!.readRange(0n, BigInt(alpha.length + 1)), + ).rejects.toThrow(/exceeds blob size/); + }); + + it("rejects fetchBlobs on a non-blob column", async () => { + const { table, rowIds } = await openBlobTable(); + await expect(table.fetchBlobs("id", rowIds)).rejects.toThrow(/blob/i); + }); + + it("discovers and fetches nested blob columns", async () => { + const db = await connect(tmpDir.name); + const schema = new Schema([ + new Field("id", new Int64(), true), + new Field("info", new Struct([blob("image")]), true), + ]); + const payload = Buffer.from("nested"); + const table = await db.createTable( + "nested_blobs", + [{ id: 1n, info: { image: payload } }], + { schema }, + ); + expect(await table.blobColumns()).toEqual(["info.image"]); + const rows = await table.query().withRowId().toArray(); + const bytes = await table.fetchBlobs("info.image", [ + rows[0]._rowid as bigint, + ]); + expect(bytes[0]!.equals(payload)).toBe(true); + }); + + it("creates and adds list blob columns", async () => { + const db = await connect(tmpDir.name); + const schema = new Schema([ + new Field("id", new Int64(), true), + new Field("images", new List(blob("image")), true), + ]); + const alpha = Buffer.from("alpha"); + const beta = Buffer.from("beta"); + const gamma = Buffer.from("gamma"); + const table = await db.createTable( + "list_blobs", + [{ id: 1n, images: [alpha, beta] }], + { schema }, + ); + await table.add([ + { id: 2n, images: null }, + { id: 3n, images: [gamma, null] }, + { id: 4n, images: [] }, + ]); + expect(await table.blobColumns()).toEqual(["images.image"]); + const rows = await table.query().toArray(); + const byId = new Map(rows.map((row) => [Number(row.id), row])); + expect(descriptorSizes(byId.get(1)!.images)).toEqual([ + alpha.length, + beta.length, + ]); + expect(byId.get(2)!.images).toBeNull(); + expect(descriptorSizes(byId.get(3)!.images)).toEqual([gamma.length, null]); + expect(Array.from(byId.get(4)!.images as Iterable)).toHaveLength( + 0, + ); + }); + + it("creates and adds list struct blob columns", async () => { + const db = await connect(tmpDir.name); + const schema = new Schema([ + new Field("id", new Int64(), true), + new Field( + "items", + new List( + new Field( + "item", + new Struct([new Field("name", new Utf8(), true), blob("image")]), + true, + ), + ), + true, + ), + ]); + const alpha = Buffer.from("nested-alpha"); + const beta = Buffer.from("nested-beta"); + const table = await db.createTable( + "list_struct_blobs", + [{ id: 1n, items: [{ name: "one", image: alpha }] }], + { schema }, + ); + await table.add([ + { + id: 2n, + items: [ + { name: "two", image: beta }, + { name: "three", image: null }, + ], + }, + ]); + const rows = await table.query().toArray(); + const byId = new Map(rows.map((row) => [Number(row.id), row])); + expect( + descriptorSizes( + Array.from(byId.get(1)!.items as Iterable<{ image: unknown }>).map( + (item) => item.image, + ), + ), + ).toEqual([alpha.length]); + expect( + descriptorSizes( + Array.from(byId.get(2)!.items as Iterable<{ image: unknown }>).map( + (item) => item.image, + ), + ), + ).toEqual([beta.length, null]); + }); + + it("rejects blob fields inside a fixed-size list", async () => { + const db = await connect(tmpDir.name); + const schema = new Schema([ + new Field("id", new Int64(), true), + new Field("frames", new FixedSizeList(2, blob("frame")), true), + ]); + await expect( + db.createTable( + "fsl_blobs", + [{ id: 1n, frames: [Buffer.from("a"), Buffer.from("b")] }], + { schema }, + ), + ).rejects.toThrow( + "Blob fields inside FixedSizeList are not supported. Use List instead.", + ); + }); + + it("rejects blob fields inside a nested fixed-size list", async () => { + const db = await connect(tmpDir.name); + const schema = new Schema([ + new Field("id", new Int64(), true), + new Field( + "clip", + new Struct([ + new Field("frames", new FixedSizeList(2, blob("frame")), true), + ]), + true, + ), + ]); + await expect( + db.createTable( + "nested_fsl_blobs", + [ + { + id: 1n, + clip: { frames: [Buffer.from("a"), Buffer.from("b")] }, + }, + ], + { schema }, + ), + ).rejects.toThrow( + "Blob fields inside FixedSizeList are not supported. Use List instead.", + ); + }); + + it("rejects an Arrow table with blob fields inside a fixed-size list", async () => { + const db = await connect(tmpDir.name); + const schema = new Schema([ + new Field("id", new Int64(), true), + new Field("frames", new FixedSizeList(2, blob("frame")), true), + ]); + await expect( + db.createTable("fsl_blobs_ipc", new ArrowTable(schema)), + ).rejects.toThrow( + "Blob fields inside FixedSizeList are not supported. Use List instead.", + ); + }); + + function descriptorSizes(values: unknown): (number | null)[] { + return Array.from( + values as Iterable<{ size?: bigint | number } | null>, + ).map((value) => (value == null ? null : Number(value.size))); + } + + async function openBlobTable() { + const db = await connect(tmpDir.name); + const schema = new Schema([ + new Field("id", new Int64(), true), + blob("image"), + ]); + const alpha = Buffer.from("alpha"); + const beta = Buffer.from("beta"); + const table = await db.createTable( + "blobs", + [ + { id: 1n, image: alpha }, + { id: 2n, image: beta }, + { id: 3n, image: null }, + ], + { schema }, + ); + const rows = await table.query().withRowId().toArray(); + const rowIdById = new Map( + rows.map((r) => [Number(r.id), r._rowid as bigint]), + ); + const rowIds = [1, 2, 3].map((id) => rowIdById.get(id)!); + return { table, rowIds, alpha, beta }; + } +}); + describe("when dealing with tags", () => { let tmpDir: tmp.DirResult; beforeEach(() => { diff --git a/nodejs/lancedb/arrow.ts b/nodejs/lancedb/arrow.ts index 119887704..81b140da7 100644 --- a/nodejs/lancedb/arrow.ts +++ b/nodejs/lancedb/arrow.ts @@ -40,6 +40,7 @@ import { } from "apache-arrow"; import { Buffers } from "apache-arrow/data"; import { typedArrayToArrowType } from "./arrow_type"; +import { coerceBlobValue, isBlobField } from "./blob"; import { type EmbeddingFunction } from "./embedding/embedding_function"; import { EmbeddingFunctionConfig, @@ -430,12 +431,14 @@ export function makeArrowTable( throw new Error("A schema must be provided if data is empty"); } else { schema = new Schema(schema.fields, schemaMetadata); + validateBlobSchema(schema); return new ArrowTable(schema); } } let inferredSchema = inferSchema(data, schema, opt); inferredSchema = new Schema(inferredSchema.fields, schemaMetadata); + validateBlobSchema(inferredSchema); const finalColumns: Record = {}; for (const field of inferredSchema.fields) { @@ -445,6 +448,35 @@ export function makeArrowTable( return new ArrowTable(inferredSchema, finalColumns); } +function validateBlobSchema(schema: Schema): void { + for (const field of schema.fields) { + validateBlobField(field); + } +} + +function validateBlobField(field: Field): void { + if ( + isFixedSizeList(field.type) && + containsBlobField(field.type.children[0]) + ) { + throw new Error( + "Blob fields inside FixedSizeList are not supported. Use List instead.", + ); + } + for (const child of field.type.children ?? []) { + validateBlobField(child); + } +} + +function containsBlobField(field: Field): boolean { + if (isBlobField(field)) { + return true; + } + return (field.type.children ?? []).some((child: Field) => + containsBlobField(child), + ); +} + function isObject(value: unknown): value is Record { return ( typeof value === "object" && @@ -480,6 +512,32 @@ function transposeData( path: string[] = [], ): Vector { const valuesPath = [...path, field.name]; + if (isBlobField(field) && field.type instanceof Struct) { + const blobRows = data.map((datum) => + coerceBlobValue(valueAtPath(datum, valuesPath)), + ); + const childVectors = field.type.children.map((child) => { + const values = blobRows.map((row) => + row == null ? null : (row[child.name as "data" | "uri"] ?? null), + ); + return makeVector(values, child.type, undefined, child.nullable); + }); + const nullCount = blobRows.filter((row) => row === null).length; + const structData = makeData({ + type: field.type, + length: blobRows.length, + nullCount, + nullBitmap: + nullCount > 0 + ? arrowUtil.packBools(blobRows.map((row) => row !== null)) + : undefined, + children: childVectors.map((v) => v.data[0]), + }); + return arrowMakeVector(structData); + } + if (isList(field.type) && containsBlobField(field.type.children[0])) { + return transposeListData(data, field, valuesPath); + } const values = data.map((datum) => valueAtPath(datum, valuesPath)); if (field.type instanceof Struct) { const childFields = field.type.children; @@ -495,7 +553,7 @@ function transposeData( nullCount > 0 ? arrowUtil.packBools(values.map((value) => value !== null)) : undefined, - children: childVectors as unknown as ArrowData[], + children: childVectors.map((v) => v.data[0]), }); return arrowMakeVector(structData); } else { @@ -503,6 +561,48 @@ function transposeData( } } +function transposeListData( + data: Record[], + field: Field, + valuesPath: string[], +): Vector { + const listType = field.type as List; + const childField = listType.children[0]; + const lists = data.map((datum) => valueAtPath(datum, valuesPath)); + const flattened: Record[] = []; + const validity: boolean[] = []; + const offsets: number[] = [0]; + + for (const list of lists) { + if (list == null) { + validity.push(false); + offsets.push(flattened.length); + continue; + } + if (!Array.isArray(list)) { + throw new Error(`expected an array for list field '${field.name}'`); + } + validity.push(true); + for (const element of list) { + flattened.push({ [childField.name]: element }); + } + offsets.push(flattened.length); + } + + const childVector = transposeData(flattened, childField, []); + const nullCount = validity.filter((valid) => !valid).length; + return arrowMakeVector( + makeData({ + type: listType, + length: lists.length, + nullCount, + nullBitmap: nullCount > 0 ? arrowUtil.packBools(validity) : undefined, + valueOffsets: Int32Array.from(offsets), + child: childVector.data[0], + }), + ); +} + /** * Create an empty Arrow table with the provided schema */ @@ -952,6 +1052,7 @@ export async function fromTableToBuffer( schema = sanitizeSchema(schema); } const tableWithEmbeddings = await applyEmbeddings(table, embeddings, schema); + validateBlobSchema(tableWithEmbeddings.schema); const writer = RecordBatchFileWriter.writeAll(tableWithEmbeddings); return Buffer.from(await writer.toUint8Array()); } diff --git a/nodejs/lancedb/blob.ts b/nodejs/lancedb/blob.ts new file mode 100644 index 000000000..244faac09 --- /dev/null +++ b/nodejs/lancedb/blob.ts @@ -0,0 +1,236 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { Field, LargeBinary, Struct, Utf8 } from "apache-arrow"; +import { BlobFile as NativeBlobFile } from "./native"; + +const BLOB_V2_EXTENSION_NAME = "lance.blob.v2"; + +const INLINE_SIZE_THRESHOLD_KEY = "lance-encoding:blob-inline-size-threshold"; +const DEDICATED_SIZE_THRESHOLD_KEY = + "lance-encoding:blob-dedicated-size-threshold"; +const PACK_FILE_SIZE_THRESHOLD_KEY = + "lance-encoding:blob-pack-file-size-threshold"; + +export type BlobInput = { + data: Buffer | Uint8Array | null; + uri: string | null; +}; + +export type BlobOptions = { + /** Defaults to true. */ + nullable?: boolean; + /** + * Max payload bytes kept inline in the data file. Zero is allowed. Must be a + * safe integer. + */ + inlineSizeThreshold?: number; + /** + * Max payload bytes stored in a packed sidecar before a dedicated file. Must + * be a positive safe integer. + */ + dedicatedSizeThreshold?: number; + /** + * Max bytes in one packed sidecar before starting another. Must be a positive + * safe integer. + */ + packFileSizeThreshold?: number; +}; + +/** + * Declares a `lance.blob.v2` column. + * + * Query results are descriptors, not payload bytes. Use {@link Table.fetchBlobs} + * or {@link Table.fetchBlobFiles} to read bytes. + * + * @example + * ```ts + * import { readFile } from "node:fs/promises"; + * import { Field, Int64, Schema } from "apache-arrow"; + * import { blob, connect } from "@lancedb/lancedb"; + * + * const db = await connect("./data"); + * const video = await readFile("clip.mp4"); + * const table = await db.createTable( + * "videos", + * [{ id: 1n, video }], + * { + * schema: new Schema([ + * new Field("id", new Int64()), + * blob("video"), + * ]), + * }, + * ); + * + * const rows = await table.query().select(["id"]).withRowId().toArray(); + * const rowIds = rows.map((row) => row._rowid as bigint); + * const bytes = await table.fetchBlobs("video", rowIds); + * + * const [handle] = await table.fetchBlobFiles("video", rowIds); + * const size = handle!.size(); + * const header = await handle!.readRange(0n, size < 65536n ? size : 65536n); + * ``` + */ +export function blob(name: string, options: BlobOptions = {}): Field { + const metadata = new Map([ + ["ARROW:extension:name", BLOB_V2_EXTENSION_NAME], + ]); + setThreshold( + metadata, + INLINE_SIZE_THRESHOLD_KEY, + "inlineSizeThreshold", + options.inlineSizeThreshold, + 0, + ); + setThreshold( + metadata, + DEDICATED_SIZE_THRESHOLD_KEY, + "dedicatedSizeThreshold", + options.dedicatedSizeThreshold, + 1, + ); + setThreshold( + metadata, + PACK_FILE_SIZE_THRESHOLD_KEY, + "packFileSizeThreshold", + options.packFileSizeThreshold, + 1, + ); + return new Field( + name, + new Struct([ + new Field("data", new LargeBinary(), true), + new Field("uri", new Utf8(), true), + ]), + options.nullable ?? true, + metadata, + ); +} + +/** + * Checks for the `lance.blob.v2` extension marker. Does not validate the + * field's storage type. + */ +export function isBlobField(field: Field): boolean { + return field.metadata?.get("ARROW:extension:name") === BLOB_V2_EXTENSION_NAME; +} + +/** + * A lazy handle to blob bytes. Create one with {@link Table.fetchBlobFiles}. + * + * @hideconstructor + */ +export class BlobFile { + private readonly inner: NativeBlobFile; + + private constructor(inner: NativeBlobFile) { + if (!(inner instanceof NativeBlobFile)) { + throw new Error("BlobFile handles come from Table.fetchBlobFiles"); + } + this.inner = inner; + } + + /** @ignore */ + static fromNative(inner: NativeBlobFile): BlobFile { + return new BlobFile(inner); + } + + /** Returns the blob size in bytes. */ + size(): bigint { + return this.inner.size(); + } + + /** + * Reads from the cursor to the end and advances the cursor. + * + * A second call returns an empty buffer. {@link BlobFile.readRange} does + * not move the cursor. + */ + read(): Promise { + return this.inner.read(); + } + + /** + * Reads the half-open byte range `[start, end)`. + * + * Fails when `end` is past the blob size. Does not move the cursor. + */ + readRange(start: bigint, end: bigint): Promise { + return this.inner.readRange(start, end); + } +} + +export function coerceBlobValue(value: unknown): BlobInput | null { + if (value == null) { + return null; + } + if (isBlobBytes(value)) { + return { data: value, uri: null }; + } + if (ArrayBuffer.isView(value)) { + throw new Error("Blob data must be Buffer or Uint8Array"); + } + if (typeof value === "string") { + if (value === "") { + throw new Error("Blob uri cannot be empty"); + } + return { data: null, uri: value }; + } + if (typeof value === "object") { + const record = value as Record; + if (!("data" in record) && !("uri" in record)) { + throw new Error( + "Blob struct values must include a 'data' or 'uri' field", + ); + } + const uri = record.uri; + if (uri === "") { + throw new Error("Blob uri cannot be empty"); + } + if (uri != null && typeof uri !== "string") { + throw new Error(`Blob uri must be a string or null, got ${typeof uri}`); + } + const data = record.data; + if (data != null && !isBlobBytes(data)) { + throw new Error("Blob data must be Buffer, Uint8Array, or null"); + } + const bytes = (data as Buffer | Uint8Array | null | undefined) ?? null; + const uriValue = uri ?? null; + if ((bytes == null) === (uriValue == null)) { + throw new Error( + "Blob struct values must set exactly one of 'data' or 'uri'", + ); + } + return { data: bytes, uri: uriValue }; + } + throw new Error( + "Blob column values must be Buffer, Uint8Array, a URI string, null, or { data?, uri? }", + ); +} + +function isBlobBytes(value: unknown): value is Buffer | Uint8Array { + return Buffer.isBuffer(value) || value instanceof Uint8Array; +} + +function setThreshold( + metadata: Map, + key: string, + optionName: string, + value: number | undefined, + minimum: number, +): void { + if (value === undefined) { + return; + } + if (!Number.isSafeInteger(value)) { + throw new Error(`${optionName} must be a safe integer`); + } + if (value < minimum) { + throw new Error( + minimum <= 0 + ? `${optionName} must be non-negative` + : `${optionName} must be positive`, + ); + } + metadata.set(key, String(value)); +} diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 4f8ff77e5..d94007a11 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -77,6 +77,9 @@ export { VectorColumnOptions, } from "./arrow"; +export { blob, isBlobField, BlobFile } from "./blob"; +export type { BlobOptions } from "./blob"; + export { Connection, CreateTableOptions, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index d1fb8acd8..eac9f490d 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -17,6 +17,7 @@ import { tableFromIPC, } from "./arrow"; +import { BlobFile } from "./blob"; import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry"; import { IndexOptions } from "./indices"; import { Job } from "./job"; @@ -510,6 +511,35 @@ export abstract class Table { */ abstract takeRowIds(rowIds: readonly (bigint | number)[]): TakeQuery; + /** + * Blob v2 columns, including nested dotted paths. + */ + abstract blobColumns(): Promise; + + /** + * Bytes for `column` at row IDs from {@link Query.withRowId}. + * + * Reads the table's current checkout. IDs from another version can fail after + * compaction unless stable row ids are enabled. Results keep input order and + * duplicates. Null blobs are `null`. Empty blobs are empty buffers. + */ + abstract fetchBlobs( + column: string, + rowIds: readonly (bigint | number)[], + ): Promise<(Buffer | null)[]>; + + /** + * Opens lazy blob handles for `column` at the given row IDs using the + * table's current checkout. + * + * Preserves input order, duplicates, and nulls. Use this for large payloads. + * See {@link Table.fetchBlobs} for row-ID validity across versions. + */ + abstract fetchBlobFiles( + column: string, + rowIds: readonly (bigint | number)[], + ): Promise<(BlobFile | null)[]>; + /** * Create a search query to find the nearest neighbors * of the given query @@ -1160,23 +1190,34 @@ export class LocalTable extends Table { } takeRowIds(rowIds: readonly (bigint | number)[]): TakeQuery { - const ids = rowIds.map((id) => { - if (typeof id === "bigint") { - return id; - } - if (!Number.isInteger(id)) { - throw new Error("Row id must be an integer (or bigint)"); - } - if (id < 0) { - throw new Error("Row id cannot be negative"); - } - if (!Number.isSafeInteger(id)) { - throw new Error("Row id is too large for number; use bigint instead"); - } - return BigInt(id); - }); + return new TakeQuery(this.inner.takeRowIds(rowIdsToBigInts(rowIds))); + } - return new TakeQuery(this.inner.takeRowIds(ids)); + blobColumns(): Promise { + return this.inner.blobColumns(); + } + + async fetchBlobs( + column: string, + rowIds: readonly (bigint | number)[], + ): Promise<(Buffer | null)[]> { + const values = await this.inner.fetchBlobs(column, rowIdsToBigInts(rowIds)); + // N-API Option maps missing values to undefined. Collapse those to null. + return values.map((value) => value ?? null); + } + + async fetchBlobFiles( + column: string, + rowIds: readonly (bigint | number)[], + ): Promise<(BlobFile | null)[]> { + const files = await this.inner.fetchBlobFiles( + column, + rowIdsToBigInts(rowIds), + ); + // N-API Option maps missing values to undefined. Collapse those to null. + return files.map((file) => + file == null ? null : BlobFile.fromNative(file), + ); } query(): Query { @@ -1733,3 +1774,21 @@ export class Branches { )) as unknown as CherryPickResult; } } + +function rowIdsToBigInts(rowIds: readonly (bigint | number)[]): bigint[] { + return rowIds.map((id) => { + if (typeof id === "bigint") { + return id; + } + if (!Number.isInteger(id)) { + throw new Error("Row id must be an integer (or bigint)"); + } + if (id < 0) { + throw new Error("Row id cannot be negative"); + } + if (!Number.isSafeInteger(id)) { + throw new Error("Row id is too large for number; use bigint instead"); + } + return BigInt(id); + }); +} diff --git a/nodejs/src/blob.rs b/nodejs/src/blob.rs new file mode 100644 index 000000000..0e19a9a8a --- /dev/null +++ b/nodejs/src/blob.rs @@ -0,0 +1,95 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +use std::ops::Range; +use std::sync::Arc; + +use arrow_array::{Array, LargeBinaryArray}; +use lancedb::blob::BlobFile as LanceBlobFile; +use napi::bindgen_prelude::*; +use napi_derive::napi; + +use crate::error::convert_error; + +#[napi] +pub struct BlobFile { + inner: Arc, +} + +impl BlobFile { + pub(crate) fn new(inner: LanceBlobFile) -> Self { + Self { + inner: Arc::new(inner), + } + } +} + +#[napi] +impl BlobFile { + #[napi] + pub fn size(&self) -> BigInt { + BigInt::from(self.inner.size()) + } + + #[napi] + pub async fn read(&self) -> napi::Result { + let bytes = self.inner.read().await.map_err(|err| convert_error(&err))?; + Ok(Buffer::from(bytes.as_ref())) + } + + #[napi] + pub async fn read_range(&self, start: BigInt, end: BigInt) -> napi::Result { + let range = bigint_range(start, end)?; + let bytes = self + .inner + .read_range(range) + .await + .map_err(|err| convert_error(&err))?; + Ok(Buffer::from(bytes.as_ref())) + } +} + +fn bigint_range(start: BigInt, end: BigInt) -> napi::Result> { + let start = parse_u64(start, "start")?; + let end = parse_u64(end, "end")?; + if start > end { + return Err(napi::Error::from_reason(format!( + "invalid blob range: start ({start}) > end ({end})" + ))); + } + Ok(start..end) +} + +pub(crate) fn parse_u64(value: BigInt, name: &str) -> napi::Result { + let (negative, value, lossless) = value.get_u64(); + if negative { + return Err(napi::Error::from_reason(format!( + "{name} cannot be negative" + ))); + } + if !lossless { + return Err(napi::Error::from_reason(format!( + "{name} is too large to fit in u64" + ))); + } + Ok(value) +} + +pub(crate) fn parse_row_ids(row_ids: Vec) -> napi::Result> { + row_ids + .into_iter() + .map(|id| parse_u64(id, "row id")) + .collect() +} + +pub(crate) 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() +} diff --git a/nodejs/src/lib.rs b/nodejs/src/lib.rs index 1110f6203..288a2b925 100644 --- a/nodejs/src/lib.rs +++ b/nodejs/src/lib.rs @@ -10,6 +10,7 @@ use std::collections::HashMap; use env_logger::Env; use napi_derive::*; +mod blob; mod connection; mod error; mod header; diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index db74d38fa..7ae4402ab 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -15,6 +15,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}; use crate::error::NapiErrorExt; use crate::index::Index; use crate::merge::NativeMergeInsertBuilder; @@ -329,6 +330,44 @@ impl Table { )) } + #[napi(catch_unwind)] + pub async fn blob_columns(&self) -> napi::Result> { + self.inner_ref()?.blob_columns().await.default_error() + } + + #[napi(catch_unwind)] + pub async fn fetch_blobs( + &self, + column: String, + row_ids: Vec, + ) -> napi::Result>> { + let row_ids = parse_row_ids(row_ids)?; + let array = self + .inner_ref()? + .fetch_blobs(column.as_str(), &row_ids) + .await + .default_error()?; + Ok(copy_blob_buffers(array)) + } + + #[napi(catch_unwind)] + pub async fn fetch_blob_files( + &self, + column: String, + row_ids: Vec, + ) -> napi::Result>> { + let row_ids = parse_row_ids(row_ids)?; + let files = self + .inner_ref()? + .fetch_blob_files(column.as_str(), &row_ids) + .await + .default_error()?; + Ok(files + .into_iter() + .map(|file| file.map(BlobFile::new)) + .collect()) + } + #[napi(catch_unwind)] pub fn vector_search(&self, vector: Float32Array) -> napi::Result { self.query()?.nearest_to(vector) From b8f0048b5a0f4bd9f9d735cb60fc444db3f5a42d Mon Sep 17 00:00:00 2001 From: LanceDB Robot Date: Sat, 12 Sep 2026 22:25:12 -0700 Subject: [PATCH 196/206] chore: update lance dependency to v12.0.0-beta.18 (#4164) Update the Rust workspace Lance dependencies, Cargo lockfile, and Java lance-core to [v12.0.0-beta.18](https://github.com/lance-format/lance/releases/tag/v12.0.0-beta.18). Fix redundant visibility declarations in the Node.js Rust blob helpers required by the workspace Clippy check. Validated with workspace Clippy (all features and tests, warnings denied), cargo fmt, pnpm build, and 13 targeted Node.js blob tests. --- Cargo.lock | 84 +++++++++++++++++++++++----------------------- Cargo.toml | 28 ++++++++-------- java/pom.xml | 2 +- nodejs/src/blob.rs | 6 ++-- 4 files changed, 60 insertions(+), 60 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 209ee4942..7176d8c76 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3490,8 +3490,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow-array", "rand 0.9.5", @@ -4862,8 +4862,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arc-swap", "arrow", @@ -4935,8 +4935,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow-array", "arrow-buffer", @@ -4958,7 +4958,7 @@ dependencies = [ [[package]] name = "lance-arrow-scalar" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow-array", "arrow-buffer", @@ -4972,7 +4972,7 @@ dependencies = [ [[package]] name = "lance-arrow-stats" version = "58.0.0" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow-array", "arrow-schema", @@ -4981,8 +4981,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrayref", "crunchy", @@ -4992,8 +4992,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow-array", "arrow-buffer", @@ -5030,8 +5030,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow", "arrow-array", @@ -5061,8 +5061,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow", "arrow-array", @@ -5079,8 +5079,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "proc-macro2", "quote", @@ -5089,8 +5089,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow-arith", "arrow-array", @@ -5123,8 +5123,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow-arith", "arrow-array", @@ -5155,8 +5155,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arc-swap", "arrow", @@ -5220,8 +5220,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow-array", "arrow-schema", @@ -5243,8 +5243,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow", "arrow-array", @@ -5284,8 +5284,8 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow-array", "arrow-schema", @@ -5299,8 +5299,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow", "async-trait", @@ -5314,8 +5314,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow", "arrow-ipc", @@ -5368,8 +5368,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow-array", "arrow-buffer", @@ -5383,8 +5383,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow", "arrow-array", @@ -5424,8 +5424,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "arrow-array", "arrow-schema", @@ -5438,8 +5438,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "12.0.0-beta.17" -source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.17#d7b031f9ca86e7cbb8c3732ab87b2b18548996ba" +version = "12.0.0-beta.18" +source = "git+https://github.com/lance-format/lance.git?tag=v12.0.0-beta.18#1047c4bdbf36331cff2d9e21ab525c45ed741f93" dependencies = [ "frostem", "icu_segmenter", diff --git a/Cargo.toml b/Cargo.toml index 2b16a6bf0..1068d48ee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,20 +13,20 @@ categories = ["database-implementations"] rust-version = "1.91.0" [workspace.dependencies] -lance = { "version" = "=12.0.0-beta.17", default-features = false, "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=12.0.0-beta.17", default-features = false, "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-linalg = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=12.0.0-beta.17", default-features = false, "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=12.0.0-beta.17", "tag" = "v12.0.0-beta.17", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=12.0.0-beta.18", default-features = false, "tag" = "v12.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=12.0.0-beta.18", "tag" = "v12.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=12.0.0-beta.18", "tag" = "v12.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=12.0.0-beta.18", "tag" = "v12.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=12.0.0-beta.18", default-features = false, "tag" = "v12.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=12.0.0-beta.18", "tag" = "v12.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=12.0.0-beta.18", "tag" = "v12.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=12.0.0-beta.18", "tag" = "v12.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=12.0.0-beta.18", default-features = false, "tag" = "v12.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=12.0.0-beta.18", "tag" = "v12.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=12.0.0-beta.18", "tag" = "v12.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=12.0.0-beta.18", "tag" = "v12.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=12.0.0-beta.18", "tag" = "v12.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=12.0.0-beta.18", "tag" = "v12.0.0-beta.18", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" # Note that this one does not include pyarrow diff --git a/java/pom.xml b/java/pom.xml index 7cbb819d9..a2456103d 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 12.0.0-beta.17 + 12.0.0-beta.18 false 2.30.0 1.7 diff --git a/nodejs/src/blob.rs b/nodejs/src/blob.rs index 0e19a9a8a..230a11bae 100644 --- a/nodejs/src/blob.rs +++ b/nodejs/src/blob.rs @@ -60,7 +60,7 @@ fn bigint_range(start: BigInt, end: BigInt) -> napi::Result> { Ok(start..end) } -pub(crate) fn parse_u64(value: BigInt, name: &str) -> napi::Result { +fn parse_u64(value: BigInt, name: &str) -> napi::Result { let (negative, value, lossless) = value.get_u64(); if negative { return Err(napi::Error::from_reason(format!( @@ -75,14 +75,14 @@ pub(crate) fn parse_u64(value: BigInt, name: &str) -> napi::Result { Ok(value) } -pub(crate) fn parse_row_ids(row_ids: Vec) -> napi::Result> { +pub fn parse_row_ids(row_ids: Vec) -> napi::Result> { row_ids .into_iter() .map(|id| parse_u64(id, "row id")) .collect() } -pub(crate) fn copy_blob_buffers(array: LargeBinaryArray) -> Vec> { +pub fn copy_blob_buffers(array: LargeBinaryArray) -> Vec> { (0..array.len()) .map(|i| { if array.is_null(i) { From 9fe10c7362b1fdfb9bfa1378412ce4d178d3e7a4 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Sun, 13 Sep 2026 21:44:13 -0700 Subject: [PATCH 197/206] fix(remote): align Function CRUD routes (#4166) Align the experimental Function HTTP transport with the equivalent Table CRUD API shape. This is an intentional breaking change to the experimental Function routes; public Rust and Python APIs remain unchanged. ## Route comparison | Operation | Function before | Function after | Equivalent Table API | | --- | --- | --- | --- | | Create | `POST /v1/functions/create` | `POST /v1/function/{id}/create` | `POST /v1/table/{id}/create` | | Describe | `POST /v1/functions/describe` | `POST /v1/function/{id}/describe` | `POST /v1/table/{id}/describe` | | List | `POST /v1/functions/list` | `GET /v1/namespace/{id}/function/list` | `GET /v1/namespace/{id}/table/list` | | Drop | `POST /v1/functions/drop` | `POST /v1/function/{id}/drop` | `POST /v1/table/{id}/drop` | ## Contract details - Create, describe, and drop use a singular resource path. Their `{id}` path parameter is the URL-encoded Function name, and the duplicate Function identifier is removed from each request body. - Create continues to accept `202 Accepted`. - List changes from a POST with a JSON body to a namespace-scoped GET. Its `{id}` path parameter is the namespace identifier rather than a Function name. - Functions do not support nested namespaces yet, so the client lists against the root namespace identifier (`$` with the default delimiter). A non-root namespace is rejected. - The optional list filter is named `name`. `limit`, `page_token`, and `include_definition` remain available as query parameters. - The paginated list response shape is unchanged. --- .../tests/test_first_class_function_slice2.py | 101 ++++++++++-------- rust/lancedb/src/remote/db.rs | 80 ++++++++------ 2 files changed, 101 insertions(+), 80 deletions(-) diff --git a/python/python/tests/test_first_class_function_slice2.py b/python/python/tests/test_first_class_function_slice2.py index 4816019d6..900f69f8d 100644 --- a/python/python/tests/test_first_class_function_slice2.py +++ b/python/python/tests/test_first_class_function_slice2.py @@ -15,6 +15,7 @@ from pathlib import Path import subprocess import sys import threading +import urllib.parse from typing import Optional import pyarrow as pa @@ -1213,14 +1214,22 @@ def _mock_remote_function_catalog(): def log_message(self, *args): pass + def _write_response(self, status, response): + encoded = json.dumps(response).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + def do_POST(self): length = int(self.headers.get("Content-Length", "0")) body = json.loads(self.rfile.read(length) or b"{}") state["requests"].append((self.path, body)) status = 200 - if self.path == "/v1/functions/create": + if self.path == "/v1/function/normalize_score/create": state["version"] = { - "name": body["name"], + "name": "normalize_score", "version": "fv_exact", "artifact": { key: body["artifact"][key] @@ -1242,43 +1251,43 @@ def _mock_remote_function_catalog(): "job_state": "DONE", "result": state["version"], } - elif self.path == "/v1/functions/describe": - assert body == { - "name": "normalize_score", - "version": "fv_exact", - } + elif self.path == "/v1/function/normalize_score/describe": + assert body == {"version": "fv_exact"} response = state["version"] - elif self.path == "/v1/functions/list": - assert body["include_definition"] is True - if "page_token" not in body: - response = { - "functions": [ - { - "name": "normalize_score", - "version": "fv_exact", - "definition": state["version"], - } - ], - "page_token": "next", - } - else: - assert body["page_token"] == "next" - response = {"functions": []} - elif self.path == "/v1/functions/drop": - assert body == { - "name": "normalize_score", - "version": "fv_exact", - } + elif self.path == "/v1/function/normalize_score/drop": + assert body == {"version": "fv_exact"} response = {"dropped": True} else: status = 404 response = {"error": "not found"} - encoded = json.dumps(response).encode() - self.send_response(status) - self.send_header("Content-Type", "application/json") - self.send_header("Content-Length", str(len(encoded))) - self.end_headers() - self.wfile.write(encoded) + self._write_response(status, response) + + def do_GET(self): + url = urllib.parse.urlsplit(self.path) + query = { + key: values[-1] + for key, values in urllib.parse.parse_qs(url.query).items() + } + state["requests"].append((url.path, query)) + if url.path != "/v1/namespace/$/function/list": + self._write_response(404, {"error": "not found"}) + return + assert query["include_definition"] == "true" + if "page_token" not in query: + response = { + "functions": [ + { + "name": "normalize_score", + "version": "fv_exact", + "definition": state["version"], + } + ], + "page_token": "next", + } + else: + assert query["page_token"] == "next" + response = {"functions": []} + self._write_response(200, response) with http.server.HTTPServer(("localhost", 0), Handler) as server: thread = threading.Thread(target=server.serve_forever) @@ -1307,9 +1316,11 @@ def test_remote_registration_job_and_exact_version_reopen_round_trip(): assert reopened.name == "normalize_score" assert reopened.version == "fv_exact" create_request = state["requests"][0][1] - assert create_request == json.loads( + expected_request = json.loads( normalize_score.registration_request.to_canonical_json() ) + expected_request.pop("name") + assert create_request == expected_request def test_blocking_remote_registration_returns_function_version(): @@ -1325,7 +1336,7 @@ def test_blocking_remote_registration_returns_function_version(): assert created.name == "normalize_score" assert created.version == "fv_exact" assert [path for path, _ in state["requests"]] == [ - "/v1/functions/create", + "/v1/function/normalize_score/create", "/v1/jobs/describe", ] @@ -1344,10 +1355,10 @@ def test_remote_list_functions_paginates_and_returns_typed_versions(): assert functions == [created] assert state["requests"] == [ - ("/v1/functions/list", {"include_definition": True}), + ("/v1/namespace/$/function/list", {"include_definition": "true"}), ( - "/v1/functions/list", - {"include_definition": True, "page_token": "next"}, + "/v1/namespace/$/function/list", + {"include_definition": "true", "page_token": "next"}, ), ] @@ -1368,8 +1379,8 @@ async def test_async_remote_list_functions_returns_typed_versions(): assert functions == [created] assert [path for path, _ in state["requests"]] == [ - "/v1/functions/list", - "/v1/functions/list", + "/v1/namespace/$/function/list", + "/v1/namespace/$/function/list", ] @@ -1385,8 +1396,8 @@ def test_remote_drop_function_sends_exact_version(): assert state["requests"] == [ ( - "/v1/functions/drop", - {"name": "normalize_score", "version": "fv_exact"}, + "/v1/function/normalize_score/drop", + {"version": "fv_exact"}, ) ] @@ -1404,7 +1415,7 @@ async def test_async_remote_drop_function_sends_exact_version(): assert state["requests"] == [ ( - "/v1/functions/drop", - {"name": "normalize_score", "version": "fv_exact"}, + "/v1/function/normalize_score/drop", + {"version": "fv_exact"}, ) ] diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 32ace368e..917bf909b 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -591,7 +591,15 @@ impl Database for RemoteDatabase { &self, request: FunctionRegistrationRequest, ) -> Result> { - let req = self.client.post("/v1/functions/create").json(&request); + let function_id = urlencoding::encode(&request.name); + let req = self + .client + .post(&format!("/v1/function/{function_id}/create")) + .json(&serde_json::json!({ + "artifact": request.artifact, + "signature": request.signature, + "runtime": request.runtime, + })); let (request_id, response) = self.client.send(req).await?; let response = self.client.check_response(&request_id, response).await?; let status = response.status(); @@ -608,11 +616,11 @@ impl Database for RemoteDatabase { } async fn get_function(&self, name: &str, version: &str) -> Result { + let function_id = urlencoding::encode(name); let req = self .client - .post("/v1/functions/describe") + .post(&format!("/v1/function/{function_id}/describe")) .json(&serde_json::json!({ - "name": name, "version": version, })); let (request_id, response) = self.client.send(req).await?; @@ -621,15 +629,19 @@ impl Database for RemoteDatabase { } async fn list_functions(&self) -> Result> { + let namespace_id = build_namespace_identifier(&[], &self.client.id_delimiter); + let path = format!("/v1/namespace/{namespace_id}/function/list"); let mut functions = Vec::new(); let mut page_token: Option = None; let mut seen_page_tokens = HashSet::new(); loop { - let mut body = serde_json::json!({ "include_definition": true }); + let mut req = self + .client + .get(&path) + .query(&[("include_definition", true)]); if let Some(token) = &page_token { - body["page_token"] = serde_json::Value::String(token.clone()); + req = req.query(&[("page_token", token)]); } - let req = self.client.post("/v1/functions/list").json(&body); let (request_id, response) = self.client.send(req).await?; let response = self.client.check_response(&request_id, response).await?; let status = response.status(); @@ -658,11 +670,11 @@ impl Database for RemoteDatabase { } async fn drop_function(&self, name: &str, version: &str) -> Result { + let function_id = urlencoding::encode(name); let req = self .client - .post("/v1/functions/drop") + .post(&format!("/v1/function/{function_id}/drop")) .json(&serde_json::json!({ - "name": name, "version": version, })); let (request_id, response) = self.client.send(req).await?; @@ -2788,9 +2800,10 @@ mod tests { ); const FUNCTION_JOB: &str = include_str!("../../tests/fixtures/first_class_functions/v1/remote_function_job.json"); - let expected: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); + let mut expected: serde_json::Value = serde_json::from_str(REQUEST).unwrap(); + expected.as_object_mut().unwrap().remove("name"); let conn = Connection::new_with_handler(move |request| match request.url().path() { - "/v1/functions/create" => { + "/v1/function/normalize_score/create" => { assert_eq!(request.method(), &reqwest::Method::POST); let body: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); @@ -2821,13 +2834,10 @@ mod tests { ); let conn = Connection::new_with_handler(|request| { assert_eq!(request.method(), &reqwest::Method::POST); - assert_eq!(request.url().path(), "/v1/functions/describe"); + assert_eq!(request.url().path(), "/v1/function/embed/describe"); let body: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); - assert_eq!( - body, - serde_json::json!({"name": "embed", "version": "fv_01K3EXACT"}) - ); + assert_eq!(body, serde_json::json!({"version": "fv_01K3EXACT"})); http::Response::builder().status(200).body(VERSION).unwrap() }); let version = conn.get_function("embed", "fv_01K3EXACT").await.unwrap(); @@ -2843,21 +2853,20 @@ mod tests { let version: serde_json::Value = serde_json::from_str(VERSION).unwrap(); let page = Arc::new(AtomicUsize::new(0)); let conn = Connection::new_with_handler(move |request| { - assert_eq!(request.method(), &reqwest::Method::POST); - assert_eq!(request.url().path(), "/v1/functions/list"); - let body: serde_json::Value = - serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); - assert_eq!(body["include_definition"], true); + assert_eq!(request.method(), &reqwest::Method::GET); + assert_eq!(request.url().path(), "/v1/namespace/$/function/list"); + let query = request.url().query_pairs().collect::>(); + assert_eq!(query.get("include_definition").unwrap(), "true"); match page.fetch_add(1, Ordering::SeqCst) { 0 => { - assert!(body.get("page_token").is_none()); + assert!(!query.contains_key("page_token")); http::Response::builder() .status(200) .body(r#"{"functions": [], "page_token": "next"}"#.to_string()) .unwrap() } _ => { - assert_eq!(body["page_token"], "next"); + assert_eq!(query.get("page_token").unwrap(), "next"); http::Response::builder() .status(200) .body( @@ -2886,9 +2895,11 @@ mod tests { let seen = requests.clone(); let conn = Connection::new_with_handler(move |request| { seen.fetch_add(1, Ordering::SeqCst); - let body: serde_json::Value = - serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); - assert!(body.get("page_token").is_none()); + assert_eq!(request.method(), &reqwest::Method::GET); + assert_eq!(request.url().path(), "/v1/namespace/$/function/list"); + let query = request.url().query_pairs().collect::>(); + assert_eq!(query.get("include_definition").unwrap(), "true"); + assert!(!query.contains_key("page_token")); http::Response::builder() .status(200) .body(r#"{"functions": [], "page_token": ""}"#) @@ -2905,19 +2916,21 @@ mod tests { let page = Arc::new(AtomicUsize::new(0)); let requests = page.clone(); let conn = Connection::new_with_handler(move |request| { - let body: serde_json::Value = - serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(request.method(), &reqwest::Method::GET); + assert_eq!(request.url().path(), "/v1/namespace/$/function/list"); + let query = request.url().query_pairs().collect::>(); + assert_eq!(query.get("include_definition").unwrap(), "true"); let next_page_token = match page.fetch_add(1, Ordering::SeqCst) { 0 => { - assert!(body.get("page_token").is_none()); + assert!(!query.contains_key("page_token")); "one" } 1 => { - assert_eq!(body["page_token"], "one"); + assert_eq!(query.get("page_token").unwrap(), "one"); "two" } 2 => { - assert_eq!(body["page_token"], "two"); + assert_eq!(query.get("page_token").unwrap(), "two"); "one" } page => panic!("unexpected page: {page}"), @@ -2952,13 +2965,10 @@ mod tests { async fn test_drop_function_sends_exact_version_and_decodes_replay() { let conn = Connection::new_with_handler(|request| { assert_eq!(request.method(), &reqwest::Method::POST); - assert_eq!(request.url().path(), "/v1/functions/drop"); + assert_eq!(request.url().path(), "/v1/function/embed/drop"); let body: serde_json::Value = serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); - assert_eq!( - body, - serde_json::json!({"name": "embed", "version": "fv_01K3EXACT"}) - ); + assert_eq!(body, serde_json::json!({"version": "fv_01K3EXACT"})); http::Response::builder() .status(200) .body(r#"{"dropped":false}"#) From ec410e015aef4787e3bb6282e298ce70874bc474 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Mon, 14 Sep 2026 04:45:01 +0000 Subject: [PATCH 198/206] =?UTF-8?q?Bump=20version:=200.39.0-beta.6=20?= =?UTF-8?q?=E2=86=92=200.39.0-beta.7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index de5f91973..a2c5fdd61 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.39.0-beta.6" +current_version = "0.39.0-beta.7" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 7176d8c76..be5040d37 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5452,7 +5452,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.39.0-beta.6" +version = "0.39.0-beta.7" dependencies = [ "ahash", "anyhow", @@ -5543,7 +5543,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.39.0-beta.6" +version = "0.39.0-beta.7" dependencies = [ "arrow-array", "arrow-buffer", @@ -5568,7 +5568,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.39.0-beta.6" +version = "0.39.0-beta.7" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 17d14df15..59c995344 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.39.0-beta.6 + 0.39.0-beta.7 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index c5c928219..afe9b8c5c 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.6 + 0.39.0-beta.7 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index a2456103d..e66e1bbd4 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.6 + 0.39.0-beta.7 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index c4ef09cda..340d8e500 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.39.0-beta.6" +version = "0.39.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 7ebfcaacb..e1ea88e62 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.39.0-beta.6", + "version": "0.39.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 1e2ad10b3..7bbbd3221 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.39.0-beta.6", + "version": "0.39.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 d4843f743..58c488e47 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.39.0-beta.6", + "version": "0.39.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 d4107659a..ca364168e 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.39.0-beta.6", + "version": "0.39.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 d14af6c09..c088a4d7d 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.39.0-beta.6", + "version": "0.39.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 823db7c7c..af28f68d3 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.39.0-beta.6", + "version": "0.39.0-beta.7", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index c2f0b0a80..ff612c4df 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.39.0-beta.6", + "version": "0.39.0-beta.7", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index dae336765..e9621ba60 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.39.0-beta.6", + "version": "0.39.0-beta.7", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index e0c72df48..ff7a98234 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.39.0-beta.6" +version = "0.39.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 c8f17d50c..404753d7a 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.39.0-beta.6" +version = "0.39.0-beta.7" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 255da8a8546cac3fe30e15939ff2ef516e4f640c Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Mon, 14 Sep 2026 15:09:29 +0800 Subject: [PATCH 199/206] fix(python): resolve native job types in API docs (#4170) Native job metadata types report `builtins` as their module, so Griffe cannot resolve the public `lancedb.job` re-exports and the Python API reference build fails. Set the PyO3 module metadata for `JobInfo`, `JobDescription`, and `JobFailureInfo`, and cover import resolution in the existing package metadata tests. Reproduced the failure and validated the fix with the docs CI toolchain (`griffe==0.49.0`, `mkdocstrings==0.25.2`, and `mkdocstrings-python==1.10.9`). After rebuilding the native extension, the full `PYTHONPATH=. mkdocs build` succeeds and all three classes and their public members appear in the generated reference. --- python/python/tests/test_package_metadata.py | 9 +++++++++ python/src/job.rs | 6 +++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/python/python/tests/test_package_metadata.py b/python/python/tests/test_package_metadata.py index 5792f457b..27def814f 100644 --- a/python/python/tests/test_package_metadata.py +++ b/python/python/tests/test_package_metadata.py @@ -9,6 +9,15 @@ from pathlib import Path import pytest +@pytest.mark.parametrize("name", ["JobInfo", "JobDescription", "JobFailureInfo"]) +def test_job_metadata_types_have_resolvable_modules(name): + """Documentation tools resolve re-exports through each type's module.""" + public_type = getattr(importlib.import_module("lancedb.job"), name) + defining_module = importlib.import_module(public_type.__module__) + + assert getattr(defining_module, public_type.__name__, None) is public_type + + def test_pyo3_abi_matches_minimum_supported_python(): project_dir = Path(__file__).parents[2] pyproject = (project_dir / "pyproject.toml").read_text() diff --git a/python/src/job.rs b/python/src/job.rs index 4922c701a..e22b2f897 100644 --- a/python/src/job.rs +++ b/python/src/job.rs @@ -151,7 +151,7 @@ impl Job { } /// A row from `Connection.list_jobs`: one server-side job. -#[pyclass(get_all, skip_from_py_object)] +#[pyclass(module = "lancedb._lancedb", get_all, skip_from_py_object)] #[derive(Clone)] pub struct JobInfo { job_id: String, @@ -184,7 +184,7 @@ impl From for JobInfo { } /// The server's account of why a job failed. -#[pyclass(get_all, skip_from_py_object)] +#[pyclass(module = "lancedb._lancedb", get_all, skip_from_py_object)] #[derive(Clone)] pub struct JobFailureInfo { phase: Option, @@ -203,7 +203,7 @@ impl JobFailureInfo { } /// The server-side record behind a `Job` handle. -#[pyclass(get_all, skip_from_py_object)] +#[pyclass(module = "lancedb._lancedb", get_all, skip_from_py_object)] #[derive(Clone)] pub struct JobDescription { job_id: String, From 6bb64c3edb50f372088d8ed34af9509daf807d0d Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Mon, 14 Sep 2026 20:50:54 +0800 Subject: [PATCH 200/206] fix: reject repeated job pagination tokens (#4139) Fixes #4138 `RemoteDatabase::list_jobs` followed every returned pagination token without remembering previously seen values. A server-side token cycle therefore caused repeated requests and duplicate accumulation until the 100-page safeguard returned partial results as a success. This change tracks non-empty job-list page tokens and returns an HTTP-context error as soon as a token repeats, matching the existing `list_functions` behavior. A mock-handler regression test verifies a repeated `loop` token is rejected after two requests. Validation: - `cargo test --quiet --features remote -p lancedb test_list_jobs` - `cargo fmt --all` - `cargo check --quiet --features remote --tests --examples` Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- rust/lancedb/src/remote/db.rs | 46 ++++++++++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index 917bf909b..1d6f9abe8 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -700,6 +700,7 @@ impl Database for RemoteDatabase { async fn list_jobs(&self) -> Result> { let mut out = Vec::new(); let mut page_token: Option = None; + let mut seen_page_tokens = HashSet::new(); for page in 0..MAX_LIST_JOBS_PAGES { let mut body = serde_json::json!({}); if let Some(token) = &page_token { @@ -708,7 +709,8 @@ impl Database for RemoteDatabase { let req = self.client.post("/v1/jobs/list").json(&body); let (request_id, rsp) = self.client.send(req).await?; let rsp = self.client.check_response(&request_id, rsp).await?; - let body: RemoteListJobsResponse = rsp.json().await.err_to_http(request_id)?; + let status = rsp.status(); + let body: RemoteListJobsResponse = rsp.json().await.err_to_http(request_id.clone())?; out.extend(body.jobs.into_iter().map(|row| JobInfo { job_id: row.job_id, table: row.table, @@ -716,10 +718,17 @@ impl Database for RemoteDatabase { state: job_state_to_client(&row.state), created_at_millis: row.created_at_millis, })); - page_token = body.page_token; - if page_token.is_none() { + let Some(next_page_token) = body.page_token.filter(|token| !token.is_empty()) else { break; + }; + if !seen_page_tokens.insert(next_page_token.clone()) { + return Err(Error::Http { + source: "Job listing response repeated a page_token".into(), + request_id, + status_code: Some(status), + }); } + page_token = Some(next_page_token); if page + 1 == MAX_LIST_JOBS_PAGES { log::warn!( "list_jobs truncated after {} pages ({} jobs)", @@ -2634,6 +2643,37 @@ mod tests { assert_eq!(jobs[2].state, "failed"); } + #[tokio::test] + async fn test_list_jobs_rejects_a_page_token_cycle() { + let requests = Arc::new(AtomicUsize::new(0)); + let seen = requests.clone(); + let conn = Connection::new_with_handler(move |request| { + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + match seen.fetch_add(1, Ordering::SeqCst) { + 0 => assert!(body.get("page_token").is_none()), + _ => assert_eq!(body["page_token"], "loop"), + } + http::Response::builder() + .status(200) + .body(r#"{"jobs": [], "page_token": "loop"}"#) + .unwrap() + }); + + let error = conn.list_jobs().await.unwrap_err(); + assert!( + matches!( + &error, + Error::Http { + status_code: Some(http::StatusCode::OK), + .. + } + ), + "got {error:?}" + ); + assert_eq!(requests.load(Ordering::SeqCst), 2); + } + #[tokio::test] async fn test_open_job() { let conn = Connection::new_with_handler(|request| { From 0113cee48976c5c4632ff251ff42a46f913ba4e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=BF=97=E8=B0=A6?= <89645338+simpleqt@users.noreply.github.com> Date: Mon, 14 Sep 2026 22:40:50 +0800 Subject: [PATCH 201/206] docs(embeddings): correct the documented max_retries default (#4145) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `lancedb/embeddings/utils.py` documents `max_retries` with "(default is 10)" — the signature default is `7`. Docs-only; conventional title per the contribution guide. Co-authored-by: Xuanwo --- python/python/lancedb/embeddings/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python/lancedb/embeddings/utils.py b/python/python/lancedb/embeddings/utils.py index 189bbe53c..98806fa52 100644 --- a/python/python/lancedb/embeddings/utils.py +++ b/python/python/lancedb/embeddings/utils.py @@ -249,7 +249,7 @@ def retry_with_exponential_backoff( initial_delay (float): Initial delay in seconds (default is 1). exponential_base (float): The base for exponential backoff (default is 2). jitter (bool): Whether to add jitter to the delay (default is True). - max_retries (int): Maximum number of retries (default is 10). + max_retries (int): Maximum number of retries (default is 7). Returns: function: The decorated function. From 0665575a76454f6e23c28d5a599310e544081e08 Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Mon, 14 Sep 2026 09:39:55 -0700 Subject: [PATCH 202/206] feat: recompute computed column rows whose inputs changed (#4161) refresh_column fills nulls, so once a row has a value nothing revisits it: an update to one of its inputs, or a definition change, leaves the computed value stale for good. This stamps the column's field metadata with the definition it was computed under and a per-fragment signature of the input storage it was read from (input data files and overlays; not the deletion file, since a delete changes no surviving value). A refresh recomputes every live row of a fragment whose stamp disagrees with the manifest, then records what it computed from in a second commit after the fill. A compacted fragment inherits freshness through the Rewrite lineage when every fragment it was built from was signed, or was appended since the stamp, never had an input moved, and left its rows of the product unfilled (a raw append may supply a value; the product's data is the evidence, and the null fill covers those rows); otherwise it recomputes. A column declared before the stamps existed keeps the null-fill contract on its first refresh, which enrolls it as it stood. The map is one entry per fragment per column, so it is kept out of the manifest: each stamp writes an immutable sidecar under `_computed/`, named by its content digest, and the field metadata holds the digest. Pruning old versions also drops the sidecars no remaining version references, keeping any younger than seven days as lance keeps unverified files, since a sidecar is put before the commit that references it. The stamp commit is metadata-only, so a materialized view's drift check treats it like the fill. The core lives in `table::freshness` so a remote refresh can share the contract. --- Cargo.lock | 1 + docs/src/js/classes/Table.md | 16 +- nodejs/lancedb/table.ts | 16 +- python/python/lancedb/table.py | 33 +- python/python/tests/test_table.py | 7 +- rust/lancedb/Cargo.toml | 3 +- rust/lancedb/src/materialized_view/refresh.rs | 64 +- rust/lancedb/src/table.rs | 15 +- rust/lancedb/src/table/add_columns.rs | 9 +- rust/lancedb/src/table/computed_columns.rs | 25 +- rust/lancedb/src/table/freshness.rs | 1536 +++++++++++++++++ rust/lancedb/src/table/optimize.rs | 12 +- rust/lancedb/src/table/refresh.rs | 424 ++++- 13 files changed, 2052 insertions(+), 109 deletions(-) create mode 100644 rust/lancedb/src/table/freshness.rs diff --git a/Cargo.lock b/Cargo.lock index be5040d37..efa59c4e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5529,6 +5529,7 @@ dependencies = [ "serde_json", "serde_with", "serial_test", + "sha2 0.10.9", "snafu 0.8.9", "tempfile", "test-log", diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index ef6e9535a..dfa0a9819 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -74,10 +74,10 @@ now: the column is committed with no values, and rows get them from [Table#refreshColumn](Table.md#refreshcolumn). Declaring one therefore costs the same on a large table as on an empty one. -A refresh does not revisit rows it has already filled, so mutating an -input leaves the value computed at fill time; recomputing means dropping -the column and declaring it again. While a declaration reads a column, -that column cannot be renamed, retyped or dropped. +A refresh also recomputes the rows whose inputs changed since they were +computed, so a mutated input is reflected by the next refresh. While a +declaration reads a column, that column cannot be renamed, retyped or +dropped. On LanceDB Cloud and Enterprise the expression is planned by the server, and the refresh runs as a server job -- see @@ -916,10 +916,10 @@ abstract refreshColumn(column): Promise Fill the rows of a computed column that hold no value yet. -Rows appended since the last refresh are filled by the next one; rows -already filled are left as they are, so the call is idempotent and does -not observe a mutated input. Local tables only: a remote refresh runs -as a server job, through [Table#refreshColumnAsync](Table.md#refreshcolumnasync). +Rows appended since the last refresh are filled by the next one, and +rows whose inputs changed since they were computed are recomputed; +everything else is left as it is. Local tables only: a remote refresh +runs as a server job, through [Table#refreshColumnAsync](Table.md#refreshcolumnasync). #### Parameters diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index eac9f490d..8d8b0d675 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -572,10 +572,10 @@ export abstract class Table { * {@link Table#refreshColumn}. Declaring one therefore costs the same on a * large table as on an empty one. * - * A refresh does not revisit rows it has already filled, so mutating an - * input leaves the value computed at fill time; recomputing means dropping - * the column and declaring it again. While a declaration reads a column, - * that column cannot be renamed, retyped or dropped. + * A refresh also recomputes the rows whose inputs changed since they were + * computed, so a mutated input is reflected by the next refresh. While a + * declaration reads a column, that column cannot be renamed, retyped or + * dropped. * * On LanceDB Cloud and Enterprise the expression is planned by the * server, and the refresh runs as a server job -- see @@ -606,10 +606,10 @@ export abstract class Table { /** * Fill the rows of a computed column that hold no value yet. * - * Rows appended since the last refresh are filled by the next one; rows - * already filled are left as they are, so the call is idempotent and does - * not observe a mutated input. Local tables only: a remote refresh runs - * as a server job, through {@link Table#refreshColumnAsync}. + * Rows appended since the last refresh are filled by the next one, and + * rows whose inputs changed since they were computed are recomputed; + * everything else is left as it is. Local tables only: a remote refresh + * runs as a server job, through {@link Table#refreshColumnAsync}. * @param {string} column The name of the computed column to fill. * @returns {Promise} A promise that resolves to the * number of rows filled and the new version number of the table. diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 72362acad..84ae4e836 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2188,10 +2188,10 @@ class Table(ABC): Declaring one therefore costs the same on a large table as on an empty one. - A refresh does not revisit rows it has already filled, so mutating - an input leaves the value computed at fill time; recomputing means - dropping the column and declaring it again. While a declaration - reads a column, that column cannot be renamed, retyped or dropped. + A refresh also recomputes the rows whose inputs changed since they + were computed, so a mutated input is reflected by the next refresh. + While a declaration reads a column, that column cannot be renamed, + retyped or dropped. On LanceDB Cloud and Enterprise the expression is planned by the server, and the refresh runs as a server job -- see @@ -2211,7 +2211,7 @@ class Table(ABC): >>> table.add_columns(computed={"doubled": "x * 2"}) AddColumnsResult(version=2) >>> table.refresh_column("doubled") - RefreshColumnResult(rows_filled=2, version=3) + RefreshColumnResult(rows_filled=2, version=4) >>> table.to_arrow().sort_by("x").to_pandas() x doubled 0 1 2 @@ -2225,8 +2225,8 @@ class Table(ABC): Declared with ``add_columns(computed=...)``, a column starts empty and gets its values here. Rows appended since the last refresh are filled - by the next one; rows already filled are left as they are, so the call - is idempotent and does not observe a mutated input. + by the next one, and rows whose inputs changed since they were computed + are recomputed; everything else is left as it is. Local tables only: a remote refresh runs as a server job, through [`refresh_column_async`][lancedb.table.Table.refresh_column_async]. @@ -4318,13 +4318,14 @@ class LanceTable(Table): return LOOP.run(self._table.add_columns(transforms, computed=computed)) def refresh_column(self, column: str) -> "RefreshColumnResult": - """Fill a computed column's unfilled rows. See + """Fill a computed column's unfilled rows and recompute those whose + inputs changed. See [`AsyncTable.refresh_column`][lancedb.AsyncTable.refresh_column].""" return LOOP.run(self._table.refresh_column(column)) def refresh_column_async(self, column: str) -> Job[RefreshColumnJobResult]: - """Fill a computed column's unfilled rows, returning a handle to the - refresh job. See + """Fill a computed column's unfilled rows and recompute those whose + inputs changed, returning a handle to the refresh job. See [`Table.refresh_column_async`][lancedb.table.Table.refresh_column_async]. """ return Job(LOOP.run(self._table.refresh_column_async(column))) @@ -6312,10 +6313,10 @@ class AsyncTable: them from [`refresh_column`][lancedb.table.AsyncTable.refresh_column]. - A refresh does not revisit rows it has already filled, so mutating - an input leaves the value computed at fill time. While a - declaration reads a column, that column cannot be renamed, retyped - or dropped. + A refresh also recomputes the rows whose inputs changed since they + were computed, so a mutated input is reflected by the next refresh. + While a declaration reads a column, that column cannot be renamed, + retyped or dropped. On LanceDB Cloud and Enterprise the expression is planned by the server. Cannot be combined with ``transforms``. @@ -6377,8 +6378,8 @@ class AsyncTable: Declared with ``add_columns(computed=...)``, a column starts empty and gets its values here. Rows appended since the last refresh are filled - by the next one; rows already filled are left as they are, so the call - is idempotent and does not observe a mutated input. + by the next one, and rows whose inputs changed since they were computed + are recomputed; everything else is left as it is. Local tables only: a remote refresh runs as a server job, through [`refresh_column_async`][lancedb.table.Table.refresh_column_async]. diff --git a/python/python/tests/test_table.py b/python/python/tests/test_table.py index b85486412..ac7dc660d 100644 --- a/python/python/tests/test_table.py +++ b/python/python/tests/test_table.py @@ -4183,13 +4183,14 @@ def test_refresh_column_async_returns_job(tmp_path): assert result.rows_failed == 0 assert result.rows_remaining == 0 assert result.source_version == 2 - assert result.published_version == 3 + # The fill lands at 3; the stamp recording its inputs is published at 4. + assert result.published_version == 4 assert job.status() == "finished" assert sorted(table.to_arrow()["doubled"].to_pylist()) == [2, 4] no_op = table.refresh_column_async("doubled").wait() assert no_op.rows_assigned == 0 - assert no_op.source_version == 3 + assert no_op.source_version == 4 assert no_op.published_version is None # Bad input raises at the call, not through the job. @@ -4208,6 +4209,6 @@ async def test_refresh_column_async_job_async_table(tmp_path): assert isinstance(result, lancedb.RefreshColumnResult) assert result.rows_assigned == 1 assert result.source_version == 2 - assert result.published_version == 3 + assert result.published_version == 4 assert await job.status() == "finished" assert (await table.to_arrow())["tripled"].to_pylist() == [9] diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 404753d7a..998d041e2 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -95,13 +95,14 @@ candle-transformers = { version = "0.9.1", optional = true } candle-nn = { version = "0.9.1", optional = true } tokenizers = { version = "0.19.1", optional = true } semver = { workspace = true } +roaring = "0.11.4" +sha2 = "0.10" [dev-dependencies] anyhow = "1" lance-testing = { workspace = true } tempfile = { workspace = true } random_word = { version = "0.4.3", features = ["en"] } -roaring = "0.11.4" tokio = { workspace = true, features = ["io-util", "macros", "net", "test-util"] } uuid = { workspace = true } walkdir = "2" diff --git a/rust/lancedb/src/materialized_view/refresh.rs b/rust/lancedb/src/materialized_view/refresh.rs index 23bb51566..433b185f7 100644 --- a/rust/lancedb/src/materialized_view/refresh.rs +++ b/rust/lancedb/src/materialized_view/refresh.rs @@ -1124,8 +1124,9 @@ struct RowScope { /// Whether every commit on the view after `recorded` is a fill of its /// computed columns: a column rewrite or data replacement touching only -/// those fields and neither adding nor removing rows. A version whose -/// transaction cannot be read is not proven, so it counts as drift. +/// those fields and neither adding nor removing rows, or the freshness +/// stamp a fill leaves on them. A version whose transaction cannot be read +/// is not proven, so it counts as drift. async fn only_computed_rewrites_since(view_ds: &Dataset, recorded: u64) -> Result { // A fill may write any field under a computed column, so the whole // subtree counts, not only the root. @@ -1176,6 +1177,19 @@ async fn only_computed_rewrites_since(view_ds: &Dataset, recorded: u64) -> Resul .all(|field| computed_fields.contains(&(*field as u32))) }) } + // The stamp `refresh_column` writes after its fill (see + // `table::freshness`): field metadata on computed columns, no data. + Operation::UpdateConfig { + config_updates: None, + table_metadata_updates: None, + schema_metadata_updates: None, + field_metadata_updates, + } => { + !field_metadata_updates.is_empty() + && field_metadata_updates + .keys() + .all(|field| computed_fields.contains(&(*field as u32))) + } _ => false, }; if !fill { @@ -3359,6 +3373,46 @@ mod tests { ); } + /// Field metadata on `field` only, the commit shape of the freshness + /// stamp `refresh_column` leaves after its fill. + async fn commit_field_metadata(view: &MaterializedView, field: &str, key: &str) { + let native = view.table().as_native().unwrap(); + native.dataset.reload().await.unwrap(); + let mut dataset = native.dataset.get().await.unwrap().as_ref().clone(); + dataset + .update_field_metadata() + .update(field, [(key.to_string(), "{}".to_string())]) + .unwrap() + .await + .unwrap(); + } + + /// The stamp is metadata on the computed column and rewrites nothing + /// refresh certifies, so it is not drift; the same commit shape on a + /// projected column is, like any other write to it. + #[tokio::test] + async fn test_a_freshness_stamp_is_not_drift() { + let conn = connect("memory://").execute().await.unwrap(); + let view = refreshed_computed_view(&conn).await; + + commit_field_metadata( + &view, + "emb", + crate::table::computed_columns::SOURCE_SIGNATURE_META_KEY, + ) + .await; + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::NoOp + ); + + commit_field_metadata(&view, "id", "probe").await; + assert_eq!( + view.refresh().execute().await.unwrap().mode, + RefreshMode::Rebuild + ); + } + /// The fill job's commit rewrites only computed columns. It is the one /// commit on a view that is not drift: the next refresh carries on from /// its watermark instead of rebuilding, which would null what the fill @@ -3524,9 +3578,9 @@ mod tests { } /// A SQL declaration is filled by `refresh_column` on the view, which - /// commits a data replacement; the next refresh continues from its - /// watermark and keeps what the fill wrote, and only rows the view added - /// since come back unfilled. + /// commits a data replacement and then its freshness stamp; the next + /// refresh continues from its watermark and keeps what the fill wrote, + /// and only rows the view added since come back unfilled. #[tokio::test] async fn test_a_sql_fill_is_not_drift() { use crate::materialized_view::tests::{people, sql_field}; diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 7f139c4cb..508c2ca49 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -75,6 +75,7 @@ mod create_index; pub mod datafusion; pub(crate) mod dataset; pub mod delete; +pub mod freshness; pub mod lsm_stats; pub mod merge; pub mod optimize; @@ -778,7 +779,8 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "Function columns are supported only on LanceDB Cloud and Enterprise".into(), }) } - /// Fill a computed column's unfilled rows. + /// Fill a computed column's unfilled rows and recompute those whose + /// inputs changed. /// /// The default returns `NotSupported`; Lance-backed tables override it. async fn refresh_column(&self, _column: &str) -> Result { @@ -786,8 +788,8 @@ pub trait BaseTable: std::fmt::Display + std::fmt::Debug + Send + Sync { message: "computed columns are supported only on local tables".into(), }) } - /// Fill a computed column's unfilled rows, returning a [`Job`] tracking - /// the operation. + /// Fill a computed column's unfilled rows and recompute those whose + /// inputs changed, returning a [`Job`] tracking the operation. async fn refresh_column_async( &self, _column: &str, @@ -1749,9 +1751,10 @@ impl Table { /// Declared with /// [`AddColumnsBuilder::computed`](add_columns::AddColumnsBuilder::computed), /// a column starts empty and gets its values here. Fragments appended - /// since the last refresh are filled by the next one; fragments already - /// filled are left as they are, so the call is idempotent and does not - /// observe a mutated input. + /// since the last refresh are filled by the next one, and fragments whose + /// inputs changed since they were computed are recomputed (see + /// [`freshness`](crate::table::freshness)); everything else is left as + /// it is. /// /// Local tables only: a remote refresh runs as a server job, through /// [`Table::refresh_column_async`]. diff --git a/rust/lancedb/src/table/add_columns.rs b/rust/lancedb/src/table/add_columns.rs index 1ac0c6b4f..635a99bea 100644 --- a/rust/lancedb/src/table/add_columns.rs +++ b/rust/lancedb/src/table/add_columns.rs @@ -60,10 +60,11 @@ impl AddColumnsBuilder { /// every fragment that has none -- including fragments appended since the /// last refresh. /// - /// Refresh does not revisit a fragment it has filled, so mutating an input - /// leaves the value computed at fill time; recomputing means dropping the - /// column and declaring it again. An input cannot be renamed, retyped or - /// dropped while a declaration reads it, since the expression names it. + /// A refresh also recomputes the rows of a fragment whose inputs changed + /// since it was computed (see [`freshness`](super::freshness)), so a + /// mutated input is reflected by the next refresh. An input cannot be + /// renamed, retyped or dropped while a declaration reads it, since the + /// expression names it. /// /// On LanceDB Cloud and Enterprise the expression is planned by the /// server, and the refresh runs as a server job -- see diff --git a/rust/lancedb/src/table/computed_columns.rs b/rust/lancedb/src/table/computed_columns.rs index f1ec75213..a70ac31ae 100644 --- a/rust/lancedb/src/table/computed_columns.rs +++ b/rust/lancedb/src/table/computed_columns.rs @@ -71,6 +71,22 @@ 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; +/// 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 +/// metadata edits, this is rewritten by every refresh. Seeded empty at +/// declaration, so a column is tracked from birth; a column without it was +/// declared before signatures existed. +pub const SOURCE_SIGNATURE_META_KEY: &str = "computed_refresh.source_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"; + +/// Field metadata key holding the table version the signature map describes: +/// where a refresh starts following compactions to carry freshness forward. +pub const RECORDED_AT_VERSION_META_KEY: &str = "computed_refresh.recorded_at_version"; + /// Value of [`KIND_META_KEY`] for a column defined by a SQL expression. pub const SQL_KIND: &str = "sql"; @@ -139,6 +155,7 @@ fn computed_column_metadata(expression: &str, inputs: &[String]) -> HashMap Result< } /// Reject a write that supplies values for a computed column directly: -/// only refresh materializes one, and refresh never revisits a filled row. +/// only refresh materializes one, and only refresh decides what it +/// recomputes. pub(crate) fn ensure_not_written<'a>( schema: &ArrowSchema, written: impl IntoIterator, @@ -1470,7 +1489,9 @@ fn ensure_no_foreign_declaration(field: &ArrowField) -> Result<()> { /// kind, the expression, the inputs -- would bypass that validation or move /// a binding out from under a refresh. Drop the column and declare it again. pub(crate) fn is_declaration_key(key: &str) -> bool { - key == COMPUTED_COLUMN_META_KEY || key.starts_with("computed_column.") + key == COMPUTED_COLUMN_META_KEY + || key.starts_with("computed_column.") + || key.starts_with("computed_refresh.") } /// Reject retyping a computed column itself. diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs new file mode 100644 index 000000000..e7a1841e6 --- /dev/null +++ b/rust/lancedb/src/table/freshness.rs @@ -0,0 +1,1536 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Source-change detection for computed columns. +//! +//! A refresh fills nulls, so once a value is durable nothing recomputes it and +//! a later write to one of its inputs leaves it stale forever. Two stamps in +//! the column's field metadata close that: the definition it was computed +//! under, and a per-fragment signature of the input storage it was computed +//! from. A refresh compares both with the manifest and recomputes what +//! disagrees. Signatures are read from manifests, never from data. +//! +//! The map is not stored in the manifest: it is one entry per fragment per +//! column, which would dominate the manifest of a large table with many +//! computed columns. It lives in an immutable sidecar object under +//! `_computed/`, named by its content digest, and the field metadata holds +//! only the reference. Sidecars no retained version references are removed +//! by [`prune_sidecars`]. + +use std::collections::{BTreeMap, HashSet}; +use std::ops::Range; + +use arrow_array::{Array, UInt64Array}; +use futures::TryStreamExt; +use lance::Dataset; +use lance::dataset::transaction::Operation; +use lance_core::ROW_ADDR; +use lance_core::datatypes::{Field as LanceField, Schema as LanceSchema}; +use lance_io::object_store::ObjectStore; +use lance_table::format::{DataFile, Fragment}; +use object_store::path::Path; +use roaring::RoaringBitmap; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; + +use crate::table::computed_columns::{ + DEFINITION_VERSION_META_KEY, RECORDED_AT_VERSION_META_KEY, SOURCE_SIGNATURE_META_KEY, +}; +use crate::{Error, Result}; + +/// A map recorded further back than this carries nothing through the +/// compactions since: the fragments they produced are recomputed instead. +const MAX_CARRY_FORWARD_VERSIONS: u64 = 1024; + +/// `{fragment id -> input signature}`. +pub type SignatureMap = BTreeMap; + +/// Every field an input covers, keyed by column path: the field's own id +/// first, then its ancestors', because a packed file records the physical +/// column under an ancestor's id. +pub type InputFields = BTreeMap, Vec>; + +fn invalid(message: String) -> Error { + Error::InvalidInput { message } +} + +/// FNV-1a over the text, as hex. Stable across processes and versions, which +/// a signature compared against a stored one has to be. +fn short_hash(value: &str) -> String { + let digest = Sha256::digest(value.as_bytes()); + digest.iter().take(8).map(|b| format!("{b:02x}")).collect() +} + +/// Digest of the definition a column is computed under. +pub fn definition_version(definition: &str) -> String { + short_hash(definition) +} + +/// The fields the named input column paths cover, children included. Paths, +/// not ids, pair one schema with another: a rewrite renumbers fields. The key +/// is the path's components, so a field named `a.b` and a nested `a` -> `b` +/// are different columns. +pub fn fields_for_paths(schema: &LanceSchema, paths: &[String]) -> Result { + fn collect(field: &LanceField, path: Vec, ancestors: &[i32], out: &mut InputFields) { + let mut ids = vec![field.id]; + ids.extend_from_slice(ancestors); + for child in &field.children { + let mut child_path = path.clone(); + child_path.push(child.name.clone()); + collect(child, child_path, &ids, out); + } + out.insert(path, ids); + } + let mut out = InputFields::new(); + for field_path in paths { + let parts = lance_core::datatypes::parse_field_path(field_path)?; + let (root, rest) = parts + .split_first() + .ok_or_else(|| invalid("computed column input path is empty".to_string()))?; + let mut field = schema + .field(root) + .ok_or_else(|| invalid(format!("unknown computed column input '{field_path}'")))?; + let mut ancestors = Vec::new(); + for name in rest { + ancestors.insert(0, field.id); + field = field + .children + .iter() + .find(|child| child.name == *name) + .ok_or_else(|| invalid(format!("unknown computed column input '{field_path}'")))?; + } + collect(field, parts, &ancestors, &mut out); + } + Ok(out) +} + +/// Where one field's values come from in a fragment: the files and physical +/// columns storing it, and the overlays overriding cells of it, newest last +/// with the physical column and the cells each covers. A file stores the +/// field under its own id or, packed, under an ancestor's; `ids` is the +/// field's id followed by its ancestors'. Object identity is by base and +/// path; field ids are left out, since a sibling column's rewrite re-labels +/// them without touching a value. +#[derive(Debug, PartialEq, Eq)] +pub struct InputBasis { + files: Vec<(Option, String, i32)>, + overlays: Vec<(Option, String, i32, RoaringBitmap, u64)>, +} + +pub fn input_basis(metadata: &Fragment, ids: &[i32]) -> Result { + let column_of = |file: &DataFile| { + file.fields + .iter() + .position(|id| ids.contains(id)) + .map(|pos| (pos, file.column_indices.get(pos).copied().unwrap_or(-1))) + }; + let files = metadata + .files + .iter() + .filter_map(|file| { + column_of(file).map(|(_, column)| (file.base_id, file.path.clone(), column)) + }) + .collect(); + let mut overlays = Vec::new(); + for overlay in &metadata.overlays { + let Some((pos, column)) = column_of(&overlay.data_file) else { + continue; + }; + overlays.push(( + overlay.data_file.base_id, + overlay.data_file.path.clone(), + column, + overlay.coverage_for_field(pos)?.as_ref().clone(), + overlay.committed_version, + )); + } + Ok(InputBasis { files, overlays }) +} + +/// Identity of the input data a fragment currently holds: per input field, +/// its storage basis. Deletions are left out: a deleted row is never +/// computed, and the rows that stay keep their values. Physical identity, +/// not content, so a rewrite that preserves values still reads as a change; +/// compaction is followed separately. +pub fn fragment_input_signature(fragment: &Fragment, inputs: &InputFields) -> Result { + let mut parts = Vec::new(); + for (path, ids) in inputs { + let basis = input_basis(fragment, ids)?; + parts.push(format!("{}={basis:?}", path.join("."))); + } + Ok(short_hash(&parts.join("|"))) +} + +fn signature_of( + dataset: &Dataset, + fragment_id: u32, + inputs: &InputFields, +) -> Result> { + dataset + .get_fragment(fragment_id as usize) + .map(|fragment| fragment_input_signature(fragment.metadata(), inputs)) + .transpose() +} + +/// Signatures for `fragment_ids` as `dataset` currently holds them. +pub fn signatures_for( + dataset: &Dataset, + fragment_ids: &[u32], + inputs: &InputFields, +) -> Result { + let wanted: HashSet = fragment_ids.iter().copied().collect(); + dataset + .get_fragments() + .iter() + .filter(|fragment| wanted.contains(&(fragment.id() as u32))) + .map(|fragment| { + Ok(( + fragment.id() as u32, + fragment_input_signature(fragment.metadata(), inputs)?, + )) + }) + .collect() +} + +fn field_meta(dataset: &Dataset, column: &str, key: &str) -> Option { + dataset + .schema() + .field(column) + .and_then(|field| field.metadata.get(key)) + .cloned() +} + +/// What the column's stored map says. The three cases are distinct and the +/// callers act differently on each: see [`staleness_against`]. +#[derive(Debug)] +pub enum StoredSignatures { + /// No map has ever been written for this column. + Absent, + Present(SignatureMap), + /// A map exists but cannot be read. + Unreadable, +} + +/// Directory of signature sidecars, under the dataset root. +const SIDECAR_DIR: &str = "_computed"; +/// Metadata value prefix referencing a sidecar by its content digest. +const SIDECAR_REF: &str = "sidecar:"; +const SIDECAR_MAGIC: &[u8; 4] = b"CSIG"; +const SIDECAR_FORMAT: u8 = 1; +/// 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. +const SIDECAR_UNVERIFIED_THRESHOLD_DAYS: i64 = 7; + +/// The dataset's root directory: the parent of its versions directory. +/// Rebuilt from the raw parts, since re-encoding them would escape a +/// Windows drive letter's colon. +fn dataset_root(dataset: &Dataset) -> Path { + let versions = dataset.versions_dir(); + let count = versions.parts().count(); + Path::from_iter(versions.parts().take(count.saturating_sub(1))) +} + +fn sidecar_path(dataset: &Dataset, digest: &str) -> Path { + dataset_root(dataset) + .join(SIDECAR_DIR) + .join(format!("{digest}.sig")) +} + +/// `CSIG`, format byte, entry count, then one fragment id and 8-byte +/// signature per entry, all little-endian; 12 bytes per fragment. +fn encode_sidecar(map: &SignatureMap) -> Result> { + let mut bytes = Vec::with_capacity(9 + map.len() * 12); + bytes.extend_from_slice(SIDECAR_MAGIC); + bytes.push(SIDECAR_FORMAT); + bytes.extend_from_slice( + &u32::try_from(map.len()) + .map_err(|_| invalid("too many fragments for a signature sidecar".to_string()))? + .to_le_bytes(), + ); + for (fragment_id, signature) in map { + let hash = u64::from_str_radix(signature, 16).map_err(|_| { + invalid(format!( + "signature '{signature}' is not a 64-bit hex digest" + )) + })?; + bytes.extend_from_slice(&fragment_id.to_le_bytes()); + bytes.extend_from_slice(&hash.to_le_bytes()); + } + Ok(bytes) +} + +fn decode_sidecar(bytes: &[u8]) -> Result { + let malformed = || invalid("signature sidecar is malformed".to_string()); + if bytes.len() < 9 || &bytes[..4] != SIDECAR_MAGIC || bytes[4] != SIDECAR_FORMAT { + return Err(malformed()); + } + let count = u32::from_le_bytes(bytes[5..9].try_into().map_err(|_| malformed())?) as usize; + let body = &bytes[9..]; + if body.len() != count * 12 { + return Err(malformed()); + } + Ok(body + .chunks_exact(12) + .map(|entry| { + let fragment_id = u32::from_le_bytes(entry[..4].try_into().unwrap()); + let hash = u64::from_le_bytes(entry[4..].try_into().unwrap()); + (fragment_id, format!("{hash:016x}")) + }) + .collect()) +} + +fn digest_of(bytes: &[u8]) -> String { + Sha256::digest(bytes) + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +async fn store(dataset: &Dataset) -> Result> { + Ok(dataset.object_store(None).await?) +} + +/// Write `map` as a sidecar and return the metadata value referencing it. +/// The object is named by its digest, so two columns with the same map +/// share one object and a rewrite is idempotent. +async fn write_sidecar(dataset: &Dataset, map: &SignatureMap) -> Result { + let bytes = encode_sidecar(map)?; + let digest = digest_of(&bytes); + store(dataset) + .await? + .put(&sidecar_path(dataset, &digest), &bytes) + .await?; + Ok(format!("{SIDECAR_REF}{digest}")) +} + +async fn read_sidecar(dataset: &Dataset, digest: &str) -> Result { + let bytes = store(dataset) + .await? + .read_one_all(&sidecar_path(dataset, digest)) + .await?; + if digest_of(&bytes) != digest { + return Err(invalid(format!( + "signature sidecar {digest} does not match its digest" + ))); + } + decode_sidecar(&bytes) +} + +/// Remove signature sidecars that no version still present references, +/// the counterpart of lance's version cleanup for `_computed/`, with the +/// same protection for objects still being published: a sidecar is put +/// before the commit that references it, so one younger than +/// [`SIDECAR_UNVERIFIED_THRESHOLD_DAYS`] is left alone unless +/// `delete_unverified`. Returns how many were removed. +pub async fn prune_sidecars(dataset: &Dataset, delete_unverified: bool) -> Result { + let store = store(dataset).await?; + let dir = dataset_root(dataset).join(SIDECAR_DIR); + let unmodified_since = (!delete_unverified) + .then(|| chrono::Utc::now() - chrono::Duration::days(SIDECAR_UNVERIFIED_THRESHOLD_DAYS)); + let present: Vec = match store + .read_dir_all(&dir, unmodified_since) + .try_collect::>() + .await + { + Ok(objects) => objects + .into_iter() + .filter_map(|object| { + object + .location + .filename() + .and_then(|name| name.strip_suffix(".sig")) + .map(str::to_string) + }) + .collect(), + Err(_) => return Ok(0), + }; + if present.is_empty() { + return Ok(0); + } + let mut referenced = HashSet::new(); + 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)) + { + referenced.insert(digest.to_string()); + } + } + } + let mut removed = 0; + for digest in present { + if !referenced.contains(&digest) { + store.delete(&sidecar_path(dataset, &digest)).await?; + removed += 1; + } + } + Ok(removed) +} + +/// Read the column's stored map. An unreadable map is a state, not an error: +/// failing here would make the column permanently unrefreshable, and the +/// unknown recomputes like every other unknown here. +pub async fn stored_signatures(dataset: &Dataset, column: &str) -> StoredSignatures { + let Some(encoded) = field_meta(dataset, column, SOURCE_SIGNATURE_META_KEY) else { + return StoredSignatures::Absent; + }; + // Inline JSON is the declaration's empty seed and the pre-sidecar form. + let read = match encoded.strip_prefix(SIDECAR_REF) { + Some(digest) => read_sidecar(dataset, digest).await, + None => serde_json::from_str(&encoded).map_err(|e| invalid(e.to_string())), + }; + match read { + Ok(map) => StoredSignatures::Present(map), + Err(error) => { + log::warn!( + "computed column '{column}' source signature map is unreadable ({error}); every fragment will be recomputed" + ); + StoredSignatures::Unreadable + } + } +} + +/// What a refresh must recompute beyond the null rows. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct StalenessPlan { + /// The definition changed, so every row is stale whatever its signature. + pub recompute_all: bool, + /// Fragments whose inputs moved since they were computed, or that were + /// never recorded. + pub dirty: HashSet, + /// Fragments a compaction produced from fresh ones, at their current + /// signature: not dirty, and for the seal to record. + pub inherited: SignatureMap, +} + +impl StalenessPlan { + pub fn is_dirty(&self, fragment_id: u32) -> bool { + self.recompute_all || self.dirty.contains(&fragment_id) + } +} + +/// 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. +enum Step { + Append, + Compaction(Vec<(Vec, Vec)>), +} + +/// The step committed at `version`. A compaction's transaction records a +/// new fragment before its id is assigned, so produced ids come from the +/// version's manifest, matched by data file. Every other operation is +/// skipped: a row-moving update rewrites the rows it moves, so it does not +/// carry their inputs unchanged. +async fn step_at(dataset: &Dataset, version: u64) -> Result> { + let Some(transaction) = dataset.read_transaction_by_version(version).await? else { + return Ok(None); + }; + let groups = match &transaction.operation { + Operation::Append { .. } => return Ok(Some(Step::Append)), + Operation::Rewrite { groups, .. } => groups, + _ => return Ok(None), + }; + let at = dataset.checkout_version(version).await?; + let by_file: BTreeMap<(Option, String), u32> = at + .get_fragments() + .iter() + .flat_map(|fragment| { + let id = fragment.id() as u32; + fragment + .metadata() + .files + .iter() + .map(move |file| ((file.base_id, file.path.clone()), id)) + }) + .collect(); + let compactions = groups + .iter() + .map(|group| { + let consumed = group.old_fragments.iter().map(|f| f.id as u32).collect(); + let produced = group + .new_fragments + .iter() + .map(|fragment| { + fragment + .files + .iter() + .find_map(|file| by_file.get(&(file.base_id, file.path.clone())).copied()) + .ok_or_else(|| { + invalid(format!( + "a fragment added in version {version} is not in that version's manifest" + )) + }) + }) + .collect::>>()?; + Ok((consumed, produced)) + }) + .collect::>>()?; + Ok(Some(Step::Compaction(compactions))) +} + +/// Manifests since the stamp, each loaded once. +struct Manifests<'a> { + dataset: &'a Dataset, + loaded: BTreeMap, +} + +impl Manifests<'_> { + async fn at(&mut self, version: u64) -> Result<&Dataset> { + if !self.loaded.contains_key(&version) { + let manifest = self.dataset.checkout_version(version).await?; + self.loaded.insert(version, manifest); + } + Ok(&self.loaded[&version]) + } +} + +/// Whether a fragment consumed by a compaction was created by an append +/// since the stamp and its inputs never moved after: `current` is its +/// signature just before the compaction. LanceDB's writes leave a computed +/// column null (see `ensure_not_written`), but a raw append need not, so +/// the rows it contributed to the product are checked to hold no value +/// (`holds_values_in`) before the product inherits freshness. +async fn appended_untouched( + manifests: &mut Manifests<'_>, + appends: &[u64], + fragment_id: u32, + current: Option<&String>, + inputs: &InputFields, +) -> Result { + let Some(current) = current else { + return Ok(false); + }; + for &version in appends.iter().rev() { + let Some(born) = signature_of(manifests.at(version).await?, fragment_id, inputs)? else { + continue; + }; + if signature_of(manifests.at(version - 1).await?, fragment_id, inputs)?.is_some() { + // Live before this append: born earlier. + continue; + } + return Ok(&born == current); + } + Ok(false) +} + +/// Whether `column` holds a value in any of `ranges`, offsets within the +/// fragment. Compaction scans its sources in order, so the rows an appended +/// source contributed sit at known offsets of the product. +async fn holds_values_in( + dataset: &Dataset, + fragment_id: u32, + column: &str, + ranges: &[Range], +) -> Result { + let Some(fragment) = dataset.get_fragment(fragment_id as usize) else { + return Ok(false); + }; + let mut scanner = dataset.scan(); + scanner + .with_fragments(vec![fragment.metadata().clone()]) + .with_row_address() + .project(&[column])? + .filter(&format!( + "{} IS NOT NULL", + super::refresh::quote_identifier(column) + ))?; + let mut batches = scanner.try_into_stream().await?; + while let Some(batch) = batches.try_next().await? { + let addresses = batch + .column_by_name(ROW_ADDR) + .and_then(|column| column.as_any().downcast_ref::()) + .ok_or_else(|| invalid("row addresses missing from a freshness scan".to_string()))?; + if addresses + .iter() + .flatten() + .map(|address| address & 0xFFFF_FFFF) + .any(|offset| ranges.iter().any(|range| range.contains(&offset))) + { + return Ok(true); + } + } + Ok(false) +} + +/// Compaction copies inputs verbatim, so a fragment it produced from +/// recorded fragments whose inputs had not moved is as fresh as they were, +/// and a fragment an append created since the stamp, untouched after and +/// unfilled in the product, changes nothing (`appended_untouched`). +/// Followed from the version the map was recorded at through every +/// compaction since, so a chain of them carries too. Returns the produced +/// fragments' signatures at production; the caller compares each with the +/// current manifest, which catches anything written to them afterwards. +async fn carried_forward( + dataset: &Dataset, + column: &str, + stored: &SignatureMap, + inputs: &InputFields, +) -> Result { + let Some(recorded_at) = field_meta(dataset, column, RECORDED_AT_VERSION_META_KEY) + .and_then(|version| version.parse::().ok()) + else { + return Ok(SignatureMap::new()); + }; + let to = dataset.version().version; + if to <= recorded_at || to - recorded_at > MAX_CARRY_FORWARD_VERSIONS { + return Ok(SignatureMap::new()); + } + let mut fresh = stored.clone(); + let mut inherited = SignatureMap::new(); + let mut appends = Vec::new(); + let mut manifests = Manifests { + dataset, + loaded: BTreeMap::new(), + }; + for version in (recorded_at + 1)..=to { + let compactions = match step_at(dataset, version).await? { + None => continue, + Some(Step::Append) => { + appends.push(version); + continue; + } + Some(Step::Compaction(compactions)) => compactions, + }; + for (consumed, produced) in compactions { + // Each source's signature and live rows just before the + // compaction; live rows place its contribution in the product. + let mut sources = Vec::with_capacity(consumed.len()); + { + let before = manifests.at(version - 1).await?; + for id in &consumed { + let live = match before.get_fragment(*id as usize) { + Some(fragment) => fragment.count_rows(None).await? as u64, + None => 0, + }; + sources.push((*id, signature_of(before, *id, inputs)?, live)); + } + } + let mut all_fresh = !consumed.is_empty(); + let mut appended = Vec::new(); + let mut offset = 0u64; + for (id, current, live) in sources { + let recorded = matches!( + (fresh.get(&id), current.as_ref()), + (Some(recorded), Some(current)) if recorded == current + ); + if !recorded { + if appended_untouched(&mut manifests, &appends, id, current.as_ref(), inputs) + .await? + { + appended.push(offset..offset + live); + } else { + all_fresh = false; + break; + } + } + offset += live; + } + if !all_fresh { + continue; + } + let after = manifests.at(version).await?; + // The products in order, each with its share of the appended + // rows; a value there was supplied by the append, not computed. + let mut base = 0u64; + let mut unfilled = true; + for id in &produced { + let rows = match after.get_fragment(*id as usize) { + Some(fragment) => fragment.count_rows(None).await? as u64, + None => 0, + }; + let local: Vec> = appended + .iter() + .filter(|range| range.start < base + rows && range.end > base) + .map(|range| range.start.max(base) - base..range.end.min(base + rows) - base) + .collect(); + if !local.is_empty() && holds_values_in(after, *id, column, &local).await? { + unfilled = false; + break; + } + base += rows; + } + if !unfilled { + continue; + } + for id in &produced { + if let Some(signature) = signature_of(after, *id, inputs)? { + fresh.insert(*id, signature.clone()); + inherited.insert(*id, signature); + } + } + } + } + Ok(inherited) +} + +/// Decide what is stale, from the manifest alone. +/// +/// A column with no map at all was declared before signatures existed. It +/// keeps its null-fill behavior until its first stamp enrolls it (see +/// [`record_freshness`]). A map that omits a fragment is authoritative: the +/// fragment's input state is unknown, and unknown recomputes -- unless a +/// compaction of fresh fragments produced it, which is followed. Lineage is +/// read only when a live fragment has no entry, so a plan over a recorded +/// table costs no transaction reads. +pub async fn staleness_against( + dataset: &Dataset, + column: &str, + definition_version: &str, + inputs: &InputFields, +) -> Result { + let stored = match stored_signatures(dataset, column).await { + StoredSignatures::Absent => return Ok(StalenessPlan::default()), + StoredSignatures::Unreadable => { + return Ok(StalenessPlan { + recompute_all: true, + ..Default::default() + }); + } + StoredSignatures::Present(stored) => stored, + }; + let stored_version = field_meta(dataset, column, DEFINITION_VERSION_META_KEY); + if stored_version.is_some_and(|version| version != definition_version) { + return Ok(StalenessPlan { + recompute_all: true, + ..Default::default() + }); + } + let unrecorded = dataset + .get_fragments() + .iter() + .any(|fragment| !stored.contains_key(&(fragment.id() as u32))); + let mut inherited = if unrecorded { + carried_forward(dataset, column, &stored, inputs).await? + } else { + SignatureMap::new() + }; + let mut dirty = HashSet::new(); + let mut live = HashSet::new(); + for fragment in dataset.get_fragments() { + let id = fragment.id() as u32; + live.insert(id); + let current = fragment_input_signature(fragment.metadata(), inputs)?; + if stored.get(&id).or_else(|| inherited.get(&id)) != Some(¤t) { + dirty.insert(id); + } + } + inherited.retain(|id, _| live.contains(id) && !dirty.contains(id)); + Ok(StalenessPlan { + recompute_all: false, + dirty, + inherited, + }) +} + +/// 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)] +pub struct FreshnessRecord { + pub version: Option, + pub recorded: usize, + pub moved: usize, +} + +/// Record, on `column`, the input state its fragments were computed from. +/// +/// `computed` is what this refresh computed in full, signed at the version +/// the values were read from. A column with no map yet was declared before +/// signatures existed; `pinned`, the version the refresh planned against, +/// is then the baseline: every fragment live there is trusted as it stood, +/// the null-fill contract its values were written under. Otherwise the +/// staleness decided on `pinned` supplies what compactions since the last +/// stamp carried forward. Either +/// way an entry is recorded only if `latest` still holds that input state -- +/// an input write can rebase under the output commit -- so a fragment whose +/// inputs moved stays unrecorded and is recomputed by the next refresh. +/// +/// Written once per refresh, after its data commit. +pub async fn record_freshness( + latest: &mut Dataset, + pinned: Option<(&Dataset, &StalenessPlan)>, + column: &str, + definition_version: &str, + inputs: &InputFields, + computed: SignatureMap, +) -> Result { + let absent = matches!( + stored_signatures(latest, column).await, + StoredSignatures::Absent + ); + let mut entries = SignatureMap::new(); + if let Some((pinned, staleness)) = pinned { + if absent { + let all: Vec = pinned + .get_fragments() + .iter() + .map(|fragment| fragment.id() as u32) + .collect(); + entries = signatures_for(pinned, &all, inputs)?; + } else { + entries = staleness.inherited.clone(); + } + } + entries.extend(computed); + if entries.is_empty() && !absent { + return Ok(FreshnessRecord::default()); + } + let fragments: Vec = entries.keys().copied().collect(); + let current = signatures_for(latest, &fragments, inputs)?; + let verified: SignatureMap = entries + .into_iter() + .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?; + Ok(FreshnessRecord { + version: Some(version), + recorded, + moved: fragments.len() - recorded, + }) +} + +/// 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. +pub async fn write_signatures( + dataset: &mut Dataset, + column: &str, + definition_version: &str, + entries: SignatureMap, +) -> Result { + let live: HashSet = dataset + .get_fragments() + .iter() + .map(|fragment| fragment.id() as u32) + .collect(); + // An unreadable map is discarded rather than merged: nothing in it can be + // trusted, and its fragments recompute until a later refresh records them. + let mut merged = match stored_signatures(dataset, column).await { + StoredSignatures::Present(stored) => stored, + StoredSignatures::Absent | StoredSignatures::Unreadable => SignatureMap::new(), + }; + merged.extend(entries); + merged.retain(|fragment_id, _| live.contains(fragment_id)); + // The sidecar is durable before the commit references it; a failure in + // between leaves an unreferenced object for `prune_sidecars`. + let encoded = if merged.is_empty() { + "{}".to_string() + } else { + write_sidecar(dataset, &merged).await? + }; + let describes = dataset.version().version; + dataset + .update_field_metadata() + .update( + column, + [ + (SOURCE_SIGNATURE_META_KEY.to_string(), encoded), + ( + DEFINITION_VERSION_META_KEY.to_string(), + definition_version.to_string(), + ), + ( + RECORDED_AT_VERSION_META_KEY.to_string(), + describes.to_string(), + ), + ], + )? + .await?; + Ok(dataset.version().version) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + use arrow_array::RecordBatchIterator; + use arrow_schema::{DataType, Field as ArrowField, Schema as ArrowSchema}; + use lance::dataset::{ + MergeInsertBuilder, MergeInsertWriteMode, NewColumnTransform, WhenMatched, WhenNotMatched, + WriteMode, WriteParams, + }; + use lance_file::version::ConcreteFileVersion; + use lance_table::format::overlay::{DataOverlayFile, OverlayCoverage}; + + const COLUMN: &str = "doubled"; + const EXPRESSION: &str = "value * 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 { + let batch = arrow_array::record_batch!( + ("id", Int32, (0..100).collect::>()), + ("value", Int32, (0..100).collect::>()) + ) + .unwrap(); + let schema = batch.schema(); + let mut dataset = Dataset::write( + RecordBatchIterator::new(vec![Ok(batch)], schema), + uri, + Some(WriteParams { + mode: WriteMode::Create, + max_rows_per_file: 50, + ..Default::default() + }), + ) + .await + .unwrap(); + let mut metadata = std::collections::HashMap::from([ + ( + crate::table::computed_columns::COMPUTED_COLUMN_META_KEY.to_string(), + "true".to_string(), + ), + ( + crate::table::computed_columns::EXPRESSION_META_KEY.to_string(), + EXPRESSION.to_string(), + ), + ]); + metadata.insert(SOURCE_SIGNATURE_META_KEY.to_string(), "{}".to_string()); + dataset + .add_columns( + NewColumnTransform::AllNulls(Arc::new(ArrowSchema::new(vec![ + ArrowField::new(COLUMN, DataType::Int64, true).with_metadata(metadata), + ]))), + None, + None, + ) + .await + .unwrap(); + dataset + } + + fn inputs(dataset: &Dataset) -> InputFields { + fields_for_paths(dataset.schema(), &["value".to_string()]).unwrap() + } + + async fn plan(dataset: &Dataset) -> StalenessPlan { + staleness_against( + dataset, + COLUMN, + &definition_version(EXPRESSION), + &inputs(dataset), + ) + .await + .unwrap() + } + + async fn stamp_all(dataset: &mut Dataset) { + let ids = inputs(dataset); + let frags: Vec = dataset + .get_fragments() + .iter() + .map(|f| f.id() as u32) + .collect(); + let entries = signatures_for(dataset, &frags, &ids).unwrap(); + write_signatures(dataset, COLUMN, &definition_version(EXPRESSION), entries) + .await + .unwrap(); + } + + /// Strip the refresh's own keys: a column from before signatures existed. + async fn make_legacy(dataset: &mut Dataset) { + let declaration = dataset + .schema() + .field(COLUMN) + .unwrap() + .metadata + .iter() + .filter(|(key, _)| !key.starts_with("computed_refresh.")) + .map(|(key, value)| (key.clone(), value.clone())) + .collect::>(); + dataset + .update_field_metadata() + .replace(COLUMN, declaration) + .unwrap() + .await + .unwrap(); + assert!(matches!( + stored_signatures(dataset, COLUMN).await, + StoredSignatures::Absent + )); + } + + /// Rewrite `value` of the row with `id` in place: a partial merge-insert + /// attaches a new column file to the row's fragment, keeping its id. + async fn rewrite_value(dataset: &mut Dataset, id: i32) { + let batch = + arrow_array::record_batch!(("id", Int32, [id]), ("value", Int32, [1000])).unwrap(); + let schema = batch.schema(); + let mut builder = + MergeInsertBuilder::try_new(Arc::new(dataset.clone()), vec!["id".to_string()]).unwrap(); + builder + .when_matched(WhenMatched::UpdateAll) + .when_not_matched(WhenNotMatched::DoNothing) + .write_mode(MergeInsertWriteMode::RewriteColumns); + let (updated, _) = builder + .try_build() + .unwrap() + .execute_reader(RecordBatchIterator::new([Ok(batch)], schema)) + .await + .unwrap(); + *dataset = (*updated).clone(); + } + + async fn compact(dataset: &mut Dataset) -> u32 { + lance::dataset::optimize::compact_files( + dataset, + lance::dataset::optimize::CompactionOptions { + target_rows_per_fragment: 1000, + ..Default::default() + }, + None, + ) + .await + .unwrap(); + dataset.checkout_latest().await.unwrap(); + dataset.get_fragments()[0].id() as u32 + } + + /// `a.b` under `root` and a nested `a` -> `b` are different columns with + /// two bases; a dotted-string key would fold them into one. + #[test] + fn a_dotted_field_name_is_not_a_nested_path() { + let leaf = |name: &str| ArrowField::new(name, DataType::Int32, true); + let root = ArrowField::new( + "root", + DataType::Struct( + vec![ + ArrowField::new("a", DataType::Struct(vec![leaf("b")].into()), true), + leaf("a.b"), + ] + .into(), + ), + true, + ); + let schema = LanceSchema::try_from(&ArrowSchema::new(vec![root])).unwrap(); + let ids = fields_for_paths(&schema, &["root".to_string()]).unwrap(); + let path = |parts: &[&str]| parts.iter().map(|p| p.to_string()).collect::>(); + let nested = &ids[&path(&["root", "a", "b"])]; + let dotted = &ids[&path(&["root", "a.b"])]; + assert_ne!(nested[0], dotted[0], "{ids:?}"); + assert_eq!(ids.len(), 4, "{ids:?}"); + } + + /// A packed file records the physical column under an ancestor's id, so a + /// nested input's basis is found through its ancestors. + #[test] + fn a_packed_nested_input_has_a_file_basis() { + let word_count = ArrowField::new("word_count", DataType::Int32, true); + let metrics = ArrowField::new("metrics", DataType::Struct(vec![word_count].into()), true); + let analysis = ArrowField::new("analysis", DataType::Struct(vec![metrics].into()), true); + let schema = LanceSchema::try_from(&ArrowSchema::new(vec![analysis])).unwrap(); + let ids = fields_for_paths(&schema, &["analysis.metrics.word_count".to_string()]).unwrap(); + let word_count = &ids[&["analysis", "metrics", "word_count"] + .map(String::from) + .to_vec()]; + let analysis = schema.field("analysis").unwrap().id; + assert_eq!(word_count.last(), Some(&analysis), "{word_count:?}"); + let mut fragment = Fragment::new(0); + fragment.files.push(DataFile::new( + "packed.lance", + vec![analysis], + vec![3], + ConcreteFileVersion::V2_2, + None, + None, + )); + let basis = input_basis(&fragment, word_count).unwrap(); + assert_eq!(basis.files, vec![(None, "packed.lance".to_string(), 3)]); + } + + /// An overlay that stores the input in another physical column of the + /// same object is a different basis. + #[test] + fn an_overlay_column_remap_changes_the_basis() { + let overlay = |column: i32| { + let mut fragment = Fragment::new(0); + fragment.overlays.push(DataOverlayFile { + data_file: DataFile::new( + "overlay.lance", + vec![7], + vec![column], + ConcreteFileVersion::V2_2, + None, + None, + ), + coverage: OverlayCoverage::dense(RoaringBitmap::from_iter([0u32])), + committed_version: 2, + }); + input_basis(&fragment, &[7]).unwrap() + }; + assert_ne!(overlay(0), overlay(1)); + assert_eq!(overlay(0), overlay(0)); + } + + async fn sidecar_names(dataset: &Dataset) -> Vec { + let mut names = store(dataset) + .await + .unwrap() + .read_dir(dataset_root(dataset).join(SIDECAR_DIR)) + .await + .unwrap_or_default(); + names.sort(); + names + } + + fn signature_ref(dataset: &Dataset, column: &str) -> String { + field_meta(dataset, column, SOURCE_SIGNATURE_META_KEY).unwrap() + } + + /// The manifest carries only a digest; the map itself is a sidecar the + /// reader fetches and verifies. The declaration's empty seed stays inline. + #[tokio::test] + async fn a_stamp_is_a_sidecar_the_manifest_only_references() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + assert_eq!(signature_ref(&dataset, COLUMN), "{}"); + stamp_all(&mut dataset).await; + let reference = signature_ref(&dataset, COLUMN); + let digest = reference.strip_prefix(SIDECAR_REF).unwrap(); + assert_eq!(reference.len(), SIDECAR_REF.len() + 64, "{reference}"); + assert_eq!(sidecar_names(&dataset).await, vec![format!("{digest}.sig")]); + let StoredSignatures::Present(stored) = stored_signatures(&dataset, COLUMN).await else { + panic!("sidecar unreadable"); + }; + assert_eq!( + stored, + signatures_for(&dataset, &[0, 1], &inputs(&dataset)).unwrap() + ); + } + + /// Two columns with the same inputs share one sidecar, and a rewrite of + /// the same map is idempotent. + #[tokio::test] + async fn identical_maps_share_one_sidecar() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + stamp_all(&mut dataset).await; + let ids = inputs(&dataset); + let entries = signatures_for(&dataset, &[0, 1], &ids).unwrap(); + write_signatures( + &mut dataset, + "value", + &definition_version(EXPRESSION), + entries, + ) + .await + .unwrap(); + assert_eq!(sidecar_names(&dataset).await.len(), 1); + assert_eq!( + signature_ref(&dataset, COLUMN), + signature_ref(&dataset, "value") + ); + } + + /// A sidecar that is missing or whose bytes do not match the digest is + /// unreadable: everything recomputes and the next stamp replaces it. + #[tokio::test] + async fn a_missing_or_corrupt_sidecar_recomputes_everything() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let digest = signature_ref(&dataset, COLUMN) + .strip_prefix(SIDECAR_REF) + .unwrap() + .to_string(); + let path = sidecar_path(&dataset, &digest); + let object_store = store(&dataset).await.unwrap(); + object_store.put(&path, b"CSIG garbage").await.unwrap(); + assert!(plan(&dataset).await.recompute_all); + object_store.delete(&path).await.unwrap(); + assert!(plan(&dataset).await.recompute_all); + stamp_all(&mut dataset).await; + assert_eq!(plan(&dataset).await, StalenessPlan::default()); + } + + /// A map written inline, the pre-sidecar form, is still read. + #[tokio::test] + async fn an_inline_map_is_still_read() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let ids = inputs(&dataset); + let entries = signatures_for(&dataset, &[0, 1], &ids).unwrap(); + dataset + .update_field_metadata() + .update( + COLUMN, + [ + ( + SOURCE_SIGNATURE_META_KEY.to_string(), + serde_json::to_string(&entries).unwrap(), + ), + ( + DEFINITION_VERSION_META_KEY.to_string(), + definition_version(EXPRESSION), + ), + ], + ) + .unwrap() + .await + .unwrap(); + assert_eq!(plan(&dataset).await, StalenessPlan::default()); + } + + /// Pruning removes only sidecars no version still present references: + /// an older stamp survives while its version does, and goes with it. + #[tokio::test] + async fn pruning_follows_version_retention() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let ids = inputs(&dataset); + let first = signatures_for(&dataset, &[0], &ids).unwrap(); + write_signatures(&mut dataset, COLUMN, &definition_version(EXPRESSION), first) + .await + .unwrap(); + stamp_all(&mut dataset).await; + assert_eq!(sidecar_names(&dataset).await.len(), 2); + // Orphan from a stamp that never committed. + store(&dataset) + .await + .unwrap() + .put(&sidecar_path(&dataset, "orphan"), b"CSIG") + .await + .unwrap(); + assert_eq!(prune_sidecars(&dataset, true).await.unwrap(), 1); + assert_eq!(sidecar_names(&dataset).await.len(), 2); + + dataset + .cleanup_old_versions(chrono::Duration::zero(), Some(true), None) + .await + .unwrap(); + assert_eq!(prune_sidecars(&dataset, true).await.unwrap(), 1); + let remaining = sidecar_names(&dataset).await; + let current = signature_ref(&dataset, COLUMN); + assert_eq!( + remaining, + vec![format!( + "{}.sig", + current.strip_prefix(SIDECAR_REF).unwrap() + )] + ); + } + + /// The gate's reproducer: a sidecar is put before the commit that + /// references it, so a prune that interleaves must leave a recent, + /// as yet unreferenced object alone whatever version retention the + /// caller chose; only an unverified prune takes it. + #[tokio::test] + async fn pruning_does_not_collect_an_in_flight_sidecar() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let ids = inputs(&dataset); + let entries = signatures_for(&dataset, &[0, 1], &ids).unwrap(); + let reference = write_sidecar(&dataset, &entries).await.unwrap(); + + let removed = prune_sidecars(&dataset, false).await.unwrap(); + assert_eq!(removed, 0); + dataset + .update_field_metadata() + .update(COLUMN, [(SOURCE_SIGNATURE_META_KEY.to_string(), reference)]) + .unwrap() + .await + .unwrap(); + assert!(matches!( + stored_signatures(&dataset, COLUMN).await, + StoredSignatures::Present(_) + )); + + let orphan = write_sidecar(&dataset, &SignatureMap::from([(9, "0".repeat(16))])) + .await + .unwrap(); + assert_eq!( + prune_sidecars(&dataset, false).await.unwrap(), + 0, + "a recent orphan waits for its window" + ); + assert_eq!(prune_sidecars(&dataset, true).await.unwrap(), 1); + assert!(!sidecar_names(&dataset).await.contains(&format!( + "{}.sig", + orphan.strip_prefix(SIDECAR_REF).unwrap() + ))); + } + + /// A freshly declared column is tracked from birth: every fragment is + /// unrecorded, so every fragment is stale until a refresh records it. + #[tokio::test] + async fn a_declared_column_is_stale_until_recorded() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + assert_eq!(plan(&dataset).await.dirty, HashSet::from([0, 1])); + stamp_all(&mut dataset).await; + assert_eq!(plan(&dataset).await, StalenessPlan::default()); + } + + /// The signature answers "did my inputs move": a write to any other + /// column, the computed column included, leaves it alone. + #[tokio::test] + async fn an_unrelated_column_rewrite_leaves_the_signature_alone() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let ids = inputs(&dataset); + let before = signatures_for(&dataset, &[0, 1], &ids).unwrap(); + dataset + .add_columns( + NewColumnTransform::SqlExpressions(vec![("extra".into(), "id * 3".into())]), + None, + None, + ) + .await + .unwrap(); + assert_eq!(before, signatures_for(&dataset, &[0, 1], &ids).unwrap()); + } + + /// An in-place write to one fragment's input keeps every fragment id, so + /// only the signature can notice -- and on that fragment alone. + #[tokio::test] + async fn an_in_place_input_change_dirties_only_its_own_fragment() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + rewrite_value(&mut dataset, 60).await; + let stale = plan(&dataset).await; + assert_eq!(stale.dirty, HashSet::from([1]), "{stale:?}"); + } + + /// A deleted row is never computed and the rows that stay keep their + /// values, so a delete dirties nothing. + #[tokio::test] + async fn a_delete_dirties_nothing() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + dataset.delete("id >= 60 AND id < 70").await.unwrap(); + assert_eq!(plan(&dataset).await, StalenessPlan::default()); + } + + /// A definition change makes every row stale whatever the signatures say. + #[tokio::test] + async fn a_definition_change_recomputes_every_row() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let rebound = staleness_against(&dataset, COLUMN, "other", &inputs(&dataset)) + .await + .unwrap(); + assert!(rebound.recompute_all); + } + + /// A column declared before signatures existed carries no map, and keeps + /// null-fill behavior until its first stamp enrolls it -- at the pinned + /// state, not the latest: an input that moved in between is left out. + #[tokio::test] + async fn a_first_stamp_enrolls_an_older_column_as_it_stood() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + make_legacy(&mut dataset).await; + assert_eq!(plan(&dataset).await, StalenessPlan::default()); + let ids = inputs(&dataset); + let pinned = dataset.clone(); + let staleness = plan(&pinned).await; + rewrite_value(&mut dataset, 60).await; + let record = record_freshness( + &mut dataset, + Some((&pinned, &staleness)), + COLUMN, + &definition_version(EXPRESSION), + &ids, + SignatureMap::new(), + ) + .await + .unwrap(); + assert_eq!((record.recorded, record.moved), (1, 1)); + assert_eq!(record.version, Some(dataset.version().version)); + assert_eq!(plan(&dataset).await.dirty, HashSet::from([1])); + } + + /// Append `count` rows after `first_id`, the computed column null as a + /// write must leave it; returns the new fragment's id. + async fn append_rows(dataset: &mut Dataset, first_id: i32, count: i32) -> u32 { + let batch = arrow_array::record_batch!( + ( + "id", + Int32, + (first_id..first_id + count).collect::>() + ), + ( + "value", + Int32, + (first_id..first_id + count).collect::>() + ), + ("doubled", Int64, vec![None::; count as usize]) + ) + .unwrap(); + let schema = batch.schema(); + *dataset = Dataset::write( + RecordBatchIterator::new(vec![Ok(batch)], schema), + dataset.uri(), + Some(WriteParams { + mode: WriteMode::Append, + ..Default::default() + }), + ) + .await + .unwrap(); + dataset.get_fragments().last().unwrap().id() as u32 + } + + /// A fragment an append created since the stamp holds no computed value, + /// so a compaction folding it into recorded fragments produces a fresh + /// fragment: nothing recomputes, and the null fill covers the new rows. + #[tokio::test] + async fn a_compaction_folding_an_untouched_appended_fragment_carries_freshness_forward() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let appended = append_rows(&mut dataset, 100, 10).await; + assert_eq!(plan(&dataset).await.dirty, HashSet::from([appended])); + let compacted = compact(&mut dataset).await; + let stale = plan(&dataset).await; + assert!(stale.dirty.is_empty(), "{stale:?}"); + assert_eq!( + stale.inherited.keys().copied().collect::>(), + vec![compacted] + ); + } + + /// The same fragment with an input rewritten after the append is not + /// neutral: what it holds may have been computed from the older input. + #[tokio::test] + async fn a_compaction_folding_an_appended_fragment_whose_input_moved_recomputes() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + append_rows(&mut dataset, 100, 10).await; + rewrite_value(&mut dataset, 105).await; + let compacted = compact(&mut dataset).await; + let stale = plan(&dataset).await; + assert_eq!(stale.dirty, HashSet::from([compacted]), "{stale:?}"); + assert!(stale.inherited.is_empty()); + } + + /// A raw append can supply a computed value LanceDB's own writes never + /// do. The product holds it where the appended rows landed, so the + /// compaction is not carried: the value is recomputed, not certified. + #[tokio::test] + async fn a_compaction_folding_an_appended_fragment_with_values_recomputes() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let batch = arrow_array::record_batch!( + ("id", Int32, [100, 101]), + ("value", Int32, [100, 101]), + ("doubled", Int64, [None, Some(999_i64)]) + ) + .unwrap(); + let schema = batch.schema(); + dataset = Dataset::write( + RecordBatchIterator::new(vec![Ok(batch)], schema), + dataset.uri(), + Some(WriteParams { + mode: WriteMode::Append, + ..Default::default() + }), + ) + .await + .unwrap(); + let compacted = compact(&mut dataset).await; + let stale = plan(&dataset).await; + assert_eq!(stale.dirty, HashSet::from([compacted]), "{stale:?}"); + assert!(stale.inherited.is_empty()); + } + + /// Compaction copies inputs unchanged: a fragment it produced from + /// recorded, unmoved fragments is fresh, and the seal records it. One + /// produced from a fragment whose inputs had moved is not. + #[tokio::test] + async fn a_compaction_of_fresh_fragments_carries_freshness_forward() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + let compacted = compact(&mut dataset).await; + let stale = plan(&dataset).await; + assert!(stale.dirty.is_empty(), "{stale:?}"); + assert_eq!( + stale.inherited.keys().copied().collect::>(), + vec![compacted] + ); + let ids = inputs(&dataset); + let pinned = dataset.clone(); + let record = record_freshness( + &mut dataset, + Some((&pinned, &stale)), + COLUMN, + &definition_version(EXPRESSION), + &ids, + SignatureMap::new(), + ) + .await + .unwrap(); + assert_eq!(record.recorded, 1); + let StoredSignatures::Present(stored) = stored_signatures(&dataset, COLUMN).await else { + panic!("stamped"); + }; + assert_eq!( + stored.keys().copied().collect::>(), + vec![compacted] + ); + + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + stamp_all(&mut dataset).await; + rewrite_value(&mut dataset, 60).await; + let compacted = compact(&mut dataset).await; + let stale = plan(&dataset).await; + assert_eq!(stale.dirty, HashSet::from([compacted]), "{stale:?}"); + assert!(stale.inherited.is_empty()); + } + + /// A recorded fragment whose signature no longer matches, or a fragment + /// the map omits without a compaction to explain it, is stale. + #[tokio::test] + async fn a_fragment_missing_from_the_stored_map_is_stale() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + let ids = inputs(&dataset); + let partial = signatures_for(&dataset, &[0], &ids).unwrap(); + write_signatures( + &mut dataset, + COLUMN, + &definition_version(EXPRESSION), + partial, + ) + .await + .unwrap(); + assert_eq!(plan(&dataset).await.dirty, HashSet::from([1])); + } + + /// An unreadable map recomputes everything rather than failing the + /// refresh, and the next stamp replaces it. + #[tokio::test] + async fn an_unreadable_stored_map_recomputes_rather_than_failing() { + let dir = tempfile::tempdir().unwrap(); + let mut dataset = table(dir.path().to_str().unwrap()).await; + dataset + .update_field_metadata() + .update( + COLUMN, + [(SOURCE_SIGNATURE_META_KEY.to_string(), "{".to_string())], + ) + .unwrap() + .await + .unwrap(); + assert!(plan(&dataset).await.recompute_all); + stamp_all(&mut dataset).await; + assert_eq!(plan(&dataset).await, StalenessPlan::default()); + } +} diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index 4ad58cffb..6e3fc0048 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -134,9 +134,17 @@ pub(crate) async fn cleanup_old_versions( ) -> Result { table.dataset.ensure_mutable()?; let dataset = table.dataset.get().await?; - Ok(dataset + let stats = dataset .cleanup_old_versions(older_than, delete_unverified, error_if_tagged_old_versions) - .await?) + .await?; + // Computed-column signature sidecars live outside lance's directories; + // drop the ones the surviving versions no longer reference. + let removed = + super::freshness::prune_sidecars(&dataset, delete_unverified.unwrap_or(false)).await?; + if removed > 0 { + log::debug!("removed {removed} unreferenced computed-column signature sidecars"); + } + Ok(stats) } /// Compact files in the dataset. diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 511fce8ff..2ed479256 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -3,9 +3,9 @@ //! Filling computed columns. //! -//! A row without a value gets one; a row that has one keeps it. Refresh is -//! therefore idempotent and does not observe input mutation -- once a row is -//! filled, changing what the expression reads leaves the stored result alone. +//! A row without a value gets one; a row that has one keeps it unless its +//! fragment's inputs moved since it was computed, which `freshness` decides +//! from the manifest and stamps after every fill. //! //! A column's computed inputs are filled first -- the dependency graph is //! walked once, each reachable column filled once in dependency order, each @@ -31,6 +31,7 @@ use std::collections::HashSet; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; use arrow_array::{ Array, ArrayRef, BooleanArray, LargeBinaryArray, RecordBatch, RecordBatchOptions, StructArray, @@ -48,6 +49,7 @@ use lance_core::datatypes::{BlobHandling, Schema as LanceSchema}; use serde::{Deserialize, Serialize}; use super::computed_columns::{BoundExpression, ComputedColumnKind, computed_column_from_field}; +use super::freshness::{self, SignatureMap, StalenessPlan}; use super::{BaseTable, NativeTable}; use crate::job::Job; use crate::{Error, Result}; @@ -110,28 +112,81 @@ async fn execute_refresh_column_with_source( }; let output_is_blob = field.is_blob_v2(); + // Which fragments the null filter cannot speak for: their inputs moved + // since they were computed, or the definition did. Decided once, from + // the manifest the values are read from. + let inputs = freshness::fields_for_paths(dataset.schema(), &bound.inputs)?; + let definition = freshness::definition_version(&expression); + let staleness = freshness::staleness_against(&dataset, column, &definition, &inputs).await?; + let mut rows_filled = 0u64; let mut replacements = Vec::new(); + // Fragments this refresh computed in full, signed at the version read. + let mut computed = SignatureMap::new(); for fragment in dataset.get_fragments() { - let gained = count_fragment_gains(&dataset, &fragment, &bound, column).await?; - if gained == 0 { - continue; + let fragment_id = u32::try_from(fragment.id()).map_err(|_| Error::Runtime { + message: format!("fragment id {} does not fit a signature map", fragment.id()), + })?; + // A recompute rewrites every live row, so it is staged without the + // probe and counted as it fills; a null fill probes first, since a + // fragment with nothing to gain is not worth a write. + let recompute = staleness.is_dirty(fragment_id); + let whole = recompute || { + let (gained, unfilled) = + count_fragment_gains(&dataset, &fragment, &bound, column).await?; + if gained == 0 { + continue; + } + rows_filled += gained; + unfilled == u64::try_from(fragment.count_rows(None).await?).unwrap_or(u64::MAX) + }; + if whole { + computed.insert( + fragment_id, + freshness::fragment_input_signature(fragment.metadata(), &inputs)?, + ); } - rows_filled += gained; - let values = - fill_stream(&dataset, &fragment, bound.clone(), column, output_is_blob).await?; + let gained = Arc::new(AtomicU64::new(0)); + let values = fill_stream( + &dataset, + &fragment, + bound.clone(), + column, + output_is_blob, + recompute, + gained.clone(), + ) + .await?; replacements.push(fragment.write_columns(values, &column_schema).await?); + if recompute { + rows_filled += gained.load(Ordering::Relaxed); + } } let source_version = dataset.version().version; if replacements.is_empty() { + // Nothing to fill; the stamp may still have something to record -- a + // column not yet enrolled, or fragments a compaction carried. + let mut latest = (*dataset).clone(); + let stamped = record( + &mut latest, + (&dataset, &staleness), + column, + &definition, + &inputs, + computed, + ) + .await; + if stamped.is_some() { + table.dataset.update(latest); + } return Ok(RefreshExecution { result: RefreshColumnResult { rows_filled: 0, - version: source_version, + version: stamped.unwrap_or(source_version), }, source_version, - published_version: None, + published_version: stamped, }); } @@ -149,7 +204,17 @@ async fn execute_refresh_column_with_source( ) .await?; - let version = new_dataset.version().version; + let mut new_dataset = new_dataset; + let version = record( + &mut new_dataset, + (&dataset, &staleness), + column, + &definition, + &inputs, + computed, + ) + .await + .unwrap_or(new_dataset.version().version); table.dataset.update(new_dataset); Ok(RefreshExecution { result: RefreshColumnResult { @@ -161,6 +226,31 @@ async fn execute_refresh_column_with_source( }) } +/// Stamp the input state the refresh computed from (see +/// [`freshness::record_freshness`]); the version the stamp landed at, which +/// is the last one the refresh wrote. Never fails the refresh: the values +/// are committed, and a missing stamp only costs a recompute next time. +async fn record( + latest: &mut Dataset, + pinned: (&Dataset, &StalenessPlan), + column: &str, + definition: &str, + inputs: &freshness::InputFields, + computed: SignatureMap, +) -> Option { + match freshness::record_freshness(latest, Some(pinned), column, definition, inputs, computed) + .await + { + Ok(record) => record.version, + Err(error) => { + log::warn!( + "could not record the input state computed column '{column}' was refreshed from ({error}); its fragments will recompute on the next refresh" + ); + None + } + } +} + /// Refuse while a computed input still has rows a refresh of it would fill: /// read now, its placeholder null would be evaluated as a value and kept. async fn ensure_inputs_filled( @@ -188,7 +278,9 @@ async fn ensure_inputs_filled( let input_bound = super::computed_columns::bind(schema.clone(), input, expression)?; let mut unfilled = 0u64; for fragment in dataset.get_fragments() { - unfilled += count_fragment_gains(dataset, &fragment, &input_bound, input).await?; + unfilled += count_fragment_gains(dataset, &fragment, &input_bound, input) + .await? + .0; } if unfilled > 0 { return Err(Error::InvalidInput { @@ -436,32 +528,35 @@ fn blob_array_from_binary( /// Scans only the unfilled live rows -- deleted rows never reach the /// expression here, the filter having already excluded them -- and counts the /// non-null results. Exact, so it is both the staging decision and the -/// fragment's contribution to `rows_filled`. +/// fragment's contribution to `rows_filled`. Returns the gains and the rows +/// scanned. async fn count_fragment_gains( dataset: &Dataset, fragment: &FileFragment, bound: &BoundExpression, column: &str, -) -> Result { +) -> Result<(u64, u64)> { let mut scanner = dataset.scan(); scanner .with_fragments(vec![fragment.metadata().clone()]) .with_row_id() - .filter(&format!("{} IS NULL", quote_identifier(column)))? - .project(&bound.roots)?; + .project(&bound.roots)? + .filter(&format!("{} IS NULL", quote_identifier(column)))?; configure_blob_inputs(&mut scanner, dataset.schema(), bound, None)?; let mut gained = 0u64; + let mut considered = 0u64; let mut batches = scanner.try_into_stream().await?; while let Some(batch) = batches.try_next().await? { let evaluated = evaluate(bound, &evaluation_batch(&batch, bound, None)?)?; gained += (batch.num_rows() - evaluated.null_count()) as u64; + considered += batch.num_rows() as u64; } - Ok(gained) + Ok((gained, considered)) } /// Stream one fragment's column in physical order, filling the unfilled live -/// rows and keeping every other value. +/// rows -- every live row, for a recompute -- and keeping every other value. /// /// Deleted rows are carried through so the values line up positionally with /// the fragment's data files; they are never read back, but the column file @@ -472,6 +567,8 @@ async fn fill_stream( bound: Arc, column: &str, output_is_blob: bool, + recompute: bool, + gained: Arc, ) -> Result> + Send + use<>> { let mut projection: Vec = bound.roots.clone(); projection.push(column.to_string()); @@ -521,14 +618,20 @@ async fn fill_stream( .column_by_name(ROW_ID) .ok_or_else(|| missing(ROW_ID))?; - // Only an unfilled live row gains a value; a deleted row has a null - // row id and keeps its (null) slot. - let unfilled = arrow::compute::is_null(existing.as_ref())?; + // Only an unfilled live row gains a value, or every live row under a + // recompute; a deleted row has a null row id and keeps its (null) slot. let live = arrow::compute::is_not_null(row_ids.as_ref())?; - let fill = arrow::compute::and(&unfilled, &live)?; + let fill = if recompute { + live + } else { + let unfilled = arrow::compute::is_null(existing.as_ref())?; + arrow::compute::and(&unfilled, &live)? + }; let keep = arrow::compute::not(&fill)?; let computed = evaluate(&bound, &evaluation_batch(&batch, &bound, Some(&keep))?)?; + let values = arrow::compute::and(&fill, &arrow::compute::is_not_null(&computed)?)?; + gained.fetch_add(values.true_count() as u64, Ordering::Relaxed); let merged = arrow_select::zip::zip(&fill, &computed, existing)?; let merged = if output_is_blob { blob_array_from_binary(&merged, projected.field(0))? @@ -737,7 +840,8 @@ mod tests { .await .unwrap(); assert_eq!(no_op.rows_assigned, 0); - assert_eq!(no_op.source_version, 3); + // The fill, then the stamp recording what it computed from. + assert_eq!(no_op.source_version, 4); assert_eq!(no_op.published_version, None); } @@ -777,8 +881,8 @@ mod tests { } /// A row is filled only by gaining a value, so an expression yielding null - /// settles at once instead of re-selecting the same rows forever. Nothing - /// is staged, so the version does not move either. + /// settles at once instead of re-selecting the same rows forever: the + /// second refresh finds the fragment signed and moves nothing. #[tokio::test] async fn test_refresh_converges_on_a_null_result() { let table = table_with("refresh_null_result", vec![1, 2, 3]).await; @@ -792,28 +896,186 @@ mod tests { let first = table.refresh_column("maybe").await.unwrap(); assert_eq!(first.rows_filled, 0); - assert_eq!(first.version, declared); + assert!(first.version > declared); assert_eq!(read(&table, "maybe").await, vec![None, None, None]); let again = table.refresh_column("maybe").await.unwrap(); assert_eq!(again.rows_filled, 0); - assert_eq!(again.version, declared); + assert_eq!(again.version, first.version); } - /// The contract's boundary: a filled fragment is not revisited, so - /// mutating an input leaves the value computed at fill time. + /// A filled row whose input moved is recomputed: the update rewrites + /// the row into a fragment the stamp never signed, and only that one. #[tokio::test] - async fn test_refresh_does_not_observe_input_mutation() { - let table = table_with("refresh_mutation", vec![1]).await; + async fn test_refresh_recomputes_a_row_whose_input_moved() { + let table = table_with("refresh_mutation", vec![1, 2]).await; + declare_doubled(&table).await.unwrap(); + append(&table, vec![5]).await; + table.refresh_column("doubled").await.unwrap(); + assert_eq!( + read(&table, "doubled").await, + vec![Some(2), Some(4), Some(10)] + ); + + table + .update() + .column("x", "7") + .only_if("x = 5") + .execute() + .await + .unwrap(); + + let again = table.refresh_column("doubled").await.unwrap(); + assert_eq!(again.rows_filled, 1); + assert_eq!( + read(&table, "doubled").await, + vec![Some(2), Some(4), Some(14)] + ); + + let settled = table.refresh_column("doubled").await.unwrap(); + assert_eq!(settled.rows_filled, 0); + assert_eq!(settled.version, again.version); + } + + /// Each stamp is a sidecar under `_computed/`; pruning old versions + /// removes the sidecars only they referenced, and keeps the current one. + #[tokio::test] + async fn test_pruning_drops_the_sidecars_of_pruned_versions() { + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let batch = record_batch!(("x", Int32, [1, 2])).unwrap(); + let table = conn + .create_table("sidecars", batch) + .execute() + .await + .unwrap(); declare_doubled(&table).await.unwrap(); table.refresh_column("doubled").await.unwrap(); - assert_eq!(read(&table, "doubled").await, vec![Some(2)]); + append(&table, vec![5]).await; + table.refresh_column("doubled").await.unwrap(); + let sidecars = || { + std::fs::read_dir(dir.path().join("sidecars.lance").join("_computed")) + .unwrap() + .count() + }; + assert_eq!(sidecars(), 2); - table.update().column("x", "3").execute().await.unwrap(); + table + .optimize(crate::table::OptimizeAction::Prune { + older_than: Some(chrono::Duration::zero()), + delete_unverified: Some(true), + error_if_tagged_old_versions: None, + }) + .await + .unwrap(); + assert_eq!(sidecars(), 1); + assert_eq!( + table.refresh_column("doubled").await.unwrap().rows_filled, + 0 + ); + } + + /// A deleted row is never computed and the rows that stay keep their + /// values: a delete recomputes nothing and stamps nothing. + #[tokio::test] + async fn test_a_delete_recomputes_nothing() { + let table = table_with("refresh_delete", vec![1, 2, 3]).await; + declare_doubled(&table).await.unwrap(); + let filled = table.refresh_column("doubled").await.unwrap(); + + table.delete("x = 2").await.unwrap(); + let deleted = table.version().await.unwrap(); let again = table.refresh_column("doubled").await.unwrap(); assert_eq!(again.rows_filled, 0); - assert_eq!(read(&table, "doubled").await, vec![Some(2)]); + assert_eq!(again.version, deleted); + assert!(deleted > filled.version); + assert_eq!(read(&table, "doubled").await, vec![Some(2), Some(6)]); + } + + /// Compaction copies inputs unchanged, so a fragment it builds from + /// signed ones is fresh: the refresh recomputes nothing and only records + /// the new fragment. + #[tokio::test] + async fn test_a_compaction_of_signed_fragments_recomputes_nothing() { + let table = table_with("refresh_compact_signed", vec![1, 2]).await; + declare_doubled(&table).await.unwrap(); + append(&table, vec![5]).await; + table.refresh_column("doubled").await.unwrap(); + + table + .optimize(crate::table::OptimizeAction::Compact { + options: crate::table::CompactionOptions::default(), + remap_options: None, + }) + .await + .unwrap(); + let compacted = table.version().await.unwrap(); + + let carried = table.refresh_column("doubled").await.unwrap(); + assert_eq!(carried.rows_filled, 0); + assert_eq!(carried.version, compacted + 1); + let settled = table.refresh_column("doubled").await.unwrap(); + assert_eq!(settled.version, carried.version); + assert_eq!( + read(&table, "doubled").await, + vec![Some(2), Some(4), Some(10)] + ); + } + + /// A column declared before signatures existed has no map. Its first + /// refresh keeps the null-fill contract and enrolls what it read from; + /// from then on a moved input is recomputed like any other. + #[tokio::test] + async fn test_an_unsigned_column_is_enrolled_by_its_first_refresh() { + let table = table_with("refresh_legacy", vec![1, 2]).await; + declare_doubled(&table).await.unwrap(); + table.refresh_column("doubled").await.unwrap(); + table + .update() + .column("x", "3") + .only_if("x = 1") + .execute() + .await + .unwrap(); + + let native = table.as_native().unwrap(); + let mut dataset = (*native.dataset.get().await.unwrap()).clone(); + let declaration = dataset + .schema() + .field("doubled") + .unwrap() + .metadata + .iter() + .filter(|(key, _)| !key.starts_with("computed_refresh.")) + .map(|(key, value)| (key.clone(), value.clone())) + .collect::>(); + dataset + .update_field_metadata() + .replace("doubled", declaration) + .unwrap() + .await + .unwrap(); + table.checkout_latest().await.unwrap(); + + // Null-fill only: the moved row keeps the value it was filled with. + let enrolled = table.refresh_column("doubled").await.unwrap(); + assert_eq!(enrolled.rows_filled, 0); + assert_eq!(read(&table, "doubled").await, vec![Some(2), Some(4)]); + + table + .update() + .column("x", "5") + .only_if("x = 3") + .execute() + .await + .unwrap(); + let again = table.refresh_column("doubled").await.unwrap(); + assert_eq!(again.rows_filled, 1); + assert_eq!(read(&table, "doubled").await, vec![Some(4), Some(10)]); } /// A row rewrite before the first refresh materializes the declared @@ -831,11 +1093,11 @@ mod tests { assert_eq!(read(&table, "doubled").await, vec![Some(6)]); } - /// The contract holds row by row, not fragment by fragment: revisiting a - /// fragment to fill one row must not recompute a filled row sitting beside - /// it, even where the input behind it has since changed. + /// A fragment compacted out of one the stamp never signed cannot vouch + /// for any of its rows: every live row is recomputed, the moved one + /// included. #[tokio::test] - async fn test_refresh_does_not_recompute_a_filled_row_beside_an_unfilled_one() { + async fn test_a_compaction_of_an_unsigned_fragment_recomputes_it() { let table = table_with("refresh_mixed", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); table.refresh_column("doubled").await.unwrap(); @@ -857,18 +1119,70 @@ mod tests { .unwrap(); let result = table.refresh_column("doubled").await.unwrap(); - assert_eq!(result.rows_filled, 1); - // 2 is the mutated row keeping the value it was filled with, not 200. + assert_eq!(result.rows_filled, 3); + assert_eq!( + read(&table, "doubled").await, + vec![Some(4), Some(10), Some(200)] + ); + } + + /// The gate's reproducer: a raw lance append may carry a value for the + /// computed column. Compaction cannot certify it, so the product is + /// recomputed and the supplied value replaced. + #[tokio::test] + async fn test_raw_append_values_are_not_trusted_after_compaction() { + use arrow_array::RecordBatchIterator; + use lance::Dataset; + use lance::dataset::{WriteMode, WriteParams}; + + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let batch = record_batch!(("x", Int32, [1, 2])).unwrap(); + let table = conn + .create_table("raw_append", batch) + .execute() + .await + .unwrap(); + declare_doubled(&table).await.unwrap(); + table.refresh_column("doubled").await.unwrap(); + + let batch = record_batch!(("x", Int32, [5]), ("doubled", Int32, [Some(999_i32)])).unwrap(); + let schema = batch.schema(); + let uri = table.uri().await.unwrap(); + Dataset::write( + RecordBatchIterator::new(vec![Ok(batch)], schema), + &uri, + Some(WriteParams { + mode: WriteMode::Append, + ..Default::default() + }), + ) + .await + .unwrap(); + table.checkout_latest().await.unwrap(); + table + .optimize(crate::table::OptimizeAction::Compact { + options: crate::table::CompactionOptions::default(), + remap_options: None, + }) + .await + .unwrap(); + + let result = table.refresh_column("doubled").await.unwrap(); + assert_eq!(result.rows_filled, 3); assert_eq!( read(&table, "doubled").await, vec![Some(2), Some(4), Some(10)] ); } - /// Filling a fragment must not disturb the values it already holds, which - /// is what makes a compaction-mixed fragment safe to revisit. + /// An appended fragment holds no values, so compacting it into a signed + /// one leaves the product fresh: only the appended rows are filled. #[tokio::test] - async fn test_refresh_preserves_already_filled_rows() { + async fn test_a_compaction_with_an_appended_fragment_fills_only_its_rows() { let table = table_with("refresh_preserves", vec![1, 2]).await; declare_doubled(&table).await.unwrap(); table.refresh_column("doubled").await.unwrap(); @@ -995,7 +1309,8 @@ mod tests { assert_eq!(result.rows_failed, 0); assert_eq!(result.rows_remaining, 0); assert_eq!(result.source_version, 2); - assert_eq!(result.published_version, Some(3)); + // The fill lands at 3; the stamp recording its inputs is published at 4. + assert_eq!(result.published_version, Some(4)); assert_eq!(job.status().await.unwrap(), "finished"); assert_eq!( read(&table, "doubled").await, @@ -1059,31 +1374,32 @@ mod tests { assert_eq!(read(&table, "quotient").await, vec![Some(10)]); } - /// The gate's reproducer: an already-filled row's value must not be - /// re-evaluated either -- its input may have mutated into one the - /// expression chokes on. + /// A filled row whose input moved is re-evaluated, and a row whose + /// input did not move is not: the untouched fragment is never read, so + /// its poison input is never reached. #[tokio::test] - async fn test_a_filled_rows_value_is_never_evaluated() { - let table = table_with("refresh_filled_poison", vec![1, 2]).await; + async fn test_only_a_moved_rows_value_is_re_evaluated() { + let table = table_with("refresh_filled_poison", vec![1, 0]).await; table .add_columns() - .computed("quotient", "10 / x") + .computed("quotient", "10 / coalesce(nullif(x, 0), 1)") .execute() .await .unwrap(); table.refresh_column("quotient").await.unwrap(); + assert_eq!(read(&table, "quotient").await, vec![Some(10), Some(10)]); + append(&table, vec![5]).await; table .update() - .column("x", "0") + .column("x", "2") .only_if("x = 1") .execute() .await .unwrap(); - append(&table, vec![5]).await; let result = table.refresh_column("quotient").await.unwrap(); - assert_eq!(result.rows_filled, 1); + assert_eq!(result.rows_filled, 2); assert_eq!( read(&table, "quotient").await, vec![Some(2), Some(5), Some(10)] From 7575c2597af5f62db5168ea2f8eb8f5088af03be Mon Sep 17 00:00:00 2001 From: Wyatt Alt Date: Mon, 14 Sep 2026 09:41:37 -0700 Subject: [PATCH 203/206] feat: recompute computed column rows whose inputs changed (#4161) refresh_column fills nulls, so once a row has a value nothing revisits it: an update to one of its inputs, or a definition change, leaves the computed value stale for good. This stamps the column's field metadata with the definition it was computed under and a per-fragment signature of the input storage it was read from (input data files and overlays; not the deletion file, since a delete changes no surviving value). A refresh recomputes every live row of a fragment whose stamp disagrees with the manifest, then records what it computed from in a second commit after the fill. A compacted fragment inherits freshness through the Rewrite lineage when every fragment it was built from was signed, or was appended since the stamp, never had an input moved, and left its rows of the product unfilled (a raw append may supply a value; the product's data is the evidence, and the null fill covers those rows); otherwise it recomputes. A column declared before the stamps existed keeps the null-fill contract on its first refresh, which enrolls it as it stood. The map is one entry per fragment per column, so it is kept out of the manifest: each stamp writes an immutable sidecar under `_computed/`, named by its content digest, and the field metadata holds the digest. Pruning old versions also drops the sidecars no remaining version references, keeping any younger than seven days as lance keeps unverified files, since a sidecar is put before the commit that references it. The stamp commit is metadata-only, so a materialized view's drift check treats it like the fill. The core lives in `table::freshness` so a remote refresh can share the contract. From c44b1923349c6355e6af02fadf03d99a7cf9bbc6 Mon Sep 17 00:00:00 2001 From: Lance Release Date: Mon, 14 Sep 2026 16:46:21 +0000 Subject: [PATCH 204/206] =?UTF-8?q?Bump=20version:=200.39.0-beta.7=20?= =?UTF-8?q?=E2=86=92=200.39.0-beta.8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.toml | 2 +- Cargo.lock | 6 +++--- docs/src/java/java.md | 2 +- java/lancedb-core/pom.xml | 2 +- java/pom.xml | 2 +- nodejs/Cargo.toml | 2 +- nodejs/npm/darwin-arm64/package.json | 2 +- nodejs/npm/linux-arm64-gnu/package.json | 2 +- nodejs/npm/linux-arm64-musl/package.json | 2 +- nodejs/npm/linux-x64-gnu/package.json | 2 +- nodejs/npm/linux-x64-musl/package.json | 2 +- nodejs/npm/win32-arm64-msvc/package.json | 2 +- nodejs/npm/win32-x64-msvc/package.json | 2 +- nodejs/package.json | 2 +- python/Cargo.toml | 2 +- rust/lancedb/Cargo.toml | 2 +- 16 files changed, 18 insertions(+), 18 deletions(-) diff --git a/.bumpversion.toml b/.bumpversion.toml index a2c5fdd61..23f097af5 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.39.0-beta.7" +current_version = "0.39.0-beta.8" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index efa59c4e3..b3ff0e299 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5452,7 +5452,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.39.0-beta.7" +version = "0.39.0-beta.8" dependencies = [ "ahash", "anyhow", @@ -5544,7 +5544,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.39.0-beta.7" +version = "0.39.0-beta.8" dependencies = [ "arrow-array", "arrow-buffer", @@ -5569,7 +5569,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.39.0-beta.7" +version = "0.39.0-beta.8" dependencies = [ "arrow", "async-trait", diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 59c995344..1b5f14153 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.39.0-beta.7 + 0.39.0-beta.8 ``` diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index afe9b8c5c..5f9702aaa 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.7 + 0.39.0-beta.8 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index e66e1bbd4..37c182feb 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.39.0-beta.7 + 0.39.0-beta.8 pom ${project.artifactId} LanceDB Java SDK Parent POM diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 340d8e500..53fc32c6a 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.39.0-beta.7" +version = "0.39.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 e1ea88e62..7e8684be8 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.39.0-beta.7", + "version": "0.39.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 7bbbd3221..274875fec 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.39.0-beta.7", + "version": "0.39.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 58c488e47..c01cac42f 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.39.0-beta.7", + "version": "0.39.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 ca364168e..1398953d4 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.39.0-beta.7", + "version": "0.39.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 c088a4d7d..9823eda62 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.39.0-beta.7", + "version": "0.39.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 af28f68d3..ce6d2922f 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.39.0-beta.7", + "version": "0.39.0-beta.8", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index ff612c4df..8f6a919b2 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.39.0-beta.7", + "version": "0.39.0-beta.8", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index e9621ba60..db979c1e7 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.39.0-beta.7", + "version": "0.39.0-beta.8", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/python/Cargo.toml b/python/Cargo.toml index ff7a98234..d7ec8cd61 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.39.0-beta.7" +version = "0.39.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 998d041e2..f9c79b042 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.39.0-beta.7" +version = "0.39.0-beta.8" edition.workspace = true description = "LanceDB: A serverless, low-latency vector database for AI applications" license.workspace = true From 37771fd4fcbc969485426c6b79ac3c3c6cd53356 Mon Sep 17 00:00:00 2001 From: Jack Ye Date: Mon, 14 Sep 2026 20:04:15 -0700 Subject: [PATCH 205/206] fix(deps): update rustls and cap aws-smithy-types to unbreak CI (#4177) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two upstream dependency releases broke CI on `main`. Both fixes are dependency constraints, so they ride together. ## `deny` — RUSTSEC-2026-0285 rustls 0.23.40 accepts TLS 1.3 handshake messages sent at the wrong encryption level ([advisory](https://rustsec.org/advisories/RUSTSEC-2026-0285)), patched in 0.23.45. rustls 0.23.45 requires `aws-lc-rs >= 1.18`, which the nodejs crate pinned to `=1.16.3`, so this also bumps that pin and its `aws-lc-sys` companion to `=1.18.1` / `=0.45.0`. The pin comment already calls for periodic updates on security patches. The workspace's other rustls (0.21.12) is below the advisory's affected range (`unaffected = ["< 0.23.13"]`). ## `build-no-lock` — aws-smithy-types 1.7.0 `aws-smithy-types` 1.7.0 and `aws-smithy-json` 0.64.0 both released 2026-09-14. 1.7.0 made `Document` `non_exhaustive`, which `aws-smithy-json` 0.63 does not compile against: ``` error[E0004]: non-exhaustive patterns: `&_` not covered --> aws-smithy-json-0.63.0/src/serialize.rs:36:15 note: `aws_smithy_types::Document` defined here --> aws-smithy-types-1.7.0/src/document/mod.rs:91:1 ``` Every `aws-sdk-*` crate moved to `aws-smithy-json ^0.64`, but `aws-config` 1.12.0 still requires `^0.63`, so a lockfile-free resolve pairs json 0.63.0 with types 1.7.0 and fails. This caps `aws-smithy-types` below 1.7 as a constraint-only dev-dependency, matching the existing `aws-smithy-runtime` entry. Revert once `aws-config` moves to `aws-smithy-json` 0.64. Note this break is not specific to this PR — `build-no-lock` fails the same way on unrelated branches (e.g. `jon/secrets-client-api` run 34903587364), which passed it hours earlier. ## Verification Resolution only, no local build: - Locked resolve unchanged: `aws-smithy-types` stays 1.4.8; the only `Cargo.lock` delta from the cap is the new dev-dep edge. - Fresh resolve (`rm Cargo.lock`): `aws-smithy-json` 0.63.0 with `aws-smithy-types` 1.6.3, `aws-sdk-*` one release back, `rustls` 0.23.45 retained. --- Cargo.lock | 72 +++++++++++++++++++++-------------------- nodejs/Cargo.toml | 5 +-- rust/lancedb/Cargo.toml | 4 +++ 3 files changed, 44 insertions(+), 37 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b3ff0e299..160ee2253 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -141,7 +141,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -152,7 +152,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -662,9 +662,9 @@ dependencies = [ [[package]] name = "aws-lc-rs" -version = "1.16.3" +version = "1.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec6fb3fe69024a75fa7e1bfb48aa6cf59706a101658ea01bfd33b2b248a038f" +checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" dependencies = [ "aws-lc-sys", "untrusted 0.7.1", @@ -673,14 +673,15 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.40.0" +version = "0.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f50037ee5e1e41e7b8f9d161680a725bd1626cb6f8c7e901f91f942850852fe7" +checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" dependencies = [ "cc", "cmake", "dunce", "fs_extra", + "pkg-config", ] [[package]] @@ -1008,7 +1009,7 @@ dependencies = [ "hyper-util", "pin-project-lite", "rustls 0.21.12", - "rustls 0.23.40", + "rustls 0.23.45", "rustls-native-certs", "rustls-pki-types", "tokio", @@ -1822,7 +1823,7 @@ version = "3.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3084,7 +3085,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -3292,7 +3293,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4262,7 +4263,7 @@ dependencies = [ "http 1.5.0", "hyper 1.9.0", "hyper-util", - "rustls 0.23.40", + "rustls 0.23.45", "rustls-native-certs", "tokio", "tokio-rustls 0.26.4", @@ -4300,7 +4301,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2 0.5.10", + "socket2 0.6.3", "system-configuration", "tokio", "tower-service", @@ -4599,7 +4600,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5474,6 +5475,7 @@ dependencies = [ "aws-sdk-kms", "aws-sdk-s3", "aws-smithy-runtime", + "aws-smithy-types", "bytes", "candle-core", "candle-nn", @@ -6305,7 +6307,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -7969,8 +7971,8 @@ dependencies = [ "quinn-proto", "quinn-udp", "rustc-hash", - "rustls 0.23.40", - "socket2 0.5.10", + "rustls 0.23.45", + "socket2 0.6.3", "thiserror 2.0.18", "tokio", "tracing", @@ -7990,7 +7992,7 @@ dependencies = [ "rand 0.9.5", "ring", "rustc-hash", - "rustls 0.23.40", + "rustls 0.23.45", "rustls-pki-types", "slab", "thiserror 2.0.18", @@ -8008,7 +8010,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2 0.5.10", + "socket2 0.6.3", "tracing", "windows-sys 0.60.2", ] @@ -8533,7 +8535,7 @@ dependencies = [ "percent-encoding", "pin-project-lite", "quinn", - "rustls 0.23.40", + "rustls 0.23.45", "rustls-native-certs", "rustls-pki-types", "serde", @@ -8576,7 +8578,7 @@ dependencies = [ "percent-encoding", "pin-project-lite", "quinn", - "rustls 0.23.40", + "rustls 0.23.45", "rustls-pki-types", "rustls-platform-verifier", "serde", @@ -8791,7 +8793,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -8808,16 +8810,16 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.40" +version = "0.23.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" dependencies = [ "aws-lc-rs", "log", "once_cell", "ring", "rustls-pki-types", - "rustls-webpki 0.103.13", + "rustls-webpki 0.103.15", "subtle", "zeroize", ] @@ -8855,14 +8857,14 @@ dependencies = [ "jni", "log", "once_cell", - "rustls 0.23.40", + "rustls 0.23.45", "rustls-native-certs", "rustls-platform-verifier-android", - "rustls-webpki 0.103.13", + "rustls-webpki 0.103.15", "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -8883,9 +8885,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.103.13" +version = "0.103.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" dependencies = [ "aws-lc-rs", "ring", @@ -9444,7 +9446,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -9551,7 +9553,7 @@ dependencies = [ "cfg-if 1.0.4", "libc", "psm", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -9843,7 +9845,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -10099,7 +10101,7 @@ version = "0.26.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" dependencies = [ - "rustls 0.23.40", + "rustls 0.23.45", "tokio", ] @@ -10513,7 +10515,7 @@ dependencies = [ "flate2", "log", "once_cell", - "rustls 0.23.40", + "rustls 0.23.45", "rustls-pki-types", "serde", "serde_json", @@ -10847,7 +10849,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 53fc32c6a..636289907 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -37,8 +37,9 @@ lzma-sys = { version = "0.1", features = ["static"] } log.workspace = true # Pin to resolve build failures; update periodically for security patches. -aws-lc-sys = "=0.40.0" -aws-lc-rs = "=1.16.3" +# rustls >= 0.23.45 (RUSTSEC-2026-0285) needs aws-lc-rs >= 1.18. +aws-lc-sys = "=0.45.0" +aws-lc-rs = "=1.18.1" [build-dependencies] napi-build = "2.3.1" diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index f9c79b042..9bc4c4a8c 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -111,6 +111,10 @@ aws-sdk-s3 = { version = "1.55.0" } aws-sdk-kms = { version = "1.48.0" } aws-config = { version = "1.5.10" } aws-smithy-runtime = { version = "1.9.1" } +# Constraint only: types 1.7 breaks aws-smithy-json 0.63, which aws-config still +# requires. Bounds must stay inside 1.x and allow the MSRV job's 1.3.6 pin. +# Drop once aws-config moves to aws-smithy-json 0.64. +aws-smithy-types = { version = ">=1.0, <1.7" } datafusion.workspace = true http-body = "1" # Matching reqwest rstest = "0.23.0" From ffe94a65a1881f0dbcf4ff84ab26d05883009279 Mon Sep 17 00:00:00 2001 From: "lancedb-gatefixer[bot]" <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Date: Tue, 15 Sep 2026 14:10:48 +0800 Subject: [PATCH 206/206] fix(node): preserve optimize cleanup timestamp (#4160) ## Summary - pass the TypeScript `cleanupOlderThan` date to the native binding as an unchanged epoch timestamp - prune with Lance's absolute `before_timestamp` policy so dispatch and compaction time cannot move the cutoff - retain versions created after the supplied cutoff and document that behavior - add boundary and end-to-end regression coverage ## Root cause The TypeScript layer converted the absolute date into an elapsed duration before calling native optimize. Lance converted that duration back into a timestamp only after compaction, which silently advanced the requested cutoff and made the cleanup count depend on a millisecond timing boundary. ## Validation - `cargo fmt --all` - `cargo clippy --quiet --features remote --tests --examples -p lancedb -p lancedb-nodejs` - `pnpm build` - `pnpm lint` - `pnpm run docs` - `pnpm test __test__/table.test.ts --runInBand` (309 passed) Fixes #4159 --------- Co-authored-by: Gatefixer <313497061+lancedb-gatefixer[bot]@users.noreply.github.com> Co-authored-by: Xuanwo --- docs/src/js/interfaces/OptimizeOptions.md | 3 +- nodejs/__test__/table.test.ts | 21 +++++++++- nodejs/lancedb/table.ts | 13 ++---- nodejs/src/table.rs | 50 ++++++++++++----------- rust/lancedb/src/table.rs | 27 ++++++++++++ rust/lancedb/src/table/optimize.rs | 30 +++++++++++++- rust/lancedb/src/table/refresh.rs | 37 +++++++++++++++++ 7 files changed, 145 insertions(+), 36 deletions(-) diff --git a/docs/src/js/interfaces/OptimizeOptions.md b/docs/src/js/interfaces/OptimizeOptions.md index 700632342..110eb3813 100644 --- a/docs/src/js/interfaces/OptimizeOptions.md +++ b/docs/src/js/interfaces/OptimizeOptions.md @@ -26,7 +26,8 @@ const olderThan = new Date(); olderThan.setDate(olderThan.getDate() - 1)); tbl.optimize({cleanupOlderThan: olderThan}); -// Delete all versions except the current version +// Delete versions committed before this point. Versions created by the +// optimize call itself are newer than the cutoff and will be retained. tbl.optimize({cleanupOlderThan: new Date()}); ``` diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index cae01d9d5..ac74c65ef 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -53,6 +53,7 @@ import { Operator, instanceOfFullTextQuery, } from "../lancedb/query"; +import { LocalTable } from "../lancedb/table"; describe.each([arrow15, arrow16, arrow17, arrow18])( "Given a table", @@ -2789,7 +2790,7 @@ describe("when optimizing a dataset", () => { it("cleanups old versions", async () => { const stats = await table.optimize({ cleanupOlderThan: new Date() }); expect(stats.prune.bytesRemoved).toBeGreaterThan(0); - expect(stats.prune.oldVersionsRemoved).toBe(3); + expect(stats.prune.oldVersionsRemoved).toBe(2); }); it("delete unverified", async () => { @@ -2810,6 +2811,24 @@ describe("when optimizing a dataset", () => { }); }); +it("passes cleanupOlderThan to the native binding as an absolute timestamp", async () => { + const optimize = jest.fn().mockResolvedValue({ + compaction: { + filesAdded: 0, + filesRemoved: 0, + fragmentsAdded: 0, + fragmentsRemoved: 0, + }, + prune: { bytesRemoved: 0, oldVersionsRemoved: 0 }, + }); + const table = new LocalTable({ optimize } as never); + const cutoff = new Date("2020-01-02T03:04:05.678Z"); + + await table.optimize({ cleanupOlderThan: cutoff, deleteUnverified: true }); + + expect(optimize).toHaveBeenCalledWith(cutoff.getTime(), true); +}); + describe.each([arrow15, arrow16, arrow17, arrow18])( "when optimizing a dataset", // biome-ignore lint/suspicious/noExplicitAny: diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 8d8b0d675..a70243402 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -148,7 +148,8 @@ export interface OptimizeOptions { * olderThan.setDate(olderThan.getDate() - 1)); * tbl.optimize({cleanupOlderThan: olderThan}); * - * // Delete all versions except the current version + * // Delete versions committed before this point. Versions created by the + * // optimize call itself are newer than the cutoff and will be retained. * tbl.optimize({cleanupOlderThan: new Date()}); */ cleanupOlderThan: Date; @@ -1486,16 +1487,8 @@ export class LocalTable extends Table { } async optimize(options?: Partial): Promise { - let cleanupOlderThanMs; - if ( - options?.cleanupOlderThan !== undefined && - options?.cleanupOlderThan !== null - ) { - cleanupOlderThanMs = - new Date().getTime() - options.cleanupOlderThan.getTime(); - } return await this.inner.optimize( - cleanupOlderThanMs, + options?.cleanupOlderThan?.getTime(), options?.deleteUnverified, ); } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 7ae4402ab..cf7ec4020 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -7,7 +7,7 @@ use chrono::{DateTime, Utc}; use lancedb::ipc::{ipc_file_to_batches, ipc_file_to_schema}; use lancedb::table::{ - AddDataMode, ColumnAlteration as LanceColumnAlteration, Duration, + AddDataMode, ColumnAlteration as LanceColumnAlteration, FieldMetadataUpdate as LanceFieldMetadataUpdate, FtsToken as LanceDbFtsToken, NewColumnTransform, OptimizeAction, OptimizeOptions, Ref, Table as LanceDbTable, }; @@ -677,22 +677,20 @@ impl Table { #[napi(catch_unwind)] pub async fn optimize( &self, - older_than_ms: Option, + before_timestamp_ms: Option, delete_unverified: Option, ) -> napi::Result { let inner = self.inner_ref()?; - let older_than = if let Some(ms) = older_than_ms { - if ms == i64::MIN { - return Err(napi::Error::from_reason(format!( - "older_than_ms can not be {}", - i32::MIN, - ))); - } - Duration::try_milliseconds(ms) - } else { - None - }; + let before_timestamp = before_timestamp_ms + .map(|ms| { + DateTime::from_timestamp_millis(ms).ok_or_else(|| { + napi::Error::from_reason(format!( + "cleanupOlderThan timestamp is out of range: {ms}" + )) + }) + }) + .transpose()?; let compaction_stats = inner .optimize(OptimizeAction::Compact { @@ -703,16 +701,22 @@ impl Table { .default_error()? .compaction .unwrap(); - let prune_stats = inner - .optimize(OptimizeAction::Prune { - older_than, - delete_unverified, - error_if_tagged_old_versions: None, - }) - .await - .default_error()? - .prune - .unwrap(); + let prune_stats = if let Some(before_timestamp) = before_timestamp { + inner + .optimize_prune_before(before_timestamp, delete_unverified, None) + .await + } else { + inner + .optimize(OptimizeAction::Prune { + older_than: None, + delete_unverified, + error_if_tagged_old_versions: None, + }) + .await + } + .default_error()? + .prune + .unwrap(); inner .optimize(lancedb::table::OptimizeAction::Index( OptimizeOptions::default(), diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index 508c2ca49..5732955f5 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1741,6 +1741,33 @@ impl Table { self.inner.optimize(action).await } + /// Prune versions committed before an absolute timestamp. + /// + /// This is an internal entry point for language bindings whose public API + /// accepts an absolute cleanup cutoff. + #[doc(hidden)] + pub async fn optimize_prune_before( + &self, + before_timestamp: chrono::DateTime, + delete_unverified: Option, + error_if_tagged_old_versions: Option, + ) -> Result { + let native = self.as_native().ok_or_else(|| Error::NotSupported { + message: "optimize is not supported on LanceDB cloud.".into(), + })?; + let prune = optimize::cleanup_old_versions_before( + native, + before_timestamp, + delete_unverified, + error_if_tagged_old_versions, + ) + .await?; + Ok(OptimizeStats { + compaction: None, + prune: Some(prune), + }) + } + /// Add new columns to the table, providing values to fill in. pub fn add_columns(&self) -> AddColumnsBuilder { AddColumnsBuilder::new(self.inner.clone()) diff --git a/rust/lancedb/src/table/optimize.rs b/rust/lancedb/src/table/optimize.rs index 6e3fc0048..2a502b059 100644 --- a/rust/lancedb/src/table/optimize.rs +++ b/rust/lancedb/src/table/optimize.rs @@ -8,7 +8,8 @@ use std::sync::Arc; -use lance::dataset::cleanup::RemovalStats; +use chrono::{DateTime, Utc}; +use lance::dataset::cleanup::{CleanupPolicyBuilder, RemovalStats}; use lance::dataset::optimize::{CompactionMetrics, IndexRemapperOptions, compact_files}; use lance::index::DatasetIndexExt; use lance_index::optimize::OptimizeOptions; @@ -147,6 +148,33 @@ pub(crate) async fn cleanup_old_versions( Ok(stats) } +/// Remove dataset versions committed before an absolute timestamp. +pub(crate) async fn cleanup_old_versions_before( + table: &NativeTable, + before_timestamp: DateTime, + delete_unverified: Option, + error_if_tagged_old_versions: Option, +) -> Result { + table.dataset.ensure_mutable()?; + let dataset = table.dataset.get().await?; + let mut policy = CleanupPolicyBuilder::default().before_timestamp(before_timestamp); + if let Some(delete_unverified) = delete_unverified { + policy = policy.delete_unverified(delete_unverified); + } + if let Some(error_if_tagged_old_versions) = error_if_tagged_old_versions { + policy = policy.error_if_tagged_old_versions(error_if_tagged_old_versions); + } + let stats = dataset.cleanup_with_policy(policy.build()).await?; + // Computed-column signature sidecars live outside lance's directories; + // drop the ones the surviving versions no longer reference. + let removed = + super::freshness::prune_sidecars(&dataset, delete_unverified.unwrap_or(false)).await?; + if removed > 0 { + log::debug!("removed {removed} unreferenced computed-column signature sidecars"); + } + Ok(stats) +} + /// Compact files in the dataset. /// /// This can be run after making several small appends to optimize the table diff --git a/rust/lancedb/src/table/refresh.rs b/rust/lancedb/src/table/refresh.rs index 2ed479256..996f2e383 100644 --- a/rust/lancedb/src/table/refresh.rs +++ b/rust/lancedb/src/table/refresh.rs @@ -978,6 +978,43 @@ mod tests { ); } + /// Absolute timestamp pruning applies the same computed-column sidecar + /// cleanup as duration-based pruning. + #[tokio::test] + async fn test_absolute_pruning_drops_the_sidecars_of_pruned_versions() { + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let batch = record_batch!(("x", Int32, [1, 2])).unwrap(); + let table = conn + .create_table("sidecars", batch) + .execute() + .await + .unwrap(); + declare_doubled(&table).await.unwrap(); + table.refresh_column("doubled").await.unwrap(); + append(&table, vec![5]).await; + table.refresh_column("doubled").await.unwrap(); + let sidecars = || { + std::fs::read_dir(dir.path().join("sidecars.lance").join("_computed")) + .unwrap() + .count() + }; + assert_eq!(sidecars(), 2); + + table + .optimize_prune_before(chrono::Utc::now(), Some(true), None) + .await + .unwrap(); + assert_eq!(sidecars(), 1); + assert_eq!( + table.refresh_column("doubled").await.unwrap().rows_filled, + 0 + ); + } + /// A deleted row is never computed and the rows that stay keep their /// values: a delete recomputes nothing and stamps nothing. #[tokio::test]