mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
Merge main updates into gatekeeper/fix-4911-1
This commit is contained in:
+1
-1
@@ -1,5 +1,5 @@
|
||||
[tool.bumpversion]
|
||||
current_version = "0.42.0-beta.13"
|
||||
current_version = "0.42.0-beta.15"
|
||||
parse = """(?x)
|
||||
(?P<major>0|[1-9]\\d*)\\.
|
||||
(?P<minor>0|[1-9]\\d*)\\.
|
||||
|
||||
Generated
+87
-53
@@ -1361,6 +1361,12 @@ version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "better_io"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef0a3155e943e341e557863e69a708999c94ede624e37865c8e2a91b94efa78f"
|
||||
|
||||
[[package]]
|
||||
name = "bigdecimal"
|
||||
version = "0.4.10"
|
||||
@@ -3327,6 +3333,12 @@ dependencies = [
|
||||
"litrs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dtype_dispatch"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab23e69df104e2fd85ee63a533a22d2132ef5975dc6b36f9f3e5a7305e4a8ed7"
|
||||
|
||||
[[package]]
|
||||
name = "dunce"
|
||||
version = "1.0.5"
|
||||
@@ -3873,8 +3885,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
|
||||
|
||||
[[package]]
|
||||
name = "fsst"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow-array",
|
||||
"rand 0.9.5",
|
||||
@@ -5352,8 +5364,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a"
|
||||
|
||||
[[package]]
|
||||
name = "lance"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"arrow",
|
||||
@@ -5428,8 +5440,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-arrow"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow-array",
|
||||
"arrow-buffer",
|
||||
@@ -5451,7 +5463,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "lance-arrow-scalar"
|
||||
version = "59.0.0"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow-array",
|
||||
"arrow-buffer",
|
||||
@@ -5465,7 +5477,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "lance-arrow-stats"
|
||||
version = "59.0.0"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow-array",
|
||||
"arrow-schema",
|
||||
@@ -5474,8 +5486,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-bitpacking"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrayref",
|
||||
"crunchy",
|
||||
@@ -5485,8 +5497,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-core"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow-array",
|
||||
"arrow-buffer",
|
||||
@@ -5524,8 +5536,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-datafusion"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow",
|
||||
"arrow-array",
|
||||
@@ -5556,8 +5568,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-datafusion-exec"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow",
|
||||
"arrow-array",
|
||||
@@ -5582,8 +5594,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-datagen"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow",
|
||||
"arrow-array",
|
||||
@@ -5595,13 +5607,13 @@ dependencies = [
|
||||
"hex",
|
||||
"rand 0.9.5",
|
||||
"rand_distr 0.5.1",
|
||||
"rand_xoshiro",
|
||||
"rand_xoshiro 0.7.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lance-derive"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -5610,8 +5622,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-encoding"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow-arith",
|
||||
"arrow-array",
|
||||
@@ -5634,6 +5646,7 @@ dependencies = [
|
||||
"log",
|
||||
"lz4",
|
||||
"num-traits",
|
||||
"pco",
|
||||
"prost",
|
||||
"serde_json",
|
||||
"tokio",
|
||||
@@ -5644,8 +5657,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-file"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow-arith",
|
||||
"arrow-array",
|
||||
@@ -5676,8 +5689,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-geo"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow-array",
|
||||
"arrow-schema",
|
||||
@@ -5708,8 +5721,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-index"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"arrow",
|
||||
@@ -5782,8 +5795,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-index-core"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow-array",
|
||||
"arrow-schema",
|
||||
@@ -5806,8 +5819,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-io"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow",
|
||||
"arrow-array",
|
||||
@@ -5852,8 +5865,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-jsonb"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"byteorder",
|
||||
"ethnum",
|
||||
@@ -5870,7 +5883,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-linalg"
|
||||
version = "15.0.0-beta.21"
|
||||
version = "15.0.0-beta.22"
|
||||
dependencies = [
|
||||
"approx",
|
||||
"argminmax 0.7.1",
|
||||
@@ -5892,8 +5905,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-namespace"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow",
|
||||
"async-trait",
|
||||
@@ -5907,8 +5920,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-namespace-impls"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"arrow",
|
||||
@@ -5962,8 +5975,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-select"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow-array",
|
||||
"arrow-buffer",
|
||||
@@ -5977,8 +5990,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-table"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow",
|
||||
"arrow-array",
|
||||
@@ -6019,8 +6032,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-testing"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"arrow-array",
|
||||
"arrow-schema",
|
||||
@@ -6033,8 +6046,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lance-tokenizer"
|
||||
version = "15.0.0-beta.21"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.21#80bc45a195279befdec42853dac8d15a37e0504d"
|
||||
version = "15.0.0-beta.22"
|
||||
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.22#49e29d7beb885e42f3ab01fc9fc25b5281cef467"
|
||||
dependencies = [
|
||||
"frostem",
|
||||
"icu_segmenter",
|
||||
@@ -6047,7 +6060,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lancedb"
|
||||
version = "0.42.0-beta.13"
|
||||
version = "0.42.0-beta.15"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"anyhow",
|
||||
@@ -6158,7 +6171,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lancedb-cli"
|
||||
version = "0.42.0-beta.13"
|
||||
version = "0.42.0-beta.15"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"arrow-array",
|
||||
@@ -6201,7 +6214,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lancedb-nodejs"
|
||||
version = "0.42.0-beta.13"
|
||||
version = "0.42.0-beta.15"
|
||||
dependencies = [
|
||||
"arrow-array",
|
||||
"arrow-buffer",
|
||||
@@ -6226,7 +6239,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lancedb-python"
|
||||
version = "0.42.0-beta.13"
|
||||
version = "0.42.0-beta.15"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"arrow",
|
||||
@@ -6707,7 +6720,7 @@ dependencies = [
|
||||
"quanta",
|
||||
"radix_trie",
|
||||
"rand 0.9.5",
|
||||
"rand_xoshiro",
|
||||
"rand_xoshiro 0.7.0",
|
||||
"sketches-ddsketch",
|
||||
]
|
||||
|
||||
@@ -7893,6 +7906,18 @@ dependencies = [
|
||||
"hmac 0.12.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pco"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "52f01ab51a847e7002371c2384b2c88f50dd45982cc2764e7997751971f1bfbf"
|
||||
dependencies = [
|
||||
"better_io",
|
||||
"dtype_dispatch",
|
||||
"half",
|
||||
"rand_xoshiro 0.6.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pem"
|
||||
version = "3.0.6"
|
||||
@@ -9116,6 +9141,15 @@ dependencies = [
|
||||
"rand_core 0.10.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_xoshiro"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f97cdb2a36ed4183de61b2f824cc45c9f1037f28afe0a322e9fff4c108b5aaa"
|
||||
dependencies = [
|
||||
"rand_core 0.6.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_xoshiro"
|
||||
version = "0.7.0"
|
||||
|
||||
+14
-14
@@ -20,20 +20,20 @@ categories = ["database-implementations"]
|
||||
rust-version = "1.95.0"
|
||||
|
||||
[workspace.dependencies]
|
||||
lance = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-core = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-datagen = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-file = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-io = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-index = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-jsonb = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-namespace = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-namespace-impls = { "version" = "=15.0.0-beta.21", default-features = false, "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-table = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-testing = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-datafusion = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-encoding = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-arrow = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-core = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-datagen = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-file = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-io = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-index = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-jsonb = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-namespace = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-namespace-impls = { "version" = "=15.0.0-beta.22", default-features = false, "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-table = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-testing = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-datafusion = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-encoding = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-arrow = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lancedb = { path = "rust/lancedb", default-features = false }
|
||||
ahash = "0.8"
|
||||
anyhow = "1"
|
||||
|
||||
@@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`:
|
||||
<dependency>
|
||||
<groupId>com.lancedb</groupId>
|
||||
<artifactId>lancedb-core</artifactId>
|
||||
<version>0.42.0-beta.13</version>
|
||||
<version>0.42.0-beta.15</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
|
||||
@@ -8,6 +8,26 @@
|
||||
|
||||
## Properties
|
||||
|
||||
### retries?
|
||||
|
||||
```ts
|
||||
optional retries: number;
|
||||
```
|
||||
|
||||
Override the remote retry budget for this execution only (an integer from
|
||||
0 to 255). Use `execute(data, { retries: 0 })` to disable even retries after
|
||||
precommit conflicts (409) or rate limits (429). This does not change
|
||||
connection-wide/read budgets or local transaction conflict retries.
|
||||
|
||||
By default, remote calls use the connection's `clientConfig.retryConfig`
|
||||
([RetryConfig](RetryConfig.md)). Its `statuses` (also set through
|
||||
`LANCE_CLIENT_RETRY_STATUSES`) selects candidates within the retry budget;
|
||||
it never permits replay of ambiguous merge outcomes. In particular, 502,
|
||||
ordinary 503, and 504 are never replayed, even if configured. Reconcile table
|
||||
contents before manually repeating a merge whose commit outcome is unknown.
|
||||
|
||||
***
|
||||
|
||||
### timeoutMs?
|
||||
|
||||
```ts
|
||||
@@ -24,3 +44,6 @@ the second attempt will be cancelled after 10 seconds, hitting the
|
||||
first attempt will not be cancelled.
|
||||
|
||||
When this is set, the timeout is enforced on all attempts, including the first.
|
||||
For remote tables this is sent as a server execution timeout. It does not
|
||||
extend HTTP read or proxy idle timeouts, or prove that a failed request did
|
||||
not commit.
|
||||
|
||||
@@ -424,6 +424,25 @@ code that used the former LanceDB Enterprise-only argument order.
|
||||
|
||||
## Functions and Jobs
|
||||
|
||||
Use `progress=True` when waiting for Function registration in a notebook or
|
||||
terminal. A callback receives structured snapshots instead:
|
||||
|
||||
```python
|
||||
fn = db.create_function(my_function, progress=True)
|
||||
registration = db.create_function_async(other_function)
|
||||
fn = registration.wait(progress=lambda snapshot: print(snapshot))
|
||||
print(fn.image.describe())
|
||||
```
|
||||
|
||||
Registration uses the existing SQL query handle. The current handle reports
|
||||
lifecycle state and `client_elapsed_time_millis` since the handle was created;
|
||||
detailed build phases and build logs are unavailable. Keep the same handle after
|
||||
a wait timeout to resume waiting. Failures retain the server error and request
|
||||
identifiers. `fn.image` has a concise representation; `describe()` exposes Python
|
||||
and CUDA requirements without inspecting Pydantic internals. Platforms, base image
|
||||
and size are `None` until the service reports them. The full image descriptor and
|
||||
canonical JSON remain available.
|
||||
|
||||
A `@function` definition is also a local callable. Call a decorated function
|
||||
directly with row inputs, or call a decorated class with its initialization fields
|
||||
and then call the returned instance; call `close()` if the class defines it. This
|
||||
@@ -564,6 +583,14 @@ with BlobReader(read_range, len(payload)) as reader:
|
||||
|
||||
::: lancedb.functions.FunctionVersion
|
||||
|
||||
::: lancedb.functions.FunctionEnvironment
|
||||
|
||||
::: lancedb.functions.ResolvedEnvironment
|
||||
|
||||
::: lancedb.functions.ResolvedPackage
|
||||
|
||||
::: lancedb.functions.ResolvedEnvironmentProvenance
|
||||
|
||||
::: lancedb.functions.HuggingFaceModel
|
||||
|
||||
::: lancedb.functions.PythonRuntimeSpec
|
||||
|
||||
@@ -177,14 +177,51 @@ for info in db.list_jobs(page_limit=50):
|
||||
live `Job` handles. Open an ID to inspect its full record. `page_limit` bounds
|
||||
each server request, not the total yielded items, and `page_token` resumes a
|
||||
listing. It is a lazy iterator: iteration performs requests and can raise
|
||||
request errors. To materialize it, use `list(db.list_jobs(...))`; it does not
|
||||
support list indexing, `len()`, or a `.to_list()` method.
|
||||
request errors. Use `list(db.list_jobs(...))` to collect all remaining results;
|
||||
there is no `.to_list()` method.
|
||||
|
||||
`Listing.num_page_results()` reports cached items remaining in the current
|
||||
page and `Listing.page_token()` reports the next request's token. Drain the
|
||||
cached items before saving that token, or resuming can skip them. A `None`
|
||||
token after the final page can coexist with unread cached items. A resumed
|
||||
listing is not a transactionally frozen view of jobs submitted in the meantime.
|
||||
<Note>
|
||||
Job filters and synchronous `Listing` indexing, slicing, and `len()` require
|
||||
a Python SDK release that includes these APIs. Older SDKs expose only
|
||||
`page_token` and `page_limit`; collect results with `list(...)` before indexing
|
||||
or counting them. Filtering also requires a matching Enterprise server that
|
||||
supports the requested filters.
|
||||
</Note>
|
||||
|
||||
Filter jobs on the server before pagination with `table`, `state`, `job_type`
|
||||
or `job_types`, and creation-time bounds. `table` names a table in
|
||||
`namespace_path` (the root by default) and includes all its branches. Requests
|
||||
stay scoped to the connected database. Creation times are Unix milliseconds:
|
||||
`created_at_gte_millis` is inclusive and `created_at_lt_millis` is exclusive.
|
||||
Choose either `job_type` or `job_types`.
|
||||
|
||||
The `state` filter uses registry states: `in_progress`, `succeeded`, `failed`,
|
||||
`canceled`, and `timed_out`. These differ from the SDK lifecycle labels such
|
||||
as `running` and `finished` returned in `JobInfo.state`.
|
||||
|
||||
```python
|
||||
jobs = db.list_jobs(table="events", state="in_progress", page_limit=5)
|
||||
first_five = jobs[:5]
|
||||
for info in first_five:
|
||||
print(info.job_id, info.state)
|
||||
```
|
||||
|
||||
Synchronous indexing and slicing refer to the remaining results without
|
||||
consuming them. A bounded forward slice such as `jobs[:5]` fetches only enough
|
||||
pages to reach its stop. `len(jobs)` returns the remaining count by fetching
|
||||
and caching every remaining result. Negative indexes and open-ended or reverse
|
||||
slices also fetch and cache all remaining results. These operations can raise
|
||||
request errors; later iteration drains their cache. `AsyncListing` remains an
|
||||
async iterator: use `async for` to read it.
|
||||
|
||||
`Listing.num_page_results()` reports cached items available without another
|
||||
request, including items retained by indexing, slicing, or counting.
|
||||
`Listing.page_token()` reports the next request's token. Drain all cached
|
||||
items before saving that token, or resuming can skip them. Resume with the same
|
||||
filters, for example `db.list_jobs(table="events", state="in_progress",
|
||||
page_token=saved_token, page_limit=5)`. A `None` token after the final page can
|
||||
coexist with unread cached items. A resumed listing is not a transactionally
|
||||
frozen view of jobs submitted in the meantime.
|
||||
|
||||
`events.schema` describes the Arrow response. Use `events.to_pylist()` for
|
||||
Python row dictionaries. Common event columns are `event_seq` (int64), `state`
|
||||
|
||||
@@ -543,6 +543,7 @@
|
||||
"group": "SQL Reference",
|
||||
"pages": [
|
||||
"sql/index",
|
||||
"sql/pagination",
|
||||
"sql/data-types",
|
||||
{
|
||||
"group": "DDL",
|
||||
|
||||
@@ -221,6 +221,13 @@ and check inserted or deleted counts when the SDK returns them. Repeating a
|
||||
merge is only safe when its keys, conditions and update values produce the
|
||||
intended result on retry.
|
||||
|
||||
To override the transport retry budget for one merge, pass `retries=0` to
|
||||
Python's synchronous or asynchronous `builder.execute(data, retries=0)`, or
|
||||
use TypeScript's `builder.execute(data, { retries: 0 })`. The override applies
|
||||
only to that execution. A larger budget does not make an ambiguous 5xx result
|
||||
safe to replay. See [write retry boundaries](/ingestion/insert#performance)
|
||||
for the distinction between retryable failures and an unknown commit outcome.
|
||||
|
||||
### Embeddings and expression predicates {#advanced}
|
||||
|
||||
When a table uses an [embedding definition](/embedding), behavior depends on
|
||||
|
||||
@@ -104,6 +104,81 @@ at all is the struct's own validity, which Enterprise keeps in a separate
|
||||
internal column when it expands the result into sibling columns, so a null
|
||||
field is a value rather than a missing row.
|
||||
|
||||
### Timestamps and durations {#timestamps-durations}
|
||||
|
||||
Bare `datetime` keeps its existing `timestamp[us]` default without a timezone.
|
||||
For any other unit or a timezone, declare the Arrow type explicitly:
|
||||
|
||||
```python
|
||||
from datetime import datetime
|
||||
from typing import Annotated
|
||||
|
||||
import pyarrow as pa
|
||||
|
||||
|
||||
@function
|
||||
def normalize(
|
||||
ts: Annotated[datetime, pa.timestamp("ns", tz="UTC")],
|
||||
) -> Annotated[datetime, pa.timestamp("ns", tz="UTC")]:
|
||||
...
|
||||
```
|
||||
|
||||
`pa.timestamp` accepts `s`, `ms`, `us`, and `ns`, and a timezone such as
|
||||
`UTC`, `America/New_York`, or `+08:00`. The canonical signature uses
|
||||
`{"type":"timestamp:<unit>:<timezone>"}`, with `-` for no timezone; the
|
||||
microsecond/no-timezone case keeps the legacy `{"type":"timestamp"}` shape.
|
||||
A timezone string of `-` is reserved for "no timezone" and is rejected.
|
||||
|
||||
`pa.duration` accepts the same four units and uses
|
||||
`{"type":"duration:<unit>"}`; the microsecond case keeps the legacy
|
||||
`{"type":"duration"}` shape. A bare `timedelta` has no unit and is rejected;
|
||||
use `Annotated[timedelta, pa.duration("s")]` or an explicit schema.
|
||||
|
||||
Other units are never downgraded to microseconds. A reader that predates the
|
||||
compound temporal representation cannot read those signatures. A deployment
|
||||
must include the corresponding Lance Namespace and Sophon support; this
|
||||
client-side declaration does not add server support.
|
||||
|
||||
### Maps and decimals {#maps-decimals}
|
||||
|
||||
A `dict[str, T]` annotation declares an Arrow map with a non-nullable `utf8`
|
||||
key. A plain `T` value is non-nullable; annotate `dict[str, Optional[T]]` for
|
||||
nullable values. An explicit `pa.map_(...)` schema preserves the value field's
|
||||
own `nullable` flag:
|
||||
|
||||
```python
|
||||
@function
|
||||
def word_counts(text: str) -> dict[str, int]:
|
||||
...
|
||||
```
|
||||
|
||||
Map keys must be non-nullable `utf8`; `keys_sorted=True` is not supported, and
|
||||
Blob v2 values inside a map are not supported.
|
||||
|
||||
`Decimal` carries no precision or scale by itself, so a bare `Decimal`
|
||||
annotation is rejected. Declare both explicitly with `Annotated`, or use an
|
||||
explicit Arrow schema:
|
||||
|
||||
```python
|
||||
from decimal import Decimal
|
||||
from typing import Annotated
|
||||
|
||||
import pyarrow as pa
|
||||
|
||||
|
||||
@function
|
||||
def add_tax(
|
||||
amount: Annotated[Decimal, pa.decimal128(12, 2)],
|
||||
) -> Annotated[Decimal, pa.decimal128(12, 2)]:
|
||||
...
|
||||
```
|
||||
|
||||
`decimal128` and `decimal256` keep the declared precision and scale in the
|
||||
canonical signature; no default is chosen. Map and decimal signatures are sent
|
||||
as canonical Arrow JSON. A deployment must support those types; an older
|
||||
Enterprise server may reject the registration, and this client-side
|
||||
declaration does not add server support.
|
||||
|
||||
## Connect and create a table {#table}
|
||||
|
||||
The remaining steps run against your Enterprise deployment. Replace the database
|
||||
@@ -143,6 +218,13 @@ with `db.get_function(name, version=...)`. The version may be an integer or
|
||||
its string form. Omit `version` to resolve and return the latest currently
|
||||
visible revision.
|
||||
|
||||
Re-registering unchanged code reuses the published version and its resolved
|
||||
environment lock. Pass `refresh_lock=True` to `create_function` or
|
||||
`create_function_async` to request a fresh lock for this registration. It is a
|
||||
registration action, not part of the Function's source or runtime identity.
|
||||
A deployment must support the field; an older server rejects the unknown
|
||||
field rather than silently reusing the old lock.
|
||||
|
||||
{/* Draft for the function exist_ok release.
|
||||
|
||||
Use `exist_ok=True` on `create_function` or `create_function_async` to return
|
||||
@@ -198,7 +280,9 @@ let latest = connection.get_function_latest("double", &[]).await?;
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
SHOW FUNCTIONS
|
||||
SHOW FUNCTIONS IN "analytics" WITH (name = 'double', limit = 100)
|
||||
SHOW FUNCTIONS IN "analytics" LIMIT 100
|
||||
SHOW FUNCTIONS HISTORY IN "analytics" LIMIT 100
|
||||
SHOW FUNCTIONS HISTORY IN "analytics" LIMIT 100 FROM '<page-token>'
|
||||
|
||||
DESCRIBE FUNCTION double WITH (version = '1')
|
||||
DESCRIBE FUNCTION double
|
||||
@@ -211,6 +295,117 @@ are not included; list each namespace separately. A version's
|
||||
`created_at_millis`, `metadata`, `disabled` flag, and `secret_bindings` are
|
||||
all readable this way without applying or calling the function.
|
||||
|
||||
### Inspect the resolved environment {#resolved-environment}
|
||||
|
||||
The version keeps the requested runtime separate from what the server actually
|
||||
installed. The typed catalog API is available in Python and Rust; TypeScript
|
||||
does not yet expose this readback API. `version.runtime` is the specification
|
||||
sent at registration. `version.resolved_environment` is measured data from the
|
||||
built image:
|
||||
|
||||
<CodeGroup>
|
||||
```python
|
||||
version = db.get_function("double")
|
||||
print(version.runtime) # requested runtime, or None for legacy
|
||||
print(version.environment.resolved) # measured environment, or None for legacy
|
||||
print(version.environment_report) # platform -> measured environment map
|
||||
|
||||
if version.environment.resolved is not None:
|
||||
for package in version.environment.resolved.packages:
|
||||
print(package.name, package.version) # versions keep labels such as +cu130
|
||||
```
|
||||
|
||||
{/* Draft for the typed Rust environment inspection release.
|
||||
```rust
|
||||
# async fn inspect_environment(connection: &lancedb::Connection) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let version = connection.get_function_latest("double", &[]).await?;
|
||||
println!("Requested runtime: {:?}", version.runtime());
|
||||
|
||||
if let Some(environment) = version.resolved_environment() {
|
||||
for package in &environment.packages {
|
||||
println!("{} {}", package.name, package.version);
|
||||
}
|
||||
}
|
||||
|
||||
for (platform, environment) in version.resolved_environments() {
|
||||
println!("{platform}: {} measured packages", environment.packages.len());
|
||||
for package in &environment.packages {
|
||||
println!("{} {}", package.name, package.version);
|
||||
}
|
||||
}
|
||||
# Ok(())
|
||||
# }
|
||||
```
|
||||
*/}
|
||||
</CodeGroup>
|
||||
|
||||
`version.environment.requested` and `version.environment.resolved` are
|
||||
convenience members over the same canonical fields; they do not add another
|
||||
wire shape. The canonical JSON exposes top-level `runtime` and
|
||||
`resolved_environment`. A missing `resolved_environment` means the version or
|
||||
environment cache predates measurement; it is unknown, not an empty installed
|
||||
package list. A package's `source` is present only when the submitted lock
|
||||
retained it, and provenance fields are reported without client-side guessing.
|
||||
|
||||
For a multiarchitecture image, the scalar field is absent and
|
||||
`version.resolved_environments` (also available as
|
||||
`version.environment_report`) maps OCI `os/architecture` keys to the measured
|
||||
environment for that platform. A missing platform key means its measurement is
|
||||
unknown; an empty `packages` list inside a key is a measured empty environment
|
||||
and is retained. The SDK never merges platforms or fabricates an aggregate
|
||||
package list.
|
||||
|
||||
The corresponding canonical payload has this shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"runtime": {
|
||||
"kind": "python",
|
||||
"python_version": "3.12",
|
||||
"environment": {"kind": "pip", "packages": ["vllm==0.11.0"]}
|
||||
},
|
||||
"resolved_environment": {
|
||||
"packages": [
|
||||
{
|
||||
"name": "torch",
|
||||
"version": "2.9.0+cu130",
|
||||
"source": "https://packages.example/simple"
|
||||
}
|
||||
],
|
||||
"provenance": {
|
||||
"configured_index_urls": ["https://packages.example/simple"],
|
||||
"resolved_indexes": ["https://packages.example/simple"],
|
||||
"cuda_toolkit": "12.8",
|
||||
"torch_version": "torch==2.9.0+cu130"
|
||||
},
|
||||
"warnings": [
|
||||
"torch resolved to torch==2.9.0+cu130 but is not pinned exactly; add torch==2.9.0+cu130 to pin it."
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The multiarchitecture form has the same package shape per platform:
|
||||
|
||||
```json
|
||||
{
|
||||
"resolved_environments": {
|
||||
"linux/amd64": {
|
||||
"packages": [{"name": "torch", "version": "2.9.0+cu130"}]
|
||||
},
|
||||
"linux/arm64": {
|
||||
"packages": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Environment warnings are part of the registration result. Waiting on
|
||||
`create_function_async(...)` (or calling `create_function`) emits each server
|
||||
warning from the scalar or per-platform measurements as a Python `UserWarning`;
|
||||
`get_function` and `list_functions` read the same version but do not
|
||||
replay those registration warnings.
|
||||
|
||||
## Try it in SQL {#try-sql}
|
||||
|
||||
A registered function is callable in SQL by its name, the same as any other
|
||||
|
||||
@@ -85,7 +85,7 @@ enables them; the SDK methods send the view's SQL query to the deployment. See
|
||||
| --- | --- | --- | --- |
|
||||
| create | `create_function`, `create_function_async` | -- | `CREATE FUNCTION` |
|
||||
| get | `get_function` | -- | `DESCRIBE FUNCTION` |
|
||||
| list | `list_functions` | -- | `SHOW FUNCTIONS` |
|
||||
| list | `list_functions` | -- | `SHOW FUNCTIONS HISTORY` |
|
||||
| drop | `drop_function` | -- | `DROP FUNCTION` |
|
||||
|
||||
<Badge color="red">Enterprise</Badge> A function runs on the server, and only on
|
||||
|
||||
@@ -57,15 +57,21 @@ properties and requires system `USAGE`.
|
||||
|
||||
## SHOW DATABASES {#show}
|
||||
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
SHOW DATABASES
|
||||
```sql
|
||||
SHOW DATABASES LIMIT 100;
|
||||
SHOW DATABASES LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
Returns a sorted `name` column containing the databases the caller has
|
||||
`USAGE` on, including `system` when permitted. `LIKE` and `WHERE` filters
|
||||
are unsupported.
|
||||
Returns one non-null `name` column, sorted by database name and filtered to
|
||||
databases the caller has `USAGE` on, including `system` when permitted.
|
||||
Databases are above namespaces, so this command does not accept `IN` or
|
||||
return a `namespace_path` column.
|
||||
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
## ATTACH DATABASE {#attach}
|
||||
|
||||
|
||||
@@ -135,20 +135,33 @@ from it.
|
||||
|
||||
## SHOW FUNCTIONS {#show}
|
||||
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
SHOW FUNCTIONS
|
||||
SHOW FUNCTIONS HISTORY IN "analytics" WITH (name = 'embed', limit = 100)
|
||||
SHOW FUNCTIONS HISTORY WITH (after_name = 'embed', after_version = '1', limit = 100)
|
||||
```sql
|
||||
SHOW FUNCTIONS IN analytics.`team$ml` LIMIT 100;
|
||||
SHOW FUNCTIONS IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
`SHOW FUNCTIONS` returns the highest published numeric revision for each name.
|
||||
Add `HISTORY` to list every published revision, as Python's `list_functions()`
|
||||
does. Rows are ordered by name and numeric revision, so `2` comes before `10`.
|
||||
`after_name` and `after_version` must be supplied together for keyset pagination.
|
||||
`limit` bounds
|
||||
the response; `include_definition = false` omits the optional definition JSON.
|
||||
Returns two non-null string columns: `namespace_path`, a compact JSON array
|
||||
of parent namespace components (`[]` for root), and `name`, the unqualified
|
||||
object name. Omitting `IN` lists all authorized namespaces in the current database;
|
||||
`IN team$ml` selects that exact path without a database qualifier; `IN public` selects
|
||||
the current database's root. Listings require the relevant database and
|
||||
namespace `USAGE` privileges.
|
||||
|
||||
`SHOW FUNCTIONS` lists each function once. Add `HISTORY` to list every
|
||||
published revision with its metadata and definition, as `list_functions()`
|
||||
does. History uses the same pagination suffix; numeric revision order is
|
||||
encoded in the token, so revision `2` precedes `10`.
|
||||
|
||||
```sql
|
||||
SHOW FUNCTIONS HISTORY IN analytics.`team$ml` LIMIT 100;
|
||||
SHOW FUNCTIONS HISTORY IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
## DROP FUNCTION {#drop}
|
||||
|
||||
|
||||
@@ -70,16 +70,25 @@ automatic execution needs the same server-side switch enabled. Omitting
|
||||
|
||||
## SHOW MATERIALIZED VIEWS {#show}
|
||||
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
SHOW MATERIALIZED VIEWS
|
||||
```sql
|
||||
SHOW MATERIALIZED VIEWS IN analytics.`team$ml` LIMIT 100;
|
||||
SHOW MATERIALIZED VIEWS IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
<Note>
|
||||
This asks the server for its views, as the SDK's `list_materialized_views` does
|
||||
on a `db://` connection.
|
||||
</Note>
|
||||
Returns two non-null string columns: `namespace_path`, a compact JSON array
|
||||
of parent namespace components (`[]` for root), and `name`, the unqualified
|
||||
object name. Omitting `IN` lists all authorized namespaces in the current database;
|
||||
`IN team$ml` selects that exact path without a database qualifier; `IN public` selects
|
||||
the current database's root. Listings require the relevant database and
|
||||
namespace `USAGE` privileges.
|
||||
|
||||
The listing contains identifiers; use `DESCRIBE MATERIALIZED VIEW` for its defining query and refresh metadata.
|
||||
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
## Refreshing one {#refresh}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ backtick-quoted identifier with `$` between components, such as
|
||||
one path component, relative to an explicit parent schema or the session's
|
||||
current schema -- it cannot contain `$` or be qualified with a database.
|
||||
|
||||
`SCHEMA` never accepts `IN`. `NAMESPACE` accepts `IN` followed by a complete
|
||||
For single-object commands, `SCHEMA` never accepts `IN`. `NAMESPACE` accepts `IN` followed by a complete
|
||||
schema identifier. Names are lowercased unless quoted.
|
||||
|
||||
## CREATE SCHEMA and CREATE NAMESPACE {#create}
|
||||
@@ -126,27 +126,30 @@ Requires `USAGE` on the database and the namespace.
|
||||
|
||||
## SHOW SCHEMAS and SHOW NAMESPACES {#show}
|
||||
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
SHOW SCHEMAS
|
||||
SHOW NAMESPACES
|
||||
SHOW NAMESPACES IN analytics.team
|
||||
```sql
|
||||
SHOW SCHEMAS LIMIT 100;
|
||||
SHOW SCHEMAS LIMIT 100 FROM '<page-token>';
|
||||
SHOW NAMESPACES IN analytics.team LIMIT 100;
|
||||
SHOW NAMESPACES IN analytics.team LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
`SHOW SCHEMAS` returns complete paths in the current database, recursively,
|
||||
including `public` when the caller can use it. It does not accept `IN`.
|
||||
Both commands return two non-null string columns: `namespace_path`, the
|
||||
parent path as a compact JSON array, and `name`, the unqualified child name.
|
||||
Results are ordered by parent path components, then name, and omit namespaces
|
||||
the caller cannot use.
|
||||
|
||||
`SHOW NAMESPACES` lists only immediate child names under the session's
|
||||
current schema. `IN` selects a different parent schema, optionally in
|
||||
another database -- use `IN public` for the current database's root, or
|
||||
`IN analytics.public` for another database's root. A missing parent is an
|
||||
error.
|
||||
`SHOW SCHEMAS` and `SHOW NAMESPACES` are equivalent listings. Without `IN`,
|
||||
both list recursively in the current database, include the implicit `public`
|
||||
root, and ignore the session namespace. With `IN`, both list immediate children
|
||||
of the selected parent. A schema path can appear directly: `IN team$features`;
|
||||
a database qualifier is optional. `IN public` selects the current database root,
|
||||
and `IN analytics.public` selects another database's root.
|
||||
|
||||
Both forms return a sorted `name` column and omit namespaces the caller
|
||||
cannot use. Large listings that exceed 10,000 namespaces, or recursive
|
||||
listings deeper than 32 levels, return an error suggesting a narrower
|
||||
listing.
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
## DROP SCHEMA and DROP NAMESPACE {#drop}
|
||||
|
||||
@@ -187,7 +190,6 @@ with `IF EXISTS`. Inspect a cascade drop's child jobs with
|
||||
| `CREATE SCHEMA child IN parent` | `CREATE NAMESPACE child IN parent` or `` CREATE SCHEMA `parent$child` `` |
|
||||
| `` DESCRIBE NAMESPACE `parent$child` `` | `` DESCRIBE SCHEMA `parent$child` `` or `DESCRIBE NAMESPACE child IN parent` |
|
||||
| `DROP NAMESPACE analytics.child` | `DROP NAMESPACE child IN analytics.public` |
|
||||
| `SHOW SCHEMAS IN parent` | `SHOW NAMESPACES IN parent` |
|
||||
|
||||
## What to read next {#next}
|
||||
|
||||
|
||||
+17
-13
@@ -98,21 +98,25 @@ picked up by every Function still bound to that name.
|
||||
|
||||
## SHOW SECRETS {#show}
|
||||
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
SHOW SECRETS
|
||||
SHOW SECRETS IN platform
|
||||
SHOW SECRETS IN analytics.`ml$vision`
|
||||
SHOW SECRETS IN public
|
||||
SHOW SECRETS IN platform WHERE name > 'model-api-key' LIMIT 50
|
||||
```sql
|
||||
SHOW SECRETS IN analytics.`team$ml` LIMIT 100;
|
||||
SHOW SECRETS IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
Lists the Secret names in one namespace as a sorted `name` column. Without
|
||||
`IN`, it lists the session's namespace; `IN public` lists the root. `WHERE
|
||||
name > '<cursor>'` pages past the last name already seen, and `LIMIT`
|
||||
bounds the page size; `WHERE` must compare `name` with `>`. Requires
|
||||
`USAGE` on the database and the namespace.
|
||||
Returns two non-null string columns: `namespace_path`, a compact JSON array
|
||||
of parent namespace components (`[]` for root), and `name`, the unqualified
|
||||
object name. Omitting `IN` lists all authorized namespaces in the current database;
|
||||
`IN team$ml` selects that exact path without a database qualifier; `IN public` selects
|
||||
the current database's root. Listings require the relevant database and
|
||||
namespace `USAGE` privileges.
|
||||
|
||||
Secret listings contain no values or Secret metadata.
|
||||
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
## DESCRIBE SECRET {#describe}
|
||||
|
||||
|
||||
@@ -194,16 +194,25 @@ only the reference naming it.
|
||||
|
||||
## SHOW STORAGE INTEGRATIONS {#show}
|
||||
|
||||
<CodeGroup>
|
||||
```sql SQL icon="database"
|
||||
SHOW STORAGE INTEGRATIONS
|
||||
SHOW STORAGE INTEGRATIONS IN platform
|
||||
LIST STORAGE INTEGRATIONS
|
||||
```sql
|
||||
SHOW STORAGE INTEGRATIONS IN analytics.`team$ml` LIMIT 100;
|
||||
SHOW STORAGE INTEGRATIONS IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
`LIST` is an alias for `SHOW` here. Returns one `name` column; `IN`
|
||||
narrows the listing to one namespace.
|
||||
Returns two non-null string columns: `namespace_path`, a compact JSON array
|
||||
of parent namespace components (`[]` for root), and `name`, the unqualified
|
||||
object name. Omitting `IN` lists all authorized namespaces in the current database;
|
||||
`IN team$ml` selects that exact path without a database qualifier; `IN public` selects
|
||||
the current database's root. Listings require the relevant database and
|
||||
namespace `USAGE` privileges.
|
||||
|
||||
`LIST STORAGE INTEGRATIONS` is an exact alias, including pagination.
|
||||
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
## DROP STORAGE INTEGRATION {#drop}
|
||||
|
||||
|
||||
@@ -268,3 +268,23 @@ deployment stores its catalog. See
|
||||
Renaming, retyping and dropping columns from the SDK.
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## SHOW TABLES {#show}
|
||||
|
||||
```sql
|
||||
SHOW TABLES IN analytics.`team$ml` LIMIT 100;
|
||||
SHOW TABLES IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
|
||||
Returns two non-null string columns: `namespace_path`, a compact JSON array
|
||||
of parent namespace components (`[]` for root), and `name`, the unqualified
|
||||
object name. Omitting `IN` lists all authorized namespaces in the current database;
|
||||
`IN team$ml` selects that exact path without a database qualifier; `IN public` selects
|
||||
the current database's root. Listings require the relevant database and
|
||||
namespace `USAGE` privileges.
|
||||
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
+13
-20
@@ -81,29 +81,22 @@ was none to begin with.
|
||||
## Listing {#listing}
|
||||
|
||||
```sql
|
||||
SHOW VIEWS
|
||||
SHOW VIEWS IN "analytics" WHERE name > 'previous_view' LIMIT 100
|
||||
SHOW VIEWS IN analytics.`team$ml` LIMIT 100;
|
||||
SHOW VIEWS IN analytics.`team$ml` LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
|
||||
`SHOW VIEWS` returns ascending `name` values. The `name` cursor is scoped to
|
||||
the selected namespace.
|
||||
Returns two non-null string columns: `namespace_path`, a compact JSON array
|
||||
of parent namespace components (`[]` for root), and `name`, the unqualified
|
||||
object name. Omitting `IN` lists all authorized namespaces in the current database;
|
||||
`IN team$ml` selects that exact path without a database qualifier; `IN public` selects
|
||||
the current database's root. Listings require the relevant database and
|
||||
namespace `USAGE` privileges.
|
||||
|
||||
Object commands retain their small results in shared storage even when general
|
||||
query-result copying is disabled, so asynchronous polling can use any query node.
|
||||
|
||||
Views and tables share a namespace, and both are things you can query. The
|
||||
catalog distinguishes them:
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| view names | the views in the database |
|
||||
| table names | the tables |
|
||||
| relation names | everything queryable (both) |
|
||||
|
||||
Use the relation listing when the question is "what can I select from," and the
|
||||
separate listings when the distinction matters: before dropping, for
|
||||
instance, since dropping a view removes only the saved query while dropping a
|
||||
table removes data.
|
||||
Page through results using `LIMIT n [FROM '<page-token>']`. Read the opaque
|
||||
`lancedb.next_page_token` from the Arrow result schema metadata and pass it back
|
||||
unchanged with the same object type and scope. Stop when no token is returned;
|
||||
a short or empty page can still carry a continuation. See
|
||||
[catalog listing pagination](/sql/pagination).
|
||||
|
||||
## Choosing between a view and a materialized view {#choosing}
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
title: "Catalog listing pagination"
|
||||
description: "Use one continuation-token syntax for SQL catalog listings."
|
||||
---
|
||||
|
||||
Catalog `SHOW` statements share one pagination suffix:
|
||||
|
||||
```sql
|
||||
SHOW <objects> [IN <scope>] [LIMIT <count> [FROM '<page-token>']];
|
||||
```
|
||||
|
||||
This applies to tables, views, materialized views, functions and function
|
||||
history, secrets, storage integrations, namespaces/schemas, and databases.
|
||||
|
||||
```sql
|
||||
SHOW TABLES LIMIT 100;
|
||||
SHOW TABLES IN team$ml LIMIT 100;
|
||||
SHOW TABLES IN team$ml LIMIT 100 FROM '<page-token>';
|
||||
SHOW TABLES IN analytics.team$ml LIMIT 100;
|
||||
SHOW DATABASES LIMIT 100 FROM '<page-token>';
|
||||
```
|
||||
|
||||
## Namespace scope
|
||||
|
||||
`IN` is optional. Without it, listings include root and every authorized
|
||||
namespace in the current database, regardless of the session's default namespace.
|
||||
With `IN`, objects are listed only in that exact namespace. The scope accepts a
|
||||
schema directly: `IN team$ml` means the absolute namespace path `["team", "ml"]`
|
||||
in the current database. Use `IN public` for root, or `IN other_db.team$ml` to
|
||||
select a different database. Quote schema identifiers containing punctuation or
|
||||
mixed case, for example `IN "Team$ML"`.
|
||||
|
||||
`SHOW SCHEMAS` and `SHOW NAMESPACES` use the same rules: without `IN` they
|
||||
include all namespace paths and the public root; with `IN` they list the
|
||||
selected parent's immediate children. `SHOW DATABASES` remains global and
|
||||
does not accept `IN`.
|
||||
|
||||
SDK APIs that take a namespace send an explicit `IN` clause and continue to
|
||||
list that one namespace.
|
||||
|
||||
## Continuation metadata
|
||||
|
||||
The Arrow result schema carries `lancedb.next_page_token` when more results
|
||||
remain. Pass that opaque value unchanged in `FROM` on the next request.
|
||||
The token identifies the object type, database, namespace scope, and complete
|
||||
position, including namespace path and any numeric revision. It cannot be
|
||||
reused with another object type or scope.
|
||||
|
||||
The token is metadata, not an additional result column or a synthetic row.
|
||||
Namespace-scoped object listings contain `namespace_path` and `name`;
|
||||
databases contain only `name`. Function history retains revision metadata.
|
||||
SDK listing APIs expose this server-issued value as the page's `page_token`.
|
||||
|
||||
Continue until no token is returned. A short or empty page may still have a
|
||||
token. Pages observe the live catalog; continuation does not create a snapshot.
|
||||
|
||||
## Page size and ordering
|
||||
|
||||
The default page limit is 1,000, with a maximum of 10,000. `LIMIT 0` returns
|
||||
no rows. Object catalogs order identifiers by namespace path components and
|
||||
unqualified name; database names are ordered by name. Table page boundaries
|
||||
follow native catalog order, which may differ from logical name order for
|
||||
directory-backed tables; table names are sorted within each returned page. Function history uses
|
||||
numeric revision order within each name. The token preserves that complete
|
||||
position, including when names repeat in different namespaces.
|
||||
|
||||
The old name-comparison `WHERE` and Function `WITH` pagination forms are no
|
||||
longer supported. Use the same `LIMIT ... FROM ...` suffix for every listing.
|
||||
@@ -8,7 +8,7 @@
|
||||
<parent>
|
||||
<groupId>com.lancedb</groupId>
|
||||
<artifactId>lancedb-parent</artifactId>
|
||||
<version>0.42.0-beta.13</version>
|
||||
<version>0.42.0-beta.15</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
+2
-2
@@ -6,7 +6,7 @@
|
||||
|
||||
<groupId>com.lancedb</groupId>
|
||||
<artifactId>lancedb-parent</artifactId>
|
||||
<version>0.42.0-beta.13</version>
|
||||
<version>0.42.0-beta.15</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>${project.artifactId}</name>
|
||||
<description>LanceDB Java SDK Parent POM</description>
|
||||
@@ -28,7 +28,7 @@
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<arrow.version>15.0.0</arrow.version>
|
||||
<lance-core.version>15.0.0-beta.21</lance-core.version>
|
||||
<lance-core.version>15.0.0-beta.22</lance-core.version>
|
||||
<jackson.version>2.18.12</jackson.version>
|
||||
<spotless.skip>false</spotless.skip>
|
||||
<spotless.version>2.30.0</spotless.version>
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "lancedb-nodejs"
|
||||
edition.workspace = true
|
||||
version = "0.42.0-beta.13"
|
||||
version = "0.42.0-beta.15"
|
||||
publish = false
|
||||
license.workspace = true
|
||||
description.workspace = true
|
||||
|
||||
+200
-10
@@ -542,6 +542,163 @@ describe("remote connection", () => {
|
||||
expect(attempts).toBe(scenario.attempts);
|
||||
});
|
||||
|
||||
it.each(
|
||||
[409, 429, 502, 503, 504].flatMap((status) =>
|
||||
[undefined, 0, 2].flatMap((retries) =>
|
||||
[[], ["analytics", "features"]].map((namespacePath) => ({
|
||||
status,
|
||||
retries,
|
||||
namespacePath,
|
||||
})),
|
||||
),
|
||||
),
|
||||
)("applies per-call merge retries: %j", async (scenario) => {
|
||||
let attempts = 0;
|
||||
const identifier = [...scenario.namespacePath, "items"].join("$");
|
||||
const succeeds =
|
||||
[409, 429].includes(scenario.status) && scenario.retries !== 0;
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
const url = new URL(req.url ?? "", "http://localhost");
|
||||
if (url.pathname === `/v1/table/${identifier}/describe/`) {
|
||||
res.writeHead(200).end(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
schema: {
|
||||
fields: [
|
||||
{ name: "id", type: { type: "int64" }, nullable: true },
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const chunks: Buffer[] = [];
|
||||
req.on("data", (chunk) => chunks.push(chunk));
|
||||
req.on("end", () => {
|
||||
try {
|
||||
expect(url.pathname).toBe(`/v1/table/${identifier}/merge_insert/`);
|
||||
expect(url.searchParams.get("use_index")).toBe("false");
|
||||
expect(req.headers["x-request-timeout-ms"]).toBe("10000");
|
||||
// Rust compresses the batches; Arrow JS can inspect the schema without a codec.
|
||||
const reader = RecordBatchReader.from(Buffer.concat(chunks)).open();
|
||||
expect(reader.schema.fields.map((field) => field.name)).toEqual([
|
||||
"id",
|
||||
]);
|
||||
} finally {
|
||||
attempts++;
|
||||
res
|
||||
.writeHead(attempts === 1 ? scenario.status : 200)
|
||||
.end('{"version":2}');
|
||||
}
|
||||
});
|
||||
},
|
||||
async (db) => {
|
||||
const table = await db.openTable("items", scenario.namespacePath);
|
||||
const merge = table
|
||||
.mergeInsert("id")
|
||||
.whenNotMatchedInsertAll()
|
||||
.useIndex(false);
|
||||
const result = merge.execute([{ id: 1n }], {
|
||||
timeoutMs: 10_000,
|
||||
retries: scenario.retries,
|
||||
});
|
||||
if (succeeds) {
|
||||
await expect(result).resolves.toMatchObject({ version: 2 });
|
||||
} else {
|
||||
await expect(result).rejects.toThrow();
|
||||
}
|
||||
},
|
||||
{
|
||||
clientConfig: {
|
||||
retryConfig: {
|
||||
retries: 3,
|
||||
statuses: [409, 429, 502, 503, 504],
|
||||
backoffFactor: 0,
|
||||
backoffJitter: 0,
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(attempts).toBe(succeeds ? 2 : 1);
|
||||
});
|
||||
|
||||
it("isolates merge retry overrides across reused builders and reads", async () => {
|
||||
let attempts = 0;
|
||||
let readAttempts = 0;
|
||||
await withMockDatabase(
|
||||
(req, res) => {
|
||||
if (req.url?.endsWith("/describe/")) {
|
||||
res.writeHead(200).end(
|
||||
JSON.stringify({
|
||||
version: 1,
|
||||
schema: {
|
||||
fields: [
|
||||
{ name: "id", type: { type: "int64" }, nullable: true },
|
||||
],
|
||||
},
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
req.resume();
|
||||
req.on("end", () => {
|
||||
if (req.url?.endsWith("/count_rows/")) {
|
||||
readAttempts++;
|
||||
res.writeHead(readAttempts % 2 ? 429 : 200).end("1");
|
||||
} else {
|
||||
attempts++;
|
||||
res
|
||||
.writeHead([1, 2, 4, 6].includes(attempts) ? 429 : 200)
|
||||
.end('{"version":2}');
|
||||
expect(req.url).toContain("/merge_insert/");
|
||||
}
|
||||
});
|
||||
},
|
||||
async (db) => {
|
||||
const table = await db.openTable("items");
|
||||
const merge = table.mergeInsert("id").whenNotMatchedInsertAll();
|
||||
for (const retries of [
|
||||
-1,
|
||||
256,
|
||||
1.5,
|
||||
Number.NaN,
|
||||
Number.POSITIVE_INFINITY,
|
||||
]) {
|
||||
await expect(
|
||||
merge.execute([{ id: 1n }], { retries }),
|
||||
).rejects.toThrow("retries must be an integer between 0 and 255");
|
||||
}
|
||||
expect(attempts).toBe(0);
|
||||
await expect(
|
||||
merge.execute([{ id: 1n }], { retries: 0 }),
|
||||
).rejects.toThrow();
|
||||
expect(attempts).toBe(1);
|
||||
await expect(merge.execute([{ id: 1n }])).resolves.toMatchObject({
|
||||
version: 2,
|
||||
});
|
||||
await expect(
|
||||
merge.execute([{ id: 1n }], { retries: 255 }),
|
||||
).resolves.toMatchObject({ version: 2 });
|
||||
expect(attempts).toBe(5);
|
||||
await expect(table.countRows()).resolves.toBe(1);
|
||||
expect(readAttempts).toBe(2);
|
||||
await expect(
|
||||
table
|
||||
.mergeInsert("id")
|
||||
.whenNotMatchedInsertAll()
|
||||
.execute([{ id: 1n }]),
|
||||
).resolves.toMatchObject({ version: 2 });
|
||||
expect(attempts).toBe(7);
|
||||
},
|
||||
{
|
||||
clientConfig: {
|
||||
retryConfig: { retries: 3, backoffFactor: 0, backoffJitter: 0 },
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("should accept partial connection options", async () => {
|
||||
await connect("db://test", {
|
||||
apiKey: "fake",
|
||||
@@ -2161,10 +2318,30 @@ describe("remote connection jobs surface", () => {
|
||||
queue_reason: "Waiting for Function worker capacity",
|
||||
});
|
||||
const descriptions = [
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 3000, unknownFleet)}}`,
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(20, 80, 2000, knownFleet)}}`,
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(40, 60, 1000, unknownFleet)}}`,
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress(60, 0, 0, unknownFleet)}}`,
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(
|
||||
20,
|
||||
80,
|
||||
3000,
|
||||
unknownFleet,
|
||||
)}}`,
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(
|
||||
20,
|
||||
80,
|
||||
2000,
|
||||
knownFleet,
|
||||
)}}`,
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"queue_reason":"Waiting for Function worker capacity","progress":${progress(
|
||||
40,
|
||||
60,
|
||||
1000,
|
||||
unknownFleet,
|
||||
)}}`,
|
||||
`{"job_id":"job-wait","job_type":"refresh_column","job_state":"DONE","creation_ms":1000,"result":{},"progress":${progress(
|
||||
60,
|
||||
0,
|
||||
0,
|
||||
unknownFleet,
|
||||
)}}`,
|
||||
];
|
||||
let describeCount = 0;
|
||||
|
||||
@@ -2236,12 +2413,24 @@ describe("remote connection jobs surface", () => {
|
||||
it("does not derive ETA across a zero-rate, epoch, or pause boundary", async () => {
|
||||
const now = Date.now();
|
||||
const descriptions = [
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 5000}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${now - 4000}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 3000}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 2000}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1500}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${now - 1000}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${
|
||||
now - 5000
|
||||
}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":20,"rows_skipped":0,"rows_remaining":80,"fragments_planned":4,"execution_epoch":1,"sample_at_millis":${
|
||||
now - 4000
|
||||
}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":40,"rows_skipped":0,"rows_remaining":60,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${
|
||||
now - 3000
|
||||
}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"phase":"initializing","progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${
|
||||
now - 2000
|
||||
}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"paused_at_millis":5000,"progress":{"rows_planned":100,"rows_computed":60,"rows_skipped":0,"rows_remaining":40,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${
|
||||
now - 1500
|
||||
}}}`,
|
||||
`{"job_id":"job-eta","job_type":"refresh_column","job_state":"IN_PROGRESS","creation_ms":1000,"progress":{"rows_planned":100,"rows_computed":80,"rows_skipped":0,"rows_remaining":20,"fragments_planned":4,"execution_epoch":2,"sample_at_millis":${
|
||||
now - 1000
|
||||
}}}`,
|
||||
];
|
||||
|
||||
await withMockDatabase(
|
||||
@@ -2417,6 +2606,7 @@ describe("lazy resource listings", () => {
|
||||
if (kind === "jobs") {
|
||||
expect(url.pathname).toBe("/v1/jobs/list");
|
||||
expect(request.body).toEqual({
|
||||
database: "dev",
|
||||
// biome-ignore lint/style/useNamingConvention: server wire format
|
||||
page_token: token,
|
||||
limit: 2,
|
||||
|
||||
@@ -938,7 +938,8 @@ describe("merge insert", () => {
|
||||
.mergeInsert("a")
|
||||
.whenMatchedUpdateAll()
|
||||
.whenNotMatchedInsertAll()
|
||||
.execute(newData, { timeoutMs: 10_000 });
|
||||
.useIndex(false)
|
||||
.execute(newData, { timeoutMs: 10_000, retries: 0 });
|
||||
expect(mergeInsertRes).toHaveProperty("version");
|
||||
expect(mergeInsertRes.version).toBe(2);
|
||||
expect(mergeInsertRes.numInsertedRows).toBe(1);
|
||||
|
||||
+27
-1
@@ -127,6 +127,14 @@ export class MergeInsertBuilder {
|
||||
data: Data,
|
||||
execOptions?: Partial<WriteExecutionOptions>,
|
||||
): Promise<MergeResult> {
|
||||
if (
|
||||
execOptions?.retries !== undefined &&
|
||||
(!Number.isInteger(execOptions.retries) ||
|
||||
execOptions.retries < 0 ||
|
||||
execOptions.retries > 255)
|
||||
) {
|
||||
throw new Error("retries must be an integer between 0 and 255");
|
||||
}
|
||||
let schema: Schema;
|
||||
if (this.#schema instanceof Promise) {
|
||||
schema = await this.#schema;
|
||||
@@ -140,7 +148,7 @@ export class MergeInsertBuilder {
|
||||
}
|
||||
|
||||
const buffer = await fromDataToBuffer(data, undefined, schema);
|
||||
return await this.#native.execute(buffer);
|
||||
return await this.#native.execute(buffer, execOptions?.retries);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,6 +164,24 @@ export interface WriteExecutionOptions {
|
||||
* first attempt will not be cancelled.
|
||||
*
|
||||
* When this is set, the timeout is enforced on all attempts, including the first.
|
||||
* For remote tables this is sent as a server execution timeout. It does not
|
||||
* extend HTTP read or proxy idle timeouts, or prove that a failed request did
|
||||
* not commit.
|
||||
*/
|
||||
timeoutMs?: number;
|
||||
|
||||
/**
|
||||
* Override the remote retry budget for this execution only (an integer from
|
||||
* 0 to 255). Use `execute(data, { retries: 0 })` to disable even retries after
|
||||
* precommit conflicts (409) or rate limits (429). This does not change
|
||||
* connection-wide/read budgets or local transaction conflict retries.
|
||||
*
|
||||
* By default, remote calls use the connection's `clientConfig.retryConfig`
|
||||
* ({@link RetryConfig}). Its `statuses` (also set through
|
||||
* `LANCE_CLIENT_RETRY_STATUSES`) selects candidates within the retry budget;
|
||||
* it never permits replay of ambiguous merge outcomes. In particular, 502,
|
||||
* ordinary 503, and 504 are never replayed, even if configured. Reconcile table
|
||||
* contents before manually repeating a merge whose commit outcome is unknown.
|
||||
*/
|
||||
retries?: number;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-darwin-arm64",
|
||||
"version": "0.42.0-beta.13",
|
||||
"version": "0.42.0-beta.15",
|
||||
"os": ["darwin"],
|
||||
"cpu": ["arm64"],
|
||||
"main": "lancedb.darwin-arm64.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-linux-arm64-gnu",
|
||||
"version": "0.42.0-beta.13",
|
||||
"version": "0.42.0-beta.15",
|
||||
"os": ["linux"],
|
||||
"cpu": ["arm64"],
|
||||
"main": "lancedb.linux-arm64-gnu.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-linux-arm64-musl",
|
||||
"version": "0.42.0-beta.13",
|
||||
"version": "0.42.0-beta.15",
|
||||
"os": ["linux"],
|
||||
"cpu": ["arm64"],
|
||||
"main": "lancedb.linux-arm64-musl.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-linux-x64-gnu",
|
||||
"version": "0.42.0-beta.13",
|
||||
"version": "0.42.0-beta.15",
|
||||
"os": ["linux"],
|
||||
"cpu": ["x64"],
|
||||
"main": "lancedb.linux-x64-gnu.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-linux-x64-musl",
|
||||
"version": "0.42.0-beta.13",
|
||||
"version": "0.42.0-beta.15",
|
||||
"os": ["linux"],
|
||||
"cpu": ["x64"],
|
||||
"main": "lancedb.linux-x64-musl.node",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-win32-arm64-msvc",
|
||||
"version": "0.42.0-beta.13",
|
||||
"version": "0.42.0-beta.15",
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@lancedb/lancedb-win32-x64-msvc",
|
||||
"version": "0.42.0-beta.13",
|
||||
"version": "0.42.0-beta.15",
|
||||
"os": ["win32"],
|
||||
"cpu": ["x64"],
|
||||
"main": "lancedb.win32-x64-msvc.node",
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
"ann"
|
||||
],
|
||||
"private": false,
|
||||
"version": "0.42.0-beta.13",
|
||||
"version": "0.42.0-beta.15",
|
||||
"main": "dist/index.js",
|
||||
"exports": {
|
||||
".": "./dist/index.js",
|
||||
|
||||
+7
-2
@@ -65,12 +65,17 @@ impl NativeMergeInsertBuilder {
|
||||
}
|
||||
|
||||
#[napi(catch_unwind)]
|
||||
pub async fn execute(&self, buf: Buffer) -> napi::Result<MergeResult> {
|
||||
pub async fn execute(&self, buf: Buffer, retries: Option<u32>) -> napi::Result<MergeResult> {
|
||||
let data = ipc_file_to_batches(buf.to_vec()).map_err(|e| {
|
||||
napi::Error::from_reason(format!("Failed to read IPC file: {}", convert_error(&e)))
|
||||
})?;
|
||||
|
||||
let this = self.clone();
|
||||
let mut this = self.clone();
|
||||
if let Some(retries) = retries {
|
||||
let retries = u8::try_from(retries)
|
||||
.map_err(|_| napi::Error::from_reason("retries must be between 0 and 255"))?;
|
||||
this.inner.retries(retries);
|
||||
}
|
||||
|
||||
let res = this.inner.execute(data).await.map_err(|e| {
|
||||
napi::Error::from_reason(format!(
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "lancedb-python"
|
||||
version = "0.42.0-beta.13"
|
||||
version = "0.42.0-beta.15"
|
||||
publish = false
|
||||
edition.workspace = true
|
||||
description = "Python bindings for LanceDB"
|
||||
|
||||
@@ -64,7 +64,7 @@ tests = [
|
||||
"polars>=0.19, <=1.32.3",
|
||||
"pyarrow>=16",
|
||||
"pyarrow-stubs>=16.0",
|
||||
"pylance==15.0.0b21",
|
||||
"pylance==15.0.0b22",
|
||||
"requests>=2.31.0",
|
||||
"datafusion>=54,<55",
|
||||
"opentelemetry-sdk>=1.30.0",
|
||||
|
||||
@@ -51,11 +51,15 @@ from .functions import (
|
||||
FunctionApplication as FunctionApplication,
|
||||
FunctionBinding as FunctionBinding,
|
||||
FunctionDefinition as FunctionDefinition,
|
||||
FunctionEnvironment as FunctionEnvironment,
|
||||
FunctionRegistrationRequest as FunctionRegistrationRequest,
|
||||
FunctionRetryPolicy as FunctionRetryPolicy,
|
||||
FunctionVersion as FunctionVersion,
|
||||
HuggingFaceModel as HuggingFaceModel,
|
||||
PythonRuntimeSpec as PythonRuntimeSpec,
|
||||
ResolvedEnvironment as ResolvedEnvironment,
|
||||
ResolvedEnvironmentProvenance as ResolvedEnvironmentProvenance,
|
||||
ResolvedPackage as ResolvedPackage,
|
||||
RefreshColumnResult as RefreshColumnResult,
|
||||
function as function,
|
||||
udf as udf,
|
||||
|
||||
@@ -300,7 +300,19 @@ class Connection(object):
|
||||
page_limit: Optional[int] = None,
|
||||
) -> NameListing: ...
|
||||
def list_jobs(
|
||||
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
page_token: Optional[str] = None,
|
||||
page_limit: Optional[int] = None,
|
||||
table: Optional[str] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
state: Optional[
|
||||
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
|
||||
] = None,
|
||||
job_type: Optional[str] = None,
|
||||
job_types: Optional[List[str]] = None,
|
||||
created_at_gte_millis: Optional[int] = None,
|
||||
created_at_lt_millis: Optional[int] = None,
|
||||
) -> JobListing: ...
|
||||
async def cancel_job(self, job_id: str) -> bool: ...
|
||||
async def pause_job(self, job_id: str) -> str: ...
|
||||
@@ -565,6 +577,12 @@ class Table:
|
||||
allow_external_blob_outside_bases: bool = False,
|
||||
retries: Optional[int] = None,
|
||||
) -> AddResult: ...
|
||||
async def execute_merge_insert(
|
||||
self,
|
||||
data: pa.RecordBatchReader,
|
||||
parameters: Dict[str, Any],
|
||||
retries: Optional[int] = None,
|
||||
) -> MergeResult: ...
|
||||
async def update(
|
||||
self, updates: Dict[str, str], where: Optional[str]
|
||||
) -> UpdateResult: ...
|
||||
@@ -925,6 +943,7 @@ class FTSQuery:
|
||||
def add_query_vector(self, query_vec: pa.Array) -> None: ...
|
||||
def nearest_to(self, query_vec: pa.Array) -> HybridQuery: ...
|
||||
def order_by(self, ordering: Optional[List[ColumnOrdering]]): ...
|
||||
async def count_rows(self) -> int: ...
|
||||
async def output_schema(self) -> pa.Schema: ...
|
||||
async def execute(
|
||||
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
|
||||
|
||||
+182
-21
@@ -154,6 +154,38 @@ def _normalize_function_version(version: Optional[Union[int, str]]) -> Optional[
|
||||
raise TypeError("version must be an int, str, or None")
|
||||
|
||||
|
||||
def _function_registration_decoder():
|
||||
"""Parse a registration result and emit its server warnings once.
|
||||
|
||||
The warnings come from the scalar environment or, for a multiarchitecture
|
||||
image, each measured platform entry. They are part of the registration job
|
||||
result, not a new client-side package policy. Catalog get/list readbacks
|
||||
use ``FunctionVersion.from_json`` directly and therefore do not replay
|
||||
them.
|
||||
"""
|
||||
warned = False
|
||||
|
||||
def decode(payload: str) -> FunctionVersion:
|
||||
nonlocal warned
|
||||
version = FunctionVersion.from_json(payload)
|
||||
if not warned:
|
||||
environments = [
|
||||
environment
|
||||
for environment in (
|
||||
version.resolved_environment,
|
||||
*version.resolved_environments.values(),
|
||||
)
|
||||
if environment is not None
|
||||
]
|
||||
for environment in environments:
|
||||
for message in environment.warnings:
|
||||
warnings.warn(message, UserWarning, stacklevel=3)
|
||||
warned = True
|
||||
return version
|
||||
|
||||
return decode
|
||||
|
||||
|
||||
class DBConnection(EnforceOverrides):
|
||||
"""An active LanceDB connection interface.
|
||||
|
||||
@@ -1018,6 +1050,8 @@ class DBConnection(EnforceOverrides):
|
||||
secrets: Optional[Sequence[EnvVarSecret]] = None,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
refresh_lock: bool = False,
|
||||
progress: Any = False,
|
||||
) -> FunctionVersion:
|
||||
"""Build and register a scalar Python function, then return its version.
|
||||
|
||||
@@ -1040,6 +1074,16 @@ class DBConnection(EnforceOverrides):
|
||||
namespace_path : list of str, optional
|
||||
The namespace holding the Function. None or an empty list is the
|
||||
root namespace.
|
||||
refresh_lock : bool, default False
|
||||
Ask the server to resolve a fresh environment lock instead of
|
||||
reusing the published version's lock.
|
||||
progress : bool, callable, or tqdm-like object, default False
|
||||
Display lifecycle state and elapsed time, or receive structured
|
||||
snapshots through a callback. See [Job.wait][lancedb.job.Job.wait].
|
||||
|
||||
When the registration job resolves, each resolved-environment warning
|
||||
reported by the server is emitted as a Python ``UserWarning``. Catalog
|
||||
reads do not replay those registration warnings.
|
||||
|
||||
Examples
|
||||
--------
|
||||
@@ -1055,12 +1099,16 @@ class DBConnection(EnforceOverrides):
|
||||
)
|
||||
```
|
||||
"""
|
||||
return self.create_function_async(
|
||||
job = self.create_function_async(
|
||||
definition,
|
||||
secrets=secrets,
|
||||
exist_ok=exist_ok,
|
||||
namespace_path=namespace_path,
|
||||
).wait()
|
||||
refresh_lock=refresh_lock,
|
||||
)
|
||||
if progress is False or progress is None:
|
||||
return job.wait()
|
||||
return job.wait(progress=progress)
|
||||
|
||||
def create_function_async(
|
||||
self,
|
||||
@@ -1069,6 +1117,7 @@ class DBConnection(EnforceOverrides):
|
||||
secrets: Optional[Sequence[EnvVarSecret]] = None,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
refresh_lock: bool = False,
|
||||
) -> Job[FunctionVersion]:
|
||||
"""Submit a scalar Python function for building and registration.
|
||||
|
||||
@@ -1079,6 +1128,11 @@ class DBConnection(EnforceOverrides):
|
||||
artifact. The returned job has type ``query`` and the SQL query UUID as
|
||||
its ID. Waiting on it returns the immutable Function version.
|
||||
LanceDB Embedded connections raise ``NotImplementedError``.
|
||||
|
||||
``refresh_lock`` asks the server to resolve a fresh environment lock
|
||||
instead of reusing the published version's lock. Waiting on the job
|
||||
emits the server's resolved-environment warnings as Python warnings;
|
||||
reading the same version later does not repeat them.
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
_append_doc_url(
|
||||
@@ -1555,13 +1609,39 @@ class DBConnection(EnforceOverrides):
|
||||
)
|
||||
|
||||
def list_jobs(
|
||||
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
page_token: Optional[str] = None,
|
||||
page_limit: Optional[int] = None,
|
||||
table: Optional[str] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
state: Optional[
|
||||
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
|
||||
] = None,
|
||||
job_type: Optional[str] = None,
|
||||
job_types: Optional[List[str]] = None,
|
||||
created_at_gte_millis: Optional[int] = None,
|
||||
created_at_lt_millis: Optional[int] = None,
|
||||
) -> Listing[JobInfo]:
|
||||
"""List server-side jobs across the database's tables.
|
||||
"""List server-side jobs, optionally filtered before pagination.
|
||||
|
||||
Returns a lazy iterator. ``page_limit`` limits each request, not the total;
|
||||
``page_token`` resumes from a saved token. Requests and errors occur during
|
||||
iteration. See [pagination state][lancedb.listing.AsyncListing].
|
||||
``table`` names a table in ``namespace_path`` (the root by default).
|
||||
Listings include all branches of the table. A namespace filter requires
|
||||
``table``.
|
||||
``state`` uses registry states such as ``in_progress``, ``succeeded``,
|
||||
``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
|
||||
``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
|
||||
Creation-time bounds are Unix milliseconds, inclusive at
|
||||
``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
|
||||
|
||||
Returns a lazy iterator. ``page_limit`` limits each request, not the total.
|
||||
Resume a ``page_token`` with the same filters. Requests and errors occur
|
||||
during iteration. See [pagination state][lancedb.listing.AsyncListing].
|
||||
|
||||
For example, to inspect up to five jobs without fetching all history::
|
||||
|
||||
jobs = db.list_jobs(table="events", page_limit=5)
|
||||
first_five = jobs[:5]
|
||||
"""
|
||||
raise NotImplementedError(
|
||||
_append_doc_url(
|
||||
@@ -2432,6 +2512,7 @@ class LanceDBConnection(DBConnection):
|
||||
secrets: Optional[Sequence[EnvVarSecret]] = None,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
refresh_lock: bool = False,
|
||||
) -> Job[FunctionVersion]:
|
||||
job = LOOP.run(
|
||||
self._conn.create_function_async(
|
||||
@@ -2439,6 +2520,7 @@ class LanceDBConnection(DBConnection):
|
||||
secrets=secrets,
|
||||
exist_ok=exist_ok,
|
||||
namespace_path=namespace_path,
|
||||
refresh_lock=refresh_lock,
|
||||
)
|
||||
)
|
||||
return Job(job)
|
||||
@@ -2750,16 +2832,52 @@ class LanceDBConnection(DBConnection):
|
||||
|
||||
@override
|
||||
def list_jobs(
|
||||
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
page_token: Optional[str] = None,
|
||||
page_limit: Optional[int] = None,
|
||||
table: Optional[str] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
state: Optional[
|
||||
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
|
||||
] = None,
|
||||
job_type: Optional[str] = None,
|
||||
job_types: Optional[List[str]] = None,
|
||||
created_at_gte_millis: Optional[int] = None,
|
||||
created_at_lt_millis: Optional[int] = None,
|
||||
) -> Listing[JobInfo]:
|
||||
"""List server-side jobs across the database's tables.
|
||||
"""List server-side jobs, optionally filtered before pagination.
|
||||
|
||||
Returns a lazy iterator. ``page_limit`` limits each request, not the total;
|
||||
``page_token`` resumes from a saved token. Requests and errors occur during
|
||||
iteration. See [pagination state][lancedb.listing.AsyncListing].
|
||||
``table`` names a table in ``namespace_path`` (the root by default).
|
||||
Listings include all branches of the table. A namespace filter requires
|
||||
``table``.
|
||||
``state`` uses registry states such as ``in_progress``, ``succeeded``,
|
||||
``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
|
||||
``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
|
||||
Creation-time bounds are Unix milliseconds, inclusive at
|
||||
``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
|
||||
|
||||
Returns a lazy iterator. ``page_limit`` limits each request, not the total.
|
||||
Resume a ``page_token`` with the same filters. Requests and errors occur
|
||||
during iteration. See [pagination state][lancedb.listing.AsyncListing].
|
||||
|
||||
For example, to inspect up to five jobs without fetching all history::
|
||||
|
||||
jobs = db.list_jobs(table="events", page_limit=5)
|
||||
first_five = jobs[:5]
|
||||
"""
|
||||
return Listing(
|
||||
self._conn.list_jobs(page_token=page_token, page_limit=page_limit)
|
||||
self._conn.list_jobs(
|
||||
page_token=page_token,
|
||||
page_limit=page_limit,
|
||||
table=table,
|
||||
namespace_path=namespace_path,
|
||||
state=state,
|
||||
job_type=job_type,
|
||||
job_types=job_types,
|
||||
created_at_gte_millis=created_at_gte_millis,
|
||||
created_at_lt_millis=created_at_lt_millis,
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
@@ -3788,6 +3906,7 @@ class AsyncConnection(object):
|
||||
secrets: Optional[Sequence[EnvVarSecret]] = None,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
refresh_lock: bool = False,
|
||||
) -> AsyncJob[FunctionVersion]:
|
||||
"""Submit a scalar Python function for building and registration.
|
||||
|
||||
@@ -3802,14 +3921,16 @@ class AsyncConnection(object):
|
||||
the environment variable its value arrives in. ``namespace_path`` is
|
||||
the namespace the Function is registered in; None or an empty list is
|
||||
the root. LanceDB Embedded connections raise ``NotImplementedError``.
|
||||
``refresh_lock`` asks the server to resolve a fresh environment lock
|
||||
instead of reusing the published version's lock.
|
||||
"""
|
||||
if not isinstance(definition, FunctionDefinition):
|
||||
raise TypeError("create_function_async requires a @function definition")
|
||||
request = definition.bind_secrets(secrets)
|
||||
request = definition.bind_secrets(secrets).with_refresh_lock(refresh_lock)
|
||||
inner = await self._inner.create_function_async(
|
||||
request.to_canonical_json(), namespace_path, exist_ok=exist_ok
|
||||
)
|
||||
return _typed_job(inner, FunctionVersion.from_json)
|
||||
return _typed_job(inner, _function_registration_decoder())
|
||||
|
||||
async def get_function(
|
||||
self,
|
||||
@@ -4323,16 +4444,56 @@ class AsyncConnection(object):
|
||||
)
|
||||
|
||||
def list_jobs(
|
||||
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
page_token: Optional[str] = None,
|
||||
page_limit: Optional[int] = None,
|
||||
table: Optional[str] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
state: Optional[
|
||||
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
|
||||
] = None,
|
||||
job_type: Optional[str] = None,
|
||||
job_types: Optional[List[str]] = None,
|
||||
created_at_gte_millis: Optional[int] = None,
|
||||
created_at_lt_millis: Optional[int] = None,
|
||||
) -> AsyncListing[JobInfo]:
|
||||
"""List server-side jobs across the database's tables.
|
||||
"""List server-side jobs, optionally filtered before pagination.
|
||||
|
||||
Returns a lazy iterator. ``page_limit`` limits each request, not the total;
|
||||
``page_token`` resumes from a saved token. Requests and errors occur during
|
||||
iteration. See [pagination state][lancedb.listing.AsyncListing].
|
||||
``table`` names a table in ``namespace_path`` (the root by default).
|
||||
Listings include all branches of the table. A namespace filter requires
|
||||
``table``.
|
||||
``state`` uses registry states such as ``in_progress``, ``succeeded``,
|
||||
``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
|
||||
``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
|
||||
Creation-time bounds are Unix milliseconds, inclusive at
|
||||
``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
|
||||
|
||||
Returns a lazy iterator. ``page_limit`` limits each request, not the total.
|
||||
Resume a ``page_token`` with the same filters. Requests and errors occur
|
||||
during iteration. See [pagination state][lancedb.listing.AsyncListing].
|
||||
|
||||
For example, to inspect up to five jobs without fetching all history::
|
||||
|
||||
jobs = db.list_jobs(table="events", page_limit=5)
|
||||
first_five = []
|
||||
async for job in jobs:
|
||||
first_five.append(job)
|
||||
if len(first_five) == 5:
|
||||
break
|
||||
"""
|
||||
return AsyncListing(
|
||||
self._inner.list_jobs(page_token=page_token, page_limit=page_limit)
|
||||
self._inner.list_jobs(
|
||||
page_token=page_token,
|
||||
page_limit=page_limit,
|
||||
table=table,
|
||||
namespace_path=namespace_path,
|
||||
state=state,
|
||||
job_type=job_type,
|
||||
job_types=job_types,
|
||||
created_at_gte_millis=created_at_gte_millis,
|
||||
created_at_lt_millis=created_at_lt_millis,
|
||||
)
|
||||
)
|
||||
|
||||
async def cancel_job(self, job_id: str) -> bool:
|
||||
|
||||
@@ -29,13 +29,15 @@ import textwrap
|
||||
import types
|
||||
import warnings
|
||||
from collections.abc import Mapping, Sequence
|
||||
from datetime import date, datetime
|
||||
from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from typing import (
|
||||
Annotated,
|
||||
Any,
|
||||
Callable,
|
||||
Literal,
|
||||
NamedTuple,
|
||||
Optional,
|
||||
TYPE_CHECKING,
|
||||
Union,
|
||||
@@ -101,6 +103,12 @@ def _validate_batch_size(value: Any) -> Optional[int]:
|
||||
return value
|
||||
|
||||
|
||||
def _validate_refresh_lock(value: Any) -> bool:
|
||||
if not isinstance(value, bool):
|
||||
raise ValueError("refresh_lock must be a boolean")
|
||||
return value
|
||||
|
||||
|
||||
def _validate_max_concurrency(value: Any) -> Optional[int]:
|
||||
if value is None:
|
||||
return None
|
||||
@@ -536,13 +544,131 @@ class PythonRuntimeSpec(_RemoteValue):
|
||||
|
||||
|
||||
class FunctionImage(_RemoteValue):
|
||||
"""A complete OCI Function image identified by its exact manifest digest."""
|
||||
"""A complete OCI Function image identified by its exact manifest digest.
|
||||
|
||||
``describe()`` and the concise representation inspect the descriptor without
|
||||
walking Pydantic model internals. Missing metadata is ``None`` (unknown).
|
||||
The current service does not report image platforms, base image or byte size;
|
||||
these cannot be inferred from the client's platform or the manifest digest.
|
||||
The full descriptor remains available through ``descriptor``.
|
||||
"""
|
||||
|
||||
manifest_digest: str
|
||||
descriptor: Mapping[str, Any]
|
||||
source: bool
|
||||
models: tuple[HuggingFaceModel, ...] = ()
|
||||
|
||||
def describe(self) -> dict[str, Any]:
|
||||
"""Return concise image details without fetching registry content.
|
||||
|
||||
``requires_gpu`` reflects a ``lance.cuda`` requirement in a v1
|
||||
descriptor, rather than promising compatibility with every GPU.
|
||||
``platforms``, ``base_image`` and ``size_bytes`` are unavailable from
|
||||
the current wire contract and return ``None``.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> print(fn.image.describe()) # doctest: +SKIP
|
||||
"""
|
||||
python = self.descriptor.get("python")
|
||||
requires = self.descriptor.get("requires")
|
||||
capabilities = (
|
||||
requires.get("capabilities") if isinstance(requires, Mapping) else None
|
||||
)
|
||||
known_capabilities = (
|
||||
self.descriptor.get("format_version") == 1
|
||||
and isinstance(capabilities, (list, tuple))
|
||||
and all(isinstance(item, Mapping) for item in capabilities)
|
||||
)
|
||||
cuda = (
|
||||
next(
|
||||
(item for item in capabilities if item.get("type") == "lance.cuda"),
|
||||
None,
|
||||
)
|
||||
if known_capabilities
|
||||
else None
|
||||
)
|
||||
python_version = python.get("version") if isinstance(python, Mapping) else None
|
||||
cuda_toolkit = cuda.get("cuda_toolkit") if cuda is not None else None
|
||||
return {
|
||||
"manifest_digest": self.manifest_digest,
|
||||
"python_version": python_version
|
||||
if isinstance(python_version, str)
|
||||
else None,
|
||||
"requires_gpu": cuda is not None if known_capabilities else None,
|
||||
"cuda_toolkit": cuda_toolkit if isinstance(cuda_toolkit, str) else None,
|
||||
"platforms": None,
|
||||
"base_image": None,
|
||||
"size_bytes": None,
|
||||
}
|
||||
|
||||
def __repr_args__(self):
|
||||
for name, value in self.describe().items():
|
||||
if isinstance(value, str) and len(value) > 80:
|
||||
value = value[:77] + "..."
|
||||
yield name, value
|
||||
|
||||
|
||||
class ResolvedPackage(_RemoteValue):
|
||||
"""One installed Python distribution measured from a baked environment.
|
||||
|
||||
``version`` is the complete version reported by package metadata,
|
||||
including local labels such as ``+cu130``. ``source`` is present only when
|
||||
the submitted lock retained a per-package source; absent means unknown, not
|
||||
an inferred index.
|
||||
"""
|
||||
|
||||
name: str
|
||||
version: str
|
||||
source: Optional[str] = None
|
||||
|
||||
|
||||
class ResolvedEnvironmentProvenance(_RemoteValue):
|
||||
"""Sanitized source and accelerator provenance for a resolved environment.
|
||||
|
||||
``configured_index_urls`` and ``configured_find_links`` record build
|
||||
inputs. ``resolved_indexes`` records indexes visible in the submitted lock,
|
||||
so a configured source is not by itself evidence that a package came from
|
||||
it. Empty lists and absent fields remain absent; the client does not
|
||||
synthesize them.
|
||||
"""
|
||||
|
||||
configured_index_urls: tuple[str, ...] = ()
|
||||
configured_find_links: tuple[str, ...] = ()
|
||||
resolved_indexes: tuple[str, ...] = ()
|
||||
cuda_toolkit: Optional[str] = None
|
||||
torch_version: Optional[str] = None
|
||||
|
||||
|
||||
class ResolvedEnvironment(_RemoteValue):
|
||||
"""Actual installed distributions and registration warnings for one platform.
|
||||
|
||||
A missing value means its measurement is unknown, not an empty
|
||||
installed-package list. Versions are retained verbatim, including local
|
||||
labels; package ``source`` is retained only when the producer recorded it.
|
||||
"""
|
||||
|
||||
packages: tuple[ResolvedPackage, ...]
|
||||
provenance: Optional[ResolvedEnvironmentProvenance] = None
|
||||
warnings: tuple[str, ...] = ()
|
||||
|
||||
|
||||
class FunctionEnvironment(NamedTuple):
|
||||
"""Requested and measured environment view for a Function version.
|
||||
|
||||
This is a view over
|
||||
[FunctionVersion.runtime][lancedb.functions.FunctionVersion.runtime]
|
||||
and
|
||||
[FunctionVersion.resolved_environment][lancedb.functions.FunctionVersion.resolved_environment].
|
||||
It adds no wire field and performs no second parse. ``requested`` is the
|
||||
runtime specification supplied at registration; ``resolved`` is measured
|
||||
data and is ``None`` when unknown. For per-platform multiarchitecture
|
||||
measurements, use ``FunctionVersion.environment_report``.
|
||||
"""
|
||||
|
||||
requested: Optional[PythonRuntimeSpec]
|
||||
resolved: Optional[ResolvedEnvironment]
|
||||
|
||||
|
||||
def _validate_object_version(value: str) -> str:
|
||||
if int(value) > 2**64 - 1:
|
||||
@@ -593,6 +719,17 @@ class FunctionVersion(_RemoteValue):
|
||||
``result_stability`` retain the execution controls reported by the
|
||||
catalog. They are ``None`` for versions registered before the
|
||||
corresponding declaration.
|
||||
|
||||
``runtime`` is the runtime specification requested at registration. It is
|
||||
not evidence of what was installed. ``resolved_environment`` is measured
|
||||
data for a single-platform image: actual package names and complete
|
||||
versions, optional per-package source, provenance, and registration
|
||||
warnings. ``resolved_environments`` is the corresponding map for a
|
||||
multiarchitecture image, keyed by OCI ``os/architecture``. It is never
|
||||
flattened into an aggregate package list. ``None`` or an empty map means
|
||||
unknown data, not an empty installed environment. ``environment`` is a
|
||||
convenience view with ``requested`` and ``resolved`` members over the same
|
||||
fields.
|
||||
"""
|
||||
|
||||
name: str
|
||||
@@ -613,6 +750,11 @@ class FunctionVersion(_RemoteValue):
|
||||
max_concurrency: Optional[int] = None
|
||||
row_timeout_seconds: Optional[float] = None
|
||||
result_stability: Optional[str] = None
|
||||
runtime: Optional[PythonRuntimeSpec] = None
|
||||
resolved_environment: Optional[ResolvedEnvironment] = None
|
||||
resolved_environments: Mapping[str, ResolvedEnvironment] = Field(
|
||||
default_factory=dict
|
||||
)
|
||||
|
||||
@field_validator("batch_size", mode="before")
|
||||
@classmethod
|
||||
@@ -629,6 +771,24 @@ class FunctionVersion(_RemoteValue):
|
||||
def _validate_row_timeout(cls, value):
|
||||
return _validate_row_timeout(value)
|
||||
|
||||
@property
|
||||
def environment(self) -> FunctionEnvironment:
|
||||
"""Requested and measured environment without adding a second parser."""
|
||||
return FunctionEnvironment(
|
||||
requested=self.runtime,
|
||||
resolved=self.resolved_environment,
|
||||
)
|
||||
|
||||
@property
|
||||
def environment_report(self) -> Mapping[str, ResolvedEnvironment]:
|
||||
"""Per-platform measured reports, keyed by OCI ``os/architecture``.
|
||||
|
||||
This is the same map as ``resolved_environments`` and is never
|
||||
flattened. Single-platform images use ``resolved_environment`` instead;
|
||||
an absent platform means its measurement is unknown.
|
||||
"""
|
||||
return self.resolved_environments
|
||||
|
||||
def __call__(self, **arguments: Any) -> FunctionApplication:
|
||||
"""Bind this exact version to named table columns and constant inputs.
|
||||
|
||||
@@ -769,6 +929,9 @@ class FunctionRegistrationRequest(_RemoteValue):
|
||||
Credential values deliberately have no field here. The only secret-shaped
|
||||
thing a client sends is ``secret_bindings``: the name of a Secret the
|
||||
database already holds, which the remote service resolves at execution.
|
||||
``refresh_lock`` is a per-registration action, not part of the Function's
|
||||
source or runtime identity; its false default is omitted from canonical
|
||||
JSON.
|
||||
"""
|
||||
|
||||
name: str
|
||||
@@ -781,6 +944,7 @@ class FunctionRegistrationRequest(_RemoteValue):
|
||||
retry_policy: Optional[FunctionRetryPolicy] = None
|
||||
secret_bindings: tuple[SecretBinding, ...] = ()
|
||||
models: tuple[HuggingFaceModel, ...] = ()
|
||||
refresh_lock: bool = False
|
||||
|
||||
@field_validator("batch_size", mode="before")
|
||||
@classmethod
|
||||
@@ -797,6 +961,18 @@ class FunctionRegistrationRequest(_RemoteValue):
|
||||
def _validate_row_timeout(cls, value):
|
||||
return _validate_row_timeout(value)
|
||||
|
||||
@field_validator("refresh_lock", mode="before")
|
||||
@classmethod
|
||||
def _validate_refresh_lock(cls, value):
|
||||
return _validate_refresh_lock(value)
|
||||
|
||||
def with_refresh_lock(self, refresh_lock: bool) -> FunctionRegistrationRequest:
|
||||
"""Return this request with the registration-time refresh action set."""
|
||||
refresh_lock = _validate_refresh_lock(refresh_lock)
|
||||
if self.refresh_lock == refresh_lock:
|
||||
return self
|
||||
return self._copy(update={"refresh_lock": refresh_lock})
|
||||
|
||||
|
||||
class FunctionVersionRef(_OpenRemoteValue):
|
||||
name: str
|
||||
@@ -1043,6 +1219,7 @@ _GRAMMAR_PRIMITIVES = (
|
||||
(pa.date32(), "date32"),
|
||||
(pa.date64(), "date64"),
|
||||
)
|
||||
_FUNCTION_TIMEUNITS = ("s", "ms", "us", "ns")
|
||||
|
||||
|
||||
def _canonical_arrow_type(
|
||||
@@ -1259,6 +1436,33 @@ def _exact_arrow_type(
|
||||
for candidate, name in _GRAMMAR_PRIMITIVES:
|
||||
if data_type == candidate:
|
||||
return {"type": name}
|
||||
if pa.types.is_decimal128(data_type) or pa.types.is_decimal256(data_type):
|
||||
return {
|
||||
"type": (
|
||||
"decimal128" if pa.types.is_decimal128(data_type) else "decimal256"
|
||||
),
|
||||
"length": data_type.precision * 1000 + data_type.scale,
|
||||
}
|
||||
if pa.types.is_timestamp(data_type):
|
||||
unit = data_type.unit
|
||||
if unit not in _FUNCTION_TIMEUNITS:
|
||||
raise TypeError(f"unsupported Function timestamp unit: {unit!r}")
|
||||
timezone = data_type.tz
|
||||
if timezone == "-":
|
||||
raise TypeError(
|
||||
"unsupported Function timestamp timezone: '-' is reserved for "
|
||||
"no timezone"
|
||||
)
|
||||
if unit == "us" and timezone is None:
|
||||
return {"type": "timestamp"}
|
||||
return {"type": f"timestamp:{unit}:{timezone if timezone is not None else '-'}"}
|
||||
if pa.types.is_duration(data_type):
|
||||
unit = data_type.unit
|
||||
if unit not in _FUNCTION_TIMEUNITS:
|
||||
raise TypeError(f"unsupported Function duration unit: {unit!r}")
|
||||
if unit == "us":
|
||||
return {"type": "duration"}
|
||||
return {"type": f"duration:{unit}"}
|
||||
if pa.types.is_struct(data_type):
|
||||
fields = list(data_type)
|
||||
names = [field.name for field in fields]
|
||||
@@ -1314,8 +1518,29 @@ def _exact_arrow_type(
|
||||
if pa.types.is_fixed_size_list(data_type):
|
||||
value["length"] = data_type.list_size
|
||||
return value
|
||||
if pa.types.is_map(data_type) and _data_type_has_blob_v2(data_type):
|
||||
raise TypeError(_NESTED_BLOB_COLLECTION_ERROR)
|
||||
if pa.types.is_map(data_type):
|
||||
if data_type.keys_sorted:
|
||||
raise TypeError(
|
||||
"unsupported Arrow type for Function signature: map keys_sorted=true "
|
||||
"is not supported"
|
||||
)
|
||||
key_field = data_type.key_field
|
||||
if key_field.nullable or key_field.type != pa.string():
|
||||
raise TypeError(
|
||||
"unsupported Arrow type for Function signature: map keys must be "
|
||||
"non-nullable utf8"
|
||||
)
|
||||
if _data_type_has_blob_v2(data_type):
|
||||
raise TypeError(_NESTED_BLOB_COLLECTION_ERROR)
|
||||
return {
|
||||
"type": "map",
|
||||
"fields": [
|
||||
_exact_arrow_field(
|
||||
data_type.field(0),
|
||||
inside_collection=True,
|
||||
)
|
||||
],
|
||||
}
|
||||
raise TypeError(f"unsupported Arrow type for Function signature: {data_type}")
|
||||
|
||||
|
||||
@@ -1344,9 +1569,15 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]:
|
||||
raise TypeError(
|
||||
"Annotated Function types require exactly one PyArrow DataType"
|
||||
)
|
||||
# A struct value is written as a dict, which has no Arrow type of its
|
||||
# own; the Annotated metadata supplies it.
|
||||
if base is dict or get_origin(base) is dict:
|
||||
# A struct value is written as a dict, while Decimal and timedelta
|
||||
# carry no precision or unit of their own; the Annotated metadata
|
||||
# supplies those types.
|
||||
if (
|
||||
base is dict
|
||||
or get_origin(base) is dict
|
||||
or base is Decimal
|
||||
or base is timedelta
|
||||
):
|
||||
base_nullable = False
|
||||
else:
|
||||
_, base_nullable = _annotation_type(base)
|
||||
@@ -1372,7 +1603,21 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]:
|
||||
if annotation is date:
|
||||
return pa.date32(), nullable
|
||||
if annotation is datetime:
|
||||
# Existing default: microsecond precision, no timezone. Other units
|
||||
# and timezones require Annotated or an explicit schema.
|
||||
return pa.timestamp("us"), nullable
|
||||
if annotation is Decimal:
|
||||
raise TypeError(
|
||||
"Decimal Function annotations require precision and scale; use "
|
||||
"Annotated[Decimal, pyarrow.decimal128(precision, scale)], "
|
||||
"Annotated[Decimal, pyarrow.decimal256(precision, scale)], or an "
|
||||
"explicit schema"
|
||||
)
|
||||
if annotation is timedelta:
|
||||
raise TypeError(
|
||||
"timedelta Function annotations require an explicit unit; use "
|
||||
"Annotated[timedelta, pyarrow.duration(unit)] or an explicit schema"
|
||||
)
|
||||
if get_origin(annotation) is list:
|
||||
arguments = get_args(annotation)
|
||||
if len(arguments) != 1:
|
||||
@@ -1381,6 +1626,21 @@ def _annotation_type(annotation: Any) -> tuple[pa.DataType, bool]:
|
||||
if value_nullable:
|
||||
raise TypeError("nullable Function list elements are not supported")
|
||||
return _list_of(value_type), nullable
|
||||
if get_origin(annotation) is dict:
|
||||
arguments = get_args(annotation)
|
||||
if len(arguments) != 2:
|
||||
raise TypeError(f"unsupported dict annotation: {annotation!r}")
|
||||
key_type, value_annotation = arguments
|
||||
if key_type is not str:
|
||||
raise TypeError("Function map keys must be str")
|
||||
value_type, value_nullable = _annotation_type(value_annotation)
|
||||
return (
|
||||
pa.map_(
|
||||
pa.string(),
|
||||
pa.field("value", value_type, nullable=value_nullable),
|
||||
),
|
||||
nullable,
|
||||
)
|
||||
raise TypeError(f"unsupported Function annotation: {annotation!r}")
|
||||
|
||||
|
||||
@@ -2702,6 +2962,16 @@ def function(
|
||||
the registration. Every named-struct field may be nullable; Enterprise
|
||||
preserves the struct's validity when the result is expanded into sibling
|
||||
columns.
|
||||
``dict[str, T]`` declares an Arrow map with a non-nullable utf8 key; the
|
||||
value is non-nullable for ``T`` and nullable for ``Optional[T]``. A bare
|
||||
``Decimal`` has no precision or scale; use
|
||||
``Annotated[Decimal, pyarrow.decimal128(precision, scale)]``,
|
||||
``Annotated[Decimal, pyarrow.decimal256(precision, scale)]``, or an
|
||||
explicit schema. Bare ``datetime`` keeps its existing ``timestamp[us]`` default
|
||||
without a timezone; other units and timezones require
|
||||
``Annotated[datetime, pyarrow.timestamp(unit, tz=...)]`` or an explicit
|
||||
schema. A bare ``timedelta`` has no unit and is rejected; use
|
||||
``Annotated[timedelta, pyarrow.duration(unit)]`` or an explicit schema.
|
||||
|
||||
**Large values.** A ``bytes`` parameter receives the whole value, which
|
||||
is held in memory with its row and counts against the server's per-row
|
||||
@@ -2808,8 +3078,12 @@ def function(
|
||||
output_schema : pyarrow.DataType, pyarrow.Field, or pyarrow.Schema, optional
|
||||
Explicit scalar or named-struct output. A scalar field's ``nullable``
|
||||
flag is preserved; a top-level named-struct field and a Blob v2 output
|
||||
must be non-nullable. Required for batch annotations. When omitted, the
|
||||
output is inferred from the return annotation.
|
||||
must be non-nullable. Map and decimal fields use canonical Arrow JSON;
|
||||
a map key must be non-nullable utf8 and its value field keeps the
|
||||
declared nullability. Temporal fields use canonical Arrow JSON; the
|
||||
microsecond/no-timezone case keeps the legacy timestamp/duration shape.
|
||||
Required for batch annotations. When omitted, the output is inferred
|
||||
from the return annotation.
|
||||
pip : sequence of str, optional
|
||||
Pip requirements for the remote environment. Syntax is validated at
|
||||
decoration time, including extras and environment markers. Named direct
|
||||
@@ -3009,6 +3283,7 @@ __all__ = [
|
||||
"FunctionArtifactContent",
|
||||
"FunctionArtifactRequest",
|
||||
"FunctionBinding",
|
||||
"FunctionEnvironment",
|
||||
"FunctionOutput",
|
||||
"FunctionParameter",
|
||||
"FunctionRegistrationRequest",
|
||||
@@ -3025,6 +3300,9 @@ __all__ = [
|
||||
"PythonEnvironmentSpec",
|
||||
"PythonAdapterSpec",
|
||||
"PythonRuntimeSpec",
|
||||
"ResolvedEnvironment",
|
||||
"ResolvedEnvironmentProvenance",
|
||||
"ResolvedPackage",
|
||||
"RefreshColumnResult",
|
||||
"FunctionDefinition",
|
||||
]
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
"""Handles to asynchronous registry jobs, SQL queries, and local operations."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import reprlib
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from datetime import timedelta
|
||||
from os import PathLike
|
||||
from pathlib import Path
|
||||
@@ -53,11 +55,13 @@ def _timeout_message(
|
||||
)
|
||||
|
||||
|
||||
def _normalize_job_progress(progress):
|
||||
def _normalize_job_progress(progress, *, query=False):
|
||||
"""Normalize ``wait(progress=...)`` using the same convention as writes."""
|
||||
if progress is True:
|
||||
from tqdm.auto import tqdm
|
||||
|
||||
if query:
|
||||
return tqdm(bar_format="Query{postfix} [{elapsed}]"), True
|
||||
return tqdm(unit=" rows"), True
|
||||
if progress is False or progress is None:
|
||||
return None, False
|
||||
@@ -65,6 +69,7 @@ def _normalize_job_progress(progress):
|
||||
|
||||
|
||||
_ETA_MAX_SAMPLE_INTERVAL_MILLIS = 10 * 60 * 1_000
|
||||
_QUERY_PROGRESS_INTERVAL_SECONDS = 1.0
|
||||
|
||||
|
||||
def _progress_eta(previous, current):
|
||||
@@ -203,6 +208,7 @@ class AsyncJob(Generic[T]):
|
||||
self._inner = inner
|
||||
self._result_decoder = result_decoder
|
||||
self._last_progress_snapshot = None
|
||||
self._created_at = time.monotonic()
|
||||
|
||||
def _enrich_progress(self, snapshot):
|
||||
enriched = _with_progress_eta(self._last_progress_snapshot, snapshot)
|
||||
@@ -235,17 +241,29 @@ class AsyncJob(Generic[T]):
|
||||
async def progress(self) -> Optional[dict[str, Any]]:
|
||||
"""Fetch a structured progress snapshot.
|
||||
|
||||
Registry jobs always report lifecycle fields. Queue metadata and
|
||||
counters are included when supplied by the server. Older servers may
|
||||
Registry jobs always report lifecycle fields. SQL query handles report
|
||||
lifecycle state and ``client_elapsed_time_millis``, measured since this
|
||||
handle was created. They do not expose server build phases or logs.
|
||||
Queue metadata and counters are included when supplied by the server.
|
||||
Older servers may
|
||||
omit counters, and in-process operations return ``None``. A missing
|
||||
counter is unknown rather than zero. This is additive to :meth:`status`,
|
||||
whose string contract is unchanged.
|
||||
"""
|
||||
if self._inner is None:
|
||||
return None
|
||||
await self._inner.status()
|
||||
state = await self._inner.status()
|
||||
description = getattr(self._inner, "_description", None)
|
||||
if description is None or description.progress is None:
|
||||
if self.job_type == "query":
|
||||
return {
|
||||
"job_id": self.id,
|
||||
"job_type": "query",
|
||||
"state": state,
|
||||
"client_elapsed_time_millis": int(
|
||||
(time.monotonic() - self._created_at) * 1_000
|
||||
),
|
||||
}
|
||||
return None
|
||||
return self._enrich_progress(description.progress)
|
||||
|
||||
@@ -270,6 +288,13 @@ class AsyncJob(Generic[T]):
|
||||
new execution epoch or smaller plan resets the bar to that plan.
|
||||
``False`` preserves the original wait behavior.
|
||||
|
||||
For SQL-backed Function registration, progress shows the query's
|
||||
lifecycle state and client elapsed time. It observes the existing
|
||||
query handle while its original waiter runs; it does not resubmit or
|
||||
cancel the registration. Detailed bake phases and build logs are not
|
||||
available from the current query handle. Failure exceptions retain the
|
||||
server's cause and request identifiers.
|
||||
|
||||
Raises `JobFailedError` if the operation failed, `JobCancelledError`
|
||||
if it was cancelled, and `TimeoutError` if `timeout` elapses first.
|
||||
Transient connection and read errors are retried with capped exponential
|
||||
@@ -285,7 +310,10 @@ class AsyncJob(Generic[T]):
|
||||
"""
|
||||
if self._inner is None:
|
||||
return cast(T, None)
|
||||
progress_obj, owns = _normalize_job_progress(progress)
|
||||
query_progress = (
|
||||
progress is not False and progress is not None and self.job_type == "query"
|
||||
)
|
||||
progress_obj, owns = _normalize_job_progress(progress, query=query_progress)
|
||||
progress_callback = _job_progress_callback(progress_obj, self._enrich_progress)
|
||||
last_error = None
|
||||
|
||||
@@ -311,13 +339,46 @@ class AsyncJob(Generic[T]):
|
||||
await asyncio.sleep(delay)
|
||||
delay = min(delay * 2, 30.0)
|
||||
|
||||
async def observe_query():
|
||||
async def report():
|
||||
try:
|
||||
snapshot = await self.progress()
|
||||
if snapshot is not None:
|
||||
progress_callback(snapshot)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).warning(
|
||||
"job progress observer failed", exc_info=True
|
||||
)
|
||||
|
||||
waiter = asyncio.create_task(wait_with_retries())
|
||||
try:
|
||||
while not waiter.done():
|
||||
await report()
|
||||
await asyncio.wait(
|
||||
{waiter}, timeout=_QUERY_PROGRESS_INTERVAL_SECONDS
|
||||
)
|
||||
try:
|
||||
return await waiter
|
||||
finally:
|
||||
await report()
|
||||
finally:
|
||||
if not waiter.done():
|
||||
waiter.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await waiter
|
||||
|
||||
wait_for_result = (
|
||||
observe_query
|
||||
if query_progress and progress_callback is not None
|
||||
else wait_with_retries
|
||||
)
|
||||
try:
|
||||
try:
|
||||
if timeout is None:
|
||||
result = await wait_with_retries()
|
||||
result = await wait_for_result()
|
||||
else:
|
||||
result = await asyncio.wait_for(
|
||||
wait_with_retries(), timeout.total_seconds()
|
||||
wait_for_result(), timeout.total_seconds()
|
||||
)
|
||||
except asyncio.TimeoutError as error:
|
||||
if last_error is None:
|
||||
|
||||
@@ -6,7 +6,19 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from typing import Any, AsyncIterator, Callable, Generic, Iterator, Optional, TypeVar
|
||||
from collections import deque
|
||||
from itertools import islice
|
||||
from operator import index
|
||||
from typing import (
|
||||
Any,
|
||||
AsyncIterator,
|
||||
Callable,
|
||||
Generic,
|
||||
Iterator,
|
||||
Optional,
|
||||
TypeVar,
|
||||
overload,
|
||||
)
|
||||
|
||||
from .background_loop import LOOP
|
||||
|
||||
@@ -59,29 +71,85 @@ class Listing(Iterator[T], Generic[T]):
|
||||
print(name)
|
||||
|
||||
Use ``list(connection.list_views())`` to collect all results.
|
||||
|
||||
Indexes and slices refer to the remaining items and do not consume them.
|
||||
A bounded forward slice, such as ``listing[:5]``, fetches only enough pages
|
||||
to reach its stop. ``len(listing)``, negative indexes, and open-ended or
|
||||
reverse slices fetch and cache all remaining results. Iteration then drains
|
||||
that cache. These operations may perform requests and raise request errors.
|
||||
"""
|
||||
|
||||
def __init__(self, inner: AsyncListing[T]):
|
||||
self._inner = inner
|
||||
self._buffer: deque[T] = deque()
|
||||
|
||||
def __iter__(self) -> Listing[T]:
|
||||
return self
|
||||
|
||||
def __next__(self) -> T:
|
||||
if self._buffer:
|
||||
return self._buffer.popleft()
|
||||
try:
|
||||
return LOOP.run(self._inner.__anext__())
|
||||
except StopAsyncIteration:
|
||||
raise StopIteration from None
|
||||
|
||||
def _fill(self, count: Optional[int]) -> None:
|
||||
while count is None or len(self._buffer) < count:
|
||||
try:
|
||||
item = LOOP.run(self._inner.__anext__())
|
||||
except StopAsyncIteration:
|
||||
return
|
||||
self._buffer.append(item)
|
||||
|
||||
def __len__(self) -> int:
|
||||
"""Fetch and cache every remaining item, returning the remaining count."""
|
||||
self._fill(None)
|
||||
return len(self._buffer)
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
self._fill(1)
|
||||
return bool(self._buffer)
|
||||
|
||||
@overload
|
||||
def __getitem__(self, key: int) -> T: ...
|
||||
|
||||
@overload
|
||||
def __getitem__(self, key: slice) -> list[T]: ...
|
||||
|
||||
def __getitem__(self, key: int | slice) -> T | list[T]:
|
||||
"""Read remaining items without consuming them; bounded slices stay lazy."""
|
||||
if isinstance(key, slice):
|
||||
start = 0 if key.start is None else index(key.start)
|
||||
stop = None if key.stop is None else index(key.stop)
|
||||
step = 1 if key.step is None else index(key.step)
|
||||
if step == 0:
|
||||
raise ValueError("slice step cannot be zero")
|
||||
if start >= 0 and stop is not None and stop >= 0 and step > 0:
|
||||
if start >= stop:
|
||||
return []
|
||||
self._fill(stop)
|
||||
start, stop, step = key.indices(len(self._buffer))
|
||||
return list(
|
||||
islice(self._buffer, start, stop, min(step, len(self._buffer) + 1))
|
||||
)
|
||||
self._fill(None)
|
||||
return list(self._buffer)[key]
|
||||
position = index(key)
|
||||
self._fill(None if position < 0 else position + 1)
|
||||
return self._buffer[position]
|
||||
|
||||
def num_page_results(self) -> int:
|
||||
"""Return the number of cached items available without another request."""
|
||||
return self._inner.num_page_results()
|
||||
return len(self._buffer) + self._inner.num_page_results()
|
||||
|
||||
def page_token(self) -> Optional[str]:
|
||||
"""Return the next request's token.
|
||||
|
||||
See [AsyncListing.page_token][lancedb.listing.AsyncListing.page_token]
|
||||
for initial, cached, final-page, and error behavior.
|
||||
Indexing, slicing, and counting can also advance this token; drain all
|
||||
``num_page_results()`` cached items before resuming from it.
|
||||
"""
|
||||
return self._inner.page_token()
|
||||
|
||||
|
||||
@@ -161,6 +161,8 @@ class LanceMergeInsertBuilder(object):
|
||||
on_bad_vectors: str = "error",
|
||||
fill_value: float = 0.0,
|
||||
timeout: Optional[timedelta] = None,
|
||||
*,
|
||||
retries: Optional[int] = None,
|
||||
) -> MergeInsertResult:
|
||||
"""
|
||||
Executes the merge insert operation
|
||||
@@ -189,7 +191,22 @@ class LanceMergeInsertBuilder(object):
|
||||
first attempt will not be cancelled.
|
||||
|
||||
When this is set, the timeout is enforced on all attempts, including
|
||||
the first.
|
||||
the first. For remote tables it is sent as a server execution timeout;
|
||||
it does not extend HTTP read or proxy idle timeouts, or prove that a
|
||||
failed request did not commit.
|
||||
retries: int, optional
|
||||
Override the remote retry budget for this execution only (0 to 255).
|
||||
Use ``execute(new_data, retries=0)`` to disable even retries after
|
||||
precommit conflicts (409) or rate limits (429). This does not change
|
||||
connection-wide/read budgets or local transaction conflict retries.
|
||||
|
||||
By default, remote calls use the connection's
|
||||
[RetryConfig][lancedb.remote.RetryConfig]. Its ``statuses`` (also set
|
||||
through ``LANCE_CLIENT_RETRY_STATUSES``) selects candidates within
|
||||
the retry budget; it never permits replay of ambiguous merge outcomes.
|
||||
In particular, 502, ordinary 503, and 504 are never replayed, even if
|
||||
configured. Reconcile table contents before manually repeating a merge
|
||||
whose commit outcome is unknown.
|
||||
|
||||
Returns
|
||||
-------
|
||||
@@ -198,4 +215,6 @@ class LanceMergeInsertBuilder(object):
|
||||
"""
|
||||
if timeout is not None:
|
||||
self._timeout = timeout
|
||||
return self._table._do_merge(self, new_data, on_bad_vectors, fill_value)
|
||||
return self._table._do_merge(
|
||||
self, new_data, on_bad_vectors, fill_value, retries=retries
|
||||
)
|
||||
|
||||
@@ -10,6 +10,7 @@ through a namespace abstraction.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import warnings
|
||||
from typing import Any, Dict, Iterable, List, Optional, Union
|
||||
@@ -39,6 +40,9 @@ from lance_namespace_urllib3_client.models.query_table_request_vector import (
|
||||
QueryTableRequestVector,
|
||||
)
|
||||
from lance_namespace_urllib3_client.models.string_fts_query import StringFtsQuery
|
||||
from lance_namespace_urllib3_client.models.structured_fts_query import (
|
||||
StructuredFtsQuery,
|
||||
)
|
||||
from lance_namespace.errors import (
|
||||
NamespaceNotEmptyError,
|
||||
NamespaceNotFoundError,
|
||||
@@ -78,6 +82,7 @@ from lancedb.materialized_view import (
|
||||
SelectArg,
|
||||
)
|
||||
from lancedb.table import AsyncTable, LanceTable, Table
|
||||
from lancedb.query import MatchQuery, MultiMatchQuery, PhraseQuery
|
||||
from lancedb.util import validate_table_name
|
||||
from lancedb.common import DATA
|
||||
from lancedb.pydantic import LanceModel
|
||||
@@ -178,6 +183,26 @@ def _query_to_namespace_request(
|
||||
full_text_query_request = QueryTableRequestFullTextQuery(
|
||||
string_query=StringFtsQuery(query=fts_query)
|
||||
)
|
||||
elif getattr(fts_query, "operator", None) is not None:
|
||||
columns = fts_query.columns or []
|
||||
text = fts_query.query
|
||||
if len(text) >= 2 and text.startswith('"') and text.endswith('"'):
|
||||
if len(columns) > 1:
|
||||
raise ValueError(
|
||||
"Phrase queries cannot be used with multiple columns."
|
||||
)
|
||||
structured = PhraseQuery(text[1:-1], columns[0] if columns else None)
|
||||
elif len(columns) > 1:
|
||||
structured = MultiMatchQuery(text, columns, operator=fts_query.operator)
|
||||
else:
|
||||
structured = MatchQuery(
|
||||
text, columns[0] if columns else None, operator=fts_query.operator
|
||||
)
|
||||
full_text_query_request = QueryTableRequestFullTextQuery(
|
||||
structured_query=StructuredFtsQuery.from_dict(
|
||||
{"query": json.loads(structured.to_json())}
|
||||
)
|
||||
)
|
||||
elif hasattr(fts_query, "query"):
|
||||
full_text_query_request = QueryTableRequestFullTextQuery(
|
||||
string_query=StringFtsQuery(
|
||||
|
||||
+116
-11
@@ -42,7 +42,7 @@ from .rerankers.base import Reranker
|
||||
from .rerankers.rrf import RRFReranker
|
||||
from .rerankers.util import check_reranker_result
|
||||
from .schema import blob_column_paths, is_blob_like_field, schema_has_blob_field
|
||||
from .util import _validate_query_vector, flatten_columns, get_uri_scheme
|
||||
from .util import _validate_query_vector, add_note, flatten_columns, get_uri_scheme
|
||||
from . import _wal_hybrid # WAL-PK-FUSION: delete.
|
||||
from ._blob import (
|
||||
BLOB_MODE_TO_HANDLING,
|
||||
@@ -873,10 +873,29 @@ class FullTextSearchQuery(pydantic.BaseModel):
|
||||
query: str | FullTextQuery
|
||||
If a string, it is treated as a MatchQuery.
|
||||
If a FullTextQuery object, it is used directly.
|
||||
operator: FullTextOperator, optional
|
||||
Combine terms in a string query using AND or OR (the default).
|
||||
Quoted strings keep phrase semantics regardless of the operator.
|
||||
"""
|
||||
|
||||
columns: Optional[List[str]] = None
|
||||
query: Union[str, FullTextQuery]
|
||||
operator: Optional[FullTextOperator] = None
|
||||
|
||||
@pydantic.model_validator(mode="after")
|
||||
def _validate_operator(self) -> Self:
|
||||
if self.operator is not None and not isinstance(self.query, str):
|
||||
raise ValueError("operator requires a string full-text query")
|
||||
return self
|
||||
|
||||
|
||||
def _add_fts_position_error_note(error: Exception) -> None:
|
||||
if "position is not found but required for phrase queries" in str(error):
|
||||
add_note(
|
||||
error,
|
||||
"Phrase queries require an index built with positions. Rebuild it with "
|
||||
"table.create_index(column, config=FTS(with_position=True), replace=True).",
|
||||
)
|
||||
|
||||
|
||||
class Query(pydantic.BaseModel):
|
||||
@@ -1147,6 +1166,7 @@ class LanceQueryBuilder(ABC):
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
fast_search: bool = None,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> Self:
|
||||
"""
|
||||
Create a query builder based on the given query and query type.
|
||||
@@ -1171,6 +1191,10 @@ class LanceQueryBuilder(ABC):
|
||||
fast_search: bool
|
||||
Skip flat search of unindexed data.
|
||||
"""
|
||||
if operator is not None:
|
||||
operator = FullTextOperator(operator)
|
||||
if not isinstance(query, str) or query_type not in ("auto", "fts"):
|
||||
raise ValueError("operator requires a string full-text query")
|
||||
if query_type != "fts":
|
||||
_validate_query_vector(query)
|
||||
|
||||
@@ -1201,6 +1225,9 @@ class LanceQueryBuilder(ABC):
|
||||
table, query, query_type, vector_column_name
|
||||
)
|
||||
|
||||
if operator is not None and query_type != "fts":
|
||||
raise ValueError("operator requires a string full-text query")
|
||||
|
||||
if query_type == "hybrid":
|
||||
return LanceHybridQueryBuilder(
|
||||
table, query, vector_column_name, fts_columns=fts_columns
|
||||
@@ -1214,7 +1241,7 @@ class LanceQueryBuilder(ABC):
|
||||
ordering_field_name=ordering_field_name,
|
||||
fts_columns=fts_columns,
|
||||
fast_search=fast_search,
|
||||
)
|
||||
).operator(operator)
|
||||
|
||||
if isinstance(query, (list, tuple)):
|
||||
query = np.array(query, dtype=np.float32)
|
||||
@@ -2563,6 +2590,7 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
|
||||
super().__init__(table)
|
||||
self._query = query
|
||||
self._phrase_query = False
|
||||
self._operator: Optional[FullTextOperator] = None
|
||||
# Deprecated compatibility parameter. Native FTS ordering is now
|
||||
# configured through order_by(); LanceQueryBuilder.create emits the warning.
|
||||
_ = ordering_field_name
|
||||
@@ -2572,6 +2600,36 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
|
||||
fts_columns = [fts_columns]
|
||||
self._fts_columns = fts_columns
|
||||
|
||||
def operator(
|
||||
self, operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]]
|
||||
) -> LanceFtsQueryBuilder:
|
||||
"""Combine terms in a string query with ``"AND"`` or ``"OR"``.
|
||||
|
||||
The default is OR. AND requires every term to match. For example,
|
||||
``table.search("gripper closed", query_type="fts").operator("AND")``.
|
||||
Structured queries specify their own operators. Quoted strings and
|
||||
``phrase_query()`` retain their phrase semantics.
|
||||
"""
|
||||
if operator is not None and not isinstance(self._query, str):
|
||||
raise ValueError("operator requires a string full-text query")
|
||||
self._operator = FullTextOperator(operator) if operator is not None else None
|
||||
return self
|
||||
|
||||
def count_rows(self) -> int:
|
||||
"""Count all full-text matches satisfying the query's filter.
|
||||
|
||||
Ignores limit, offset, selection, ordering, and reranking. ``fast_search``
|
||||
still restricts the count to indexed data. This streams matching scores
|
||||
without loading document columns and may scan every match.
|
||||
|
||||
For example, ``table.search("gripper closed", query_type="fts",``
|
||||
``operator="AND").where("active = true").count_rows()``.
|
||||
"""
|
||||
self._table._ensure_no_legacy_fts_index()
|
||||
query = self._table._table._sync_query_to_async(self.to_query_object())
|
||||
assert isinstance(query, AsyncFTSQuery)
|
||||
return LOOP.run(query.count_rows())
|
||||
|
||||
def phrase_query(self, phrase_query: bool = True) -> LanceFtsQueryBuilder:
|
||||
"""Set whether to use phrase query.
|
||||
|
||||
@@ -2628,7 +2686,9 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
|
||||
fragment_ids=self._fragment_ids,
|
||||
use_rte=self._use_rte,
|
||||
full_text_query=FullTextSearchQuery(
|
||||
query=self._query_with_phrase_semantics(), columns=self._fts_columns
|
||||
query=self._query_with_phrase_semantics(),
|
||||
columns=self._fts_columns,
|
||||
operator=self._operator,
|
||||
),
|
||||
offset=self._offset,
|
||||
fast_search=self._fast_search,
|
||||
@@ -4443,7 +4503,11 @@ class AsyncQuery(AsyncStandardQuery):
|
||||
)
|
||||
|
||||
def nearest_to_text(
|
||||
self, query: str | FullTextQuery, columns: Union[str, List[str], None] = None
|
||||
self,
|
||||
query: str | FullTextQuery,
|
||||
columns: Union[str, List[str], None] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> AsyncFTSQuery:
|
||||
"""
|
||||
Find the documents that are most relevant to the given text query.
|
||||
@@ -4464,7 +4528,11 @@ class AsyncQuery(AsyncStandardQuery):
|
||||
columns: str or list of str, default None
|
||||
The columns to search in. If None, all indexed columns are searched.
|
||||
For now only one column can be searched at a time.
|
||||
operator: "AND" or "OR", optional
|
||||
Combine terms in a string query. Defaults to OR. Quoted strings use
|
||||
phrase semantics and require an index built with positions.
|
||||
"""
|
||||
fts_query = FullTextSearchQuery(query=query, operator=operator)
|
||||
if isinstance(columns, str):
|
||||
columns = [columns]
|
||||
if columns is None:
|
||||
@@ -4472,7 +4540,13 @@ class AsyncQuery(AsyncStandardQuery):
|
||||
|
||||
if isinstance(query, str):
|
||||
return AsyncFTSQuery(
|
||||
self._inner.nearest_to_text({"query": query, "columns": columns}),
|
||||
self._inner.nearest_to_text(
|
||||
{
|
||||
"query": query,
|
||||
"columns": columns,
|
||||
"operator": fts_query.operator,
|
||||
}
|
||||
),
|
||||
self._table,
|
||||
)
|
||||
# FullTextQuery object
|
||||
@@ -4487,6 +4561,22 @@ class AsyncFTSQuery(AsyncStandardQuery):
|
||||
self._inner = inner
|
||||
self._reranker = None
|
||||
|
||||
async def count_rows(self) -> int:
|
||||
"""Count all full-text matches satisfying the query's filter.
|
||||
|
||||
Ignores limit, offset, selection, ordering, and reranking. ``fast_search``
|
||||
still restricts the count to indexed data. Matching scores are streamed
|
||||
without loading document columns, so counting may scan every match.
|
||||
|
||||
For example, ``await table.query().nearest_to_text("gripper closed",``
|
||||
``operator="AND").where("active = true").count_rows()``.
|
||||
"""
|
||||
try:
|
||||
return await self._inner.count_rows()
|
||||
except Exception as error:
|
||||
_add_fts_position_error_note(error)
|
||||
raise
|
||||
|
||||
def get_query(self) -> str:
|
||||
return self._inner.get_query()
|
||||
|
||||
@@ -4580,10 +4670,16 @@ class AsyncFTSQuery(AsyncStandardQuery):
|
||||
timeout: Optional[timedelta] = None,
|
||||
blob_sources: Optional[dict[str, str]] = None,
|
||||
) -> AsyncRecordBatchReader:
|
||||
reader = await super()._execute_batches(
|
||||
timeout=timeout, blob_sources=blob_sources
|
||||
)
|
||||
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
|
||||
try:
|
||||
reader = await super()._execute_batches(
|
||||
max_batch_length=max_batch_length,
|
||||
timeout=timeout,
|
||||
blob_sources=blob_sources,
|
||||
)
|
||||
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
|
||||
except Exception as error:
|
||||
_add_fts_position_error_note(error)
|
||||
raise
|
||||
if self._reranker:
|
||||
source = results
|
||||
results = self._reranker.rerank_fts(self.get_query(), results)
|
||||
@@ -4861,7 +4957,11 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
return self
|
||||
|
||||
def nearest_to_text(
|
||||
self, query: str | FullTextQuery, columns: Union[str, List[str], None] = None
|
||||
self,
|
||||
query: str | FullTextQuery,
|
||||
columns: Union[str, List[str], None] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> AsyncHybridQuery:
|
||||
"""
|
||||
Find the documents that are most relevant to the given text query,
|
||||
@@ -4886,7 +4986,10 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
columns: str or list of str, default None
|
||||
The columns to search in. If None, all indexed columns are searched.
|
||||
For now only one column can be searched at a time.
|
||||
operator: "AND" or "OR", optional
|
||||
Combine terms in a string query. Defaults to OR.
|
||||
"""
|
||||
fts_query = FullTextSearchQuery(query=query, operator=operator)
|
||||
if isinstance(columns, str):
|
||||
columns = [columns]
|
||||
if columns is None:
|
||||
@@ -4894,7 +4997,9 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
|
||||
if isinstance(query, str):
|
||||
return AsyncHybridQuery(
|
||||
self._inner.nearest_to_text({"query": query, "columns": columns}),
|
||||
self._inner.nearest_to_text(
|
||||
{"query": query, "columns": columns, "operator": fts_query.operator}
|
||||
),
|
||||
self._table,
|
||||
)
|
||||
# FullTextQuery object
|
||||
|
||||
@@ -1002,6 +1002,7 @@ class RemoteDBConnection(DBConnection):
|
||||
secrets: Optional[Sequence[EnvVarSecret]] = None,
|
||||
exist_ok: bool = False,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
refresh_lock: bool = False,
|
||||
) -> Job[FunctionVersion]:
|
||||
job = LOOP.run(
|
||||
self._conn.create_function_async(
|
||||
@@ -1009,6 +1010,7 @@ class RemoteDBConnection(DBConnection):
|
||||
secrets=secrets,
|
||||
exist_ok=exist_ok,
|
||||
namespace_path=namespace_path,
|
||||
refresh_lock=refresh_lock,
|
||||
)
|
||||
)
|
||||
return Job(job)
|
||||
@@ -1322,16 +1324,52 @@ class RemoteDBConnection(DBConnection):
|
||||
|
||||
@override
|
||||
def list_jobs(
|
||||
self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None
|
||||
self,
|
||||
*,
|
||||
page_token: Optional[str] = None,
|
||||
page_limit: Optional[int] = None,
|
||||
table: Optional[str] = None,
|
||||
namespace_path: Optional[List[str]] = None,
|
||||
state: Optional[
|
||||
Literal["in_progress", "succeeded", "failed", "canceled", "timed_out"]
|
||||
] = None,
|
||||
job_type: Optional[str] = None,
|
||||
job_types: Optional[List[str]] = None,
|
||||
created_at_gte_millis: Optional[int] = None,
|
||||
created_at_lt_millis: Optional[int] = None,
|
||||
) -> Listing[JobInfo]:
|
||||
"""List server-side jobs across the database's tables.
|
||||
"""List server-side jobs, optionally filtered before pagination.
|
||||
|
||||
Returns a lazy iterator. ``page_limit`` limits each request, not the total;
|
||||
``page_token`` resumes from a saved token. Requests and errors occur during
|
||||
iteration. See [pagination state][lancedb.listing.AsyncListing].
|
||||
``table`` names a table in ``namespace_path`` (the root by default).
|
||||
Listings include all branches of the table. A namespace filter requires
|
||||
``table``.
|
||||
``state`` uses registry states such as ``in_progress``, ``succeeded``,
|
||||
``failed``, ``timed_out``, and ``canceled``, rather than the SDK's
|
||||
``running``/``finished`` labels. Set either ``job_type`` or ``job_types``.
|
||||
Creation-time bounds are Unix milliseconds, inclusive at
|
||||
``created_at_gte_millis`` and exclusive at ``created_at_lt_millis``.
|
||||
|
||||
Returns a lazy iterator. ``page_limit`` limits each request, not the total.
|
||||
Resume a ``page_token`` with the same filters. Requests and errors occur
|
||||
during iteration. See [pagination state][lancedb.listing.AsyncListing].
|
||||
|
||||
For example, to inspect up to five jobs without fetching all history::
|
||||
|
||||
jobs = db.list_jobs(table="events", page_limit=5)
|
||||
first_five = jobs[:5]
|
||||
"""
|
||||
return Listing(
|
||||
self._conn.list_jobs(page_token=page_token, page_limit=page_limit)
|
||||
self._conn.list_jobs(
|
||||
page_token=page_token,
|
||||
page_limit=page_limit,
|
||||
table=table,
|
||||
namespace_path=namespace_path,
|
||||
state=state,
|
||||
job_type=job_type,
|
||||
job_types=job_types,
|
||||
created_at_gte_millis=created_at_gte_millis,
|
||||
created_at_lt_millis=created_at_lt_millis,
|
||||
)
|
||||
)
|
||||
|
||||
@override
|
||||
|
||||
@@ -65,6 +65,7 @@ from lancedb.embeddings import EmbeddingFunctionRegistry
|
||||
from lancedb.table import _normalize_progress
|
||||
|
||||
from ..query import (
|
||||
FullTextOperator,
|
||||
AnalyzePlanDistributedMetrics,
|
||||
DocumentGranularity,
|
||||
FullTextQuery,
|
||||
@@ -799,6 +800,8 @@ class RemoteTable(Table):
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
fast_search: Optional[bool] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> LanceQueryBuilder:
|
||||
"""Create a search query to find the nearest neighbors
|
||||
of the given query vector. We currently support
|
||||
@@ -857,6 +860,10 @@ class RemoteTable(Table):
|
||||
|
||||
- *default None*, which leaves fast search disabled.
|
||||
|
||||
operator: "AND" or "OR", optional
|
||||
Combine terms in a string full-text query; the default is OR.
|
||||
Use ``query_type="fts"`` when the table also has embeddings.
|
||||
|
||||
Returns
|
||||
-------
|
||||
LanceQueryBuilder
|
||||
@@ -893,6 +900,7 @@ class RemoteTable(Table):
|
||||
ordering_field_name=ordering_field_name,
|
||||
fts_columns=fts_columns or [],
|
||||
fast_search=fast_search,
|
||||
operator=operator,
|
||||
)
|
||||
|
||||
def _execute_query(
|
||||
@@ -945,9 +953,10 @@ class RemoteTable(Table):
|
||||
new_data: DATA,
|
||||
on_bad_vectors: str,
|
||||
fill_value: float,
|
||||
retries: Optional[int] = None,
|
||||
) -> MergeResult:
|
||||
return LOOP.run(
|
||||
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value)
|
||||
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value, retries)
|
||||
)
|
||||
|
||||
@_deprecated_keyword("predicate", "where")
|
||||
|
||||
@@ -91,6 +91,7 @@ from .functions import (
|
||||
from .merge import LanceMergeInsertBuilder
|
||||
from .pydantic import LanceModel, model_to_dict
|
||||
from .query import (
|
||||
FullTextOperator,
|
||||
AnalyzePlanDistributedMetrics,
|
||||
AsyncFTSQuery,
|
||||
AsyncHybridQuery,
|
||||
@@ -138,6 +139,11 @@ def _requires_local_namespace_execution(query: Query) -> bool:
|
||||
or query.take_row_ids is not None
|
||||
or query.search_effort is not None
|
||||
or query.approx_mode is not None
|
||||
or (
|
||||
query.full_text_query is not None
|
||||
and query.fast_search is True
|
||||
and query.vector is None
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -2443,6 +2449,8 @@ class Table(ABC):
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
fast_search: Optional[bool] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> LanceQueryBuilder:
|
||||
"""Create a search query to find the nearest neighbors
|
||||
of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/)
|
||||
@@ -2506,6 +2514,10 @@ class Table(ABC):
|
||||
- If `query` is a string, then the query type is "vector" if the
|
||||
table has embedding functions else the query type is "fts"
|
||||
|
||||
operator: "AND" or "OR", optional
|
||||
Combine terms in a string full-text query; the default is OR.
|
||||
Use ``query_type="fts"`` when the table also has embeddings.
|
||||
|
||||
Returns
|
||||
-------
|
||||
LanceQueryBuilder
|
||||
@@ -2810,6 +2822,7 @@ class Table(ABC):
|
||||
new_data: DATA,
|
||||
on_bad_vectors: OnBadVectorsType,
|
||||
fill_value: float,
|
||||
retries: Optional[int] = None,
|
||||
) -> MergeResult: ...
|
||||
|
||||
@abstractmethod
|
||||
@@ -5060,6 +5073,8 @@ class LanceTable(Table):
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
fast_search: Optional[bool] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> LanceVectorQueryBuilder: ...
|
||||
|
||||
@overload
|
||||
@@ -5071,6 +5086,8 @@ class LanceTable(Table):
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
fast_search: Optional[bool] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> LanceFtsQueryBuilder: ...
|
||||
|
||||
@overload
|
||||
@@ -5084,6 +5101,8 @@ class LanceTable(Table):
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
fast_search: Optional[bool] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> LanceHybridQueryBuilder: ...
|
||||
|
||||
@overload
|
||||
@@ -5095,6 +5114,8 @@ class LanceTable(Table):
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
fast_search: Optional[bool] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> LanceEmptyQueryBuilder: ...
|
||||
|
||||
def search(
|
||||
@@ -5107,6 +5128,8 @@ class LanceTable(Table):
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
fast_search: Optional[bool] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> LanceQueryBuilder:
|
||||
"""Create a search query to find the nearest neighbors
|
||||
of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/)
|
||||
@@ -5167,6 +5190,10 @@ class LanceTable(Table):
|
||||
If None then the search is performed on all indexed columns.
|
||||
For now, only one column can be searched at a time.
|
||||
|
||||
operator: "AND" or "OR", optional
|
||||
Combine terms in a string full-text query; the default is OR.
|
||||
Use ``query_type="fts"`` when the table also has embeddings.
|
||||
|
||||
Returns
|
||||
-------
|
||||
LanceQueryBuilder
|
||||
@@ -5192,6 +5219,7 @@ class LanceTable(Table):
|
||||
ordering_field_name=ordering_field_name,
|
||||
fts_columns=fts_columns or [],
|
||||
fast_search=fast_search,
|
||||
operator=operator,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@@ -5443,9 +5471,10 @@ class LanceTable(Table):
|
||||
new_data: DATA,
|
||||
on_bad_vectors: OnBadVectorsType,
|
||||
fill_value: float,
|
||||
retries: Optional[int] = None,
|
||||
) -> MergeResult:
|
||||
return LOOP.run(
|
||||
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value)
|
||||
self._table._do_merge(merge, new_data, on_bad_vectors, fill_value, retries)
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -7374,6 +7403,8 @@ class AsyncTable:
|
||||
query_type: QueryType = "auto",
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> AsyncQuery: ...
|
||||
|
||||
@overload
|
||||
@@ -7384,6 +7415,8 @@ class AsyncTable:
|
||||
query_type: Literal["auto"] = ...,
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> Union[AsyncHybridQuery, AsyncFTSQuery, AsyncVectorQuery]: ...
|
||||
|
||||
@overload
|
||||
@@ -7394,6 +7427,8 @@ class AsyncTable:
|
||||
query_type: Literal["hybrid"] = ...,
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> AsyncHybridQuery: ...
|
||||
|
||||
@overload
|
||||
@@ -7404,6 +7439,8 @@ class AsyncTable:
|
||||
query_type: Literal["auto"] = ...,
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> AsyncVectorQuery: ...
|
||||
|
||||
@overload
|
||||
@@ -7414,6 +7451,8 @@ class AsyncTable:
|
||||
query_type: Literal["fts"] = ...,
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> AsyncFTSQuery: ...
|
||||
|
||||
@overload
|
||||
@@ -7424,6 +7463,8 @@ class AsyncTable:
|
||||
query_type: Literal["vector"] = ...,
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> AsyncVectorQuery: ...
|
||||
|
||||
async def search(
|
||||
@@ -7435,6 +7476,8 @@ class AsyncTable:
|
||||
query_type: QueryType = "auto",
|
||||
ordering_field_name: Optional[str] = None,
|
||||
fts_columns: Optional[Union[str, List[str]]] = None,
|
||||
*,
|
||||
operator: Optional[Union[FullTextOperator, Literal["AND", "OR"]]] = None,
|
||||
) -> Union[AsyncQuery, AsyncHybridQuery, AsyncFTSQuery, AsyncVectorQuery]:
|
||||
"""Create a search query to find the nearest neighbors
|
||||
of the given query vector. We currently support [vector search](https://lancedb.com/docs/search/vector-search/)
|
||||
@@ -7478,12 +7521,20 @@ class AsyncTable:
|
||||
- If `query` is a string, then the query type is "vector" if the
|
||||
table has embedding functions else the query type is "fts"
|
||||
|
||||
operator: "AND" or "OR", optional
|
||||
Combine terms in a string full-text query; the default is OR.
|
||||
Use ``query_type="fts"`` when the table also has embeddings.
|
||||
|
||||
Returns
|
||||
-------
|
||||
AsyncQuery, AsyncHybridQuery, AsyncFTSQuery, or AsyncVectorQuery
|
||||
A query builder object representing the query.
|
||||
"""
|
||||
|
||||
if operator is not None:
|
||||
operator = FullTextOperator(operator)
|
||||
if not isinstance(query, str) or query_type not in ("auto", "fts"):
|
||||
raise ValueError("operator requires a string full-text query")
|
||||
if query is None:
|
||||
return self.query()
|
||||
|
||||
@@ -7602,13 +7653,17 @@ class AsyncTable:
|
||||
)
|
||||
vector_query = await make_embedding(embedding_conf, query)
|
||||
|
||||
if operator is not None and query_type != "fts":
|
||||
raise ValueError("operator requires a string full-text query")
|
||||
if query_type == "vector":
|
||||
builder = self.query().nearest_to(vector_query)
|
||||
if vector_column_name:
|
||||
builder = builder.column(vector_column_name)
|
||||
return builder
|
||||
elif query_type == "fts":
|
||||
return self.query().nearest_to_text(query, columns=fts_columns)
|
||||
return self.query().nearest_to_text(
|
||||
query, columns=fts_columns, operator=operator
|
||||
)
|
||||
elif query_type == "hybrid":
|
||||
builder = self.query().nearest_to(vector_query)
|
||||
if vector_column_name:
|
||||
@@ -7718,7 +7773,9 @@ class AsyncTable:
|
||||
|
||||
if query.full_text_query:
|
||||
async_query = async_query.nearest_to_text(
|
||||
query.full_text_query.query, query.full_text_query.columns
|
||||
query.full_text_query.query,
|
||||
query.full_text_query.columns,
|
||||
operator=query.full_text_query.operator,
|
||||
)
|
||||
|
||||
return async_query
|
||||
@@ -7777,6 +7834,7 @@ class AsyncTable:
|
||||
new_data: DATA,
|
||||
on_bad_vectors: OnBadVectorsType,
|
||||
fill_value: float,
|
||||
retries: Optional[int] = None,
|
||||
) -> MergeResult:
|
||||
schema = await self.schema()
|
||||
if on_bad_vectors is None:
|
||||
@@ -7808,6 +7866,7 @@ class AsyncTable:
|
||||
use_rte=merge._use_rte,
|
||||
validate_single_shard=merge._validate_single_shard,
|
||||
),
|
||||
retries=retries,
|
||||
)
|
||||
|
||||
async def delete(self, where: Union[str, Expr]) -> DeleteResult:
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
import json
|
||||
import warnings
|
||||
from collections import UserDict
|
||||
from pathlib import Path
|
||||
from types import MappingProxyType
|
||||
@@ -13,6 +14,7 @@ import lancedb.functions as functions
|
||||
from lancedb.functions import (
|
||||
FunctionApplication,
|
||||
FunctionBinding,
|
||||
FunctionImage,
|
||||
FunctionVersion,
|
||||
PythonRuntimeSpec,
|
||||
SecretBinding,
|
||||
@@ -149,6 +151,59 @@ def test_function_version_identity_is_immutable_and_exact():
|
||||
FunctionVersion(**{**value, "version": invalid})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gpu", [False, True])
|
||||
def test_image_inspection_is_concise_warning_free_and_preserves_wire_state(gpu):
|
||||
value = job_result("remote_function_job.json")["image"]
|
||||
value["descriptor"]["future_metadata"] = "x" * 100_000
|
||||
if gpu:
|
||||
value["descriptor"]["requires"]["capabilities"] = [
|
||||
{
|
||||
"type": "lance.cuda",
|
||||
"version": 1,
|
||||
"device_count": 1,
|
||||
"cuda_toolkit": "12.4",
|
||||
}
|
||||
]
|
||||
image = FunctionImage(**value)
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", DeprecationWarning)
|
||||
details = image.describe()
|
||||
rendered = repr(image)
|
||||
assert "manifest_digest=" in str(image)
|
||||
encoded = json.loads(image.to_canonical_json())
|
||||
assert details == {
|
||||
"manifest_digest": value["manifest_digest"],
|
||||
"python_version": "3.12.14",
|
||||
"requires_gpu": gpu,
|
||||
"cuda_toolkit": "12.4" if gpu else None,
|
||||
"platforms": None,
|
||||
"base_image": None,
|
||||
"size_bytes": None,
|
||||
}
|
||||
assert len(rendered) < 350
|
||||
assert f"requires_gpu={gpu}" in rendered
|
||||
assert "future_metadata" not in rendered
|
||||
assert encoded == value
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"descriptor",
|
||||
[
|
||||
{},
|
||||
{"format_version": 2, "requires": {"capabilities": []}},
|
||||
{"format_version": 1, "requires": {"capabilities": [None]}},
|
||||
{"python": {"version": {"future": "x" * 100_000}}},
|
||||
],
|
||||
)
|
||||
def test_image_inspection_leaves_missing_or_unrecognized_metadata_unknown(descriptor):
|
||||
image = FunctionImage(
|
||||
manifest_digest="sha256:example", descriptor=descriptor, source=True
|
||||
)
|
||||
assert image.describe()["requires_gpu"] is None
|
||||
assert image.describe()["python_version"] is None
|
||||
assert len(repr(image)) < 350
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"case", json.loads(fixture("runtime_identity.json")), ids=lambda case: case["name"]
|
||||
)
|
||||
|
||||
@@ -9,7 +9,7 @@ import functools
|
||||
import importlib.util
|
||||
import inspect
|
||||
import types
|
||||
from datetime import date
|
||||
from datetime import date, datetime, timedelta
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
@@ -19,15 +19,17 @@ import sys
|
||||
import typing
|
||||
import urllib.parse
|
||||
import warnings
|
||||
from typing import Optional
|
||||
from decimal import Decimal
|
||||
from typing import Annotated, Optional
|
||||
|
||||
import pyarrow as pa
|
||||
import pytest
|
||||
|
||||
import lancedb
|
||||
from lancedb import BlobReader
|
||||
from lancedb.db import AsyncConnection
|
||||
from lancedb.db import AsyncConnection, DBConnection, LanceDBConnection
|
||||
from lancedb.functions import (
|
||||
FunctionRegistrationRequest,
|
||||
FunctionSignature,
|
||||
FunctionVersion,
|
||||
HuggingFaceModel,
|
||||
@@ -82,6 +84,63 @@ def analyze_caption(caption: str) -> str:
|
||||
return caption.strip()
|
||||
|
||||
|
||||
def _function_version_with_resolved_environment():
|
||||
version = json.loads(
|
||||
(FIXTURES / "remote_function_version.canonical.json").read_text()
|
||||
)
|
||||
version["runtime"] = json.loads(
|
||||
normalize_score.registration_request.runtime.to_canonical_json()
|
||||
)
|
||||
version["resolved_environment"] = {
|
||||
"packages": [
|
||||
{
|
||||
"name": "torch",
|
||||
"version": "2.9.0+cu130",
|
||||
"source": "https://packages.example/simple",
|
||||
},
|
||||
{"name": "transformers", "version": "4.57.1"},
|
||||
],
|
||||
"provenance": {
|
||||
"configured_index_urls": ["https://packages.example/simple"],
|
||||
"configured_find_links": ["https://downloads.example/wheels"],
|
||||
"resolved_indexes": ["https://packages.example/simple"],
|
||||
"cuda_toolkit": "12.8",
|
||||
"torch_version": "torch==2.9.0+cu130",
|
||||
},
|
||||
"warnings": [
|
||||
"transformers resolved to transformers==4.57.1 but is not pinned "
|
||||
"exactly; add transformers==4.57.1 to pin it."
|
||||
],
|
||||
}
|
||||
return version
|
||||
|
||||
|
||||
def _function_version_with_resolved_environments():
|
||||
version = json.loads(
|
||||
(FIXTURES / "remote_function_version.canonical.json").read_text()
|
||||
)
|
||||
version["runtime"] = json.loads(
|
||||
normalize_score.registration_request.runtime.to_canonical_json()
|
||||
)
|
||||
version["resolved_environments"] = {
|
||||
"linux/amd64": {
|
||||
"packages": [
|
||||
{
|
||||
"name": "torch",
|
||||
"version": "2.9.0+cu130",
|
||||
"source": "https://packages.example/simple",
|
||||
}
|
||||
],
|
||||
"warnings": ["amd64 environment warning"],
|
||||
},
|
||||
"linux/arm64": {
|
||||
"packages": [],
|
||||
"warnings": ["arm64 environment warning"],
|
||||
},
|
||||
}
|
||||
return version
|
||||
|
||||
|
||||
def test_scalar_function_matches_shared_registration_golden_and_remains_callable():
|
||||
assert isinstance(normalize_score, FunctionDefinition)
|
||||
assert normalize_score(25.0) == 0.25
|
||||
@@ -98,6 +157,118 @@ def test_scalar_function_matches_shared_registration_golden_and_remains_callable
|
||||
}
|
||||
|
||||
|
||||
def test_refresh_lock_is_a_registration_option_not_part_of_identity():
|
||||
default = normalize_score.registration_request
|
||||
old_json = default.to_canonical_json()
|
||||
assert "refresh_lock" not in json.loads(old_json)
|
||||
|
||||
refreshed = default.with_refresh_lock(True)
|
||||
payload = json.loads(refreshed.to_canonical_json())
|
||||
assert payload["refresh_lock"] is True
|
||||
assert (
|
||||
FunctionRegistrationRequest.from_json(
|
||||
refreshed.to_canonical_json()
|
||||
).refresh_lock
|
||||
is True
|
||||
)
|
||||
assert refreshed.artifact.digest == default.artifact.digest
|
||||
assert refreshed.runtime.digest == default.runtime.digest
|
||||
assert default.with_refresh_lock(False).to_canonical_json() == old_json
|
||||
with pytest.raises(ValueError, match="refresh_lock must be a boolean"):
|
||||
default.with_refresh_lock(1)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("exist_ok", [False, True])
|
||||
async def test_async_create_function_forwards_refresh_lock(exist_ok):
|
||||
calls = []
|
||||
|
||||
class Inner:
|
||||
async def create_function_async(
|
||||
self, request_json, namespace_path=None, *, exist_ok=False
|
||||
):
|
||||
calls.append((json.loads(request_json), namespace_path, exist_ok))
|
||||
return object()
|
||||
|
||||
connection = object.__new__(AsyncConnection)
|
||||
connection._inner = Inner()
|
||||
await connection.create_function_async(normalize_score)
|
||||
await connection.create_function_async(
|
||||
normalize_score, refresh_lock=True, exist_ok=exist_ok, namespace_path=["team"]
|
||||
)
|
||||
with pytest.raises(ValueError, match="refresh_lock must be a boolean"):
|
||||
await connection.create_function_async(normalize_score, refresh_lock=1)
|
||||
|
||||
assert len(calls) == 2
|
||||
assert "refresh_lock" not in calls[0][0]
|
||||
assert calls[0][1:] == (None, False)
|
||||
assert calls[1][0]["refresh_lock"] is True
|
||||
assert calls[1][1:] == (["team"], exist_ok)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("exist_ok", [False, True])
|
||||
def test_sync_create_function_paths_forward_refresh_lock(exist_ok):
|
||||
calls = []
|
||||
|
||||
class AsyncInner:
|
||||
async def create_function_async(
|
||||
self,
|
||||
definition,
|
||||
*,
|
||||
secrets=None,
|
||||
exist_ok=False,
|
||||
namespace_path=None,
|
||||
refresh_lock=False,
|
||||
):
|
||||
calls.append(("wrapped", refresh_lock, namespace_path, exist_ok))
|
||||
return object()
|
||||
|
||||
for connection_type in (LanceDBConnection, RemoteDBConnection):
|
||||
connection = object.__new__(connection_type)
|
||||
connection._conn = AsyncInner()
|
||||
connection.create_function_async(
|
||||
normalize_score,
|
||||
refresh_lock=True,
|
||||
exist_ok=exist_ok,
|
||||
namespace_path=["team"],
|
||||
)
|
||||
|
||||
class BlockingConnection:
|
||||
def create_function_async(
|
||||
self,
|
||||
definition,
|
||||
*,
|
||||
secrets=None,
|
||||
exist_ok=False,
|
||||
namespace_path=None,
|
||||
refresh_lock=False,
|
||||
):
|
||||
calls.append(("blocking", refresh_lock, namespace_path, exist_ok))
|
||||
|
||||
class ImmediateJob:
|
||||
def wait(self):
|
||||
return "version"
|
||||
|
||||
return ImmediateJob()
|
||||
|
||||
blocking = BlockingConnection()
|
||||
assert (
|
||||
DBConnection.create_function(
|
||||
blocking,
|
||||
normalize_score,
|
||||
refresh_lock=True,
|
||||
exist_ok=exist_ok,
|
||||
namespace_path=["team"],
|
||||
)
|
||||
== "version"
|
||||
)
|
||||
assert calls == [
|
||||
("wrapped", True, ["team"], exist_ok),
|
||||
("wrapped", True, ["team"], exist_ok),
|
||||
("blocking", True, ["team"], exist_ok),
|
||||
]
|
||||
|
||||
|
||||
def test_function_declares_pinned_hugging_face_models():
|
||||
model = HuggingFaceModel(
|
||||
repo="sentence-transformers/all-MiniLM-L6-v2",
|
||||
@@ -884,12 +1055,10 @@ def test_canonical_arrow_type_prefers_the_compact_grammar():
|
||||
== "large_list<float32>"
|
||||
)
|
||||
for outside in [
|
||||
pa.timestamp("us"),
|
||||
pa.decimal128(10, 2),
|
||||
pa.binary(4),
|
||||
pa.duration("s"),
|
||||
pa.time32("s"),
|
||||
pa.time64("us"),
|
||||
pa.list_(pa.float32(), 0),
|
||||
pa.list_(pa.timestamp("us")),
|
||||
]:
|
||||
with pytest.raises(TypeError, match="unsupported Arrow type"):
|
||||
_canonical_arrow_type(outside)
|
||||
@@ -1215,6 +1384,304 @@ def test_explicit_arrow_schema_is_deterministic():
|
||||
assert signature.output.nullable is False
|
||||
|
||||
|
||||
def test_timestamp_annotation_and_explicit_schema_serialization():
|
||||
for unit in ("s", "ms", "us", "ns"):
|
||||
for timezone in (None, "UTC", "America/New_York", "+08:00", "-05:00"):
|
||||
encoded = json.loads(_canonical_arrow_type(pa.timestamp(unit, tz=timezone)))
|
||||
if unit == "us" and timezone is None:
|
||||
assert encoded == {"type": "timestamp"}
|
||||
else:
|
||||
suffix = timezone if timezone is not None else "-"
|
||||
assert encoded == {"type": f"timestamp:{unit}:{suffix}"}
|
||||
|
||||
with pytest.raises(TypeError, match="reserved for no timezone"):
|
||||
_canonical_arrow_type(pa.timestamp("us", tz="-"))
|
||||
|
||||
@function
|
||||
def normalize(
|
||||
ts: Annotated[datetime, pa.timestamp("ns", tz="UTC")],
|
||||
) -> Annotated[datetime, pa.timestamp("ns", tz="UTC")]:
|
||||
return ts
|
||||
|
||||
signature = normalize.registration_request.signature
|
||||
assert json.loads(signature.inputs[0].arrow_type) == {"type": "timestamp:ns:UTC"}
|
||||
assert json.loads(signature.output.arrow_type) == {"type": "timestamp:ns:UTC"}
|
||||
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
|
||||
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
|
||||
assert round_trip.output.arrow_type == signature.output.arrow_type
|
||||
|
||||
@function
|
||||
def optional_timestamp(
|
||||
ts: Optional[Annotated[datetime, pa.timestamp("ms", tz="UTC")]],
|
||||
) -> int:
|
||||
return 0
|
||||
|
||||
optional_input = optional_timestamp.registration_request.signature.inputs[0]
|
||||
assert optional_input.nullable is True
|
||||
assert json.loads(optional_input.arrow_type) == {"type": "timestamp:ms:UTC"}
|
||||
|
||||
@function
|
||||
def legacy(ts: datetime) -> datetime:
|
||||
return ts
|
||||
|
||||
legacy_signature = legacy.registration_request.signature
|
||||
assert json.loads(legacy_signature.inputs[0].arrow_type) == {"type": "timestamp"}
|
||||
assert json.loads(legacy_signature.output.arrow_type) == {"type": "timestamp"}
|
||||
legacy_round_trip = FunctionSignature.from_json(
|
||||
legacy_signature.to_canonical_json()
|
||||
)
|
||||
assert legacy_round_trip.inputs[0].arrow_type == '{"type":"timestamp"}'
|
||||
|
||||
input_schema = pa.schema(
|
||||
[pa.field("ts", pa.timestamp("ms", tz="America/New_York"), nullable=True)]
|
||||
)
|
||||
output_schema = pa.schema(
|
||||
[
|
||||
pa.field("ts", pa.timestamp("ns", tz="+08:00"), nullable=True),
|
||||
pa.field("elapsed", pa.duration("ms"), nullable=False),
|
||||
]
|
||||
)
|
||||
|
||||
@function(input_schema=input_schema, output_schema=output_schema)
|
||||
def nested(ts):
|
||||
return {"ts": ts, "elapsed": None}
|
||||
|
||||
nested_signature = nested.registration_request.signature
|
||||
assert nested_signature.inputs[0].nullable is True
|
||||
assert json.loads(nested_signature.inputs[0].arrow_type) == {
|
||||
"type": "timestamp:ms:America/New_York"
|
||||
}
|
||||
assert nested_signature.output.kind == "named_struct"
|
||||
assert nested_signature.output.fields[0].nullable is True
|
||||
assert json.loads(nested_signature.output.fields[0].arrow_type) == {
|
||||
"type": "timestamp:ns:+08:00"
|
||||
}
|
||||
assert json.loads(nested_signature.output.fields[1].arrow_type) == {
|
||||
"type": "duration:ms"
|
||||
}
|
||||
|
||||
list_type = pa.list_(pa.field("item", pa.timestamp("ms", tz="UTC"), nullable=False))
|
||||
assert json.loads(_canonical_arrow_type(list_type)) == {
|
||||
"type": "list",
|
||||
"fields": [
|
||||
{
|
||||
"name": "item",
|
||||
"nullable": False,
|
||||
"type": {"type": "timestamp:ms:UTC"},
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_duration_annotation_and_explicit_schema_serialization():
|
||||
for unit in ("s", "ms", "us", "ns"):
|
||||
encoded = json.loads(_canonical_arrow_type(pa.duration(unit)))
|
||||
expected = (
|
||||
{"type": "duration"} if unit == "us" else {"type": f"duration:{unit}"}
|
||||
)
|
||||
assert encoded == expected
|
||||
|
||||
@function
|
||||
def elapsed(
|
||||
value: Annotated[timedelta, pa.duration("s")],
|
||||
) -> Annotated[timedelta, pa.duration("ns")]:
|
||||
return value
|
||||
|
||||
signature = elapsed.registration_request.signature
|
||||
assert json.loads(signature.inputs[0].arrow_type) == {"type": "duration:s"}
|
||||
assert json.loads(signature.output.arrow_type) == {"type": "duration:ns"}
|
||||
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
|
||||
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
|
||||
assert round_trip.output.arrow_type == signature.output.arrow_type
|
||||
|
||||
@function
|
||||
def optional_elapsed(
|
||||
value: Optional[Annotated[timedelta, pa.duration("ms")]],
|
||||
) -> int:
|
||||
return 0
|
||||
|
||||
optional_input = optional_elapsed.registration_request.signature.inputs[0]
|
||||
assert optional_input.nullable is True
|
||||
assert json.loads(optional_input.arrow_type) == {"type": "duration:ms"}
|
||||
|
||||
with pytest.raises(
|
||||
TypeError, match="timedelta Function annotations require an explicit unit"
|
||||
):
|
||||
|
||||
@function
|
||||
def missing(value: timedelta) -> timedelta:
|
||||
return value
|
||||
|
||||
input_schema = pa.schema([pa.field("elapsed", pa.duration("ms"), nullable=True)])
|
||||
output_schema = pa.field("result", pa.duration("us"), nullable=False)
|
||||
|
||||
@function(input_schema=input_schema, output_schema=output_schema)
|
||||
def explicit(elapsed: timedelta) -> timedelta:
|
||||
return elapsed
|
||||
|
||||
explicit_signature = explicit.registration_request.signature
|
||||
assert explicit_signature.inputs[0].nullable is True
|
||||
assert json.loads(explicit_signature.inputs[0].arrow_type) == {
|
||||
"type": "duration:ms"
|
||||
}
|
||||
assert json.loads(explicit_signature.output.arrow_type) == {"type": "duration"}
|
||||
explicit_round_trip = FunctionSignature.from_json(
|
||||
explicit_signature.to_canonical_json()
|
||||
)
|
||||
assert explicit_round_trip.output.arrow_type == '{"type":"duration"}'
|
||||
|
||||
|
||||
def test_map_annotation_and_explicit_schema_serialization():
|
||||
@function
|
||||
def map_round_trip(values: dict[str, int]) -> dict[str, int]:
|
||||
return values
|
||||
|
||||
signature = map_round_trip.registration_request.signature
|
||||
expected = {
|
||||
"type": "map",
|
||||
"fields": [
|
||||
{
|
||||
"name": "entries",
|
||||
"nullable": False,
|
||||
"type": {
|
||||
"type": "struct",
|
||||
"fields": [
|
||||
{
|
||||
"name": "key",
|
||||
"nullable": False,
|
||||
"type": {"type": "utf8"},
|
||||
},
|
||||
{
|
||||
"name": "value",
|
||||
"nullable": False,
|
||||
"type": {"type": "int64"},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
assert json.loads(signature.inputs[0].arrow_type) == expected
|
||||
assert json.loads(signature.output.arrow_type) == expected
|
||||
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
|
||||
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
|
||||
assert round_trip.output.arrow_type == signature.output.arrow_type
|
||||
|
||||
@function
|
||||
def nullable_values(
|
||||
values: dict[str, Optional[int]],
|
||||
) -> dict[str, Optional[int]]:
|
||||
return values
|
||||
|
||||
nullable_signature = nullable_values.registration_request.signature
|
||||
nullable_map = json.loads(nullable_signature.inputs[0].arrow_type)
|
||||
assert nullable_map["fields"][0]["type"]["fields"][1] == {
|
||||
"name": "value",
|
||||
"nullable": True,
|
||||
"type": {"type": "int64"},
|
||||
}
|
||||
|
||||
input_schema = pa.schema(
|
||||
[
|
||||
pa.field(
|
||||
"values",
|
||||
pa.map_(pa.string(), pa.field("custom", pa.int64(), nullable=True)),
|
||||
nullable=False,
|
||||
)
|
||||
]
|
||||
)
|
||||
output_schema = pa.field(
|
||||
"result",
|
||||
pa.map_(pa.string(), pa.field("value", pa.int64(), nullable=False)),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
@function(input_schema=input_schema, output_schema=output_schema)
|
||||
def explicit(values):
|
||||
return {}
|
||||
|
||||
explicit_signature = explicit.registration_request.signature
|
||||
explicit_input = json.loads(explicit_signature.inputs[0].arrow_type)
|
||||
assert explicit_input["fields"][0]["type"]["fields"][1] == {
|
||||
"name": "custom",
|
||||
"nullable": True,
|
||||
"type": {"type": "int64"},
|
||||
}
|
||||
explicit_output = json.loads(explicit_signature.output.arrow_type)
|
||||
assert explicit_output["fields"][0]["type"]["fields"][1]["nullable"] is False
|
||||
|
||||
|
||||
def test_map_rejects_unsupported_boundaries():
|
||||
with pytest.raises(TypeError, match="map keys_sorted=true"):
|
||||
_canonical_arrow_type(pa.map_(pa.string(), pa.int64(), keys_sorted=True))
|
||||
with pytest.raises(TypeError, match="map keys must be non-nullable utf8"):
|
||||
_canonical_arrow_type(pa.map_(pa.int64(), pa.int64()))
|
||||
with pytest.raises(TypeError, match="Blob v2 fields nested under"):
|
||||
_canonical_arrow_type(pa.map_(pa.string(), lancedb.blob("image").type))
|
||||
with pytest.raises(TypeError, match="map keys must be str"):
|
||||
|
||||
@function
|
||||
def invalid_keys(values: dict[int, int]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def test_decimal_annotation_and_explicit_schema_serialization():
|
||||
@function
|
||||
def price(
|
||||
amount: Annotated[Decimal, pa.decimal128(10, 2)],
|
||||
) -> Annotated[Decimal, pa.decimal256(50, 4)]:
|
||||
return Decimal("1.0000")
|
||||
|
||||
signature = price.registration_request.signature
|
||||
assert json.loads(signature.inputs[0].arrow_type) == {
|
||||
"type": "decimal128",
|
||||
"length": 10002,
|
||||
}
|
||||
assert json.loads(signature.output.arrow_type) == {
|
||||
"type": "decimal256",
|
||||
"length": 50004,
|
||||
}
|
||||
round_trip = FunctionSignature.from_json(signature.to_canonical_json())
|
||||
assert round_trip.inputs[0].arrow_type == signature.inputs[0].arrow_type
|
||||
assert round_trip.output.arrow_type == signature.output.arrow_type
|
||||
assert json.loads(_canonical_arrow_type(pa.decimal128(10, -2))) == {
|
||||
"type": "decimal128",
|
||||
"length": 9998,
|
||||
}
|
||||
decimal_map = json.loads(
|
||||
_canonical_arrow_type(pa.map_(pa.string(), pa.decimal128(10, 2)))
|
||||
)
|
||||
assert decimal_map["fields"][0]["type"]["fields"][1]["type"] == {
|
||||
"type": "decimal128",
|
||||
"length": 10002,
|
||||
}
|
||||
|
||||
input_schema = pa.schema([pa.field("amount", pa.decimal128(12, 2), nullable=False)])
|
||||
output_schema = pa.field("result", pa.decimal256(60, 6), nullable=False)
|
||||
|
||||
@function(input_schema=input_schema, output_schema=output_schema)
|
||||
def explicit(amount: Decimal) -> Decimal:
|
||||
return amount
|
||||
|
||||
explicit_signature = explicit.registration_request.signature
|
||||
assert json.loads(explicit_signature.inputs[0].arrow_type) == {
|
||||
"type": "decimal128",
|
||||
"length": 12002,
|
||||
}
|
||||
assert json.loads(explicit_signature.output.arrow_type) == {
|
||||
"type": "decimal256",
|
||||
"length": 60006,
|
||||
}
|
||||
|
||||
with pytest.raises(
|
||||
TypeError, match="Decimal Function annotations require precision and scale"
|
||||
):
|
||||
|
||||
@function
|
||||
def missing(amount: Decimal) -> Decimal:
|
||||
return amount
|
||||
|
||||
|
||||
def test_nullable_scalar_output_annotation_and_explicit_schema():
|
||||
input_schema = pa.schema([pa.field("value", pa.int64(), nullable=False)])
|
||||
|
||||
@@ -2059,6 +2526,205 @@ class _RawFunctionCatalog:
|
||||
return None
|
||||
|
||||
|
||||
def test_function_version_reads_requested_and_resolved_environments():
|
||||
legacy = json.loads(
|
||||
(FIXTURES / "remote_function_version.canonical.json").read_text()
|
||||
)
|
||||
legacy_version = FunctionVersion.from_json(json.dumps(legacy))
|
||||
assert legacy_version.runtime is None
|
||||
assert legacy_version.resolved_environment is None
|
||||
assert legacy_version.environment.requested is None
|
||||
assert legacy_version.environment.resolved is None
|
||||
|
||||
payload = _function_version_with_resolved_environment()
|
||||
version = FunctionVersion.from_json(json.dumps(payload))
|
||||
assert version.environment.requested is version.runtime
|
||||
assert version.environment.resolved is version.resolved_environment
|
||||
assert version.runtime.kind == "python"
|
||||
resolved = version.resolved_environment
|
||||
assert resolved.packages[0].version == "2.9.0+cu130"
|
||||
assert resolved.packages[0].source == "https://packages.example/simple"
|
||||
assert resolved.packages[1].source is None
|
||||
assert resolved.provenance.torch_version == "torch==2.9.0+cu130"
|
||||
assert resolved.warnings == tuple(payload["resolved_environment"]["warnings"])
|
||||
|
||||
encoded = json.loads(version.to_canonical_json())
|
||||
assert encoded["runtime"]["kind"] == "python"
|
||||
assert encoded["resolved_environment"]["packages"][0]["version"] == "2.9.0+cu130"
|
||||
assert "source" not in encoded["resolved_environment"]["packages"][1]
|
||||
assert (
|
||||
encoded["resolved_environment"]["provenance"]["torch_version"]
|
||||
== "torch==2.9.0+cu130"
|
||||
)
|
||||
assert FunctionVersion.from_json(version.to_canonical_json()) == version
|
||||
|
||||
invalid = json.loads(json.dumps(payload))
|
||||
del invalid["resolved_environment"]["packages"]
|
||||
with pytest.raises(ValueError):
|
||||
FunctionVersion.from_json(json.dumps(invalid))
|
||||
|
||||
|
||||
def test_function_version_reads_resolved_environments_by_platform():
|
||||
legacy = json.loads(
|
||||
(FIXTURES / "remote_function_version.canonical.json").read_text()
|
||||
)
|
||||
legacy_version = FunctionVersion.from_json(json.dumps(legacy))
|
||||
assert legacy_version.resolved_environment is None
|
||||
assert legacy_version.resolved_environments == {}
|
||||
assert legacy_version.environment_report == {}
|
||||
|
||||
payload = _function_version_with_resolved_environments()
|
||||
version = FunctionVersion.from_json(json.dumps(payload))
|
||||
assert version.resolved_environment is None
|
||||
assert version.resolved_environments == version.environment_report
|
||||
assert set(version.environment_report) == {"linux/amd64", "linux/arm64"}
|
||||
assert (
|
||||
version.environment_report["linux/amd64"].packages[0].version == "2.9.0+cu130"
|
||||
)
|
||||
assert version.environment_report["linux/arm64"].packages == ()
|
||||
assert version.environment_report["linux/arm64"].warnings == (
|
||||
"arm64 environment warning",
|
||||
)
|
||||
|
||||
encoded = json.loads(version.to_canonical_json())
|
||||
assert "resolved_environment" not in encoded
|
||||
assert (
|
||||
encoded["resolved_environments"]["linux/amd64"]["packages"][0]["version"]
|
||||
== "2.9.0+cu130"
|
||||
)
|
||||
assert encoded["resolved_environments"]["linux/arm64"]["packages"] == []
|
||||
assert FunctionVersion.from_json(version.to_canonical_json()) == version
|
||||
|
||||
missing_platform = json.loads(json.dumps(payload))
|
||||
del missing_platform["resolved_environments"]["linux/arm64"]
|
||||
missing_version = FunctionVersion.from_json(json.dumps(missing_platform))
|
||||
assert "linux/arm64" not in missing_version.environment_report
|
||||
assert "linux/amd64" in missing_version.environment_report
|
||||
|
||||
empty_map = json.loads(json.dumps(payload))
|
||||
empty_map["resolved_environments"] = {}
|
||||
empty_version = FunctionVersion.from_json(json.dumps(empty_map))
|
||||
assert empty_version.resolved_environments == {}
|
||||
assert "resolved_environments" not in json.loads(empty_version.to_canonical_json())
|
||||
|
||||
invalid = json.loads(json.dumps(payload))
|
||||
del invalid["resolved_environments"]["linux/amd64"]["packages"]
|
||||
with pytest.raises(ValueError):
|
||||
FunctionVersion.from_json(json.dumps(invalid))
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_registration_job_emits_server_environment_warnings_once():
|
||||
payload = _function_version_with_resolved_environment()
|
||||
|
||||
class InnerJob:
|
||||
async def wait(self):
|
||||
return json.dumps(payload)
|
||||
|
||||
class Inner:
|
||||
async def create_function_async(
|
||||
self, request_json, namespace_path=None, *, exist_ok=False
|
||||
):
|
||||
assert "refresh_lock" not in json.loads(request_json)
|
||||
return InnerJob()
|
||||
|
||||
connection = object.__new__(AsyncConnection)
|
||||
connection._inner = Inner()
|
||||
job = await connection.create_function_async(normalize_score)
|
||||
with pytest.warns(UserWarning) as recorded:
|
||||
version = await job.wait()
|
||||
assert [str(w.message) for w in recorded] == list(
|
||||
payload["resolved_environment"]["warnings"]
|
||||
)
|
||||
assert version.environment.resolved.warnings == tuple(
|
||||
payload["resolved_environment"]["warnings"]
|
||||
)
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
assert await job.wait() is not None
|
||||
assert caught == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_registration_job_emits_per_platform_environment_warnings():
|
||||
payload = _function_version_with_resolved_environments()
|
||||
|
||||
class InnerJob:
|
||||
async def wait(self):
|
||||
return json.dumps(payload)
|
||||
|
||||
class Inner:
|
||||
async def create_function_async(
|
||||
self, request_json, namespace_path=None, *, exist_ok=False
|
||||
):
|
||||
return InnerJob()
|
||||
|
||||
connection = object.__new__(AsyncConnection)
|
||||
connection._inner = Inner()
|
||||
job = await connection.create_function_async(normalize_score)
|
||||
with pytest.warns(UserWarning) as recorded:
|
||||
version = await job.wait()
|
||||
assert [str(w.message) for w in recorded] == [
|
||||
"amd64 environment warning",
|
||||
"arm64 environment warning",
|
||||
]
|
||||
assert version.environment_report["linux/arm64"].warnings == (
|
||||
"arm64 environment warning",
|
||||
)
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
assert await job.wait() is not None
|
||||
assert caught == []
|
||||
|
||||
|
||||
def test_blocking_create_function_emits_server_environment_warnings():
|
||||
payload = _function_version_with_resolved_environment()
|
||||
|
||||
class InnerJob:
|
||||
async def wait(self):
|
||||
return json.dumps(payload)
|
||||
|
||||
class Inner:
|
||||
async def create_function_async(
|
||||
self, request_json, namespace_path=None, *, exist_ok=False
|
||||
):
|
||||
return InnerJob()
|
||||
|
||||
connection = object.__new__(RemoteDBConnection)
|
||||
connection._conn = AsyncConnection(Inner())
|
||||
with pytest.warns(UserWarning) as recorded:
|
||||
version = DBConnection.create_function(connection, normalize_score)
|
||||
assert [str(w.message) for w in recorded] == list(
|
||||
payload["resolved_environment"]["warnings"]
|
||||
)
|
||||
assert version.environment.resolved.packages[0].version == "2.9.0+cu130"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_readback_does_not_replay_registration_warnings():
|
||||
payload = _function_version_with_resolved_environment()
|
||||
connection = AsyncConnection(_RawFunctionCatalog(payload, encode=True))
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
version = await connection.get_function("embed")
|
||||
listed = [item async for item in connection.list_functions()]
|
||||
assert caught == []
|
||||
assert version.environment.resolved.packages[0].version == "2.9.0+cu130"
|
||||
assert listed[0].environment.resolved == version.resolved_environment
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_catalog_readback_does_not_replay_per_platform_warnings():
|
||||
payload = _function_version_with_resolved_environments()
|
||||
connection = AsyncConnection(_RawFunctionCatalog(payload, encode=True))
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
version = await connection.get_function("embed")
|
||||
listed = [item async for item in connection.list_functions()]
|
||||
assert caught == []
|
||||
assert version.environment_report == listed[0].environment_report
|
||||
|
||||
|
||||
def _assert_execution_control_encoding(version):
|
||||
encoded = json.loads(version.to_canonical_json())
|
||||
assert type(encoded["batch_size"]) is int
|
||||
|
||||
+172
-12
@@ -29,6 +29,7 @@ from lancedb.query import (
|
||||
CombinedFieldsQuery,
|
||||
DocumentGranularity,
|
||||
FullTextOperator,
|
||||
FullTextSearchQuery,
|
||||
MatchQuery,
|
||||
MultiMatchQuery,
|
||||
PhraseQuery,
|
||||
@@ -530,11 +531,9 @@ async def test_fts_select_async(async_table):
|
||||
|
||||
def test_search_fts_phrase_query(table):
|
||||
table.create_fts_index("text", with_position=False)
|
||||
try:
|
||||
phrase_results = table.search('"puppy runs"').limit(100).to_list()
|
||||
assert False
|
||||
except Exception:
|
||||
pass
|
||||
with pytest.raises(Exception) as error:
|
||||
table.search('"puppy runs"').limit(100).to_list()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
table.create_fts_index("text", with_position=True, replace=True)
|
||||
results = table.search("puppy").limit(100).to_list()
|
||||
|
||||
@@ -559,13 +558,9 @@ def test_search_fts_phrase_query(table):
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_fts_phrase_query_async(async_table):
|
||||
await async_table.create_index("text", config=FTS(with_position=False))
|
||||
try:
|
||||
phrase_results = (
|
||||
await async_table.query().nearest_to_text("puppy runs").limit(100).to_list()
|
||||
)
|
||||
assert False
|
||||
except Exception:
|
||||
pass
|
||||
with pytest.raises(Exception) as error:
|
||||
await async_table.query().nearest_to_text('"puppy runs"').to_list()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
await async_table.create_index("text", config=FTS(with_position=True))
|
||||
results = await async_table.query().nearest_to_text("puppy").limit(100).to_list()
|
||||
phrase_results = (
|
||||
@@ -1948,3 +1943,168 @@ async def test_async_fts_code_analyzer(mem_db_async):
|
||||
|
||||
rows = await table.query().nearest_to_text("http").to_list()
|
||||
assert len(rows) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)])
|
||||
def test_simple_fts_operator_and_count(tmp_path, indexed, operator, expected):
|
||||
db = ldb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"matches",
|
||||
pa.table(
|
||||
{
|
||||
"id": list(range(30)),
|
||||
"text": ["gripper closed"] * 15
|
||||
+ ["gripper open"] * 10
|
||||
+ ["camera ready"] * 5,
|
||||
}
|
||||
),
|
||||
)
|
||||
if indexed:
|
||||
table.create_index("text", config=FTS())
|
||||
kwargs = {"fts_columns": "text"}
|
||||
if operator is not None:
|
||||
kwargs["operator"] = operator
|
||||
query = table.search("gripper closed", query_type="fts", **kwargs)
|
||||
assert query.count_rows() == expected
|
||||
assert len(query.limit(100).to_list()) == expected
|
||||
assert (
|
||||
table.search("gripper closed", query_type="fts", fts_columns="text")
|
||||
.operator("AND")
|
||||
.count_rows()
|
||||
== 15
|
||||
)
|
||||
if operator is not None:
|
||||
assert query.to_query_object().full_text_query.operator == operator
|
||||
query.where("id >= 5", prefilter=False).select(["id"]).limit(2).offset(1)
|
||||
before = query.to_query_object()
|
||||
assert query.count_rows() == expected - 5
|
||||
assert query.to_query_object() == before
|
||||
assert len(query.to_list()) <= 2
|
||||
assert (
|
||||
table.search("absent", query_type="fts", fts_columns="text").count_rows() == 0
|
||||
)
|
||||
assert (
|
||||
table.search(MatchQuery("gripper closed", "text", operator="AND")).count_rows()
|
||||
== 15
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("indexed", [False, True])
|
||||
@pytest.mark.parametrize("operator,expected", [(None, 25), ("OR", 25), ("AND", 15)])
|
||||
async def test_simple_fts_operator_and_count_async(
|
||||
tmp_path, indexed, operator, expected
|
||||
):
|
||||
db = await ldb.connect_async(tmp_path)
|
||||
table = await db.create_table(
|
||||
"matches",
|
||||
pa.table(
|
||||
{
|
||||
"id": list(range(30)),
|
||||
"text": ["gripper closed"] * 15
|
||||
+ ["gripper open"] * 10
|
||||
+ ["camera ready"] * 5,
|
||||
}
|
||||
),
|
||||
)
|
||||
if indexed:
|
||||
await table.create_index("text", config=FTS())
|
||||
query = await table.search(
|
||||
"gripper closed", query_type="fts", fts_columns="text", operator=operator
|
||||
)
|
||||
assert await query.count_rows() == expected
|
||||
assert len(await query.limit(100).to_list()) == expected
|
||||
query.where("id >= 5").postfilter().select(["id"]).limit(2).offset(1)
|
||||
before = query.to_query_object()
|
||||
assert await query.count_rows() == expected - 5
|
||||
assert query.to_query_object() == before
|
||||
direct = table.query().nearest_to_text(
|
||||
"gripper closed", columns="text", operator="AND"
|
||||
)
|
||||
assert await direct.count_rows() == 15
|
||||
assert direct.to_query_object().full_text_query.query.operator == "AND"
|
||||
assert (
|
||||
await table.query().nearest_to_text("absent", columns="text").count_rows() == 0
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("with_position", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"query", ['"gripper closed"', PhraseQuery("gripper closed", "text")]
|
||||
)
|
||||
def test_fts_phrase_count_positions(tmp_path, with_position, query):
|
||||
table = ldb.connect(tmp_path).create_table(
|
||||
"phrases", pa.table({"text": ["gripper closed", "gripper often closed"]})
|
||||
)
|
||||
table.create_index("text", config=FTS(with_position=with_position))
|
||||
search = table.search(query, query_type="fts")
|
||||
if with_position:
|
||||
assert search.count_rows() == 1
|
||||
assert len(search.to_list()) == 1
|
||||
assert (
|
||||
table.search("gripper closed", query_type="fts", operator="AND")
|
||||
.phrase_query()
|
||||
.count_rows()
|
||||
== 1
|
||||
)
|
||||
else:
|
||||
with pytest.raises(Exception) as error:
|
||||
search.count_rows()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("with_position", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"query", ['"gripper closed"', PhraseQuery("gripper closed", "text")]
|
||||
)
|
||||
async def test_fts_phrase_count_positions_async(tmp_path, with_position, query):
|
||||
db = await ldb.connect_async(tmp_path)
|
||||
table = await db.create_table(
|
||||
"phrases", pa.table({"text": ["gripper closed", "gripper often closed"]})
|
||||
)
|
||||
await table.create_index("text", config=FTS(with_position=with_position))
|
||||
search = table.query().nearest_to_text(query)
|
||||
if with_position:
|
||||
assert await search.count_rows() == 1
|
||||
assert len(await search.to_list()) == 1
|
||||
else:
|
||||
with pytest.raises(Exception) as error:
|
||||
await search.count_rows()
|
||||
assert "FTS(with_position=True)" in exception_output(error)
|
||||
|
||||
|
||||
def test_fts_operator_rejects_invalid_queries(table):
|
||||
with pytest.raises(ValueError):
|
||||
table.search("gripper", query_type="fts", operator="XOR")
|
||||
for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]:
|
||||
with pytest.raises(
|
||||
ValueError, match="operator requires a string full-text query"
|
||||
):
|
||||
table.search(query, operator="AND")
|
||||
with pytest.raises(ValueError, match="operator requires a string full-text query"):
|
||||
FullTextSearchQuery(query=MatchQuery("gripper"), operator="AND")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fts_operator_rejects_invalid_queries_async(async_table):
|
||||
with pytest.raises(ValueError):
|
||||
await async_table.search("gripper", query_type="fts", operator="XOR")
|
||||
for query in [None, [1.0, 2.0], MatchQuery("gripper", "text")]:
|
||||
with pytest.raises(
|
||||
ValueError, match="operator requires a string full-text query"
|
||||
):
|
||||
await async_table.search(query, operator="AND")
|
||||
with pytest.raises(ValueError):
|
||||
async_table.query().nearest_to_text(query, operator="AND")
|
||||
|
||||
|
||||
def test_fts_count_fast_search(tmp_path):
|
||||
table = ldb.connect(tmp_path).create_table(
|
||||
"matches", pa.table({"text": ["gripper closed"] * 15})
|
||||
)
|
||||
table.create_index("text", config=FTS())
|
||||
table.add(pa.table({"text": ["gripper closed"] * 5}))
|
||||
assert table.search("gripper", query_type="fts").count_rows() == 20
|
||||
assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15
|
||||
|
||||
@@ -11,6 +11,7 @@ from unittest.mock import AsyncMock, MagicMock
|
||||
import pytest
|
||||
|
||||
from lancedb.exceptions import JobCancelledError, JobFailedError
|
||||
from lancedb.db import DBConnection
|
||||
from lancedb.job import AsyncJob, Job, _progress_eta
|
||||
from lancedb.remote.errors import HttpError, RetryError
|
||||
|
||||
@@ -729,15 +730,198 @@ async def test_wait_progress_bar_tracks_late_planning_without_regressing(
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_wait_progress_false_keeps_legacy_inner_wait_call():
|
||||
@pytest.mark.parametrize("progress", [False, None])
|
||||
async def test_wait_progress_false_keeps_legacy_inner_wait_call(progress):
|
||||
class NoProgressArgument:
|
||||
id = "job-legacy"
|
||||
job_type = None
|
||||
|
||||
@property
|
||||
def job_type(self):
|
||||
raise AssertionError("quiet waits must not inspect progress metadata")
|
||||
|
||||
async def wait(self):
|
||||
return None
|
||||
|
||||
assert await AsyncJob(NoProgressArgument()).wait(progress=False) is None
|
||||
assert await AsyncJob(NoProgressArgument()).wait(progress=progress) is None
|
||||
|
||||
|
||||
class _RegistrationQuery:
|
||||
id = "registration-query"
|
||||
job_type = "query"
|
||||
_description = None
|
||||
|
||||
def __init__(self, error=None):
|
||||
self.ready = asyncio.Event()
|
||||
self.error = error
|
||||
self.state = "running"
|
||||
self.wait_calls = 0
|
||||
self.cancel_calls = 0
|
||||
|
||||
async def status(self):
|
||||
return self.state
|
||||
|
||||
async def wait(self, progress=None):
|
||||
self.wait_calls += 1
|
||||
await self.ready.wait()
|
||||
if self.error is not None:
|
||||
self.state = (
|
||||
"cancelled" if isinstance(self.error, JobCancelledError) else "failed"
|
||||
)
|
||||
raise self.error
|
||||
self.state = "finished"
|
||||
return '{"version": "1"}'
|
||||
|
||||
async def cancel(self):
|
||||
self.cancel_calls += 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("sync", [False, True])
|
||||
async def test_query_progress_observes_one_registration_waiter(sync, monkeypatch):
|
||||
monkeypatch.setattr("lancedb.job._QUERY_PROGRESS_INTERVAL_SECONDS", 0)
|
||||
inner = _RegistrationQuery()
|
||||
job = AsyncJob(inner, json.loads)
|
||||
updates = []
|
||||
|
||||
def observe(snapshot):
|
||||
updates.append(snapshot)
|
||||
if len(updates) == 2:
|
||||
inner.ready.set()
|
||||
|
||||
if sync:
|
||||
result = await asyncio.to_thread(Job(job).wait, progress=observe)
|
||||
else:
|
||||
result = await job.wait(progress=observe)
|
||||
assert result == {"version": "1"}
|
||||
assert inner.wait_calls == 1
|
||||
assert inner.cancel_calls == 0
|
||||
assert updates[0]["state"] == "running"
|
||||
assert updates[-1]["state"] == "finished"
|
||||
assert all(snapshot["job_id"] == inner.id for snapshot in updates)
|
||||
elapsed = [snapshot["client_elapsed_time_millis"] for snapshot in updates]
|
||||
assert elapsed == sorted(elapsed)
|
||||
assert elapsed[0] >= 0
|
||||
assert all("phase" not in snapshot for snapshot in updates)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[
|
||||
JobFailedError("bake failed", job_id="registration-query"),
|
||||
JobCancelledError("cancelled"),
|
||||
],
|
||||
)
|
||||
async def test_query_progress_preserves_terminal_exceptions(error):
|
||||
inner = _RegistrationQuery(error)
|
||||
inner.ready.set()
|
||||
updates = []
|
||||
with pytest.raises(type(error)) as raised:
|
||||
await AsyncJob(inner).wait(progress=updates.append)
|
||||
assert raised.value is error
|
||||
assert updates[-1]["state"] == inner.state
|
||||
assert inner.wait_calls == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_progress_display_has_no_row_counter_and_closes_on_failure(
|
||||
monkeypatch,
|
||||
):
|
||||
tqdm_module = pytest.importorskip("tqdm.auto")
|
||||
bar = SimpleNamespace(
|
||||
n=0,
|
||||
total=None,
|
||||
update=MagicMock(),
|
||||
set_postfix_str=MagicMock(),
|
||||
close=MagicMock(),
|
||||
)
|
||||
constructor = MagicMock(return_value=bar)
|
||||
monkeypatch.setattr(tqdm_module, "tqdm", constructor)
|
||||
inner = _RegistrationQuery(JobFailedError("bake failed"))
|
||||
inner.ready.set()
|
||||
|
||||
with pytest.raises(JobFailedError, match="bake failed"):
|
||||
await AsyncJob(inner).wait(progress=True)
|
||||
assert "elapsed" in constructor.call_args.kwargs["bar_format"]
|
||||
assert "rows" not in str(constructor.call_args)
|
||||
assert bar.set_postfix_str.call_args.args == ("failed",)
|
||||
bar.close.assert_called_once_with()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("failed", [False, True])
|
||||
@pytest.mark.parametrize("observer_error", ["status", "callback"])
|
||||
async def test_query_progress_observer_errors_do_not_replace_result_or_server_failure(
|
||||
failed, observer_error, caplog
|
||||
):
|
||||
error = (
|
||||
JobFailedError("bake failed", job_id="registration-query") if failed else None
|
||||
)
|
||||
inner = _RegistrationQuery(error)
|
||||
inner.ready.set()
|
||||
if observer_error == "status":
|
||||
inner.status = AsyncMock(side_effect=RuntimeError("observer failed"))
|
||||
|
||||
def observe(snapshot):
|
||||
if observer_error == "callback":
|
||||
raise RuntimeError("observer failed")
|
||||
|
||||
job = AsyncJob(inner, json.loads)
|
||||
if failed:
|
||||
with pytest.raises(JobFailedError) as raised:
|
||||
await job.wait(progress=observe)
|
||||
assert raised.value is error
|
||||
else:
|
||||
assert await job.wait(progress=observe) == {"version": "1"}
|
||||
assert inner.wait_calls == 1
|
||||
assert inner.cancel_calls == 0
|
||||
assert "job progress observer failed" in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_query_progress_timeout_keeps_registration_available_on_same_handle():
|
||||
inner = _RegistrationQuery()
|
||||
job = AsyncJob(inner, json.loads)
|
||||
updates = []
|
||||
with pytest.raises(TimeoutError, match="keep this handle"):
|
||||
await job.wait(timeout=timedelta(seconds=0.01), progress=updates.append)
|
||||
assert inner.state == "running"
|
||||
assert inner.cancel_calls == 0
|
||||
inner.ready.set()
|
||||
assert await job.wait(progress=updates.append) == {"version": "1"}
|
||||
assert inner.wait_calls == 2
|
||||
assert updates[-1]["state"] == "finished"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("refresh_lock", [False, True])
|
||||
def test_blocking_create_function_forwards_progress_to_registration_handle(
|
||||
refresh_lock,
|
||||
):
|
||||
connection = MagicMock()
|
||||
definition = object()
|
||||
progress = object()
|
||||
result = DBConnection.create_function(
|
||||
connection, definition, refresh_lock=refresh_lock, progress=progress
|
||||
)
|
||||
connection.create_function_async.assert_called_once_with(
|
||||
definition,
|
||||
secrets=None,
|
||||
exist_ok=False,
|
||||
namespace_path=None,
|
||||
refresh_lock=refresh_lock,
|
||||
)
|
||||
connection.create_function_async.return_value.wait.assert_called_once_with(
|
||||
progress=progress
|
||||
)
|
||||
assert result is connection.create_function_async.return_value.wait.return_value
|
||||
|
||||
|
||||
@pytest.mark.parametrize("progress", [False, None])
|
||||
def test_blocking_create_function_preserves_quiet_wait_call(progress):
|
||||
connection = MagicMock()
|
||||
result = DBConnection.create_function(connection, object(), progress=progress)
|
||||
connection.create_function_async.return_value.wait.assert_called_once_with()
|
||||
assert result is connection.create_function_async.return_value.wait.return_value
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -268,7 +268,7 @@ async def test_listing_lazy_pages_and_resume(listing_server, kind, asynchronous)
|
||||
if kind == "jobs":
|
||||
assert verb == "POST"
|
||||
assert path.path == "/v1/jobs/list"
|
||||
assert body == {"page_token": token, "limit": 2}
|
||||
assert body == {"database": "dev", "page_token": token, "limit": 2}
|
||||
else:
|
||||
namespace = "team"
|
||||
resource = kind.removesuffix("s")
|
||||
@@ -326,3 +326,179 @@ async def test_listing_invalid_limit_does_not_fetch(listing_server, kind, page_l
|
||||
with pytest.raises(ValueError, match="limit"):
|
||||
await items.__anext__()
|
||||
assert requests == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize("namespace", [[], ["team", "project"]])
|
||||
@pytest.mark.parametrize("multiple_types", [False, True])
|
||||
async def test_job_filters_persist_across_pages_and_resume(
|
||||
listing_server, asynchronous, namespace, multiple_types
|
||||
):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.extend(
|
||||
(200, response_page("jobs", names, token))
|
||||
for names, token in [(["a"], "empty"), ([], "last"), (["b"], None)]
|
||||
)
|
||||
db = await connection(endpoint, asynchronous)
|
||||
types = ["column_refresh", "materialized_view_refresh"]
|
||||
filters = dict(
|
||||
table="events",
|
||||
namespace_path=namespace,
|
||||
state="in_progress",
|
||||
created_at_gte_millis=100,
|
||||
created_at_lt_millis=200,
|
||||
**({"job_types": types} if multiple_types else {"job_type": types[0]}),
|
||||
)
|
||||
items = db.list_jobs(page_limit=1, **filters)
|
||||
assert requests == []
|
||||
assert (await advance(items, asynchronous)).job_id == "a"
|
||||
assert len(requests) == 1
|
||||
resumed = db.list_jobs(page_token=items.page_token(), page_limit=1, **filters)
|
||||
assert (await advance(resumed, asynchronous)).job_id == "b"
|
||||
assert resumed.page_token() is None
|
||||
assert len(requests) == 3
|
||||
expected = dict(
|
||||
database="dev",
|
||||
limit=1,
|
||||
table_ref={
|
||||
"db_name": "dev",
|
||||
"table_id": {"namespace_path": namespace, "table_name": "events"},
|
||||
},
|
||||
state="in_progress",
|
||||
job_types=types if multiple_types else types[:1],
|
||||
created_at_gte_millis=100,
|
||||
created_at_lt_millis=200,
|
||||
)
|
||||
for (_, path, body), token in zip(requests, [None, "empty", "last"]):
|
||||
assert path == "/v1/jobs/list"
|
||||
assert body == {**expected, **({"page_token": token} if token else {})}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"filters",
|
||||
[
|
||||
{},
|
||||
{"state": "failed"},
|
||||
{"job_types": ["column_refresh"]},
|
||||
{"created_at_lt_millis": 200},
|
||||
],
|
||||
)
|
||||
async def test_job_listing_without_table_stays_in_connected_database(
|
||||
listing_server, asynchronous, filters
|
||||
):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.append((200, response_page("jobs", ["a"], None)))
|
||||
db = await connection(endpoint, asynchronous)
|
||||
items = db.list_jobs(**filters)
|
||||
assert (await advance(items, asynchronous)).job_id == "a"
|
||||
assert requests[0][2] == {"database": "dev", **filters}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True])
|
||||
@pytest.mark.parametrize(
|
||||
"filters, message",
|
||||
[
|
||||
({"namespace_path": ["team"]}, "requires a table"),
|
||||
({"created_at_gte_millis": 200, "created_at_lt_millis": 200}, "less than"),
|
||||
({"created_at_gte_millis": 201, "created_at_lt_millis": 200}, "less than"),
|
||||
({"job_type": "column_refresh", "job_types": []}, "only one"),
|
||||
({"state": "unknown"}, "state must be"),
|
||||
],
|
||||
)
|
||||
async def test_invalid_job_filters_do_not_fetch(
|
||||
listing_server, asynchronous, filters, message
|
||||
):
|
||||
endpoint, requests, _ = listing_server
|
||||
db = await connection(endpoint, asynchronous)
|
||||
with pytest.raises(ValueError, match=message):
|
||||
items = db.list_jobs(**filters)
|
||||
await advance(items, asynchronous)
|
||||
assert requests == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listing_slice_and_index_fetch_only_needed_pages(listing_server):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.extend(
|
||||
(200, response_page("jobs", names, token))
|
||||
for names, token in [(["a", "b"], "second"), (["c", "d"], "last")]
|
||||
)
|
||||
db = await connection(endpoint, False)
|
||||
items = db.list_jobs(table="events", page_limit=2)
|
||||
assert items[:0] == []
|
||||
assert items[5:2] == []
|
||||
assert requests == []
|
||||
assert [job.job_id for job in items[:2]] == ["a", "b"]
|
||||
assert len(requests) == 1
|
||||
assert items.num_page_results() == 2
|
||||
assert items.page_token() == "second"
|
||||
assert items[1].job_id == "b"
|
||||
assert next(items).job_id == "a"
|
||||
assert [job.job_id for job in items[:2]] == ["b", "c"]
|
||||
assert len(requests) == 2
|
||||
assert items.num_page_results() == 3
|
||||
assert items.page_token() == "last"
|
||||
assert [job.job_id for job in items[0:3:2][:1]] == ["b"]
|
||||
assert len(requests) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listing_length_and_slices_preserve_remaining_items(listing_server):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.extend(
|
||||
(200, response_page("jobs", names, token))
|
||||
for names, token in [(["a", "b"], "empty"), ([], "last"), (["c", "d"], None)]
|
||||
)
|
||||
db = await connection(endpoint, False)
|
||||
items = db.list_jobs(page_limit=2)
|
||||
assert bool(items)
|
||||
assert len(requests) == 1
|
||||
assert next(items).job_id == "a"
|
||||
assert len(items) == 3
|
||||
assert len(requests) == 3
|
||||
assert items.num_page_results() == 3
|
||||
assert items.page_token() is None
|
||||
assert items[-1].job_id == "d"
|
||||
assert [job.job_id for job in items[::-1]] == ["d", "c", "b"]
|
||||
assert [job.job_id for job in items[1:]] == ["c", "d"]
|
||||
assert [job.job_id for job in items[:100:2]] == ["b", "d"]
|
||||
assert [job.job_id for job in items[: 2**100 : 2**100]] == ["b"]
|
||||
with pytest.raises(IndexError):
|
||||
_ = items[3]
|
||||
assert [job.job_id for job in items] == ["b", "c", "d"]
|
||||
assert len(items) == 0
|
||||
assert not items
|
||||
assert len(requests) == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listing_invalid_slice_does_not_fetch(listing_server):
|
||||
endpoint, requests, _ = listing_server
|
||||
db = await connection(endpoint, False)
|
||||
items = db.list_jobs()
|
||||
with pytest.raises(ValueError, match="step"):
|
||||
_ = items[::0]
|
||||
with pytest.raises(TypeError):
|
||||
_ = items["invalid"]
|
||||
with pytest.raises(TypeError):
|
||||
_ = items[:1.5]
|
||||
assert requests == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_listing_slice_failure_preserves_cache_and_retry_token(listing_server):
|
||||
endpoint, requests, responses = listing_server
|
||||
responses.extend([(200, response_page("jobs", ["a", "b"], "retry")), (401, {})])
|
||||
db = await connection(endpoint, False)
|
||||
items = db.list_jobs(page_limit=2)
|
||||
with pytest.raises(HttpError):
|
||||
_ = items[:3]
|
||||
assert items.page_token() == "retry"
|
||||
assert items.num_page_results() == 2
|
||||
assert [job.job_id for job in items[:2]] == ["a", "b"]
|
||||
assert [job.job_id for job in items] == ["a", "b"]
|
||||
assert len(requests) == 2
|
||||
|
||||
@@ -18,6 +18,7 @@ import lancedb
|
||||
from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError
|
||||
from utils import start_server_thread
|
||||
from lancedb.listing import AsyncListing, Listing
|
||||
from lancedb.index import FTS
|
||||
from lancedb.materialized_view import DEFINITION_FORMAT, DEFINITION_META_KEY
|
||||
from lancedb.namespace import (
|
||||
_MAX_QUERY_K,
|
||||
@@ -25,7 +26,7 @@ from lancedb.namespace import (
|
||||
LanceNamespaceDBConnection,
|
||||
_query_to_namespace_request,
|
||||
)
|
||||
from lancedb.query import Query
|
||||
from lancedb.query import FullTextSearchQuery, Query
|
||||
from lancedb.table import AsyncTable, LanceTable
|
||||
|
||||
|
||||
@@ -1524,3 +1525,42 @@ def test_python_namespace_attribute_access(tmp_path):
|
||||
# Missing dunder lookups still raise, so copy/hasattr probes work.
|
||||
assert not hasattr(request, "__missing_dunder__")
|
||||
assert copy.deepcopy(request) == request
|
||||
|
||||
|
||||
@pytest.mark.parametrize("columns", [None, ["text"], ["title", "body"]])
|
||||
def test_namespace_fts_operator_is_preserved(columns):
|
||||
request = _query_to_namespace_request(
|
||||
["matches"],
|
||||
Query(
|
||||
full_text_query=FullTextSearchQuery(
|
||||
query="gripper closed", columns=columns, operator="AND"
|
||||
)
|
||||
),
|
||||
)
|
||||
structured = request.to_dict()["full_text_query"]["structured_query"]["query"]
|
||||
if columns and len(columns) > 1:
|
||||
assert all(
|
||||
query["operator"] == "And"
|
||||
for query in structured["multi_match"]["match_queries"]
|
||||
)
|
||||
else:
|
||||
assert structured["match"]["operator"] == "And"
|
||||
assert structured["match"].get("column") == (columns[0] if columns else None)
|
||||
|
||||
|
||||
def test_namespace_fts_count_fast_search(tmp_path):
|
||||
properties = {"root": str(tmp_path)}
|
||||
db = lancedb.connect_namespace("dir", properties)
|
||||
table = db.create_table("matches", pa.table({"text": ["gripper"] * 15}))
|
||||
table.create_index("text", config=FTS())
|
||||
table.add(pa.table({"text": ["gripper"] * 5}))
|
||||
assert table.search("gripper", query_type="fts").fast_search().count_rows() == 15
|
||||
pushed = lancedb.connect_namespace(
|
||||
"dir", properties, namespace_client_pushdown_operations=["QueryTable"]
|
||||
).open_table("matches")
|
||||
assert pushed.search("gripper", query_type="fts").count_rows() == 20
|
||||
query = pushed.search("gripper", query_type="fts").fast_search()
|
||||
assert query.use_rte(False).count_rows() == 15
|
||||
query = pushed.search("gripper", query_type="fts").fast_search()
|
||||
assert query.count_rows() == 15
|
||||
assert len(query.limit(100).to_list()) == 15
|
||||
|
||||
@@ -310,6 +310,164 @@ async def test_add_retry_override(sync_api, retries, status):
|
||||
assert attempts == (2 if expected_success else 1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sync_api", [False, True])
|
||||
@pytest.mark.parametrize("namespace_path", [[], ["analytics", "features"]])
|
||||
@pytest.mark.parametrize("retries", [None, 0, 2])
|
||||
@pytest.mark.parametrize("status", [409, 429, 502, 503, 504])
|
||||
@pytest.mark.asyncio
|
||||
async def test_merge_retry_override(sync_api, namespace_path, retries, status, capfd):
|
||||
attempts = 0
|
||||
identifier = "$".join(namespace_path + ["test"])
|
||||
|
||||
def handler(request):
|
||||
nonlocal attempts
|
||||
if request.path == f"/v1/table/{identifier}/describe/":
|
||||
send_json(
|
||||
request,
|
||||
{
|
||||
"version": 1,
|
||||
"schema": {
|
||||
"fields": [
|
||||
{"name": "id", "type": {"type": "int64"}, "nullable": True}
|
||||
]
|
||||
},
|
||||
},
|
||||
)
|
||||
return
|
||||
assert urlparse(request.path).path == f"/v1/table/{identifier}/merge_insert/"
|
||||
query = parse_qs(urlparse(request.path).query)
|
||||
assert query["use_index"] == ["false"]
|
||||
assert request.headers["x-request-timeout-ms"] == "10000"
|
||||
body = bytearray()
|
||||
if request.headers.get("Transfer-Encoding") == "chunked":
|
||||
while True:
|
||||
size = int(request.rfile.readline().strip(), 16)
|
||||
if size == 0:
|
||||
request.rfile.readline()
|
||||
break
|
||||
body.extend(request.rfile.read(size))
|
||||
request.rfile.read(2)
|
||||
else:
|
||||
body.extend(
|
||||
request.rfile.read(int(request.headers.get("Content-Length", 0)))
|
||||
)
|
||||
assert pa.ipc.open_stream(body).read_all().to_pylist() == [{"id": 1}]
|
||||
attempts += 1
|
||||
send_json(request, {"version": 2}, status if attempts == 1 else 200)
|
||||
|
||||
config = {
|
||||
"retry_config": {
|
||||
"retries": 3,
|
||||
"statuses": [409, 429, 502, 503, 504],
|
||||
"backoff_factor": 0,
|
||||
"backoff_jitter": 0,
|
||||
}
|
||||
}
|
||||
expected_success = status in (409, 429) and retries != 0
|
||||
|
||||
async def check(table):
|
||||
merge = table.merge_insert("id").when_not_matched_insert_all().use_index(False)
|
||||
options = {"timeout": timedelta(seconds=10)}
|
||||
if retries is not None:
|
||||
options["retries"] = retries
|
||||
if expected_success:
|
||||
result = merge.execute([{"id": 1}], **options)
|
||||
if not sync_api:
|
||||
result = await result
|
||||
assert result.version == 2
|
||||
else:
|
||||
with pytest.raises((HttpError, RetryError)):
|
||||
result = merge.execute([{"id": 1}], **options)
|
||||
if not sync_api:
|
||||
await result
|
||||
|
||||
if sync_api:
|
||||
with mock_lancedb_connection(handler, **config) as db:
|
||||
await check(db.open_table("test", namespace_path=namespace_path))
|
||||
else:
|
||||
async with mock_lancedb_connection_async(handler, **config) as db:
|
||||
await check(await db.open_table("test", namespace_path=namespace_path))
|
||||
assert attempts == (2 if expected_success else 1)
|
||||
warnings = [
|
||||
line
|
||||
for line in capfd.readouterr().err.splitlines()
|
||||
if "Retrying merge insert" in line
|
||||
]
|
||||
assert len(warnings) == (1 if expected_success else 0)
|
||||
if expected_success:
|
||||
assert "WARN" in warnings[0]
|
||||
assert f"status Some({status}); attempt 2" in warnings[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sync_api", [False, True])
|
||||
@pytest.mark.asyncio
|
||||
async def test_merge_retry_override_isolation(sync_api):
|
||||
attempts = 0
|
||||
read_attempts = 0
|
||||
|
||||
def handler(request):
|
||||
nonlocal attempts, read_attempts
|
||||
if request.path.endswith("/describe/"):
|
||||
send_json(
|
||||
request,
|
||||
{
|
||||
"version": 1,
|
||||
"schema": {
|
||||
"fields": [
|
||||
{"name": "id", "type": {"type": "int64"}, "nullable": True}
|
||||
]
|
||||
},
|
||||
},
|
||||
)
|
||||
elif request.path.endswith("/count_rows/"):
|
||||
read_attempts += 1
|
||||
send_json(request, 1, 429 if read_attempts % 2 else 200)
|
||||
else:
|
||||
assert urlparse(request.path).path.endswith("/merge_insert/")
|
||||
attempts += 1
|
||||
send_json(request, {"version": 2}, 429 if attempts in (1, 2, 4, 6) else 200)
|
||||
|
||||
async def check(table):
|
||||
merge = table.merge_insert("id").when_not_matched_insert_all()
|
||||
for retries in [-1, 256, 1.5, "1"]:
|
||||
with pytest.raises((OverflowError, TypeError, ValueError)):
|
||||
result = merge.execute([{"id": 1}], retries=retries)
|
||||
if not sync_api:
|
||||
await result
|
||||
assert attempts == 0
|
||||
with pytest.raises((HttpError, RetryError)):
|
||||
result = merge.execute([{"id": 1}], retries=0)
|
||||
if not sync_api:
|
||||
await result
|
||||
assert attempts == 1
|
||||
for options in ({}, {"retries": 255}):
|
||||
result = merge.execute([{"id": 1}], **options)
|
||||
if not sync_api:
|
||||
result = await result
|
||||
assert result.version == 2
|
||||
assert attempts == 5
|
||||
result = table.count_rows()
|
||||
if not sync_api:
|
||||
result = await result
|
||||
assert result == 1
|
||||
assert read_attempts == 2
|
||||
result = (
|
||||
table.merge_insert("id").when_not_matched_insert_all().execute([{"id": 1}])
|
||||
)
|
||||
if not sync_api:
|
||||
result = await result
|
||||
assert result.version == 2
|
||||
assert attempts == 7
|
||||
|
||||
config = {"retry_config": {"retries": 3, "backoff_factor": 0, "backoff_jitter": 0}}
|
||||
if sync_api:
|
||||
with mock_lancedb_connection(handler, **config) as db:
|
||||
await check(db.open_table("test"))
|
||||
else:
|
||||
async with mock_lancedb_connection_async(handler, **config) as db:
|
||||
await check(await db.open_table("test"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def missing_table_handler(cached, namespace_path):
|
||||
request_ids = []
|
||||
@@ -7644,3 +7802,46 @@ async def test_remote_index_exist_ok_wire(is_async, background, kwargs):
|
||||
assert body["replace"] is False
|
||||
else:
|
||||
assert "replace" not in body
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operator", ["AND", "OR"])
|
||||
def test_remote_fts_operator_and_count(operator):
|
||||
def handler(body):
|
||||
query = body["full_text_query"]["query"]["match"]
|
||||
assert query["terms"] == "gripper closed"
|
||||
assert query["operator"] == operator.title()
|
||||
assert query["column"] == "text"
|
||||
assert body["k"] == 2**63 - 1
|
||||
assert "offset" not in body
|
||||
assert body["columns"] == ["_score"]
|
||||
assert body["filter"] == "text IS NOT NULL"
|
||||
assert body["prefilter"] is False
|
||||
return pa.table({"_score": [1.0] * 25})
|
||||
|
||||
with query_test_table(
|
||||
handler, server_version=Version("0.6.0"), vector_columns={}
|
||||
) as table:
|
||||
query = (
|
||||
table.search(
|
||||
"gripper closed",
|
||||
query_type="fts",
|
||||
fts_columns="text",
|
||||
operator=operator,
|
||||
)
|
||||
.where("text IS NOT NULL", prefilter=False)
|
||||
.select(["text"])
|
||||
.limit(1)
|
||||
.offset(3)
|
||||
)
|
||||
assert query.count_rows() == 25
|
||||
assert query.to_query_object().limit == 1
|
||||
assert query.to_query_object().offset == 3
|
||||
|
||||
|
||||
def test_remote_fts_and_rejects_legacy_server():
|
||||
def handler(body):
|
||||
pytest.fail("AND must not silently become OR on a legacy server")
|
||||
|
||||
with query_test_table(handler, vector_columns={}) as table:
|
||||
with pytest.raises(NotImplementedError, match="server version 0.3.0"):
|
||||
table.search("gripper closed", query_type="fts", operator="AND").to_list()
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -39,7 +40,30 @@ def remote_server(text_type=pa.string()):
|
||||
command = ticket.ticket
|
||||
calls.append(command)
|
||||
if b"SHOW STORAGE INTEGRATIONS" in command:
|
||||
result = pa.table({"name": pa.array(["zeta", NAME], type=text_type)})
|
||||
match = re.search(
|
||||
rb'SHOW STORAGE INTEGRATIONS IN "public" '
|
||||
rb"LIMIT (\d+)(?: FROM '([^']+)')?",
|
||||
command,
|
||||
)
|
||||
assert match is not None, command
|
||||
limit = int(match.group(1))
|
||||
names = [NAME, "zeta"]
|
||||
if match.group(2) is not None:
|
||||
assert match.group(2) == b"server-storage-page", command
|
||||
names = names[1:]
|
||||
page = names[:limit]
|
||||
result = pa.table(
|
||||
{
|
||||
"namespace_path": pa.array(
|
||||
["[]"] * len(page), type=pa.string()
|
||||
),
|
||||
"name": pa.array(page, type=text_type),
|
||||
}
|
||||
)
|
||||
if len(names) > limit:
|
||||
result = result.replace_schema_metadata(
|
||||
{b"lancedb.next_page_token": b"server-storage-page"}
|
||||
)
|
||||
elif b"DROP STORAGE INTEGRATION" in command:
|
||||
result = pa.table({"dropped": [True]})
|
||||
else:
|
||||
@@ -195,6 +219,10 @@ def test_sync_storage_integration_lifecycle_and_aws_information(text_type):
|
||||
assert b'CREATE STORAGE INTEGRATION "raw"' in calls[0]
|
||||
assert b"STORAGE_AWS_ROLE_ARN = '" + ROLE.encode() + b"'" in calls[0]
|
||||
assert b'DROP STORAGE INTEGRATION "raw"' in calls[-1]
|
||||
listings = [call for call in calls if b"SHOW STORAGE INTEGRATIONS" in call]
|
||||
assert len(listings) == 2
|
||||
assert b'SHOW STORAGE INTEGRATIONS IN "public" LIMIT 1' in listings[0]
|
||||
assert b"FROM 'server-storage-page'" in listings[1]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -3448,7 +3448,8 @@ def test_merge_insert(mem_db: DBConnection):
|
||||
table.merge_insert("a")
|
||||
.when_matched_update_all()
|
||||
.when_not_matched_insert_all()
|
||||
.execute(new_data, timeout=timedelta(seconds=10))
|
||||
.use_index(False)
|
||||
.execute(new_data, timeout=timedelta(seconds=10), retries=0)
|
||||
)
|
||||
assert merge_insert_res.version == 2
|
||||
assert merge_insert_res.num_inserted_rows == 1
|
||||
@@ -3527,7 +3528,7 @@ def test_merge_insert(mem_db: DBConnection):
|
||||
# timeout
|
||||
with pytest.raises(Exception, match="merge insert timed out"):
|
||||
table.merge_insert("a").when_matched_update_all().execute(
|
||||
new_data, timeout=timedelta(0)
|
||||
new_data, timeout=timedelta(0), retries=255
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ use lancedb::{
|
||||
connection::Connection as LanceConnection,
|
||||
connection::NamespaceClientPushdownOperation,
|
||||
database::namespace::LanceNamespaceDatabase,
|
||||
database::{CreateTableMode, Database, ReadConsistency},
|
||||
database::{CreateTableMode, Database, JobListFilter, JobListState, ReadConsistency},
|
||||
function::{GpuClass as LanceGpuClass, RefreshColumnResult},
|
||||
graph::PropertyGraphDefinition,
|
||||
materialized_view::CreateMaterializedViewBuilder,
|
||||
@@ -1319,15 +1319,47 @@ impl Connection {
|
||||
))
|
||||
}
|
||||
|
||||
#[pyo3(signature = (*, page_token=None, page_limit=None))]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[pyo3(signature = (*, page_token=None, page_limit=None, table=None, namespace_path=None, state=None, job_type=None, job_types=None, created_at_gte_millis=None, created_at_lt_millis=None))]
|
||||
pub fn list_jobs(
|
||||
&self,
|
||||
page_token: Option<String>,
|
||||
page_limit: Option<u32>,
|
||||
table: Option<String>,
|
||||
namespace_path: Option<Vec<String>>,
|
||||
state: Option<String>,
|
||||
job_type: Option<String>,
|
||||
job_types: Option<Vec<String>>,
|
||||
created_at_gte_millis: Option<i64>,
|
||||
created_at_lt_millis: Option<i64>,
|
||||
) -> PyResult<crate::listing::JobListing> {
|
||||
if job_type.is_some() && job_types.is_some() {
|
||||
return Err(PyValueError::new_err(
|
||||
"set only one of job_type and job_types",
|
||||
));
|
||||
}
|
||||
let mut filter = JobListFilter::default();
|
||||
filter.table = table;
|
||||
filter.namespace_path = namespace_path.unwrap_or_default();
|
||||
filter.state = state
|
||||
.as_deref()
|
||||
.map(|state| match state {
|
||||
"in_progress" => Ok(JobListState::InProgress),
|
||||
"succeeded" => Ok(JobListState::Succeeded),
|
||||
"failed" => Ok(JobListState::Failed),
|
||||
"canceled" => Ok(JobListState::Canceled),
|
||||
"timed_out" => Ok(JobListState::TimedOut),
|
||||
_ => Err(PyValueError::new_err(
|
||||
"state must be one of: in_progress, succeeded, failed, canceled, timed_out",
|
||||
)),
|
||||
})
|
||||
.transpose()?;
|
||||
filter.job_types = job_types.unwrap_or_else(|| job_type.into_iter().collect());
|
||||
filter.created_at_gte_millis = created_at_gte_millis;
|
||||
filter.created_at_lt_millis = created_at_lt_millis;
|
||||
Ok(crate::listing::JobListing::new(
|
||||
self.get_inner()?
|
||||
.list_jobs(crate::listing::options(page_token, page_limit)),
|
||||
.list_jobs_filtered(filter, crate::listing::options(page_token, page_limit)),
|
||||
))
|
||||
}
|
||||
|
||||
|
||||
+35
-2
@@ -16,19 +16,20 @@ use arrow::array::make_array;
|
||||
use arrow::pyarrow::FromPyArrow;
|
||||
use arrow::pyarrow::IntoPyArrow;
|
||||
use arrow::pyarrow::ToPyArrow;
|
||||
use futures::TryStreamExt;
|
||||
use lancedb::ApproxMode;
|
||||
use lancedb::index::scalar::{
|
||||
BooleanQuery, BoostQuery, CombinedFieldsQuery, DocumentGranularity, FtsQuery,
|
||||
FullTextSearchQuery, MatchQuery, MultiMatchQuery, Occur, Operator, PhraseQuery,
|
||||
};
|
||||
use lancedb::query::AnalyzePlanDistributedMetrics;
|
||||
use lancedb::query::QueryBase;
|
||||
use lancedb::query::QueryExecutionOptions;
|
||||
use lancedb::query::QueryFilter;
|
||||
use lancedb::query::{
|
||||
ColumnOrdering, ExecutableQuery, Query as LanceDbQuery, Select, TakeQuery as LanceDbTakeQuery,
|
||||
VectorQuery as LanceDbVectorQuery,
|
||||
};
|
||||
use lancedb::query::{HasQuery, QueryBase};
|
||||
use lancedb::table::AnyQuery;
|
||||
use pyo3::Bound;
|
||||
use pyo3::IntoPyObject;
|
||||
@@ -616,8 +617,18 @@ impl Query {
|
||||
query_text = query_text[1..query_text.len() - 1].to_string();
|
||||
}
|
||||
|
||||
let operator = query
|
||||
.get_item("operator")?
|
||||
.filter(|operator| !operator.is_none())
|
||||
.map(|operator| {
|
||||
let operator = operator.extract::<String>()?;
|
||||
Operator::try_from(operator.as_str())
|
||||
.map_err(|err| PyValueError::new_err(err.to_string()))
|
||||
})
|
||||
.transpose()?
|
||||
.unwrap_or(Operator::Or);
|
||||
let query: FtsQuery = match (is_phrase, is_multi_match) {
|
||||
(false, _) => MatchQuery::new(query_text).into(),
|
||||
(false, _) => MatchQuery::new(query_text).with_operator(operator).into(),
|
||||
(true, false) => PhraseQuery::new(query_text).into(),
|
||||
(true, true) => {
|
||||
return Err(PyValueError::new_err(
|
||||
@@ -898,6 +909,28 @@ impl FTSQuery {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let mut inner = self_
|
||||
.inner
|
||||
.clone()
|
||||
.full_text_search(self_.fts_query.clone());
|
||||
let request = inner.mut_query();
|
||||
request.limit = None;
|
||||
request.offset = None;
|
||||
request.select = Select::columns(&["_score"]);
|
||||
request.order_by = None;
|
||||
request.with_row_id = false;
|
||||
request.reranker = None;
|
||||
future_into_py(self_.py(), async move {
|
||||
let mut stream = inner.execute().await.infer_error()?;
|
||||
let mut count = 0_u64;
|
||||
while let Some(batch) = stream.try_next().await.infer_error()? {
|
||||
count += batch.num_rows() as u64;
|
||||
}
|
||||
Ok(count)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn nearest_to(&mut self, vector: Bound<'_, PyAny>) -> PyResult<HybridQuery> {
|
||||
let vector_query = Query::new(self.inner.clone()).nearest_to(vector)?;
|
||||
Ok(HybridQuery {
|
||||
|
||||
@@ -2269,10 +2269,12 @@ impl Table {
|
||||
})
|
||||
}
|
||||
|
||||
#[pyo3(signature = (data, parameters, retries=None))]
|
||||
pub fn execute_merge_insert<'a>(
|
||||
self_: PyRef<'a, Self>,
|
||||
data: Bound<'a, PyAny>,
|
||||
parameters: MergeInsertParams,
|
||||
retries: Option<u8>,
|
||||
) -> PyResult<Bound<'a, PyAny>> {
|
||||
let batches: ArrowArrayStreamReader = ArrowArrayStreamReader::from_pyarrow_bound(&data)?;
|
||||
let on = parameters.on.iter().map(|s| s.as_str()).collect::<Vec<_>>();
|
||||
@@ -2295,6 +2297,9 @@ impl Table {
|
||||
if let Some(timeout) = parameters.timeout {
|
||||
builder.timeout(timeout);
|
||||
}
|
||||
if let Some(retries) = retries {
|
||||
builder.retries(retries);
|
||||
}
|
||||
if let Some(use_index) = parameters.use_index {
|
||||
builder.use_index(use_index);
|
||||
}
|
||||
|
||||
Generated
+9
-9
@@ -2147,7 +2147,7 @@ requires-dist = [
|
||||
{ name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" },
|
||||
{ name = "pydantic", specifier = ">=2.7.4,<3" },
|
||||
{ name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" },
|
||||
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b21" },
|
||||
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b22" },
|
||||
{ name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" },
|
||||
{ name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" },
|
||||
{ name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" },
|
||||
@@ -4301,7 +4301,7 @@ crypto = [
|
||||
|
||||
[[package]]
|
||||
name = "pylance"
|
||||
version = "15.0.0b21"
|
||||
version = "15.0.0b22"
|
||||
source = { registry = "https://pypi.fury.io/lance-format/" }
|
||||
dependencies = [
|
||||
{ name = "lance-namespace" },
|
||||
@@ -4312,13 +4312,13 @@ dependencies = [
|
||||
{ name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
]
|
||||
wheels = [
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_mzSgZ/pylance-15.0.0b21-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:251682fe543131c371a6af45d8c672ea53b6ee83b5f777885f15ce383144d820" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1UfHMZ/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cbc92a2bac73f179a382e1bdb495fa3631a17e35687c2f00721af073eeb445a" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_Ugv8b/pylance-15.0.0b21-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:59bd56971aa41a21783e938e18a752fdaa97a37cfdd8940ed2f37d0c665d0fdd" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1mO0GG/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a0da124e95240e448daa981664a5e64e87bc99411eb4c408cbd50147096654f4" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1n5aaN/pylance-15.0.0b21-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:341a1abcd62e6134982968a5236f8128d88211ab288d329924a812d87e555555" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_RVDDc/pylance-15.0.0b21-cp310-abi3-win_amd64.whl", hash = "sha256:f5dbd51b2553d70b927c537672bad41075cd8615f5e951008d7cd59c7365e587" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_GJeqW/pylance-15.0.0b21-cp310-abi3-win_arm64.whl", hash = "sha256:ddd517d555c6674c94b0eeee78ed6c3c3ac7b32319e27c47dd6f78a2639d6837" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_2gkGO/pylance-15.0.0b22-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:401df8ce31ae6263656915c63d3da4411cae59bde2a6d71d12c552e3fa72b6bf" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_pfuJc/pylance-15.0.0b22-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f5c9ee37b23da4d6fbc341d0e18d355b1602c98fbf096e4589b08ecce57c56ea" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_YPb1X/pylance-15.0.0b22-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:38e6ed648816ae54ee3e76f21a30c092d47028da1f99242922ec1288d79a1722" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1a1jcd/pylance-15.0.0b22-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:1b7e9f1dfe7ff8e3cbb3b06a3ebd99667629725b6d9a119146f9e1bfac20871f" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_KRwHG/pylance-15.0.0b22-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:c31b41b8a8d070f969dcb9dd06aa31190f79d036b27cb5d5ae6d64d5d425502f" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_2cABdZ/pylance-15.0.0b22-cp310-abi3-win_amd64.whl", hash = "sha256:7b3d36ea7ab7a6a43caecc96ca7f969be11ad89d24ccc6d1788d751fb39e720d" },
|
||||
{ url = "https://pypi.fury.io/lance-format/-/ver_1j6gGW/pylance-15.0.0b22-cp310-abi3-win_arm64.whl", hash = "sha256:20c4e391b4b83008dc2b7877bdd0ad9b3b1251ea05116d79b5637807f4961cc8" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "lancedb"
|
||||
version = "0.42.0-beta.13"
|
||||
version = "0.42.0-beta.15"
|
||||
edition.workspace = true
|
||||
description = "LanceDB: A serverless, low-latency vector database for AI applications"
|
||||
license.workspace = true
|
||||
@@ -46,7 +46,7 @@ lance-io = { workspace = true }
|
||||
lance-index = { workspace = true, features = ["tokenizer-jieba", "tokenizer-lindera"] }
|
||||
lance-table = { workspace = true }
|
||||
# Keep the upstream source for downstream SDKs, where workspace patches do not apply.
|
||||
lance-linalg = { "version" = "=15.0.0-beta.21", "tag" = "v15.0.0-beta.21", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-linalg = { "version" = "=15.0.0-beta.22", "tag" = "v15.0.0-beta.22", "git" = "https://github.com/lance-format/lance.git" }
|
||||
lance-encoding = { workspace = true }
|
||||
lance-arrow = { workspace = true }
|
||||
lance-namespace = { workspace = true }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "lancedb-cli"
|
||||
version = "0.42.0-beta.13"
|
||||
version = "0.42.0-beta.15"
|
||||
edition = "2021"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
@@ -23,8 +23,8 @@ use crate::connection::create_table::CreateTableBuilder;
|
||||
use crate::data::scannable::Scannable;
|
||||
use crate::database::listing::ListingDatabase;
|
||||
use crate::database::{
|
||||
CloneTableRequest, Database, DatabaseOptions, ExecuteQueryRequest, JobInfo, OpenTableRequest,
|
||||
PauseJobStatus, ReadConsistency, ResumeJobStatus, TableNamesRequest,
|
||||
CloneTableRequest, Database, DatabaseOptions, ExecuteQueryRequest, JobInfo, JobListFilter,
|
||||
OpenTableRequest, PauseJobStatus, ReadConsistency, ResumeJobStatus, TableNamesRequest,
|
||||
};
|
||||
use crate::embeddings::{EmbeddingRegistry, MemoryRegistry};
|
||||
use crate::error::{Error, Result};
|
||||
@@ -1366,6 +1366,37 @@ impl Connection {
|
||||
})
|
||||
}
|
||||
|
||||
/// List jobs using server-side filters, without scanning all history in the client.
|
||||
///
|
||||
/// Filters are preserved on every page, including when resuming with a saved
|
||||
/// token. Requests and errors occur during iteration, as with [`Self::list_jobs`].
|
||||
///
|
||||
/// ```
|
||||
/// # async fn example(connection: &lancedb::Connection) -> lancedb::Result<()> {
|
||||
/// use futures::TryStreamExt;
|
||||
/// use lancedb::{database::JobListFilter, listing::ListingOptions};
|
||||
/// let mut filter = JobListFilter::default();
|
||||
/// filter.table = Some("events".into());
|
||||
/// let mut jobs = connection.list_jobs_filtered(filter, ListingOptions::default().page_limit(5));
|
||||
/// if let Some(job) = jobs.try_next().await? {
|
||||
/// println!("{}", job.job_id);
|
||||
/// }
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn list_jobs_filtered(
|
||||
&self,
|
||||
filter: JobListFilter,
|
||||
options: ListingOptions,
|
||||
) -> Listing<JobInfo> {
|
||||
let database = self.database().clone();
|
||||
Listing::new(options, move |options| {
|
||||
let database = database.clone();
|
||||
let filter = filter.clone();
|
||||
async move { database.list_jobs_filtered(filter, options).await }
|
||||
})
|
||||
}
|
||||
|
||||
/// Request cancellation of a server-side job by id. Returns true if the
|
||||
/// server accepted the cancellation, false if no such job exists.
|
||||
pub async fn cancel_job(&self, job_id: impl AsRef<str>) -> Result<bool> {
|
||||
|
||||
@@ -238,6 +238,45 @@ pub enum ReadConsistency {
|
||||
Strong,
|
||||
}
|
||||
|
||||
/// Registry lifecycle states accepted when filtering jobs.
|
||||
#[derive(Clone, Copy, Debug, serde::Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum JobListState {
|
||||
/// A job that has not reached a terminal state.
|
||||
InProgress,
|
||||
/// A job that completed successfully.
|
||||
Succeeded,
|
||||
/// A job that failed.
|
||||
Failed,
|
||||
/// A job that was canceled.
|
||||
Canceled,
|
||||
/// A job that exceeded its timeout.
|
||||
TimedOut,
|
||||
}
|
||||
|
||||
/// Server-side filters applied before job pagination.
|
||||
///
|
||||
/// Continuation tokens must be resumed with the same filters. Creation times
|
||||
/// are Unix timestamps in milliseconds; the lower bound is inclusive and the
|
||||
/// upper bound is exclusive.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
#[non_exhaustive]
|
||||
pub struct JobListFilter {
|
||||
/// Table name within `namespace_path`, including all its branches; absent means all tables.
|
||||
pub table: Option<String>,
|
||||
/// Namespace of `table`; requires a table name.
|
||||
pub namespace_path: Vec<String>,
|
||||
/// Registry state, such as `in_progress`, `succeeded`, or `failed`.
|
||||
/// These are server states, rather than the labels in [`JobInfo::state`].
|
||||
pub state: Option<JobListState>,
|
||||
/// Include jobs of any of these types; empty means all types.
|
||||
pub job_types: Vec<String>,
|
||||
/// Inclusive creation-time lower bound.
|
||||
pub created_at_gte_millis: Option<i64>,
|
||||
/// Exclusive creation-time upper bound.
|
||||
pub created_at_lt_millis: Option<i64>,
|
||||
}
|
||||
|
||||
/// A row from [`Database::list_jobs`]: one server-side job (index build,
|
||||
/// compaction, column refresh, ...).
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -781,6 +820,14 @@ pub trait Database:
|
||||
async fn list_jobs(&self, _options: ListingOptions) -> Result<ListingPage<JobInfo>> {
|
||||
job_op_not_supported("list_jobs")
|
||||
}
|
||||
/// Fetch one page of jobs matching server-side filters.
|
||||
async fn list_jobs_filtered(
|
||||
&self,
|
||||
_filter: JobListFilter,
|
||||
_options: ListingOptions,
|
||||
) -> Result<ListingPage<JobInfo>> {
|
||||
job_op_not_supported("list_jobs_filtered")
|
||||
}
|
||||
/// Request cancellation of a job by id. Returns true if the server
|
||||
/// accepted the cancellation, false if no such job exists. Cancelling an
|
||||
/// already-terminal job is a no-op success.
|
||||
|
||||
@@ -521,6 +521,59 @@ pub struct HuggingFaceModel {
|
||||
pub revision: String,
|
||||
}
|
||||
|
||||
/// One installed Python distribution as measured from a Function's baked
|
||||
/// environment.
|
||||
///
|
||||
/// `version` is the complete version string reported by the package metadata,
|
||||
/// including local labels such as `+cu130`. `source` is present only when the
|
||||
/// submitted lock retained a per-package source; a missing value is unknown and
|
||||
/// must not be inferred from other package indexes.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResolvedPackage {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub source: Option<String>,
|
||||
}
|
||||
|
||||
/// Sanitized source and accelerator provenance retained with a resolved
|
||||
/// environment.
|
||||
///
|
||||
/// `configured_*` records what the build was asked to use. `resolved_indexes`
|
||||
/// records indexes visible in the submitted lock, so a configured source is
|
||||
/// not mistaken for evidence that a package came from it. Empty lists and
|
||||
/// absent fields remain absent rather than being synthesized by the client.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResolvedEnvironmentProvenance {
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub configured_index_urls: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub configured_find_links: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub resolved_indexes: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cuda_toolkit: Option<String>,
|
||||
/// The fully resolved `torch==<version>` when torch was installed.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub torch_version: Option<String>,
|
||||
}
|
||||
|
||||
/// Actual installed distributions and registration warnings for one native
|
||||
/// Function environment.
|
||||
///
|
||||
/// A missing environment means its measurement is unknown, not an empty
|
||||
/// installed-package list. The field keeps the complete versions and only the
|
||||
/// provenance the producer recorded; SDK readers do not recompute package
|
||||
/// policy.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ResolvedEnvironment {
|
||||
pub packages: Vec<ResolvedPackage>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub provenance: Option<ResolvedEnvironmentProvenance>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// A complete OCI Function image. Its digest is independent of catalog names.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct FunctionImage {
|
||||
@@ -578,7 +631,9 @@ impl<'de> Deserialize<'de> for RowTimeoutSeconds {
|
||||
/// decoding, but they are not part of this value and are omitted from
|
||||
/// canonical JSON. Known fields retain their complete values, while unknown
|
||||
/// fields inside the open [`FunctionImage::descriptor`] JSON object remain
|
||||
/// available.
|
||||
/// available. Single-platform measurements use `resolved_environment`;
|
||||
/// multiarchitecture measurements use `resolved_environments`, keyed by OCI
|
||||
/// `os/architecture`, without flattening the platforms.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct FunctionVersion {
|
||||
name: String,
|
||||
@@ -626,6 +681,28 @@ pub struct FunctionVersion {
|
||||
/// Result-stability value declared at registration.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
result_stability: Option<String>,
|
||||
/// The runtime requested at registration, with submitted lock bytes omitted.
|
||||
///
|
||||
/// This is a specification, not the measured installation. Compare it with
|
||||
/// [`Self::resolved_environment`] when the caller needs actual package
|
||||
/// versions.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
runtime: Option<PythonRuntimeSpec>,
|
||||
/// Actual installed distributions, provenance, and registration warnings.
|
||||
///
|
||||
/// This is the single-platform compatibility field. `None` on a
|
||||
/// multiarchitecture version is expected; use
|
||||
/// [`Self::resolved_environments`] for its per-platform measurements.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
resolved_environment: Option<ResolvedEnvironment>,
|
||||
/// Measurements for a multiarchitecture image, keyed by OCI
|
||||
/// `os/architecture`.
|
||||
///
|
||||
/// Unmeasured platforms are absent. An empty map is unknown, not an
|
||||
/// aggregate of packages from the available platforms. Single-platform
|
||||
/// images use [`Self::resolved_environment`] instead.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
resolved_environments: BTreeMap<String, ResolvedEnvironment>,
|
||||
}
|
||||
|
||||
impl FunctionVersion {
|
||||
@@ -716,6 +793,35 @@ impl FunctionVersion {
|
||||
self.result_stability.as_deref()
|
||||
}
|
||||
|
||||
/// The runtime specification requested at registration, when exposed by the
|
||||
/// server.
|
||||
///
|
||||
/// This is the requested configuration, not evidence of what was installed.
|
||||
pub fn runtime(&self) -> Option<&PythonRuntimeSpec> {
|
||||
self.runtime.as_ref()
|
||||
}
|
||||
|
||||
/// Actual installed distributions and registration warnings for a
|
||||
/// single-platform image, when measured by the server.
|
||||
///
|
||||
/// `None` is unknown, not an empty environment. Package versions are
|
||||
/// retained verbatim, including local labels such as `+cu130`; `source`
|
||||
/// remains absent when the producer did not retain it.
|
||||
pub fn resolved_environment(&self) -> Option<&ResolvedEnvironment> {
|
||||
self.resolved_environment.as_ref()
|
||||
}
|
||||
|
||||
/// Per-platform measurements for a multiarchitecture image, keyed by OCI
|
||||
/// `os/architecture`.
|
||||
///
|
||||
/// The map is returned without flattening or synthesis. A missing platform
|
||||
/// means its measurement is unknown; an empty environment value is a
|
||||
/// measured empty environment and is retained. Single-platform images use
|
||||
/// [`Self::resolved_environment`] instead.
|
||||
pub fn resolved_environments(&self) -> &BTreeMap<String, ResolvedEnvironment> {
|
||||
&self.resolved_environments
|
||||
}
|
||||
|
||||
pub fn signature(&self) -> &FunctionSignature {
|
||||
&self.signature
|
||||
}
|
||||
@@ -827,6 +933,10 @@ fn validate_row_timeout_value(value: Option<f64>) -> std::result::Result<(), &'s
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_false(value: &bool) -> bool {
|
||||
!*value
|
||||
}
|
||||
|
||||
/// Stable request envelope for remote immutable Function registration.
|
||||
///
|
||||
/// Credential values deliberately have no field here. The only secret-shaped
|
||||
@@ -877,10 +987,10 @@ pub struct FunctionRegistrationRequest {
|
||||
/// Model snapshots prepared by the service before user code runs.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub models: Vec<HuggingFaceModel>,
|
||||
}
|
||||
|
||||
fn is_false(value: &bool) -> bool {
|
||||
!*value
|
||||
/// Ask the service to resolve a fresh environment lock for this request
|
||||
/// instead of reusing the published version's lock. Omitted when false.
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
pub refresh_lock: bool,
|
||||
}
|
||||
|
||||
impl FunctionRegistrationRequest {
|
||||
@@ -1465,6 +1575,165 @@ mod tests {
|
||||
assert!(FunctionVersion::from_json(&document.to_string()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_version_preserves_requested_and_resolved_environments() {
|
||||
const VERSION: &str = include_str!(
|
||||
"../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json"
|
||||
);
|
||||
let mut document: Value = serde_json::from_str(VERSION).unwrap();
|
||||
let legacy = FunctionVersion::from_json(VERSION).unwrap();
|
||||
assert!(legacy.runtime().is_none());
|
||||
assert!(legacy.resolved_environment().is_none());
|
||||
assert!(legacy.resolved_environments().is_empty());
|
||||
|
||||
document["runtime"] = serde_json::json!({
|
||||
"kind": "python",
|
||||
"python_version": "3.12",
|
||||
"environment": {
|
||||
"kind": "pip",
|
||||
"packages": ["vllm==0.11.0"]
|
||||
}
|
||||
});
|
||||
document["resolved_environment"] = serde_json::json!({
|
||||
"packages": [
|
||||
{
|
||||
"name": "torch",
|
||||
"version": "2.9.0+cu130",
|
||||
"source": "https://packages.example/simple"
|
||||
},
|
||||
{
|
||||
"name": "transformers",
|
||||
"version": "4.57.1"
|
||||
}
|
||||
],
|
||||
"provenance": {
|
||||
"configured_index_urls": ["https://packages.example/simple"],
|
||||
"configured_find_links": ["https://downloads.example/wheels"],
|
||||
"resolved_indexes": ["https://packages.example/simple"],
|
||||
"cuda_toolkit": "12.8",
|
||||
"torch_version": "torch==2.9.0+cu130"
|
||||
},
|
||||
"warnings": [
|
||||
"transformers resolved to transformers==4.57.1 but is not pinned exactly; add transformers==4.57.1 to pin it."
|
||||
]
|
||||
});
|
||||
|
||||
let version = FunctionVersion::from_json(&document.to_string()).unwrap();
|
||||
assert_eq!(version.runtime().unwrap().kind(), "python");
|
||||
assert!(version.resolved_environments().is_empty());
|
||||
let resolved = version.resolved_environment().unwrap();
|
||||
assert_eq!(resolved.packages[0].version, "2.9.0+cu130");
|
||||
assert_eq!(
|
||||
resolved.packages[0].source.as_deref(),
|
||||
Some("https://packages.example/simple")
|
||||
);
|
||||
assert_eq!(resolved.packages[1].source, None);
|
||||
assert_eq!(
|
||||
resolved
|
||||
.provenance
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.torch_version
|
||||
.as_deref(),
|
||||
Some("torch==2.9.0+cu130")
|
||||
);
|
||||
assert_eq!(resolved.warnings.len(), 1);
|
||||
|
||||
let encoded = version.to_canonical_json().unwrap();
|
||||
let encoded_value: Value = serde_json::from_str(&encoded).unwrap();
|
||||
assert_eq!(
|
||||
encoded_value["resolved_environment"]["packages"][0]["version"],
|
||||
"2.9.0+cu130"
|
||||
);
|
||||
assert!(
|
||||
encoded_value["resolved_environment"]["packages"][1]
|
||||
.get("source")
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version);
|
||||
|
||||
document["resolved_environment"] = serde_json::json!({"warnings": []});
|
||||
assert!(FunctionVersion::from_json(&document.to_string()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_version_preserves_resolved_environments_by_platform() {
|
||||
const VERSION: &str = include_str!(
|
||||
"../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json"
|
||||
);
|
||||
let mut document: Value = serde_json::from_str(VERSION).unwrap();
|
||||
document["runtime"] = serde_json::json!({
|
||||
"kind": "python",
|
||||
"python_version": "3.12",
|
||||
"environment": {
|
||||
"kind": "pip",
|
||||
"packages": ["vllm==0.11.0"]
|
||||
}
|
||||
});
|
||||
document["resolved_environments"] = serde_json::json!({
|
||||
"linux/amd64": {
|
||||
"packages": [
|
||||
{"name": "torch", "version": "2.9.0+cu130"}
|
||||
],
|
||||
"warnings": ["amd64 measurement"]
|
||||
},
|
||||
"linux/arm64": {
|
||||
"packages": [],
|
||||
"warnings": ["arm64 measurement"]
|
||||
}
|
||||
});
|
||||
|
||||
let version = FunctionVersion::from_json(&document.to_string()).unwrap();
|
||||
assert!(version.resolved_environment().is_none());
|
||||
let environments = version.resolved_environments();
|
||||
assert_eq!(environments.len(), 2);
|
||||
assert_eq!(
|
||||
environments["linux/amd64"].packages[0].version,
|
||||
"2.9.0+cu130"
|
||||
);
|
||||
assert!(environments["linux/arm64"].packages.is_empty());
|
||||
assert_eq!(environments["linux/arm64"].warnings, ["arm64 measurement"]);
|
||||
|
||||
let encoded = version.to_canonical_json().unwrap();
|
||||
let encoded_value: Value = serde_json::from_str(&encoded).unwrap();
|
||||
assert!(encoded_value.get("resolved_environment").is_none());
|
||||
assert_eq!(
|
||||
encoded_value["resolved_environments"]["linux/amd64"]["packages"][0]["version"],
|
||||
"2.9.0+cu130"
|
||||
);
|
||||
assert_eq!(
|
||||
encoded_value["resolved_environments"]["linux/arm64"]["packages"],
|
||||
serde_json::json!([])
|
||||
);
|
||||
assert_eq!(FunctionVersion::from_json(&encoded).unwrap(), version);
|
||||
|
||||
document["resolved_environments"]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("linux/arm64");
|
||||
let missing_platform = FunctionVersion::from_json(&document.to_string()).unwrap();
|
||||
assert!(
|
||||
!missing_platform
|
||||
.resolved_environments()
|
||||
.contains_key("linux/arm64")
|
||||
);
|
||||
|
||||
document["resolved_environments"] = serde_json::json!({});
|
||||
let empty_map = FunctionVersion::from_json(&document.to_string()).unwrap();
|
||||
assert!(empty_map.resolved_environments().is_empty());
|
||||
assert!(
|
||||
!empty_map
|
||||
.to_canonical_json()
|
||||
.unwrap()
|
||||
.contains("resolved_environments")
|
||||
);
|
||||
|
||||
document["resolved_environments"] = serde_json::json!({
|
||||
"linux/amd64": {"warnings": []}
|
||||
});
|
||||
assert!(FunctionVersion::from_json(&document.to_string()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blob_reader_access_survives_signature_round_trip() {
|
||||
let parameter: FunctionParameter = serde_json::from_value(serde_json::json!({
|
||||
|
||||
@@ -19,7 +19,10 @@ pub struct ListingOptions {
|
||||
/// Starting continuation token; `None` starts at the beginning.
|
||||
pub page_token: Option<String>,
|
||||
/// Maximum results per request, not a limit on the entire listing.
|
||||
/// `None` uses the backend default. Must be between 1 and `i32::MAX`.
|
||||
/// `None` uses the backend default. SQL-backed catalog listings default to
|
||||
/// 1,000 rows and accept 1 through 10,000. The public listing API rejects
|
||||
/// zero; SQL statements can separately use `LIMIT 0`. Other backends may
|
||||
/// impose different limits.
|
||||
pub page_limit: Option<u32>,
|
||||
}
|
||||
|
||||
@@ -31,6 +34,9 @@ impl ListingOptions {
|
||||
}
|
||||
|
||||
/// Set the maximum number of results requested per page.
|
||||
///
|
||||
/// SQL-backed catalog listings accept 1 through 10,000. A server can return
|
||||
/// fewer rows, including none, with a continuation token.
|
||||
pub fn page_limit(mut self, limit: u32) -> Self {
|
||||
self.page_limit = Some(limit);
|
||||
self
|
||||
|
||||
+136
-28
@@ -22,7 +22,8 @@ use lance_namespace::models::{
|
||||
use crate::Error;
|
||||
use crate::database::{
|
||||
CloneTableRequest, CreateTableMode, CreateTableRequest, Database, DatabaseOptions,
|
||||
ExecuteQueryRequest, JobInfo, OpenTableRequest, ReadConsistency, TableNamesRequest,
|
||||
ExecuteQueryRequest, JobInfo, JobListFilter, OpenTableRequest, ReadConsistency,
|
||||
TableNamesRequest,
|
||||
};
|
||||
use crate::error::Result;
|
||||
use crate::function::{FunctionRegistrationRequest, FunctionVersion, GpuClass};
|
||||
@@ -1008,30 +1009,9 @@ impl<S: HttpSend> Database for RemoteDatabase<S> {
|
||||
namespace_path: &[String],
|
||||
options: ListingOptions,
|
||||
) -> Result<ListingPage<String>> {
|
||||
validate_namespace(namespace_path)?;
|
||||
let result = self
|
||||
.execute_query_async(ExecuteQueryRequest {
|
||||
query: "SHOW STORAGE INTEGRATIONS".into(),
|
||||
default_namespace_path: namespace_path.to_vec(),
|
||||
parameters: None,
|
||||
})
|
||||
.await?;
|
||||
let mut names =
|
||||
integration_sql::decode_names(&result.reader().await?.try_collect::<Vec<_>>().await?)?;
|
||||
if let Some(token) = options.page_token {
|
||||
names.retain(|name| name > &token);
|
||||
}
|
||||
let mut page_token = None;
|
||||
if let Some(limit) = options.page_limit
|
||||
&& names.len() > limit as usize
|
||||
{
|
||||
names.truncate(limit as usize);
|
||||
page_token = names.last().cloned();
|
||||
}
|
||||
Ok(ListingPage {
|
||||
items: names,
|
||||
page_token,
|
||||
})
|
||||
self.sql_client()?
|
||||
.list_names("SHOW STORAGE INTEGRATIONS", namespace_path, options)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn drop_storage_integration(&self, name: &str, namespace_path: &[String]) -> Result<()> {
|
||||
@@ -1311,7 +1291,54 @@ impl<S: HttpSend> Database for RemoteDatabase<S> {
|
||||
}
|
||||
|
||||
async fn list_jobs(&self, options: ListingOptions) -> Result<ListingPage<JobInfo>> {
|
||||
let mut body = serde_json::json!({});
|
||||
self.list_jobs_filtered(JobListFilter::default(), options)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn list_jobs_filtered(
|
||||
&self,
|
||||
filter: JobListFilter,
|
||||
options: ListingOptions,
|
||||
) -> Result<ListingPage<JobInfo>> {
|
||||
if self.db_name.is_empty() {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "list_jobs requires a connected database".into(),
|
||||
});
|
||||
}
|
||||
if filter.table.is_none() && !filter.namespace_path.is_empty() {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "namespace_path requires a table filter".into(),
|
||||
});
|
||||
}
|
||||
if let (Some(start), Some(end)) =
|
||||
(filter.created_at_gte_millis, filter.created_at_lt_millis)
|
||||
&& start >= end
|
||||
{
|
||||
return Err(Error::InvalidInput {
|
||||
message: "created_at_gte_millis must be less than created_at_lt_millis".into(),
|
||||
});
|
||||
}
|
||||
let mut body = serde_json::json!({"database": self.db_name});
|
||||
if let Some(table) = filter.table {
|
||||
validate_table_name(&table)?;
|
||||
validate_namespace(&filter.namespace_path)?;
|
||||
body["table_ref"] = serde_json::json!({
|
||||
"db_name": self.db_name,
|
||||
"table_id": {"namespace_path": filter.namespace_path, "table_name": table},
|
||||
});
|
||||
}
|
||||
if let Some(state) = filter.state {
|
||||
body["state"] = serde_json::json!(state);
|
||||
}
|
||||
if !filter.job_types.is_empty() {
|
||||
body["job_types"] = serde_json::json!(filter.job_types);
|
||||
}
|
||||
if let Some(start) = filter.created_at_gte_millis {
|
||||
body["created_at_gte_millis"] = start.into();
|
||||
}
|
||||
if let Some(end) = filter.created_at_lt_millis {
|
||||
body["created_at_lt_millis"] = end.into();
|
||||
}
|
||||
if let Some(token) = options.page_token {
|
||||
body["page_token"] = token.into();
|
||||
}
|
||||
@@ -2020,7 +2047,7 @@ mod tests {
|
||||
use rstest::rstest;
|
||||
|
||||
use crate::connection::ConnectBuilder;
|
||||
use crate::database::Database;
|
||||
use crate::database::{Database, JobListFilter, JobListState};
|
||||
use crate::error::{JobFailure, RemoteErrorMetadata, RemoteResourceIdentity};
|
||||
use crate::graph::{EdgeTable, Endpoint, NodeTable, PropertyGraphDefinition};
|
||||
use crate::materialized_view::CreateMaterializedViewRequest;
|
||||
@@ -4154,7 +4181,10 @@ mod tests {
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(request.body().unwrap().as_bytes().unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(body, serde_json::json!({"page_token": token, "limit": 2}));
|
||||
assert_eq!(
|
||||
body,
|
||||
serde_json::json!({"database": "default", "page_token": token, "limit": 2})
|
||||
);
|
||||
} else {
|
||||
let ns = "team";
|
||||
assert_eq!(
|
||||
@@ -4357,6 +4387,84 @@ mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_list_jobs_filters_every_page_without_eager_fetching() {
|
||||
let count = Arc::new(AtomicUsize::new(0));
|
||||
let seen = count.clone();
|
||||
let conn = Connection::new_with_handler(move |request| {
|
||||
let page = seen.fetch_add(1, Ordering::SeqCst);
|
||||
let body: serde_json::Value =
|
||||
serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap();
|
||||
let mut expected = serde_json::json!({
|
||||
"database": "default",
|
||||
"table_ref": {
|
||||
"db_name": "default",
|
||||
"table_id": {"namespace_path": ["team", "project"], "table_name": "events"},
|
||||
},
|
||||
"state": "in_progress",
|
||||
"job_types": ["column_refresh", "materialized_view_refresh"],
|
||||
"created_at_gte_millis": 100,
|
||||
"created_at_lt_millis": 200,
|
||||
"limit": 1,
|
||||
});
|
||||
if page > 0 {
|
||||
expected["page_token"] = "next".into();
|
||||
}
|
||||
assert_eq!(body, expected);
|
||||
http::Response::builder().status(200).body(serde_json::json!({
|
||||
"jobs": [{"job_id": format!("job-{page}"), "table": "events", "job_type": "column_refresh", "state": "in_progress", "created_at_millis": 100}],
|
||||
"page_token": (page == 0).then_some("next"),
|
||||
}).to_string()).unwrap()
|
||||
});
|
||||
let filter = JobListFilter {
|
||||
table: Some("events".into()),
|
||||
namespace_path: vec!["team".into(), "project".into()],
|
||||
state: Some(JobListState::InProgress),
|
||||
job_types: vec!["column_refresh".into(), "materialized_view_refresh".into()],
|
||||
created_at_gte_millis: Some(100),
|
||||
created_at_lt_millis: Some(200),
|
||||
};
|
||||
let mut jobs =
|
||||
conn.list_jobs_filtered(filter.clone(), ListingOptions::default().page_limit(1));
|
||||
assert_eq!(count.load(Ordering::SeqCst), 0);
|
||||
assert_eq!(jobs.try_next().await.unwrap().unwrap().job_id, "job-0");
|
||||
assert_eq!(count.load(Ordering::SeqCst), 1);
|
||||
let resumed = conn.list_jobs_filtered(
|
||||
filter,
|
||||
ListingOptions::default()
|
||||
.page_limit(1)
|
||||
.page_token(jobs.page_token().unwrap()),
|
||||
);
|
||||
let remaining = resumed.try_collect::<Vec<_>>().await.unwrap();
|
||||
assert_eq!(remaining.len(), 1);
|
||||
assert_eq!(remaining[0].job_id, "job-1");
|
||||
assert_eq!(count.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_list_jobs_invalid_filters_never_reach_server() {
|
||||
let conn = Connection::new_with_handler(|_| -> http::Response<String> {
|
||||
panic!("invalid filters must not reach the server")
|
||||
});
|
||||
let namespace_only = JobListFilter {
|
||||
namespace_path: vec!["team".into()],
|
||||
..Default::default()
|
||||
};
|
||||
let invalid_time = JobListFilter {
|
||||
created_at_gte_millis: Some(200),
|
||||
created_at_lt_millis: Some(100),
|
||||
..Default::default()
|
||||
};
|
||||
for filter in [namespace_only, invalid_time] {
|
||||
let mut jobs = conn.list_jobs_filtered(filter, ListingOptions::default());
|
||||
assert!(matches!(
|
||||
jobs.try_next().await,
|
||||
Err(Error::InvalidInput { .. })
|
||||
));
|
||||
assert!(jobs.try_next().await.unwrap().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_list_jobs_does_not_truncate_after_100_pages() {
|
||||
let conn = Connection::new_with_handler(|request| {
|
||||
|
||||
@@ -14,7 +14,6 @@ use crate::{
|
||||
listing::{ListingOptions, ListingPage},
|
||||
utils::{validate_function_name, validate_namespace},
|
||||
};
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
|
||||
/// The SQL result of one Function drop, before the public boolean wrapper
|
||||
/// discards the advisory details.
|
||||
@@ -89,81 +88,17 @@ impl SqlClient {
|
||||
namespace: &[String],
|
||||
options: ListingOptions,
|
||||
) -> Result<ListingPage<FunctionVersion>> {
|
||||
validate_namespace(namespace)?;
|
||||
let limit = options.page_limit.unwrap_or(100);
|
||||
if limit == 0 || limit > i32::MAX as u32 {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "page limit must be between 1 and i32::MAX".into(),
|
||||
});
|
||||
}
|
||||
let invalid = || Error::InvalidInput {
|
||||
message: "invalid function page token for this database or namespace".into(),
|
||||
};
|
||||
let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) {
|
||||
let bytes = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid())?;
|
||||
let (database, prefix, path, name, version): (
|
||||
String,
|
||||
Option<String>,
|
||||
Vec<String>,
|
||||
String,
|
||||
String,
|
||||
) = serde_json::from_slice(&bytes).map_err(|_| invalid())?;
|
||||
if database != self.inner.database
|
||||
|| prefix != self.inner.database_prefix
|
||||
|| path != namespace
|
||||
{
|
||||
return Err(invalid());
|
||||
}
|
||||
Some((name, version))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut sql_options = vec![
|
||||
format!("limit = {}", u64::from(limit) + 1),
|
||||
"include_definition = true".to_owned(),
|
||||
];
|
||||
if let Some((name, version)) = &after {
|
||||
sql_options.push(format!("after_name = {}", literal(name)));
|
||||
sql_options.push(format!("after_version = {}", literal(version)));
|
||||
}
|
||||
let mut items: Vec<FunctionVersion> = self
|
||||
.object_job(
|
||||
ExecuteQueryRequest {
|
||||
query: format!("SHOW FUNCTIONS HISTORY WITH ({})", sql_options.join(", ")),
|
||||
default_namespace_path: namespace.to_vec(),
|
||||
parameters: None,
|
||||
},
|
||||
|batches| {
|
||||
strings(&batches, "definition")?
|
||||
.into_iter()
|
||||
.map(|value| {
|
||||
serde_json::from_str(&value).map_err(|error| Error::Runtime {
|
||||
message: error.to_string(),
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<FunctionVersion>>>()
|
||||
},
|
||||
)
|
||||
.await?
|
||||
.wait()
|
||||
let (batches, page_token) = self
|
||||
.listing_page("SHOW FUNCTIONS HISTORY", namespace, options)
|
||||
.await?;
|
||||
let page_token = if items.len() > limit as usize {
|
||||
items.truncate(limit as usize);
|
||||
let last = items.last().unwrap();
|
||||
let bytes = serde_json::to_vec(&(
|
||||
&self.inner.database,
|
||||
&self.inner.database_prefix,
|
||||
namespace,
|
||||
last.name(),
|
||||
last.version(),
|
||||
))
|
||||
.map_err(|error| Error::Runtime {
|
||||
message: error.to_string(),
|
||||
})?;
|
||||
Some(URL_SAFE_NO_PAD.encode(bytes))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let items = strings(&batches, "definition")?
|
||||
.into_iter()
|
||||
.map(|value| {
|
||||
serde_json::from_str(&value).map_err(|error| Error::Runtime {
|
||||
message: error.to_string(),
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<FunctionVersion>>>()?;
|
||||
Ok(ListingPage { items, page_token })
|
||||
}
|
||||
pub(in crate::remote) async fn drop_function_outcome(
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use arrow_array::{Array, RecordBatch, StringArray};
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use futures::TryStreamExt;
|
||||
|
||||
use super::SqlClient;
|
||||
@@ -157,60 +156,7 @@ impl SqlClient {
|
||||
namespace: &[String],
|
||||
options: ListingOptions,
|
||||
) -> Result<ListingPage<String>> {
|
||||
validate_namespace(namespace)?;
|
||||
let limit = options.page_limit.unwrap_or(100);
|
||||
if limit == 0 || limit > i32::MAX as u32 {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "page limit must be between 1 and i32::MAX".into(),
|
||||
});
|
||||
}
|
||||
let invalid_token = || Error::InvalidInput {
|
||||
message: "invalid materialized-view page token for this database or namespace".into(),
|
||||
};
|
||||
let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) {
|
||||
let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?;
|
||||
let (database, prefix, path, last): (String, Option<String>, Vec<String>, String) =
|
||||
serde_json::from_slice(&decoded).map_err(|_| invalid_token())?;
|
||||
if database != self.inner.database
|
||||
|| prefix != self.inner.database_prefix
|
||||
|| path != namespace
|
||||
{
|
||||
return Err(invalid_token());
|
||||
}
|
||||
format!(" WHERE name > '{}'", last.replace('\'', "''"))
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let query = self
|
||||
.execute(ExecuteQueryRequest {
|
||||
query: format!(
|
||||
"SHOW MATERIALIZED VIEWS{after} LIMIT {}",
|
||||
u64::from(limit) + 1
|
||||
),
|
||||
default_namespace_path: namespace.to_vec(),
|
||||
parameters: None,
|
||||
})
|
||||
.await?;
|
||||
let mut reader = query.reader().await?;
|
||||
let mut items = Vec::new();
|
||||
while let Some(batch) = reader.try_next().await? {
|
||||
items.extend(strings(&batch, "name")?);
|
||||
}
|
||||
let page_token = if items.len() > limit as usize {
|
||||
items.truncate(limit as usize);
|
||||
let cursor = serde_json::to_vec(&(
|
||||
&self.inner.database,
|
||||
&self.inner.database_prefix,
|
||||
namespace,
|
||||
items.last().unwrap(),
|
||||
))
|
||||
.map_err(|error| Error::Runtime {
|
||||
message: error.to_string(),
|
||||
})?;
|
||||
Some(URL_SAFE_NO_PAD.encode(cursor))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(ListingPage { items, page_token })
|
||||
self.list_names("SHOW MATERIALIZED VIEWS", namespace, options)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,42 +1,118 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
|
||||
|
||||
use super::SqlClient;
|
||||
use super::{SqlClient, materialized_view::quote_identifier};
|
||||
use crate::{
|
||||
database::ExecuteQueryRequest,
|
||||
error::{Error, Result},
|
||||
job::Job,
|
||||
listing::{ListingOptions, ListingPage},
|
||||
utils::validate_namespace,
|
||||
};
|
||||
use arrow_array::{Array, ListArray, RecordBatch, StringArray};
|
||||
use arrow_array::{Array, LargeStringArray, ListArray, RecordBatch, StringArray, StringViewArray};
|
||||
use futures::TryStreamExt;
|
||||
use serde::{Serialize, de::DeserializeOwned};
|
||||
use std::sync::Arc;
|
||||
|
||||
const DEFAULT_SQL_LISTING_LIMIT: u32 = 1_000;
|
||||
const MAX_SQL_LISTING_LIMIT: u32 = 10_000;
|
||||
const NEXT_PAGE_TOKEN_METADATA_KEY: &str = "lancedb.next_page_token";
|
||||
|
||||
impl SqlClient {
|
||||
pub(in crate::remote) async fn listing_page(
|
||||
&self,
|
||||
statement: &str,
|
||||
namespace: &[String],
|
||||
options: ListingOptions,
|
||||
) -> Result<(Vec<RecordBatch>, Option<String>)> {
|
||||
validate_namespace(namespace)?;
|
||||
let limit = options.page_limit.unwrap_or(DEFAULT_SQL_LISTING_LIMIT);
|
||||
if limit > MAX_SQL_LISTING_LIMIT {
|
||||
return Err(Error::InvalidInput {
|
||||
message: format!("page limit must be between 0 and {MAX_SQL_LISTING_LIMIT}"),
|
||||
});
|
||||
}
|
||||
if options.page_token.as_ref().is_some_and(String::is_empty) {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "page token must not be empty".into(),
|
||||
});
|
||||
}
|
||||
if limit == 0 {
|
||||
return Ok((Vec::new(), None));
|
||||
}
|
||||
let schema = if namespace.is_empty() {
|
||||
"public".to_owned()
|
||||
} else {
|
||||
namespace.join("$")
|
||||
};
|
||||
let mut statement = format!("{statement} IN {} LIMIT {limit}", quote_identifier(&schema));
|
||||
if let Some(token) = options.page_token {
|
||||
statement.push_str(&format!(" FROM {}", literal(&token)));
|
||||
}
|
||||
let query = self
|
||||
.execute(ExecuteQueryRequest {
|
||||
query: statement,
|
||||
default_namespace_path: namespace.to_vec(),
|
||||
parameters: None,
|
||||
})
|
||||
.await?;
|
||||
let reader = query.reader().await?;
|
||||
let token = reader
|
||||
.schema()
|
||||
.metadata()
|
||||
.get(NEXT_PAGE_TOKEN_METADATA_KEY)
|
||||
.cloned()
|
||||
.filter(|token| !token.is_empty());
|
||||
let batches = reader.try_collect::<Vec<_>>().await?;
|
||||
if batches.iter().map(RecordBatch::num_rows).sum::<usize>() > limit as usize {
|
||||
return Err(Error::Runtime {
|
||||
message: "SQL listing exceeded its requested page size".into(),
|
||||
});
|
||||
}
|
||||
Ok((batches, token))
|
||||
}
|
||||
|
||||
pub(in crate::remote) async fn list_names(
|
||||
&self,
|
||||
statement: &str,
|
||||
namespace: &[String],
|
||||
options: ListingOptions,
|
||||
) -> Result<ListingPage<String>> {
|
||||
let (batches, page_token) = self.listing_page(statement, namespace, options).await?;
|
||||
Ok(ListingPage {
|
||||
items: strings(&batches, "name")?,
|
||||
page_token,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn literal(value: &str) -> String {
|
||||
format!("'{}'", value.replace('\'', "''"))
|
||||
}
|
||||
pub(super) fn strings(batches: &[RecordBatch], name: &str) -> Result<Vec<String>> {
|
||||
batches
|
||||
.iter()
|
||||
.map(|batch| {
|
||||
let values = batch
|
||||
.column_by_name(name)
|
||||
.and_then(|column| column.as_any().downcast_ref::<StringArray>())
|
||||
.ok_or_else(|| Error::Runtime {
|
||||
message: format!("SQL result is missing UTF-8 column '{name}'"),
|
||||
})?;
|
||||
if values.null_count() != 0 {
|
||||
return Err(Error::Runtime {
|
||||
message: format!("SQL result contains null '{name}'"),
|
||||
});
|
||||
}
|
||||
Ok(values
|
||||
.iter()
|
||||
.map(|value| value.unwrap().to_owned())
|
||||
.collect::<Vec<_>>())
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()
|
||||
.map(|rows| rows.into_iter().flatten().collect())
|
||||
let mut result = Vec::new();
|
||||
for batch in batches {
|
||||
let column = batch.column_by_name(name).ok_or_else(|| Error::Runtime {
|
||||
message: format!("SQL result is missing string column '{name}'"),
|
||||
})?;
|
||||
if column.null_count() != 0 {
|
||||
return Err(Error::Runtime {
|
||||
message: format!("SQL result contains null '{name}'"),
|
||||
});
|
||||
}
|
||||
if let Some(values) = column.as_any().downcast_ref::<StringArray>() {
|
||||
result.extend(values.iter().map(|value| value.unwrap().to_owned()));
|
||||
} else if let Some(values) = column.as_any().downcast_ref::<LargeStringArray>() {
|
||||
result.extend(values.iter().map(|value| value.unwrap().to_owned()));
|
||||
} else if let Some(values) = column.as_any().downcast_ref::<StringViewArray>() {
|
||||
result.extend(values.iter().map(|value| value.unwrap().to_owned()));
|
||||
} else {
|
||||
return Err(Error::Runtime {
|
||||
message: format!("SQL result column '{name}' is not a string"),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Read an optional `List<Utf8>` column. Older servers do not return the
|
||||
@@ -112,9 +188,9 @@ impl SqlClient {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::string_lists;
|
||||
use super::{string_lists, strings};
|
||||
use arrow_array::builder::{ListBuilder, StringBuilder};
|
||||
use arrow_array::{ArrayRef, RecordBatch};
|
||||
use arrow_array::{ArrayRef, LargeStringArray, RecordBatch, StringArray, StringViewArray};
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -126,6 +202,24 @@ mod tests {
|
||||
)]))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listing_strings_accept_all_arrow_string_representations() {
|
||||
for values in [
|
||||
Arc::new(StringArray::from(vec!["a", "z"])) as ArrayRef,
|
||||
Arc::new(LargeStringArray::from(vec!["a", "z"])) as ArrayRef,
|
||||
Arc::new(StringViewArray::from(vec!["a", "z"])) as ArrayRef,
|
||||
] {
|
||||
let batch = RecordBatch::try_from_iter(vec![("name", values)]).unwrap();
|
||||
assert_eq!(strings(&[batch], "name").unwrap(), ["a", "z"]);
|
||||
}
|
||||
let batch = RecordBatch::try_from_iter(vec![(
|
||||
"name",
|
||||
Arc::new(StringViewArray::from(vec![Some("a"), None])) as ArrayRef,
|
||||
)])
|
||||
.unwrap();
|
||||
assert!(strings(&[batch], "name").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_warnings_after_an_empty_first_batch() {
|
||||
let schema = warning_schema();
|
||||
|
||||
@@ -10,8 +10,6 @@ use crate::{
|
||||
utils::{validate_namespace, validate_secret_name},
|
||||
};
|
||||
use arrow_array::{Array, Int64Array, RecordBatch, StringArray};
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use futures::TryStreamExt;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(in crate::remote) enum SecretWriteOperation {
|
||||
@@ -135,65 +133,7 @@ impl SqlClient {
|
||||
namespace: &[String],
|
||||
options: ListingOptions,
|
||||
) -> Result<ListingPage<String>> {
|
||||
validate_namespace(namespace)?;
|
||||
let limit = options.page_limit.unwrap_or(100);
|
||||
if limit == 0 || limit > i32::MAX as u32 {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "page limit must be between 1 and i32::MAX".into(),
|
||||
});
|
||||
}
|
||||
let invalid_token = || Error::InvalidInput {
|
||||
message: "invalid secret page token for this database or namespace".into(),
|
||||
};
|
||||
let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) {
|
||||
let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?;
|
||||
let (kind, database, prefix, path, last): (
|
||||
String,
|
||||
String,
|
||||
Option<String>,
|
||||
Vec<String>,
|
||||
String,
|
||||
) = serde_json::from_slice(&decoded).map_err(|_| invalid_token())?;
|
||||
if kind != "secret"
|
||||
|| database != self.inner.database
|
||||
|| prefix != self.inner.database_prefix
|
||||
|| path != namespace
|
||||
{
|
||||
return Err(invalid_token());
|
||||
}
|
||||
format!(" WHERE name > '{}'", last.replace('\'', "''"))
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let query = self
|
||||
.execute(ExecuteQueryRequest {
|
||||
query: format!("SHOW SECRETS{after} LIMIT {}", u64::from(limit) + 1),
|
||||
default_namespace_path: namespace.to_vec(),
|
||||
parameters: None,
|
||||
})
|
||||
.await?;
|
||||
let mut reader = query.reader().await?;
|
||||
let mut items = Vec::new();
|
||||
while let Some(batch) = reader.try_next().await? {
|
||||
items.extend(strings(&[batch], "name")?);
|
||||
}
|
||||
let page_token = if items.len() > limit as usize {
|
||||
items.truncate(limit as usize);
|
||||
let cursor = serde_json::to_vec(&(
|
||||
"secret",
|
||||
&self.inner.database,
|
||||
&self.inner.database_prefix,
|
||||
namespace,
|
||||
items.last().unwrap(),
|
||||
))
|
||||
.map_err(|error| Error::Runtime {
|
||||
message: error.to_string(),
|
||||
})?;
|
||||
Some(URL_SAFE_NO_PAD.encode(cursor))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(ListingPage { items, page_token })
|
||||
self.list_names("SHOW SECRETS", namespace, options).await
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,8 +9,6 @@ use crate::{
|
||||
utils::{validate_namespace, validate_view_name},
|
||||
view::ViewDescription,
|
||||
};
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use futures::TryStreamExt;
|
||||
use lance_namespace::models::JsonArrowSchema;
|
||||
use std::sync::Arc;
|
||||
#[derive(Clone, serde::Serialize, serde::Deserialize)]
|
||||
@@ -147,64 +145,6 @@ impl SqlClient {
|
||||
namespace: &[String],
|
||||
options: ListingOptions,
|
||||
) -> Result<ListingPage<String>> {
|
||||
validate_namespace(namespace)?;
|
||||
let limit = options.page_limit.unwrap_or(100);
|
||||
if limit == 0 || limit > i32::MAX as u32 {
|
||||
return Err(Error::InvalidInput {
|
||||
message: "page limit must be between 1 and i32::MAX".into(),
|
||||
});
|
||||
}
|
||||
let invalid_token = || Error::InvalidInput {
|
||||
message: "invalid view page token for this database or namespace".into(),
|
||||
};
|
||||
let after = if let Some(token) = options.page_token.filter(|token| !token.is_empty()) {
|
||||
let decoded = URL_SAFE_NO_PAD.decode(token).map_err(|_| invalid_token())?;
|
||||
let (kind, database, prefix, path, last): (
|
||||
String,
|
||||
String,
|
||||
Option<String>,
|
||||
Vec<String>,
|
||||
String,
|
||||
) = serde_json::from_slice(&decoded).map_err(|_| invalid_token())?;
|
||||
if kind != "view"
|
||||
|| database != self.inner.database
|
||||
|| prefix != self.inner.database_prefix
|
||||
|| path != namespace
|
||||
{
|
||||
return Err(invalid_token());
|
||||
}
|
||||
format!(" WHERE name > '{}'", last.replace('\'', "''"))
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let query = self
|
||||
.execute(ExecuteQueryRequest {
|
||||
query: format!("SHOW VIEWS{after} LIMIT {}", u64::from(limit) + 1),
|
||||
default_namespace_path: namespace.to_vec(),
|
||||
parameters: None,
|
||||
})
|
||||
.await?;
|
||||
let mut reader = query.reader().await?;
|
||||
let mut items = Vec::new();
|
||||
while let Some(batch) = reader.try_next().await? {
|
||||
items.extend(strings(&[batch], "name")?);
|
||||
}
|
||||
let page_token = if items.len() > limit as usize {
|
||||
items.truncate(limit as usize);
|
||||
let cursor = serde_json::to_vec(&(
|
||||
"view",
|
||||
&self.inner.database,
|
||||
&self.inner.database_prefix,
|
||||
namespace,
|
||||
items.last().unwrap(),
|
||||
))
|
||||
.map_err(|error| Error::Runtime {
|
||||
message: error.to_string(),
|
||||
})?;
|
||||
Some(URL_SAFE_NO_PAD.encode(cursor))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(ListingPage { items, page_token })
|
||||
self.list_names("SHOW VIEWS", namespace, options).await
|
||||
}
|
||||
}
|
||||
|
||||
+410
-279
@@ -14,7 +14,6 @@ use arrow_flight::{
|
||||
FlightInfo, HandshakeRequest, HandshakeResponse, PollInfo, PutResult, SchemaResult, Ticket,
|
||||
};
|
||||
use arrow_schema::{DataType, Field, Schema};
|
||||
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use futures::stream::BoxStream;
|
||||
use futures::{StreamExt, TryStreamExt};
|
||||
use tonic::metadata::MetadataMap;
|
||||
@@ -2919,25 +2918,54 @@ async fn remote_optimize_full_rejects_explicit_pruning_options() {
|
||||
assert_rejected_before_submission(None, None, Some(true)).await;
|
||||
}
|
||||
|
||||
fn sql_listing_batch(column: &str, values: &[&str], token: Option<&str>) -> RecordBatch {
|
||||
let mut columns: Vec<(&str, ArrayRef)> = Vec::new();
|
||||
if column == "name" {
|
||||
columns.push((
|
||||
"namespace_path",
|
||||
Arc::new(StringArray::from(vec![
|
||||
r#"["team","reports"]"#;
|
||||
values.len()
|
||||
])),
|
||||
));
|
||||
}
|
||||
columns.push((column, Arc::new(StringArray::from(values.to_vec()))));
|
||||
let batch = RecordBatch::try_from_iter(columns).unwrap();
|
||||
let metadata = token
|
||||
.map(|token| HashMap::from([("lancedb.next_page_token".to_owned(), token.to_owned())]))
|
||||
.unwrap_or_default();
|
||||
let schema = Arc::new(batch.schema().as_ref().clone().with_metadata(metadata));
|
||||
RecordBatch::try_new(schema, batch.columns().to_vec()).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn remote_mv_listing_uses_scoped_sql_keyset_pagination() {
|
||||
async fn remote_mv_listing_uses_server_continuation_tokens() {
|
||||
for defer in [false, true] {
|
||||
let result = RecordBatch::try_from_iter(vec![(
|
||||
"name",
|
||||
Arc::new(StringArray::from(vec!["a", "b'c", "z"])) as ArrayRef,
|
||||
)])
|
||||
.unwrap();
|
||||
let token = "server'opaque:token";
|
||||
let next_sql =
|
||||
"SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'";
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
defer,
|
||||
result,
|
||||
result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([
|
||||
(
|
||||
"SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2".to_owned(),
|
||||
sql_listing_batch("name", &["a", "b"], Some(token)),
|
||||
),
|
||||
(next_sql.to_owned(), sql_listing_batch("name", &["z"], None)),
|
||||
]))),
|
||||
..Default::default()
|
||||
};
|
||||
let statements = service.statements.clone();
|
||||
let headers = service.headers.clone();
|
||||
let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await;
|
||||
let db = RemoteDatabase::new_mock(|request| -> http::Response<String> {
|
||||
panic!("unexpected REST request: {}", request.url().path());
|
||||
let (client, shutdown) = start_sql_service_with_prefix(
|
||||
service,
|
||||
ClientConfig::default(),
|
||||
Some("tenant/production"),
|
||||
)
|
||||
.await;
|
||||
let db = RemoteDatabase::new_mock(|_| -> http::Response<String> {
|
||||
panic!("unexpected REST request")
|
||||
})
|
||||
.with_sql_client(client);
|
||||
let namespace = vec!["team".to_owned(), "reports".to_owned()];
|
||||
@@ -2948,41 +2976,31 @@ async fn remote_mv_listing_uses_scoped_sql_keyset_pagination() {
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(first.items, ["a", "b'c"]);
|
||||
let token = first.page_token.unwrap();
|
||||
db.list_materialized_views(
|
||||
&namespace,
|
||||
crate::listing::ListingOptions::default()
|
||||
.page_limit(2)
|
||||
.page_token(&token),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(first.items, ["a", "b"]);
|
||||
assert_eq!(first.page_token.as_deref(), Some(token));
|
||||
let second = db
|
||||
.list_materialized_views(
|
||||
&namespace,
|
||||
crate::listing::ListingOptions::default()
|
||||
.page_limit(2)
|
||||
.page_token(first.page_token.unwrap()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(second.items, ["z"]);
|
||||
assert!(second.page_token.is_none());
|
||||
assert_eq!(
|
||||
*statements.lock().unwrap(),
|
||||
[
|
||||
"SHOW MATERIALIZED VIEWS LIMIT 3",
|
||||
"SHOW MATERIALIZED VIEWS WHERE name > 'b''c' LIMIT 3"
|
||||
"SHOW MATERIALIZED VIEWS IN \"team$reports\" LIMIT 2",
|
||||
next_sql
|
||||
]
|
||||
);
|
||||
assert!(
|
||||
headers
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|header| header.namespace_path == "team$reports")
|
||||
);
|
||||
for (path, token) in [(vec![], token), (namespace, "invalid".into())] {
|
||||
assert!(matches!(
|
||||
db.list_materialized_views(
|
||||
&path,
|
||||
crate::listing::ListingOptions::default().page_token(token)
|
||||
)
|
||||
.await,
|
||||
Err(Error::InvalidInput { .. })
|
||||
));
|
||||
for header in headers.lock().unwrap().iter() {
|
||||
assert_eq!(header.database, "analytics");
|
||||
assert_eq!(header.database_prefix, "tenant/production");
|
||||
assert_eq!(header.namespace_path, "team$reports");
|
||||
}
|
||||
assert_eq!(statements.lock().unwrap().len(), 2);
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -3123,7 +3141,10 @@ async fn storage_integration_methods_use_sql_with_namespace_and_typed_metadata()
|
||||
let statements = statements.lock().unwrap();
|
||||
assert!(statements[0].contains("STORAGE_AWS_REGION = 'us-east-1'"));
|
||||
assert_eq!(statements[1], "DESCRIBE STORAGE INTEGRATION \"raw\"");
|
||||
assert_eq!(statements[2], "SHOW STORAGE INTEGRATIONS");
|
||||
assert_eq!(
|
||||
statements[2],
|
||||
"SHOW STORAGE INTEGRATIONS IN \"platform$aws\" LIMIT 1000"
|
||||
);
|
||||
assert_eq!(statements[3], "DROP STORAGE INTEGRATION \"raw\"");
|
||||
assert!(statements[4].contains(
|
||||
"STORAGE_AWS_ACCESS_KEY_ID_SECRET = \"platform/raw\".\"credentials\".\"key\""
|
||||
@@ -3171,6 +3192,38 @@ async fn function_creation_and_description_use_sql_query_handles() {
|
||||
version_json["max_concurrency"] = serde_json::json!(4);
|
||||
version_json["row_timeout_seconds"] = serde_json::json!(8.0);
|
||||
version_json["result_stability"] = serde_json::json!("input_and_context");
|
||||
version_json["runtime"] = request_json["runtime"].clone();
|
||||
version_json["resolved_environment"] = serde_json::json!({
|
||||
"packages": [
|
||||
{
|
||||
"name": "torch",
|
||||
"version": "2.9.0+cu130",
|
||||
"source": "https://packages.example/simple"
|
||||
},
|
||||
{
|
||||
"name": "transformers",
|
||||
"version": "4.57.1"
|
||||
}
|
||||
],
|
||||
"provenance": {
|
||||
"configured_index_urls": ["https://packages.example/simple"],
|
||||
"configured_find_links": [],
|
||||
"resolved_indexes": ["https://packages.example/simple"],
|
||||
"cuda_toolkit": "12.8",
|
||||
"torch_version": "torch==2.9.0+cu130"
|
||||
},
|
||||
"warnings": [
|
||||
"transformers resolved to transformers==4.57.1 but is not pinned exactly; add transformers==4.57.1 to pin it."
|
||||
]
|
||||
});
|
||||
version_json["resolved_environments"] = serde_json::json!({
|
||||
"linux/amd64": {
|
||||
"packages": [{"name": "torch", "version": "2.9.0+cu130"}]
|
||||
},
|
||||
"linux/arm64": {
|
||||
"packages": []
|
||||
}
|
||||
});
|
||||
if with_models {
|
||||
let models = serde_json::json!([{
|
||||
"repo": "sentence-transformers/all-MiniLM-L6-v2",
|
||||
@@ -3217,6 +3270,17 @@ async fn function_creation_and_description_use_sql_query_handles() {
|
||||
assert_eq!(created.max_concurrency(), Some(4));
|
||||
assert_eq!(created.row_timeout_seconds(), Some(8.0));
|
||||
assert_eq!(created.result_stability(), Some("input_and_context"));
|
||||
assert_eq!(created.runtime().unwrap().kind(), "python");
|
||||
assert_eq!(
|
||||
created.resolved_environment().unwrap().packages[0].version,
|
||||
"2.9.0+cu130"
|
||||
);
|
||||
assert_eq!(created.resolved_environments().len(), 2);
|
||||
assert!(
|
||||
created.resolved_environments()["linux/arm64"]
|
||||
.packages
|
||||
.is_empty()
|
||||
);
|
||||
// Assert the actual SQL body, after the same native JSON decode used
|
||||
// by the Python binding, rather than only the Python declaration.
|
||||
{
|
||||
@@ -3240,6 +3304,23 @@ async fn function_creation_and_description_use_sql_query_handles() {
|
||||
assert_eq!(created_json["max_concurrency"], 4);
|
||||
assert_eq!(created_json["row_timeout_seconds"], 8.0);
|
||||
assert_eq!(created_json["result_stability"], "input_and_context");
|
||||
assert_eq!(
|
||||
created_json["resolved_environment"]["packages"][0]["version"],
|
||||
"2.9.0+cu130"
|
||||
);
|
||||
assert!(
|
||||
created_json["resolved_environment"]["packages"][1]
|
||||
.get("source")
|
||||
.is_none()
|
||||
);
|
||||
assert_eq!(
|
||||
created_json["resolved_environments"]["linux/amd64"]["packages"][0]["version"],
|
||||
"2.9.0+cu130"
|
||||
);
|
||||
assert_eq!(
|
||||
created_json["resolved_environments"]["linux/arm64"]["packages"],
|
||||
serde_json::json!([])
|
||||
);
|
||||
assert_eq!(
|
||||
client.describe(id).await.unwrap().status,
|
||||
QueryStatus::Finished
|
||||
@@ -3253,6 +3334,19 @@ async fn function_creation_and_description_use_sql_query_handles() {
|
||||
assert_eq!(described.max_concurrency(), Some(4));
|
||||
assert_eq!(described.row_timeout_seconds(), Some(8.0));
|
||||
assert_eq!(described.result_stability(), Some("input_and_context"));
|
||||
assert_eq!(described.runtime().unwrap().kind(), "python");
|
||||
assert_eq!(
|
||||
described
|
||||
.resolved_environment()
|
||||
.unwrap()
|
||||
.provenance
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.torch_version
|
||||
.as_deref(),
|
||||
Some("torch==2.9.0+cu130")
|
||||
);
|
||||
assert_eq!(described.resolved_environments().len(), 2);
|
||||
let described_json: serde_json::Value =
|
||||
serde_json::from_str(&described.to_canonical_json().unwrap()).unwrap();
|
||||
assert_eq!(described_json["image"].get("models"), expected_models);
|
||||
@@ -3279,6 +3373,16 @@ async fn function_creation_and_description_use_sql_query_handles() {
|
||||
listed.items[0].result_stability(),
|
||||
Some("input_and_context")
|
||||
);
|
||||
assert_eq!(listed.items[0].runtime().unwrap().kind(), "python");
|
||||
assert_eq!(
|
||||
listed.items[0]
|
||||
.resolved_environment()
|
||||
.unwrap()
|
||||
.warnings
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
assert_eq!(listed.items[0].resolved_environments().len(), 2);
|
||||
let listed_json: serde_json::Value =
|
||||
serde_json::from_str(&listed.items[0].to_canonical_json().unwrap()).unwrap();
|
||||
assert_eq!(listed_json["image"].get("models"), expected_models);
|
||||
@@ -3293,6 +3397,58 @@ async fn function_creation_and_description_use_sql_query_handles() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn function_creation_refresh_lock_is_forwarded_only_when_true() {
|
||||
const VERSION: &str = include_str!(
|
||||
"../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json"
|
||||
);
|
||||
const REQUEST: &str = include_str!(
|
||||
"../../tests/fixtures/first_class_functions/v1/remote_function_registration_request.json"
|
||||
);
|
||||
for (refresh_lock, expect_field) in [(false, false), (true, true)] {
|
||||
let mut request_json: serde_json::Value = serde_json::from_str(REQUEST).unwrap();
|
||||
if refresh_lock {
|
||||
request_json["refresh_lock"] = serde_json::json!(true);
|
||||
}
|
||||
let request =
|
||||
crate::function::FunctionRegistrationRequest::from_json(&request_json.to_string())
|
||||
.unwrap();
|
||||
assert_eq!(request.refresh_lock, refresh_lock);
|
||||
let result = RecordBatch::try_from_iter(vec![(
|
||||
"definition",
|
||||
Arc::new(StringArray::from(vec![VERSION.to_string()])) as ArrayRef,
|
||||
)])
|
||||
.unwrap();
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
defer: false,
|
||||
result,
|
||||
..Default::default()
|
||||
};
|
||||
let statements = service.statements.clone();
|
||||
let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await;
|
||||
let db = RemoteDatabase::new_mock(|request| -> http::Response<String> {
|
||||
panic!("unexpected REST request: {}", request.url().path());
|
||||
})
|
||||
.with_sql_client(client.clone());
|
||||
let job = db.create_function_async(request, &[]).await.unwrap();
|
||||
job.wait().await.unwrap();
|
||||
let seen = statements.lock().unwrap();
|
||||
let encoded = seen[0]
|
||||
.strip_prefix(r#"CREATE FUNCTION "normalize_score" FROM '"#)
|
||||
.unwrap()
|
||||
.strip_suffix('\'')
|
||||
.unwrap();
|
||||
let sent: serde_json::Value = serde_json::from_str(&encoded.replace("''", "'")).unwrap();
|
||||
assert_eq!(sent.get("refresh_lock").is_some(), expect_field);
|
||||
if expect_field {
|
||||
assert_eq!(sent["refresh_lock"], serde_json::json!(true));
|
||||
}
|
||||
drop(seen);
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn function_creation_rejects_invalid_execution_controls_before_sql() {
|
||||
const REQUEST: &str = include_str!(
|
||||
@@ -3535,29 +3691,20 @@ async fn secret_description_uses_the_sql_metadata_projection() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn secret_listing_uses_bounded_sql_and_scoped_cursors() {
|
||||
async fn secret_listing_uses_server_continuation_tokens() {
|
||||
for defer in [false, true] {
|
||||
let first_result = RecordBatch::try_from_iter(vec![(
|
||||
"name",
|
||||
Arc::new(StringArray::from(vec!["api-key", "hf'prod", "openai-prod"])) as ArrayRef,
|
||||
)])
|
||||
.unwrap();
|
||||
let second_result = RecordBatch::try_from_iter(vec![(
|
||||
"name",
|
||||
Arc::new(StringArray::from(vec!["openai-prod"])) as ArrayRef,
|
||||
)])
|
||||
.unwrap();
|
||||
let result_overrides = Arc::new(std::sync::Mutex::new(HashMap::from([
|
||||
("SHOW SECRETS LIMIT 3".to_string(), first_result),
|
||||
(
|
||||
"SHOW SECRETS WHERE name > 'hf''prod' LIMIT 3".to_string(),
|
||||
second_result,
|
||||
),
|
||||
])));
|
||||
let token = "server'opaque:token";
|
||||
let next_sql = "SHOW SECRETS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'";
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
defer,
|
||||
result_overrides,
|
||||
result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([
|
||||
(
|
||||
"SHOW SECRETS IN \"team$reports\" LIMIT 2".to_owned(),
|
||||
sql_listing_batch("name", &["a", "b"], Some(token)),
|
||||
),
|
||||
(next_sql.to_owned(), sql_listing_batch("name", &["z"], None)),
|
||||
]))),
|
||||
..Default::default()
|
||||
};
|
||||
let statements = service.statements.clone();
|
||||
@@ -3569,11 +3716,10 @@ async fn secret_listing_uses_bounded_sql_and_scoped_cursors() {
|
||||
)
|
||||
.await;
|
||||
let db = RemoteDatabase::new_mock(|_| -> http::Response<String> {
|
||||
panic!("unexpected REST request");
|
||||
panic!("unexpected REST request")
|
||||
})
|
||||
.with_sql_client(client);
|
||||
let namespace = vec!["team".to_owned(), "reports".to_owned()];
|
||||
|
||||
let first = db
|
||||
.list_secrets(
|
||||
&namespace,
|
||||
@@ -3581,90 +3727,144 @@ async fn secret_listing_uses_bounded_sql_and_scoped_cursors() {
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(first.items, ["api-key", "hf'prod"]);
|
||||
let token = first.page_token.expect("a third row must produce a token");
|
||||
|
||||
assert_eq!(first.items, ["a", "b"]);
|
||||
assert_eq!(first.page_token.as_deref(), Some(token));
|
||||
let second = db
|
||||
.list_secrets(
|
||||
&namespace,
|
||||
crate::listing::ListingOptions::default()
|
||||
.page_limit(2)
|
||||
.page_token(&token),
|
||||
.page_token(first.page_token.unwrap()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(second.items, ["openai-prod"]);
|
||||
assert_eq!(second.items, ["z"]);
|
||||
assert!(second.page_token.is_none());
|
||||
|
||||
assert_eq!(
|
||||
*statements.lock().unwrap(),
|
||||
[
|
||||
"SHOW SECRETS LIMIT 3",
|
||||
"SHOW SECRETS WHERE name > 'hf''prod' LIMIT 3"
|
||||
]
|
||||
["SHOW SECRETS IN \"team$reports\" LIMIT 2", next_sql]
|
||||
);
|
||||
{
|
||||
let headers = headers.lock().unwrap();
|
||||
assert!(!headers.is_empty());
|
||||
for header in headers.iter() {
|
||||
assert_eq!(header.database, "analytics");
|
||||
assert_eq!(header.database_prefix, "tenant/production");
|
||||
assert_eq!(header.namespace_path, "team$reports");
|
||||
}
|
||||
for header in headers.lock().unwrap().iter() {
|
||||
assert_eq!(header.database, "analytics");
|
||||
assert_eq!(header.database_prefix, "tenant/production");
|
||||
assert_eq!(header.namespace_path, "team$reports");
|
||||
}
|
||||
|
||||
for (path, token) in [
|
||||
(vec!["other".to_owned()], token),
|
||||
(namespace.clone(), "invalid".to_owned()),
|
||||
] {
|
||||
assert!(matches!(
|
||||
db.list_secrets(
|
||||
&path,
|
||||
crate::listing::ListingOptions::default().page_token(token)
|
||||
)
|
||||
.await,
|
||||
Err(Error::InvalidInput { .. })
|
||||
));
|
||||
}
|
||||
assert_eq!(statements.lock().unwrap().len(), 2);
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn secret_listing_handles_empty_pages_and_rejects_invalid_limits() {
|
||||
let empty = RecordBatch::try_from_iter(vec![(
|
||||
"name",
|
||||
Arc::new(StringArray::from(Vec::<String>::new())) as ArrayRef,
|
||||
)])
|
||||
.unwrap();
|
||||
async fn storage_integration_listing_uses_server_continuation_tokens() {
|
||||
for defer in [false, true] {
|
||||
let token = "server'opaque:token";
|
||||
let next_sql =
|
||||
"SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'";
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
defer,
|
||||
result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([
|
||||
(
|
||||
"SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2".to_owned(),
|
||||
sql_listing_batch("name", &["a", "b"], Some(token)),
|
||||
),
|
||||
(next_sql.to_owned(), sql_listing_batch("name", &["z"], None)),
|
||||
]))),
|
||||
..Default::default()
|
||||
};
|
||||
let statements = service.statements.clone();
|
||||
let headers = service.headers.clone();
|
||||
let (client, shutdown) = start_sql_service_with_prefix(
|
||||
service,
|
||||
ClientConfig::default(),
|
||||
Some("tenant/production"),
|
||||
)
|
||||
.await;
|
||||
let db = RemoteDatabase::new_mock(|_| -> http::Response<String> {
|
||||
panic!("unexpected REST request")
|
||||
})
|
||||
.with_sql_client(client);
|
||||
let namespace = vec!["team".to_owned(), "reports".to_owned()];
|
||||
let first = db
|
||||
.list_storage_integrations(
|
||||
&namespace,
|
||||
crate::listing::ListingOptions::default().page_limit(2),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(first.items, ["a", "b"]);
|
||||
assert_eq!(first.page_token.as_deref(), Some(token));
|
||||
let second = db
|
||||
.list_storage_integrations(
|
||||
&namespace,
|
||||
crate::listing::ListingOptions::default()
|
||||
.page_limit(2)
|
||||
.page_token(first.page_token.unwrap()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(second.items, ["z"]);
|
||||
assert!(second.page_token.is_none());
|
||||
assert_eq!(
|
||||
*statements.lock().unwrap(),
|
||||
[
|
||||
"SHOW STORAGE INTEGRATIONS IN \"team$reports\" LIMIT 2",
|
||||
next_sql
|
||||
]
|
||||
);
|
||||
for header in headers.lock().unwrap().iter() {
|
||||
assert_eq!(header.database, "analytics");
|
||||
assert_eq!(header.database_prefix, "tenant/production");
|
||||
assert_eq!(header.namespace_path, "team$reports");
|
||||
}
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn secret_listing_preserves_empty_continuations_and_validates_page_options() {
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
defer: true,
|
||||
result: empty,
|
||||
result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([
|
||||
(
|
||||
"SHOW SECRETS IN \"team$reports\" LIMIT 2".to_owned(),
|
||||
sql_listing_batch("name", &[], Some("continue-empty")),
|
||||
),
|
||||
(
|
||||
"SHOW SECRETS IN \"team$reports\" LIMIT 2 FROM 'continue-empty'".to_owned(),
|
||||
sql_listing_batch("name", &["last"], None),
|
||||
),
|
||||
]))),
|
||||
..Default::default()
|
||||
};
|
||||
let statements = service.statements.clone();
|
||||
let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await;
|
||||
let db = RemoteDatabase::new_mock(|_| -> http::Response<String> {
|
||||
panic!("unexpected REST request");
|
||||
panic!("unexpected REST request")
|
||||
})
|
||||
.with_sql_client(client);
|
||||
let namespace = vec!["team".to_owned(), "reports".to_owned()];
|
||||
|
||||
let page = db
|
||||
.list_secrets(
|
||||
&namespace,
|
||||
crate::listing::ListingOptions::default()
|
||||
.page_limit(2)
|
||||
.page_token(""),
|
||||
crate::listing::ListingOptions::default().page_limit(2),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(page.items.is_empty());
|
||||
assert!(page.page_token.is_none());
|
||||
|
||||
for limit in [0, i32::MAX as u32 + 1] {
|
||||
assert_eq!(page.page_token.as_deref(), Some("continue-empty"));
|
||||
let last = db
|
||||
.list_secrets(
|
||||
&namespace,
|
||||
crate::listing::ListingOptions::default()
|
||||
.page_limit(2)
|
||||
.page_token(page.page_token.unwrap()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(last.items, ["last"]);
|
||||
assert!(last.page_token.is_none());
|
||||
for limit in [10_001, u32::MAX] {
|
||||
assert!(matches!(
|
||||
db.list_secrets(
|
||||
&namespace,
|
||||
@@ -3674,12 +3874,29 @@ async fn secret_listing_handles_empty_pages_and_rejects_invalid_limits() {
|
||||
Err(Error::InvalidInput { .. })
|
||||
));
|
||||
}
|
||||
assert_eq!(*statements.lock().unwrap(), ["SHOW SECRETS LIMIT 3"]);
|
||||
assert!(
|
||||
db.list_secrets(
|
||||
&namespace,
|
||||
crate::listing::ListingOptions::default().page_token("")
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let zero = db
|
||||
.list_secrets(
|
||||
&namespace,
|
||||
crate::listing::ListingOptions::default().page_limit(0),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(zero.items.is_empty());
|
||||
assert!(zero.page_token.is_none());
|
||||
assert_eq!(statements.lock().unwrap().len(), 2);
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn function_listing_uses_bounded_sql_and_scoped_version_cursors() {
|
||||
async fn function_listing_uses_server_tokens_for_numeric_revision_pages() {
|
||||
const VERSION: &str = include_str!(
|
||||
"../../tests/fixtures/first_class_functions/v1/remote_function_version.canonical.json"
|
||||
);
|
||||
@@ -3689,74 +3906,65 @@ async fn function_listing_uses_bounded_sql_and_scoped_version_cursors() {
|
||||
let mut tenth: serde_json::Value = serde_json::from_str(VERSION).unwrap();
|
||||
tenth["version"] = serde_json::json!("10");
|
||||
let tenth = tenth.to_string();
|
||||
let result = RecordBatch::try_from_iter(vec![(
|
||||
"definition",
|
||||
Arc::new(StringArray::from(vec![
|
||||
VERSION,
|
||||
second.as_str(),
|
||||
tenth.as_str(),
|
||||
])) as ArrayRef,
|
||||
)])
|
||||
.unwrap();
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
defer: true,
|
||||
result,
|
||||
..Default::default()
|
||||
};
|
||||
service.result_overrides.lock().unwrap().insert(
|
||||
"SHOW FUNCTIONS HISTORY WITH (limit = 3, include_definition = true, after_name = 'embed', after_version = '2')".into(),
|
||||
RecordBatch::try_from_iter(vec![("definition", Arc::new(StringArray::from(vec![tenth.as_str()])) as ArrayRef)]).unwrap(),
|
||||
);
|
||||
let statements = service.statements.clone();
|
||||
let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await;
|
||||
let db = RemoteDatabase::new_mock(|_| -> http::Response<String> {
|
||||
panic!("unexpected REST request");
|
||||
})
|
||||
.with_sql_client(client);
|
||||
let first = db
|
||||
.list_functions(
|
||||
&["team".into()],
|
||||
crate::listing::ListingOptions::default().page_limit(2),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
first
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| item.version())
|
||||
.collect::<Vec<_>>(),
|
||||
["1", "2"]
|
||||
);
|
||||
let token = first.page_token.unwrap();
|
||||
let second = db
|
||||
.list_functions(
|
||||
&["team".into()],
|
||||
crate::listing::ListingOptions::default()
|
||||
.page_limit(2)
|
||||
.page_token(token.clone()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(second.items.len(), 1);
|
||||
assert_eq!(second.items[0].version(), "10");
|
||||
assert!(second.page_token.is_none());
|
||||
assert!(
|
||||
db.list_functions(
|
||||
&["other".into()],
|
||||
crate::listing::ListingOptions::default()
|
||||
.page_limit(2)
|
||||
.page_token(token)
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let seen = statements.lock().unwrap();
|
||||
assert_eq!(seen.len(), 2);
|
||||
assert!(seen[0].starts_with("SHOW FUNCTIONS HISTORY WITH (limit = 3,"));
|
||||
assert!(seen[1].contains("after_version = '2'"));
|
||||
shutdown.send(()).unwrap();
|
||||
for defer in [false, true] {
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
defer,
|
||||
result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([
|
||||
(
|
||||
"SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2".to_owned(),
|
||||
sql_listing_batch("definition", &[VERSION, &second], Some("revision-cursor")),
|
||||
),
|
||||
(
|
||||
"SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2 FROM 'revision-cursor'".to_owned(),
|
||||
sql_listing_batch("definition", &[&tenth], None),
|
||||
),
|
||||
]))),
|
||||
..Default::default()
|
||||
};
|
||||
let statements = service.statements.clone();
|
||||
let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await;
|
||||
let db = RemoteDatabase::new_mock(|_| -> http::Response<String> {
|
||||
panic!("unexpected REST request")
|
||||
})
|
||||
.with_sql_client(client);
|
||||
let first = db
|
||||
.list_functions(
|
||||
&["team".into()],
|
||||
crate::listing::ListingOptions::default().page_limit(2),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
first
|
||||
.items
|
||||
.iter()
|
||||
.map(|item| item.version())
|
||||
.collect::<Vec<_>>(),
|
||||
["1", "2"]
|
||||
);
|
||||
assert_eq!(first.page_token.as_deref(), Some("revision-cursor"));
|
||||
let last = db
|
||||
.list_functions(
|
||||
&["team".into()],
|
||||
crate::listing::ListingOptions::default()
|
||||
.page_limit(2)
|
||||
.page_token(first.page_token.unwrap()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(last.items.len(), 1);
|
||||
assert_eq!(last.items[0].version(), "10");
|
||||
assert!(last.page_token.is_none());
|
||||
assert_eq!(
|
||||
*statements.lock().unwrap(),
|
||||
[
|
||||
"SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2",
|
||||
"SHOW FUNCTIONS HISTORY IN \"team\" LIMIT 2 FROM 'revision-cursor'"
|
||||
]
|
||||
);
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -3864,29 +4072,20 @@ async fn view_drop_uses_a_repeatable_query_job() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn view_listing_uses_bounded_sql_and_scoped_cursors() {
|
||||
async fn view_listing_uses_server_continuation_tokens() {
|
||||
for defer in [false, true] {
|
||||
let first_result = RecordBatch::try_from_iter(vec![(
|
||||
"name",
|
||||
Arc::new(StringArray::from(vec!["adults", "hf'prod", "openai-prod"])) as ArrayRef,
|
||||
)])
|
||||
.unwrap();
|
||||
let second_result = RecordBatch::try_from_iter(vec![(
|
||||
"name",
|
||||
Arc::new(StringArray::from(vec!["openai-prod"])) as ArrayRef,
|
||||
)])
|
||||
.unwrap();
|
||||
let result_overrides = Arc::new(std::sync::Mutex::new(HashMap::from([
|
||||
("SHOW VIEWS LIMIT 3".to_string(), first_result),
|
||||
(
|
||||
"SHOW VIEWS WHERE name > 'hf''prod' LIMIT 3".to_string(),
|
||||
second_result,
|
||||
),
|
||||
])));
|
||||
let token = "server'opaque:token";
|
||||
let next_sql = "SHOW VIEWS IN \"team$reports\" LIMIT 2 FROM 'server''opaque:token'";
|
||||
let service = TestSqlService {
|
||||
adaptive: true,
|
||||
defer,
|
||||
result_overrides,
|
||||
result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([
|
||||
(
|
||||
"SHOW VIEWS IN \"team$reports\" LIMIT 2".to_owned(),
|
||||
sql_listing_batch("name", &["a", "b"], Some(token)),
|
||||
),
|
||||
(next_sql.to_owned(), sql_listing_batch("name", &["z"], None)),
|
||||
]))),
|
||||
..Default::default()
|
||||
};
|
||||
let statements = service.statements.clone();
|
||||
@@ -3898,107 +4097,39 @@ async fn view_listing_uses_bounded_sql_and_scoped_cursors() {
|
||||
)
|
||||
.await;
|
||||
let db = RemoteDatabase::new_mock(|_| -> http::Response<String> {
|
||||
panic!("unexpected REST request");
|
||||
panic!("unexpected REST request")
|
||||
})
|
||||
.with_sql_client(client);
|
||||
let connection = Connection::new(
|
||||
Arc::new(db),
|
||||
Arc::new(crate::embeddings::MemoryRegistry::new()),
|
||||
);
|
||||
let namespace = vec!["team".to_owned(), "reports".to_owned()];
|
||||
|
||||
let first = connection
|
||||
let first = db
|
||||
.list_views(
|
||||
&namespace,
|
||||
crate::listing::ListingOptions::default().page_limit(2),
|
||||
)
|
||||
.next_page()
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(first.items, ["adults", "hf'prod"]);
|
||||
let token = first.page_token.expect("a third row must produce a token");
|
||||
|
||||
let second = connection
|
||||
assert_eq!(first.items, ["a", "b"]);
|
||||
assert_eq!(first.page_token.as_deref(), Some(token));
|
||||
let second = db
|
||||
.list_views(
|
||||
&namespace,
|
||||
crate::listing::ListingOptions::default()
|
||||
.page_limit(2)
|
||||
.page_token(&token),
|
||||
.page_token(first.page_token.unwrap()),
|
||||
)
|
||||
.next_page()
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(second.items, ["openai-prod"]);
|
||||
assert_eq!(second.items, ["z"]);
|
||||
assert!(second.page_token.is_none());
|
||||
|
||||
assert_eq!(
|
||||
*statements.lock().unwrap(),
|
||||
[
|
||||
"SHOW VIEWS LIMIT 3",
|
||||
"SHOW VIEWS WHERE name > 'hf''prod' LIMIT 3"
|
||||
]
|
||||
["SHOW VIEWS IN \"team$reports\" LIMIT 2", next_sql]
|
||||
);
|
||||
{
|
||||
let headers = headers.lock().unwrap();
|
||||
assert!(!headers.is_empty());
|
||||
for header in headers.iter() {
|
||||
assert_eq!(header.database, "analytics");
|
||||
assert_eq!(header.database_prefix, "tenant/production");
|
||||
assert_eq!(header.namespace_path, "team$reports");
|
||||
}
|
||||
for header in headers.lock().unwrap().iter() {
|
||||
assert_eq!(header.database, "analytics");
|
||||
assert_eq!(header.database_prefix, "tenant/production");
|
||||
assert_eq!(header.namespace_path, "team$reports");
|
||||
}
|
||||
|
||||
let encode_token =
|
||||
|kind: &str, database: &str, prefix: Option<&str>, path: &[String], last: &str| {
|
||||
URL_SAFE_NO_PAD.encode(
|
||||
serde_json::to_vec(&(kind, database, prefix, path.to_vec(), last)).unwrap(),
|
||||
)
|
||||
};
|
||||
for forged in [
|
||||
encode_token(
|
||||
"secret",
|
||||
"analytics",
|
||||
Some("tenant/production"),
|
||||
&namespace,
|
||||
"hf'prod",
|
||||
),
|
||||
encode_token(
|
||||
"view",
|
||||
"billing",
|
||||
Some("tenant/production"),
|
||||
&namespace,
|
||||
"hf'prod",
|
||||
),
|
||||
encode_token("view", "analytics", Some("other"), &namespace, "hf'prod"),
|
||||
encode_token(
|
||||
"view",
|
||||
"analytics",
|
||||
Some("tenant/production"),
|
||||
&["other".to_owned()],
|
||||
"hf'prod",
|
||||
),
|
||||
"not-a-json-token".to_string(),
|
||||
] {
|
||||
let mut listing = connection.list_views(
|
||||
&namespace,
|
||||
crate::listing::ListingOptions::default().page_token(forged),
|
||||
);
|
||||
assert!(matches!(
|
||||
listing.next_page().await,
|
||||
Err(Error::InvalidInput { .. })
|
||||
));
|
||||
}
|
||||
let mut listing = connection.list_views(
|
||||
&["other".to_owned()],
|
||||
crate::listing::ListingOptions::default().page_token(&token),
|
||||
);
|
||||
assert!(matches!(
|
||||
listing.next_page().await,
|
||||
Err(Error::InvalidInput { .. })
|
||||
));
|
||||
assert_eq!(statements.lock().unwrap().len(), 2);
|
||||
shutdown.send(()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,29 +259,6 @@ pub(super) fn decode_info(batches: &[RecordBatch]) -> Result<StorageIntegrationI
|
||||
.map_err(|error| invalid(format!("Invalid storage integration SQL result: {error}")))
|
||||
}
|
||||
|
||||
pub(super) fn decode_names(batches: &[RecordBatch]) -> Result<Vec<String>> {
|
||||
let mut names = Vec::new();
|
||||
for batch in batches {
|
||||
let column = batch
|
||||
.column_by_name("name")
|
||||
.ok_or_else(|| invalid("SQL storage integration listing is missing names"))?;
|
||||
for row in 0..batch.num_rows() {
|
||||
if column.is_null(row) {
|
||||
return Err(invalid("SQL storage integration name cannot be null"));
|
||||
}
|
||||
names.push(
|
||||
string_value(column.as_ref(), row)
|
||||
.ok_or_else(|| {
|
||||
invalid("SQL storage integration listing requires string names")
|
||||
})?
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
names.sort();
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -20,7 +20,7 @@ use crate::error::{HttpErrorSource, RemoteErrorMetadata};
|
||||
use crate::expr::expr_to_sql_string;
|
||||
use crate::index::Index;
|
||||
use crate::index::IndexStatistics;
|
||||
use crate::index::scalar::FtsQuery;
|
||||
use crate::index::scalar::{FtsQuery, Operator};
|
||||
use crate::index::waiter::{MAX_WAIT, wait_for_index};
|
||||
use crate::job::Job;
|
||||
use crate::materialized_view::{MaterializedViewInfo, RefreshMaterializedViewResult};
|
||||
@@ -1374,6 +1374,20 @@ impl<S: HttpSend> RemoteTable<S> {
|
||||
"query": full_text_search.query.clone(),
|
||||
});
|
||||
} else {
|
||||
let has_and = match &full_text_search.query {
|
||||
FtsQuery::Match(query) => query.operator == Operator::And,
|
||||
FtsQuery::MultiMatch(query) => query
|
||||
.match_queries
|
||||
.iter()
|
||||
.any(|query| query.operator == Operator::And),
|
||||
_ => false,
|
||||
};
|
||||
if has_and {
|
||||
return Err(Error::NotSupported {
|
||||
message: "AND full-text queries require server version 0.3.0 or later"
|
||||
.into(),
|
||||
});
|
||||
}
|
||||
body["full_text_query"] = serde_json::json!({
|
||||
"columns": full_text_search.columns().into_iter().collect::<Vec<_>>(),
|
||||
"query": full_text_search.query.query(),
|
||||
@@ -3707,7 +3721,17 @@ impl<S: HttpSend> BaseTable for RemoteTable<S> {
|
||||
return Ok(merge_result);
|
||||
}
|
||||
Err(err) if rescannable && self.is_retryable_write_error(&err) => {
|
||||
let status = err.status_code();
|
||||
retry_counter.increment_from_error(err)?;
|
||||
log::warn!(
|
||||
"Retrying merge insert {} after status {:?}; attempt {}",
|
||||
retry_counter.request_id,
|
||||
status.map(|s| s.as_u16()),
|
||||
u16::from(retry_counter.request_failures)
|
||||
+ u16::from(retry_counter.connect_failures)
|
||||
+ u16::from(retry_counter.read_failures)
|
||||
+ 1,
|
||||
);
|
||||
tokio::time::sleep(retry_counter.next_sleep_time()).await;
|
||||
merge = merge.reset_state()?;
|
||||
continue;
|
||||
|
||||
@@ -3460,15 +3460,18 @@ mod tests {
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::input_same_rows("body", "a", true)]
|
||||
#[case::input_other_rows("body", "c", false)]
|
||||
#[case::output_same_rows("search_text", "a", true)]
|
||||
#[case::output_other_rows("search_text", "c", false)]
|
||||
#[case::input_same_rows("body", "a", true, 1)]
|
||||
#[case::input_other_rows("body", "c", false, 1)]
|
||||
#[case::input_no_rows("body", "missing", false, 0)]
|
||||
#[case::output_same_rows("search_text", "a", true, 1)]
|
||||
#[case::output_other_rows("search_text", "c", false, 1)]
|
||||
#[case::output_no_rows("search_text", "missing", false, 0)]
|
||||
#[tokio::test]
|
||||
async fn function_write_preserves_prior_invalidation(
|
||||
#[case] changed_column: &str,
|
||||
#[case] title: &str,
|
||||
#[case] dirty_product: bool,
|
||||
#[case] expected_updated_rows: u64,
|
||||
) {
|
||||
let table = fresh_function_table().await;
|
||||
let native = table.as_native().unwrap();
|
||||
@@ -3489,14 +3492,20 @@ mod tests {
|
||||
);
|
||||
native.dataset.update(result.new_dataset.as_ref().clone());
|
||||
|
||||
table
|
||||
let before_version = table.version().await.unwrap();
|
||||
let update = table
|
||||
.update()
|
||||
.only_if(format!("title = '{title}'"))
|
||||
.column("spare", "1")
|
||||
.execute()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(update.rows_updated, expected_updated_rows);
|
||||
let dataset = native.dataset.get().await.unwrap();
|
||||
if expected_updated_rows == 0 {
|
||||
assert_eq!(update.version, before_version);
|
||||
assert_eq!(dataset.version().version, before_version);
|
||||
}
|
||||
let stale = function_plan(&dataset, "search_text").await;
|
||||
assert_eq!(stale.is_dirty(3), dirty_product, "{stale:?}");
|
||||
if !dirty_product {
|
||||
|
||||
@@ -12,6 +12,7 @@ use super::NativeTable;
|
||||
use crate::connection::NamespaceClientPushdownOperation;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::expr::expr_to_sql_string;
|
||||
use crate::index::scalar::{FtsQuery, Operator as FullTextOperator};
|
||||
use crate::query::{
|
||||
DEFAULT_TOP_K, QueryExecutionOptions, QueryFilter, QueryRequest, Select, VectorQueryRequest,
|
||||
};
|
||||
@@ -36,12 +37,13 @@ use lance::io::exec::{ANNIvfBatchExec, ANNIvfSubIndexExec};
|
||||
use lance_datafusion::exec::{analyze_plan as lance_analyze_plan, execute_plan};
|
||||
use lance_index::IndexType;
|
||||
use lance_index::metrics::NoOpMetricsCollector;
|
||||
use lance_index::scalar::FullTextSearchQuery;
|
||||
use lance_index::vector::DIST_COL;
|
||||
use lance_linalg::distance::DistanceType as LanceDistanceType;
|
||||
use lance_namespace::LanceNamespace;
|
||||
use lance_namespace::models::{
|
||||
QueryTableRequest as NsQueryTableRequest, QueryTableRequestColumns,
|
||||
QueryTableRequestFullTextQuery, QueryTableRequestVector, StringFtsQuery,
|
||||
QueryTableRequestFullTextQuery, QueryTableRequestVector, StringFtsQuery, StructuredFtsQuery,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -124,6 +126,10 @@ fn requires_local_namespace_execution(query: &AnyQuery) -> bool {
|
||||
if query.base().use_rte.is_some() || query.base().has_take() {
|
||||
return true;
|
||||
}
|
||||
if matches!(query, AnyQuery::Query(query) if query.fast_search && query.full_text_search.is_some())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
matches!(
|
||||
query,
|
||||
AnyQuery::VectorQuery(vector_query)
|
||||
@@ -858,6 +864,33 @@ async fn execute_namespace_query(
|
||||
parse_arrow_ipc_response(response_bytes).await
|
||||
}
|
||||
|
||||
fn namespace_fts_query(fts: &FullTextSearchQuery) -> Result<Box<QueryTableRequestFullTextQuery>> {
|
||||
if !matches!(&fts.query, FtsQuery::Match(query) if query.operator == FullTextOperator::Or) {
|
||||
let query = serde_json::to_value(&fts.query)
|
||||
.and_then(serde_json::from_value)
|
||||
.map_err(|error| Error::InvalidInput {
|
||||
message: format!("Cannot serialize namespace full-text query: {error}"),
|
||||
})?;
|
||||
Ok(Box::new(QueryTableRequestFullTextQuery {
|
||||
string_query: None,
|
||||
structured_query: Some(Box::new(StructuredFtsQuery::new(query))),
|
||||
}))
|
||||
} else {
|
||||
let columns = fts.columns();
|
||||
Ok(Box::new(QueryTableRequestFullTextQuery {
|
||||
string_query: Some(Box::new(StringFtsQuery {
|
||||
query: fts.query.query().clone(),
|
||||
columns: if columns.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(columns.into_iter().collect())
|
||||
},
|
||||
})),
|
||||
structured_query: None,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert an AnyQuery to the namespace QueryTableRequest format.
|
||||
fn convert_to_namespace_query(query: &AnyQuery) -> Result<NsQueryTableRequest> {
|
||||
query.base().check_filter()?;
|
||||
@@ -912,21 +945,12 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result<NsQueryTableRequest> {
|
||||
}
|
||||
|
||||
// Convert FTS query if present
|
||||
let full_text_query = vq.base.full_text_search.as_ref().map(|fts| {
|
||||
let columns = fts.columns();
|
||||
let columns_vec = if columns.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(columns.into_iter().collect())
|
||||
};
|
||||
Box::new(QueryTableRequestFullTextQuery {
|
||||
string_query: Some(Box::new(StringFtsQuery {
|
||||
query: fts.query.to_string(),
|
||||
columns: columns_vec,
|
||||
})),
|
||||
structured_query: None,
|
||||
})
|
||||
});
|
||||
let full_text_query = vq
|
||||
.base
|
||||
.full_text_search
|
||||
.as_ref()
|
||||
.map(namespace_fts_query)
|
||||
.transpose()?;
|
||||
|
||||
Ok(NsQueryTableRequest {
|
||||
id: None, // Will be set in namespace_query
|
||||
@@ -963,7 +987,6 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result<NsQueryTableRequest> {
|
||||
|
||||
let k = match q.limit {
|
||||
Some(limit) => limit as i32,
|
||||
None if q.full_text_search.is_some() => DEFAULT_TOP_K as i32,
|
||||
None => i32::MAX,
|
||||
};
|
||||
|
||||
@@ -995,20 +1018,11 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result<NsQueryTableRequest> {
|
||||
};
|
||||
|
||||
// Handle full text search if present
|
||||
let full_text_query = q.full_text_search.as_ref().map(|fts| {
|
||||
let columns_vec = if fts.columns().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(fts.columns().iter().cloned().collect())
|
||||
};
|
||||
Box::new(QueryTableRequestFullTextQuery {
|
||||
string_query: Some(Box::new(StringFtsQuery {
|
||||
query: fts.query.to_string(),
|
||||
columns: columns_vec,
|
||||
})),
|
||||
structured_query: None,
|
||||
})
|
||||
});
|
||||
let full_text_query = q
|
||||
.full_text_search
|
||||
.as_ref()
|
||||
.map(namespace_fts_query)
|
||||
.transpose()?;
|
||||
|
||||
// Empty vector for non-vector queries
|
||||
let vector = Box::new(QueryTableRequestVector {
|
||||
@@ -1023,6 +1037,7 @@ fn convert_to_namespace_query(query: &AnyQuery) -> Result<NsQueryTableRequest> {
|
||||
filter,
|
||||
columns,
|
||||
prefilter: Some(q.prefilter),
|
||||
fast_search: Some(q.fast_search),
|
||||
offset: q.offset.map(|o| o as i32),
|
||||
vector_column: None, // No vector column for plain queries
|
||||
with_row_id: Some(q.with_row_id),
|
||||
@@ -1147,6 +1162,7 @@ async fn parse_arrow_ipc_response(bytes: bytes::Bytes) -> Result<DatasetRecordBa
|
||||
#[cfg(test)]
|
||||
#[allow(deprecated)]
|
||||
mod tests {
|
||||
use crate::index::scalar::MatchQuery;
|
||||
use arrow_array::{
|
||||
ArrayRef, FixedSizeListArray, Float32Array, Int32Array, RecordBatch, StringArray,
|
||||
StructArray,
|
||||
@@ -1414,7 +1430,45 @@ mod tests {
|
||||
|
||||
let ns_request = convert_to_namespace_query(&any_query).unwrap();
|
||||
|
||||
assert_eq!(ns_request.k, 10);
|
||||
assert_eq!(ns_request.k, i32::MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_namespace_fts_operators_and_unbounded_counts() {
|
||||
for columns in [
|
||||
vec!["text".to_string()],
|
||||
vec!["title".to_string(), "body".to_string()],
|
||||
] {
|
||||
let fts = FullTextSearchQuery::new_query(
|
||||
MatchQuery::new("gripper closed".to_string())
|
||||
.with_operator(FullTextOperator::And)
|
||||
.into(),
|
||||
)
|
||||
.with_columns(&columns)
|
||||
.unwrap();
|
||||
let request = convert_to_namespace_query(&AnyQuery::Query(QueryRequest {
|
||||
full_text_search: Some(fts),
|
||||
..Default::default()
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(request.k, i32::MAX);
|
||||
let full_text_query = request.full_text_query.unwrap();
|
||||
assert!(full_text_query.string_query.is_none());
|
||||
let query =
|
||||
serde_json::to_value(full_text_query.structured_query.unwrap().query).unwrap();
|
||||
if columns.len() == 1 {
|
||||
assert_eq!(query["match"]["operator"], "And");
|
||||
assert_eq!(query["match"]["column"], "text");
|
||||
} else {
|
||||
let leaves = query["multi_match"]["match_queries"].as_array().unwrap();
|
||||
assert_eq!(leaves.len(), 2);
|
||||
assert!(leaves.iter().all(|leaf| leaf["operator"] == "And"));
|
||||
}
|
||||
}
|
||||
let request =
|
||||
namespace_fts_query(&FullTextSearchQuery::new("gripper closed".to_string())).unwrap();
|
||||
assert_eq!(request.string_query.unwrap().query, "gripper closed");
|
||||
assert!(request.structured_query.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -130,13 +130,14 @@ pub(crate) async fn execute_update(
|
||||
let operation = builder.build()?;
|
||||
let res = operation.execute().await?;
|
||||
let mut new_dataset = res.new_dataset.as_ref().clone();
|
||||
if let Err(error) = super::freshness::preserve_function_freshness(
|
||||
&mut new_dataset,
|
||||
super::freshness::FunctionWrite::Update {
|
||||
columns: &written_columns,
|
||||
},
|
||||
)
|
||||
.await
|
||||
if res.rows_updated > 0
|
||||
&& let Err(error) = super::freshness::preserve_function_freshness(
|
||||
&mut new_dataset,
|
||||
super::freshness::FunctionWrite::Update {
|
||||
columns: &written_columns,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
log::warn!("update committed but Function freshness could not be preserved: {error}");
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "lance-linalg"
|
||||
version = "15.0.0-beta.21"
|
||||
version = "15.0.0-beta.22"
|
||||
publish = false
|
||||
edition = { workspace = true }
|
||||
license = { workspace = true }
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.21`
|
||||
(commit `80bc45a195279befdec42853dac8d15a37e0504d`), licensed under Apache-2.0.
|
||||
This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.22`
|
||||
(commit `49e29d7beb885e42f3ab01fc9fc25b5281cef467`), licensed under Apache-2.0.
|
||||
|
||||
LanceDB patches `src/distance/cosine.rs` to recompute FLOAT32 cosine distances
|
||||
in FLOAT64 when squared norms or dot products overflow or underflow. Ordinary
|
||||
|
||||
Reference in New Issue
Block a user