Merge main into gatekeeper/fix-4911-1

This commit is contained in:
Gatefixer
2026-11-10 09:11:17 +00:00
50 changed files with 1730 additions and 191 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
[tool.bumpversion]
current_version = "0.42.0-beta.9"
current_version = "0.42.0-beta.10"
parse = """(?x)
(?P<major>0|[1-9]\\d*)\\.
(?P<minor>0|[1-9]\\d*)\\.
+1 -1
View File
@@ -44,7 +44,7 @@ jobs:
- platform: x86_64
manylinux: "2_28"
extra_args: "--features fp16kernels"
runner: ubuntu-22.04
runner: ubuntu-2404-8x-x64
package_name: "lancedb"
rustflags: ""
# For successful fat LTO builds, we need a large runner to avoid OOM errors.
Generated
+51 -51
View File
@@ -3814,8 +3814,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
[[package]]
name = "fsst"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow-array",
"rand 0.9.5",
@@ -5292,8 +5292,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a"
[[package]]
name = "lance"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arc-swap",
"arrow",
@@ -5368,8 +5368,8 @@ dependencies = [
[[package]]
name = "lance-arrow"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5391,7 +5391,7 @@ dependencies = [
[[package]]
name = "lance-arrow-scalar"
version = "59.0.0"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5405,7 +5405,7 @@ dependencies = [
[[package]]
name = "lance-arrow-stats"
version = "59.0.0"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -5414,8 +5414,8 @@ dependencies = [
[[package]]
name = "lance-bitpacking"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrayref",
"crunchy",
@@ -5425,8 +5425,8 @@ dependencies = [
[[package]]
name = "lance-core"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5464,8 +5464,8 @@ dependencies = [
[[package]]
name = "lance-datafusion"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow",
"arrow-array",
@@ -5496,8 +5496,8 @@ dependencies = [
[[package]]
name = "lance-datafusion-exec"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow",
"arrow-array",
@@ -5522,8 +5522,8 @@ dependencies = [
[[package]]
name = "lance-datagen"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow",
"arrow-array",
@@ -5540,8 +5540,8 @@ dependencies = [
[[package]]
name = "lance-derive"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"proc-macro2",
"quote",
@@ -5550,8 +5550,8 @@ dependencies = [
[[package]]
name = "lance-encoding"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow-arith",
"arrow-array",
@@ -5584,8 +5584,8 @@ dependencies = [
[[package]]
name = "lance-file"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow-arith",
"arrow-array",
@@ -5616,8 +5616,8 @@ dependencies = [
[[package]]
name = "lance-geo"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -5648,8 +5648,8 @@ dependencies = [
[[package]]
name = "lance-index"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arc-swap",
"arrow",
@@ -5720,8 +5720,8 @@ dependencies = [
[[package]]
name = "lance-index-core"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -5744,8 +5744,8 @@ dependencies = [
[[package]]
name = "lance-io"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow",
"arrow-array",
@@ -5790,8 +5790,8 @@ dependencies = [
[[package]]
name = "lance-jsonb"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"byteorder",
"ethnum",
@@ -5808,7 +5808,7 @@ dependencies = [
[[package]]
name = "lance-linalg"
version = "15.0.0-beta.15"
version = "15.0.0-beta.16"
dependencies = [
"approx",
"argminmax 0.7.1",
@@ -5830,8 +5830,8 @@ dependencies = [
[[package]]
name = "lance-namespace"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow",
"async-trait",
@@ -5845,8 +5845,8 @@ dependencies = [
[[package]]
name = "lance-namespace-impls"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arc-swap",
"arrow",
@@ -5900,8 +5900,8 @@ dependencies = [
[[package]]
name = "lance-select"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -5915,8 +5915,8 @@ dependencies = [
[[package]]
name = "lance-table"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow",
"arrow-array",
@@ -5957,8 +5957,8 @@ dependencies = [
[[package]]
name = "lance-testing"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"arrow-array",
"arrow-schema",
@@ -5971,8 +5971,8 @@ dependencies = [
[[package]]
name = "lance-tokenizer"
version = "15.0.0-beta.15"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.15#a826a940d550ee1f3bb5b470c3e10e670c1e38ce"
version = "15.0.0-beta.16"
source = "git+https://github.com/lance-format/lance.git?tag=v15.0.0-beta.16#03b7ff329e656636c581f1e3547048101990bc1f"
dependencies = [
"frostem",
"icu_segmenter",
@@ -5985,7 +5985,7 @@ dependencies = [
[[package]]
name = "lancedb"
version = "0.42.0-beta.9"
version = "0.42.0-beta.10"
dependencies = [
"ahash",
"anyhow",
@@ -6096,7 +6096,7 @@ dependencies = [
[[package]]
name = "lancedb-cli"
version = "0.42.0-beta.9"
version = "0.42.0-beta.10"
dependencies = [
"anyhow",
"arrow-array",
@@ -6139,7 +6139,7 @@ dependencies = [
[[package]]
name = "lancedb-nodejs"
version = "0.42.0-beta.9"
version = "0.42.0-beta.10"
dependencies = [
"arrow-array",
"arrow-buffer",
@@ -6164,7 +6164,7 @@ dependencies = [
[[package]]
name = "lancedb-python"
version = "0.42.0-beta.9"
version = "0.42.0-beta.10"
dependencies = [
"arc-swap",
"arrow",
+14 -14
View File
@@ -20,20 +20,20 @@ categories = ["database-implementations"]
rust-version = "1.95.0"
[workspace.dependencies]
lance = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-core = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-datagen = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-file = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-io = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-index = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-jsonb = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace-impls = { "version" = "=15.0.0-beta.15", default-features = false, "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-table = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-testing = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-datafusion = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-encoding = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-arrow = { "version" = "=15.0.0-beta.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lance-core = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lance-datagen = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lance-file = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lance-io = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lance-index = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lance-jsonb = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lance-namespace-impls = { "version" = "=15.0.0-beta.16", default-features = false, "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lance-table = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lance-testing = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lance-datafusion = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lance-encoding = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lance-arrow = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lancedb = { path = "rust/lancedb", default-features = false }
ahash = "0.8"
anyhow = "1"
+1 -1
View File
@@ -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.9</version>
<version>0.42.0-beta.10</version>
</dependency>
```
@@ -64,3 +64,6 @@ optional timeoutMs: number;
```
Timeout for query execution in milliseconds
The timeout also covers reading the results, so consuming them slowly can
exceed it.
+9
View File
@@ -859,6 +859,13 @@ older server omits structured resource details. A structured `already_exists`
response keeps its more specific `AlreadyExistsError` type. Both are subclasses
of `HttpError`.
A remote query whose streamed response stops partway raises
`ResponseInterruptedError`, also a subclass of `HttpError`. It carries the number
of batches and rows already returned and, when the server reports it, the table
version the response reflected, so the query can be run again against that
version. It is never retried automatically, because the batches already returned
would be returned again.
SQL response failures raise `SqlError`, retaining the numeric `grpc_code` and
`request_id`. Servers that report a recognized `x-lancedb-error-code` select a
specific input-error subclass. HTTP failures use the corresponding `HttpError`
@@ -926,6 +933,8 @@ generic HTTP/SQL exceptions with their transport status and current request ID.
::: lancedb.remote.errors.ConflictError
::: lancedb.remote.errors.ResponseInterruptedError
::: lancedb.exceptions.MissingValueError
::: lancedb.exceptions.MissingColumnError
@@ -261,6 +261,38 @@ release. TypeScript does not expose GPU class discovery; pass `gpuClass`
and `gpuCount` in the `refreshColumnAsync` options.
</Note>
Completed Function outputs publish with their fragment by default. To opt into
a row-count publication threshold, set `publication_interval_rows` in Python or
`publication_interval_rows()` in Rust:
<CodeGroup>
```python Python icon="python"
job = table.refresh_column_async(
"embedding",
publication_interval_rows=60,
)
job.wait()
```
```rust Rust icon="rust"
use lancedb::table::RefreshColumnOptions;
let _job = table
.refresh_column_async_with_options(
"embedding",
RefreshColumnOptions::default().publication_interval_rows(60),
)
.await?;
```
</CodeGroup>
The threshold is opt-in and must be greater than zero. The number of rows in an
individual publication can differ from this value depending on completed work
and Function batching; this is not an exact-N contract. Omit it to keep
whole-fragment publication.
The TypeScript SDK does not expose the publication threshold option yet.
The job APIs also take the row filter and failure handling of the SQL
`REFRESH COLUMN ... WHERE ... WITH (...)` form, so a refresh can be narrowed
to new rows (see [what a filter recomputes](#partial)) and told to skip rows
+1 -1
View File
@@ -8,7 +8,7 @@
<parent>
<groupId>com.lancedb</groupId>
<artifactId>lancedb-parent</artifactId>
<version>0.42.0-beta.9</version>
<version>0.42.0-beta.10</version>
<relativePath>../pom.xml</relativePath>
</parent>
+2 -2
View File
@@ -6,7 +6,7 @@
<groupId>com.lancedb</groupId>
<artifactId>lancedb-parent</artifactId>
<version>0.42.0-beta.9</version>
<version>0.42.0-beta.10</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.15</lance-core.version>
<lance-core.version>15.0.0-beta.16</lance-core.version>
<jackson.version>2.18.12</jackson.version>
<spotless.skip>false</spotless.skip>
<spotless.version>2.30.0</spotless.version>
+1 -1
View File
@@ -1,7 +1,7 @@
[package]
name = "lancedb-nodejs"
edition.workspace = true
version = "0.42.0-beta.9"
version = "0.42.0-beta.10"
publish = false
license.workspace = true
description.workspace = true
+3
View File
@@ -237,6 +237,9 @@ export interface QueryExecutionOptions {
/**
* Timeout for query execution in milliseconds
*
* The timeout also covers reading the results, so consuming them slowly can
* exceed it.
*/
timeoutMs?: number;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-darwin-arm64",
"version": "0.42.0-beta.9",
"version": "0.42.0-beta.10",
"os": ["darwin"],
"cpu": ["arm64"],
"main": "lancedb.darwin-arm64.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-arm64-gnu",
"version": "0.42.0-beta.9",
"version": "0.42.0-beta.10",
"os": ["linux"],
"cpu": ["arm64"],
"main": "lancedb.linux-arm64-gnu.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-arm64-musl",
"version": "0.42.0-beta.9",
"version": "0.42.0-beta.10",
"os": ["linux"],
"cpu": ["arm64"],
"main": "lancedb.linux-arm64-musl.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-x64-gnu",
"version": "0.42.0-beta.9",
"version": "0.42.0-beta.10",
"os": ["linux"],
"cpu": ["x64"],
"main": "lancedb.linux-x64-gnu.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-linux-x64-musl",
"version": "0.42.0-beta.9",
"version": "0.42.0-beta.10",
"os": ["linux"],
"cpu": ["x64"],
"main": "lancedb.linux-x64-musl.node",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-win32-arm64-msvc",
"version": "0.42.0-beta.9",
"version": "0.42.0-beta.10",
"os": [
"win32"
],
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@lancedb/lancedb-win32-x64-msvc",
"version": "0.42.0-beta.9",
"version": "0.42.0-beta.10",
"os": ["win32"],
"cpu": ["x64"],
"main": "lancedb.win32-x64-msvc.node",
+1 -1
View File
@@ -11,7 +11,7 @@
"ann"
],
"private": false,
"version": "0.42.0-beta.9",
"version": "0.42.0-beta.10",
"main": "dist/index.js",
"exports": {
".": "./dist/index.js",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb-python"
version = "0.42.0-beta.9"
version = "0.42.0-beta.10"
publish = false
edition.workspace = true
description = "Python bindings for LanceDB"
+1 -1
View File
@@ -64,7 +64,7 @@ tests = [
"polars>=0.19, <=1.32.3",
"pyarrow>=16",
"pyarrow-stubs>=16.0",
"pylance==15.0.0b15",
"pylance==15.0.0b16",
"requests>=2.31.0",
"datafusion>=54,<55",
"opentelemetry-sdk>=1.30.0",
+2
View File
@@ -619,6 +619,7 @@ class Table:
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[str] = None,
@@ -636,6 +637,7 @@ class Table:
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[str] = None,
+21
View File
@@ -1335,6 +1335,9 @@ class LanceQueryBuilder(ABC):
and also the "_distance" column which is the distance between the query
vector and the returned vectors.
This collects all results in memory. To process a large result a batch
at a time, use [to_batches][lancedb.query.LanceQueryBuilder.to_batches].
Parameters
----------
timeout: Optional[timedelta]
@@ -1366,6 +1369,11 @@ class LanceQueryBuilder(ABC):
``fetch_blobs``. The ``"bytes"`` and ``"descriptions"`` modes hide
automatic row ids.
A remote table decodes batches as they arrive when the server streams
query results. If the response stops partway, reading raises
[ResponseInterruptedError][lancedb.remote.errors.ResponseInterruptedError]
after the batches already returned, which are valid but incomplete.
Parameters
----------
batch_size: int
@@ -1373,6 +1381,8 @@ class LanceQueryBuilder(ABC):
timeout: Optional[timedelta]
The maximum time to wait for the query to complete.
If None, wait indefinitely.
The timeout also covers reading the batches, so consuming them
slowly can exceed it.
blob_mode: str, default "lazy"
``"lazy"`` keeps blob descriptors and auto row ids for manual fetches.
``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2
@@ -2303,6 +2313,8 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
timeout: timedelta, default None
The maximum time to wait for the query to complete.
If None, wait indefinitely.
The timeout also covers reading the batches, so consuming them
slowly can exceed it.
blob_mode: str, default "lazy"
Controls blob conversion as described in
:meth:`LanceQueryBuilder.to_batches`.
@@ -3570,6 +3582,11 @@ class AsyncQueryBase(object):
"""
Execute the query and return the results as an Apache Arrow RecordBatchReader.
A remote table decodes batches as they arrive when the server streams
query results. If the response stops partway, reading raises
[ResponseInterruptedError][lancedb.remote.errors.ResponseInterruptedError]
after the batches already returned, which are valid but incomplete.
Parameters
----------
@@ -3582,6 +3599,8 @@ class AsyncQueryBase(object):
The maximum time to wait for the query to complete.
If not specified, no timeout is applied. If the query does not
complete within the specified time, an error will be raised.
The timeout also covers reading the batches, so consuming them
slowly can exceed it.
blob_mode: str, default "lazy"
``"lazy"`` keeps blob descriptors and auto row ids for manual fetches.
``"descriptions"`` omits auto row ids. ``"bytes"`` fetches blob v2
@@ -5114,6 +5133,8 @@ class BaseQueryBuilder(object):
The maximum time to wait for the query to complete.
If not specified, no timeout is applied. If the query does not
complete within the specified time, an error will be raised.
The timeout also covers reading the batches, so consuming them
slowly can exceed it.
blob_mode: str, default "lazy"
Controls blob conversion as described in
:meth:`AsyncQueryBase.to_batches`.
+58
View File
@@ -286,6 +286,64 @@ class ConflictError(HttpError):
"""
class ResponseInterruptedError(HttpError):
"""A streamed query response stopped before the server finished sending it.
The batches already returned are valid, but the result is incomplete. The
query is not retried automatically, because a new attempt would return those
rows a second time. To read the same data in a new attempt, check out
``table_version`` first.
Attributes
----------
batches: int
The number of batches returned before the interruption.
rows: int
The number of rows in those batches.
table_version: int or None
The table version the response reflected, if the server reported it.
Examples
--------
>>> error = ResponseInterruptedError("interrupted", "req-1", 2, 2048, 7)
>>> isinstance(error, HttpError)
True
>>> (error.rows, error.table_version)
(2048, 7)
"""
# HttpError.__new__ takes HttpError's arguments, to choose a subclass.
def __new__(cls, *args, **kwargs):
return RuntimeError.__new__(cls)
def __init__(
self,
message: str,
request_id: str,
batches: int,
rows: int,
table_version: Optional[int] = None,
is_transport_error: bool = False,
):
super().__init__(message, request_id, is_transport_error=is_transport_error)
self.batches = batches
self.rows = rows
self.table_version = table_version
def __reduce__(self) -> tuple[type, tuple]:
return (
self.__class__,
(
str(self),
self.request_id,
self.batches,
self.rows,
self.table_version,
self.is_transport_error,
),
)
class TableNotFoundError(HttpError, ValueError, _NamespaceTableNotFoundError):
"""A remote table was not found.
+4
View File
@@ -1143,6 +1143,7 @@ class RemoteTable(Table):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -1159,6 +1160,7 @@ class RemoteTable(Table):
column,
where=where,
batch_size=batch_size,
publication_interval_rows=publication_interval_rows,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -1178,6 +1180,7 @@ class RemoteTable(Table):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -1195,6 +1198,7 @@ class RemoteTable(Table):
column,
where=where,
batch_size=batch_size,
publication_interval_rows=publication_interval_rows,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
+34
View File
@@ -3178,6 +3178,7 @@ class Table(ABC):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -3216,6 +3217,12 @@ class Table(ABC):
Maximum rows per Function call on the remote server. Must be
greater than zero. None uses the server default. Has no effect on
local expression-backed columns.
publication_interval_rows: int, optional
Opt-in publication threshold for completed Function outputs. Must
be greater than zero. None keeps whole-fragment publication. The
actual publication boundary can be larger than this threshold
because it also depends on completed work and Function batching.
LanceDB Enterprise only; local refreshes reject this option.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
@@ -3263,6 +3270,7 @@ class Table(ABC):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -3300,6 +3308,12 @@ class Table(ABC):
greater than zero. None uses the server default. Lower this for
slow Functions to stay within the executor's per-call deadline.
Has no effect on local expression-backed columns.
publication_interval_rows: int, optional
Opt-in publication threshold for completed Function outputs. Must
be greater than zero. None keeps whole-fragment publication. The
actual publication boundary can be larger than this threshold
because it also depends on completed work and Function batching.
LanceDB Enterprise only; local refreshes reject this option.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
@@ -5442,6 +5456,7 @@ class LanceTable(Table):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -5461,6 +5476,7 @@ class LanceTable(Table):
column,
where=where,
batch_size=batch_size,
publication_interval_rows=publication_interval_rows,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -5480,6 +5496,7 @@ class LanceTable(Table):
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -5501,6 +5518,7 @@ class LanceTable(Table):
column,
where=where,
batch_size=batch_size,
publication_interval_rows=publication_interval_rows,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=retry_policy,
@@ -7865,6 +7883,7 @@ class AsyncTable:
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -7903,6 +7922,12 @@ class AsyncTable:
Maximum rows per Function call on the remote server. Must be
greater than zero. None uses the server default. Has no effect on
local expression-backed columns.
publication_interval_rows: int, optional
Opt-in publication threshold for completed Function outputs. Must
be greater than zero. None keeps whole-fragment publication. The
actual publication boundary can be larger than this threshold
because it also depends on completed work and Function batching.
LanceDB Enterprise only; local refreshes reject this option.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
@@ -7945,6 +7970,7 @@ class AsyncTable:
column,
where=where,
batch_size=batch_size,
publication_interval_rows=publication_interval_rows,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=None
@@ -8054,6 +8080,7 @@ class AsyncTable:
*,
where: Optional[str] = None,
batch_size: Optional[int] = None,
publication_interval_rows: Optional[int] = None,
gpu_class: Optional[str] = None,
gpu_count: Optional[int] = None,
retry_policy: Optional[FunctionRetryPolicy] = None,
@@ -8091,6 +8118,12 @@ class AsyncTable:
greater than zero. None uses the server default. Lower this for
slow Functions to stay within the executor's per-call deadline.
Has no effect on local expression-backed columns.
publication_interval_rows: int, optional
Opt-in publication threshold for completed Function outputs. Must
be greater than zero. None keeps whole-fragment publication. The
actual publication boundary can be larger than this threshold
because it also depends on completed work and Function batching.
LanceDB Enterprise only; local refreshes reject this option.
gpu_class: str, optional
GPU class for Function workers. Must be a lowercase name of 1-63
letters, digits, or hyphens, without a leading or trailing hyphen.
@@ -8150,6 +8183,7 @@ class AsyncTable:
column,
where=where,
batch_size=batch_size,
publication_interval_rows=publication_interval_rows,
gpu_class=gpu_class,
gpu_count=gpu_count,
retry_policy=None
+12
View File
@@ -15,6 +15,7 @@ from lancedb.remote.errors import (
HttpError,
LanceDBClientError,
NamespaceNotFoundError,
ResponseInterruptedError,
RetryError,
SecretNotFoundError,
TableNotFoundError,
@@ -73,6 +74,17 @@ def test_pickle_http_transport_error():
assert restored.request_id == "req-789"
def test_pickle_response_interrupted_error():
err = ResponseInterruptedError("interrupted", "req-1", 2, 2048, 7, True)
restored = pickle.loads(pickle.dumps(err))
assert type(restored) is ResponseInterruptedError
assert str(restored) == "interrupted"
assert restored.request_id == "req-1"
assert (restored.batches, restored.rows, restored.table_version) == (2, 2048, 7)
assert restored.is_transport_error is True
assert restored.status_code is None
@pytest.mark.parametrize("error_code", [None, "conflict", "future_conflict_code"])
def test_http_conflict_error_preserves_reason_and_metadata(error_code):
reason = "Conflict: branch 'exp' cannot be deleted, main depends on its files"
+99
View File
@@ -48,6 +48,7 @@ from lancedb.remote.errors import (
ConflictError,
HttpError,
NamespaceNotFoundError,
ResponseInterruptedError,
RetryError,
)
import pytest
@@ -1862,6 +1863,7 @@ def test_remote_create_index_async_returns_job():
{"batch_size": None},
{"batch_size": 1},
{"batch_size": 8},
{"publication_interval_rows": 60},
{"gpu_class": "a10g", "gpu_count": 2},
{
"retry_policy": {"transient": True, "max_attempts": 3},
@@ -1910,6 +1912,7 @@ async def test_remote_refresh_async_returns_typed_terminal_result(
expected["error_policy"] = refresh_kwargs["error_policy"]
for key in (
"where",
"publication_interval_rows",
"max_failed_fraction",
"max_failed_rows",
"row_timeout_seconds",
@@ -2087,6 +2090,8 @@ def test_remote_refresh_async_forwards_progress_from_submitted_handle():
({"max_failed_rows": -1}, "max_failed_rows"),
({"row_timeout_seconds": 0}, "row_timeout_seconds"),
({"init_timeout_seconds": -5}, "init_timeout_seconds"),
({"publication_interval_rows": 0}, "publication_interval_rows"),
({"publication_interval_rows": -1}, "publication_interval_rows"),
({"num_workers": 0}, "num_workers"),
(
{"max_executor_processes_per_worker": -2},
@@ -3398,6 +3403,100 @@ def test_query_sync_minimal():
assert data == expected
def _arrow_stream(batches):
sink = pa.BufferOutputStream()
with pa.ipc.new_stream(sink, batches[0].schema) as writer:
for batch in batches:
writer.write_batch(batch)
return sink.getvalue().to_pybytes()
@contextlib.contextmanager
def streamed_query_table(write_body):
"""Yield a remote table and the headers of each query request it sends.
Queries get a 200 response with stream framing, whose body ``write_body``
writes after the other headers.
"""
queries = []
def handler(request):
if request.path == "/v1/table/test/describe/":
id_field = {"name": "id", "type": {"type": "int32"}, "nullable": True}
schema = {"fields": [id_field]}
request.send_response(200)
request.send_header("Content-Type", "application/json")
request.end_headers()
request.wfile.write(json.dumps({"version": 7, "schema": schema}).encode())
elif request.path == "/v1/table/test/query/":
queries.append(request.headers)
request.rfile.read(int(request.headers["Content-Length"]))
request.send_response(200)
request.send_header("Content-Type", "application/vnd.apache.arrow.stream")
request.send_header("x-lancedb-version", "7")
write_body(request)
else:
request.send_response(404)
request.end_headers()
with mock_lancedb_connection(handler) as db:
yield db.open_table("test"), queries
def test_query_sync_to_batches_yields_before_the_body_is_complete():
batches = [pa.record_batch({"id": pa.array([i], pa.int32())}) for i in range(3)]
body = _arrow_stream(batches)
# The schema and first batch, without the 8-byte end-of-stream marker.
head = _arrow_stream(batches[:1])[:-8]
first_batch_read = threading.Event()
waited_for_client = []
def write_body(request):
request.end_headers()
request.wfile.write(head)
waited_for_client.append(first_batch_read.wait(10))
request.wfile.write(body[len(head) :])
with streamed_query_table(write_body) as (table, queries):
reader = table.search().to_batches()
assert reader.read_next_batch()["id"].to_pylist() == [0]
first_batch_read.set()
assert reader.read_all()["id"].to_pylist() == [1, 2]
# The wait times out if the client needs the whole body for the first batch.
assert waited_for_client == [True]
assert queries[0]["Accept"] == (
"application/vnd.apache.arrow.stream, application/vnd.apache.arrow.file;q=0.9"
)
@pytest.mark.parametrize("abort", [False, True], ids=["clean_end", "abort"])
def test_query_sync_interrupted_response_raises(abort):
batches = [pa.record_batch({"id": pa.array([i], pa.int32())}) for i in range(3)]
head = _arrow_stream(batches[:1])[:-8]
def write_body(request):
if abort:
# Closing before the promised length is a transport error. Otherwise
# the body ends cleanly, but without the end-of-stream marker.
request.send_header("Content-Length", str(len(head) + 100))
request.end_headers()
request.wfile.write(head)
with streamed_query_table(write_body) as (table, queries):
reader = table.search().to_batches()
assert reader.read_next_batch()["id"].to_pylist() == [0]
with pytest.raises(ResponseInterruptedError) as exc_info:
reader.read_next_batch()
error = exc_info.value
assert isinstance(error, HttpError)
assert (error.batches, error.rows, error.table_version) == (1, 1, 7)
assert error.request_id == queries[0]["x-request-id"]
assert error.is_transport_error is abort
assert len(queries) == 1
@pytest.mark.parametrize("query_type", ["auto", "vector", "hybrid"])
@pytest.mark.parametrize("vector_column_name", [None, "embedding"])
def test_query_sync_text_embedding(query_type, vector_column_name):
+1
View File
@@ -5995,6 +5995,7 @@ def test_refresh_column_rejects_invalid_batch_size(tmp_path, method, batch_size)
({"max_failed_rows": 10}, "max_failed_rows"),
({"row_timeout_seconds": 30}, "row_timeout_seconds"),
({"init_timeout_seconds": 60}, "init_timeout_seconds"),
({"publication_interval_rows": 60}, "publication_interval_rows"),
({"num_workers": 2}, "num_workers"),
({"max_executor_processes_per_worker": 2}, "max_executor_processes_per_worker"),
],
+22
View File
@@ -168,6 +168,28 @@ impl<T> PythonErrorExt<T> for std::result::Result<T, LanceError> {
err.setattr(intern!(py, "__cause__"), cause_err)?;
Err(PyErr::from_value(err))
}),
LanceError::ResponseInterrupted {
request_id,
batches,
rows,
table_version,
source,
} => Python::attach(|py| {
let error = py
.import(intern!(py, "lancedb.remote.errors"))?
.getattr(intern!(py, "ResponseInterruptedError"))?
.call1((
err.to_string(),
request_id,
*batches,
*rows,
*table_version,
is_transport_error(&**source),
))?;
let cause = http_from_rust_error(py, &**source, request_id, None)?;
error.setattr(intern!(py, "__cause__"), cause)?;
Err(PyErr::from_value(error))
}),
LanceError::Sql {
message,
request_id,
+10 -2
View File
@@ -46,6 +46,7 @@ mod scannable;
struct RefreshColumnArgs {
where_clause: Option<String>,
batch_size: Option<i64>,
publication_interval_rows: Option<i64>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -73,6 +74,7 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOpti
let RefreshColumnArgs {
where_clause,
batch_size,
publication_interval_rows,
gpu_class,
gpu_count,
retry_policy,
@@ -114,6 +116,8 @@ fn refresh_column_options(args: RefreshColumnArgs) -> PyResult<RefreshColumnOpti
.map(usize::try_from)
.transpose()
.map_err(|_| PyValueError::new_err("batch_size must be greater than zero"))?;
options.publication_interval_rows =
positive_count(publication_interval_rows, "publication_interval_rows")?;
options.gpu_class = gpu_class;
options.gpu_count = gpu_count
.map(|count| {
@@ -2206,13 +2210,14 @@ impl Table {
})
}
#[pyo3(signature = (column, *, r#where=None, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[pyo3(signature = (column, *, r#where=None, batch_size=None, publication_interval_rows=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_column(
self_: PyRef<'_, Self>,
column: String,
r#where: Option<String>,
batch_size: Option<i64>,
publication_interval_rows: Option<i64>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -2227,6 +2232,7 @@ impl Table {
let options = refresh_column_options(RefreshColumnArgs {
where_clause: r#where,
batch_size,
publication_interval_rows,
gpu_class,
gpu_count,
retry_policy,
@@ -2248,13 +2254,14 @@ impl Table {
})
}
#[pyo3(signature = (column, *, r#where=None, batch_size=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[pyo3(signature = (column, *, r#where=None, batch_size=None, publication_interval_rows=None, gpu_class=None, gpu_count=None, retry_policy=None, error_policy=None, max_failed_fraction=None, max_failed_rows=None, row_timeout_seconds=None, init_timeout_seconds=None, num_workers=None, max_executor_processes_per_worker=None))]
#[allow(clippy::too_many_arguments)]
pub fn refresh_column_async(
self_: PyRef<'_, Self>,
column: String,
r#where: Option<String>,
batch_size: Option<i64>,
publication_interval_rows: Option<i64>,
gpu_class: Option<String>,
gpu_count: Option<i64>,
retry_policy: Option<String>,
@@ -2269,6 +2276,7 @@ impl Table {
let options = refresh_column_options(RefreshColumnArgs {
where_clause: r#where,
batch_size,
publication_interval_rows,
gpu_class,
gpu_count,
retry_policy,
+7 -7
View File
@@ -2147,7 +2147,7 @@ requires-dist = [
{ name = "pyarrow-stubs", marker = "extra == 'tests'", specifier = ">=16.0" },
{ name = "pydantic", specifier = ">=2.7.4,<3" },
{ name = "pylance", marker = "extra == 'pylance'", specifier = ">=15.0.0b3" },
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b15" },
{ name = "pylance", marker = "extra == 'tests'", specifier = "==15.0.0b16" },
{ name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.350" },
{ name = "pytest", marker = "extra == 'tests'", specifier = ">=7.0" },
{ name = "pytest-asyncio", marker = "extra == 'tests'", specifier = ">=0.21" },
@@ -4301,7 +4301,7 @@ crypto = [
[[package]]
name = "pylance"
version = "15.0.0b15"
version = "15.0.0b16"
source = { registry = "https://pypi.fury.io/lance-format/" }
dependencies = [
{ name = "lance-namespace" },
@@ -4312,11 +4312,11 @@ dependencies = [
{ name = "pyarrow", version = "26.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
]
wheels = [
{ url = "https://pypi.fury.io/lance-format/-/ver_29HO58/pylance-15.0.0b15-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:46c870c3d650f911eccb7406ec77f72fa448f80b2f827ff35dd86bbc0b9e08ca" },
{ url = "https://pypi.fury.io/lance-format/-/ver_OBkXR/pylance-15.0.0b15-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b3f418584cdee98d27aac538ebe5203051a0b78a98668aff22bc29aebe3dd3c9" },
{ url = "https://pypi.fury.io/lance-format/-/ver_TMbLm/pylance-15.0.0b15-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3656d52ba65d297b41f1973d1a3efbb888f761cf7c934ff15e0c1aecc560b2d5" },
{ url = "https://pypi.fury.io/lance-format/-/ver_mmYmR/pylance-15.0.0b15-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:a50d06e3a86d68acf8edf5a83736890a648a16a1cb8c8ccde9ef5b6c82ebef76" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1aYiTc/pylance-15.0.0b15-cp310-abi3-win_amd64.whl", hash = "sha256:6451499f0612d0326d54168bedcc6df29c1e0700c4f92902f5f00a6ecdf17745" },
{ url = "https://pypi.fury.io/lance-format/-/ver_uZ4Az/pylance-15.0.0b16-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c4ed0ab9213082d9d8cc93aa09351e84574c76ddefc422a2ad073115bd9a1b43" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1nenYa/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7f28f7b757ade1e4b556e788bc77d4ffcc351a9c8c570b35f769c457e9cc13bf" },
{ url = "https://pypi.fury.io/lance-format/-/ver_1cb3ns/pylance-15.0.0b16-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:49f358f3ddf33d76567f56d0e4a66c218dc1a2d2f06d37d779e13c87b1c3d9a6" },
{ url = "https://pypi.fury.io/lance-format/-/ver_g7LAk/pylance-15.0.0b16-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:288c1b41f5068990672c8c182b4b79d6389c1a907c59ef6047cbee494d1e34ec" },
{ url = "https://pypi.fury.io/lance-format/-/ver_12YRtQ/pylance-15.0.0b16-cp310-abi3-win_amd64.whl", hash = "sha256:fa69acdd0960280f6fe8a83ea992fc92e2ed5a0eeb5159b90493dfc76831f752" },
]
[[package]]
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb"
version = "0.42.0-beta.9"
version = "0.42.0-beta.10"
edition.workspace = true
description = "LanceDB: A serverless, low-latency vector database for AI applications"
license.workspace = true
@@ -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.15", "tag" = "v15.0.0-beta.15", "git" = "https://github.com/lance-format/lance.git" }
lance-linalg = { "version" = "=15.0.0-beta.16", "tag" = "v15.0.0-beta.16", "git" = "https://github.com/lance-format/lance.git" }
lance-encoding = { workspace = true }
lance-arrow = { workspace = true }
lance-namespace = { workspace = true }
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "lancedb-cli"
version = "0.42.0-beta.9"
version = "0.42.0-beta.10"
edition = "2021"
license.workspace = true
repository.workspace = true
+3
View File
@@ -336,6 +336,9 @@ impl Database for LanceNamespaceDatabase {
// Refuse a bad declaration before the namespace records a table.
crate::table::computed_columns::ensure_declarations_are_planned(
&request.data.arrow_schema(),
self.session
.as_deref()
.and_then(lance::session::Session::datafusion_session),
)?;
let mut table_id = request.namespace_path.clone();
table_id.push(request.name.clone());
+167
View File
@@ -205,6 +205,48 @@ fn http_timeout_hint(source: &(dyn std::error::Error + 'static)) -> &'static str
}
}
/// The error that ended a streamed response.
///
/// It is shared so that a copy of [`Error::ResponseInterrupted`] keeps it:
/// DataFusion hands one error to every partition that reads the failed input.
/// It dereferences to the underlying error, which is also the next error in the
/// source chain.
#[cfg(feature = "remote")]
#[derive(Debug, Clone)]
pub struct InterruptionSource(Arc<dyn std::error::Error + Send + Sync>);
#[cfg(feature = "remote")]
impl From<BoxError> for InterruptionSource {
fn from(source: BoxError) -> Self {
Self(source.into())
}
}
#[cfg(feature = "remote")]
impl std::ops::Deref for InterruptionSource {
type Target = dyn std::error::Error + Send + Sync;
fn deref(&self) -> &Self::Target {
self.0.as_ref()
}
}
#[cfg(feature = "remote")]
impl Display for InterruptionSource {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
// Not `Error`: an `Arc` in the source chain hides the error it holds from
// `downcast_ref`, and so would a wrapper that implements `Error`.
#[cfg(feature = "remote")]
impl snafu::AsErrorSource for InterruptionSource {
fn as_error_source(&self) -> &(dyn std::error::Error + 'static) {
self.0.as_ref()
}
}
/// Why a job failed, to whatever precision the backend provides.
///
/// A job run in this process carries the error it failed with in [`Self::source`].
@@ -362,6 +404,27 @@ pub enum Error {
source: Box<dyn std::error::Error + Send + Sync>,
status_code: Option<reqwest::StatusCode>,
},
/// A streamed response stopped before the server signalled that it was complete.
///
/// The batches already returned are valid, but the result is incomplete. The
/// request is not retried, because re-issuing it would return those batches
/// again. `table_version` is the table version the response reflected, when
/// the server reported one, so a caller can re-issue the request against it.
#[cfg(feature = "remote")]
#[snafu(display(
"Response for request_id={request_id} interrupted after {batches} batches \
({rows} rows): {source}{}",
http_timeout_hint(&**source)
))]
ResponseInterrupted {
request_id: String,
/// Batches returned before the interruption.
batches: u64,
/// Rows in those batches.
rows: u64,
table_version: Option<u64>,
source: InterruptionSource,
},
#[snafu(display("Arrow error: {source}"))]
Arrow { source: ArrowError },
#[snafu(display("LanceDBError: not supported: {message}"))]
@@ -393,6 +456,20 @@ impl From<DataFusionError> for Error {
match source {
DataFusionError::ArrowError(source, _) => (*source).into(),
DataFusionError::External(source) => Self::from_box_error(source),
// DataFusion adds context to an error, and shares one error between
// the partitions that read a failed input. An error of ours beneath
// either keeps its type; other errors keep the wrapper's message.
DataFusionError::Context(_, inner) if find_error(inner.as_ref()).is_some() => {
(*inner).into()
}
DataFusionError::Shared(shared) => match Arc::try_unwrap(shared) {
Ok(inner) => inner.into(),
Err(shared) => find_error(shared.as_ref())
.and_then(Self::clone_shared)
.unwrap_or_else(|| Self::External {
source: Box::new(DataFusionError::Shared(shared)),
}),
},
other => Self::External {
source: Box::new(other),
},
@@ -400,6 +477,12 @@ impl From<DataFusionError> for Error {
}
}
/// The first error of ours in an error's source chain.
fn find_error<'a>(error: &'a (dyn std::error::Error + 'static)) -> Option<&'a Error> {
std::iter::successors(Some(error), |error| error.source())
.find_map(|error| error.downcast_ref::<Error>())
}
impl From<lance::Error> for Error {
fn from(source: lance::Error) -> Self {
if has_unsupported_local_filesystem_source(&source) {
@@ -509,6 +592,29 @@ impl Error {
}
}
/// A copy of an error that other partitions of a DataFusion plan still hold.
/// Only an interrupted response can be copied, because it shares its source.
fn clone_shared(&self) -> Option<Self> {
#[cfg(feature = "remote")]
if let Self::ResponseInterrupted {
request_id,
batches,
rows,
table_version,
source,
} = self
{
return Some(Self::ResponseInterrupted {
request_id: request_id.clone(),
batches: *batches,
rows: *rows,
table_version: *table_version,
source: source.clone(),
});
}
None
}
fn from_box_error(mut source: Box<dyn std::error::Error + Send + Sync>) -> Self {
source = match source.downcast::<Self>() {
Ok(e) => match *e {
@@ -619,6 +725,67 @@ mod tests {
assert!(matches!(Error::from(source), Error::InvalidInput { .. }));
}
/// DataFusion shares an error between the partitions that read a failed
/// input, and may add context to it. Whether or not another partition still
/// holds it, an interrupted response keeps its fields and its source.
#[cfg(feature = "remote")]
#[rstest::rstest]
fn shared_interruption_keeps_its_type_and_source(
#[values(false, true)] still_held: bool,
#[values(false, true)] with_context: bool,
) {
let reset = BoxError::from(std::io::Error::from(std::io::ErrorKind::ConnectionReset));
let interrupted = Error::ResponseInterrupted {
request_id: "req-1".into(),
batches: 2,
rows: 2048,
table_version: Some(7),
source: reset.into(),
};
let shared = Arc::new(DataFusionError::External(Box::new(interrupted)));
let held = still_held.then(|| shared.clone());
let mut error = DataFusionError::Shared(shared);
if with_context {
error = error.context("merging query results");
}
let error = Error::from(error);
assert!(
matches!(
&error,
Error::ResponseInterrupted {
request_id,
batches: 2,
rows: 2048,
table_version: Some(7),
..
} if request_id == "req-1"
),
"{error:?}"
);
let source = std::error::Error::source(&error).unwrap();
assert_eq!(
source.downcast_ref::<std::io::Error>().map(|e| e.kind()),
Some(std::io::ErrorKind::ConnectionReset)
);
drop(held);
}
#[test]
fn other_shared_errors_keep_their_message() {
let shared = Arc::new(DataFusionError::Execution("boom".into()));
let _held = shared.clone();
let error = Error::from(DataFusionError::Shared(shared).context("merging"));
assert!(matches!(error, Error::External { .. }), "{error:?}");
assert_eq!(
error.to_string(),
"merging\ncaused by\nExecution error: boom"
);
}
#[cfg(feature = "remote")]
#[test]
fn non_timeout_http_error_message_is_unchanged() {
+9 -4
View File
@@ -958,7 +958,7 @@ fn is_declaration(key: &str) -> bool {
|| crate::table::computed_columns::is_declaration_key(key)
}
fn without_declarations(field: &ArrowField) -> ArrowField {
pub(crate) fn without_declarations(field: &ArrowField) -> ArrowField {
let metadata: HashMap<String, String> = field
.metadata()
.iter()
@@ -1123,6 +1123,10 @@ impl PreparedDeclaration {
/// are validated over the assembled schema, and read only columns the
/// view holds (see [`PreparedDeclaration::input_column`]).
///
/// `session` holds the DataFusion functions a declaration may call, as
/// for [`AddColumnsBuilder::computed`](crate::table::AddColumnsBuilder::computed);
/// `None` plans against Lance's built-in functions only.
///
/// ```no_run
/// # #![recursion_limit = "256"]
/// # use std::collections::HashMap;
@@ -1148,7 +1152,7 @@ impl PreparedDeclaration {
/// (INPUTS_META_KEY.into(), format!("[\"{text}\"]")),
/// ]));
/// let view = prepared
/// .with_computed_columns(vec![(1, length)], &[])?
/// .with_computed_columns(vec![(1, length)], &[], None)?
/// .create("lengths")
/// .await?;
/// view.refresh().execute().await?; // rows land with `length` NULL
@@ -1160,6 +1164,7 @@ impl PreparedDeclaration {
mut self,
columns: Vec<(usize, ArrowField)>,
bindings: &[FunctionBinding],
session: Option<&datafusion::execution::context::SessionContext>,
) -> Result<Self> {
let invalid = |message: String| Error::InvalidInput { message };
if columns.is_empty() {
@@ -1223,7 +1228,7 @@ impl PreparedDeclaration {
}
rewrite_column_definitions(&mut metadata, self.schema.as_ref(), &fields)?;
let schema = ArrowSchema::new_with_metadata(fields, metadata);
ensure_declarations_are_planned(&schema)?;
ensure_declarations_are_planned(&schema, session)?;
self.schema = Arc::new(schema);
Ok(self)
}
@@ -2685,7 +2690,7 @@ mod tests {
(INPUTS_META_KEY.into(), "[\"x\"]".into()),
]));
let view = prepared
.with_computed_columns(vec![(1, doubled)], &[])
.with_computed_columns(vec![(1, doubled)], &[], None)
.unwrap()
.create("m")
.await
@@ -133,7 +133,7 @@ pub(crate) async fn execute_refresh(
})?;
let physical = Arc::new(ArrowSchema::from(view_ds.schema()));
ensure_declarations_are_planned(&physical)?;
ensure_declarations_are_planned(&physical, view_ds.session().datafusion_session())?;
if let Some(field) = physical
.fields()
.iter()
+9
View File
@@ -661,6 +661,10 @@ pub struct QueryExecutionOptions {
/// By default, this is 1024
pub max_batch_length: u32,
/// Max duration to wait for the query to execute before timing out.
///
/// The timeout also covers reading the results, so a caller that consumes
/// the stream slowly can exceed it. For a remote table it counts from when
/// the query is sent, and the server is given the same timeout.
pub timeout: Option<Duration>,
/// How distributed worker metrics should be displayed by
/// [`ExecutableQuery::analyze_plan`].
@@ -747,6 +751,11 @@ pub trait ExecutableQuery {
/// stream is consumed slowly (this constrains the maximum memory used by a
/// single query.
///
/// A remote table decodes batches as they arrive when the server streams
/// query results. If the response stops partway, the stream ends with
/// `Error::ResponseInterrupted`. The batches already returned are valid but
/// incomplete, and the query is not retried.
///
/// For simpler access or row-based access we recommend creating extension traits
/// to convert Arrow data into your internal data model.
fn execute_with_options(
+78 -42
View File
@@ -3,6 +3,7 @@
pub mod blobs;
pub mod insert;
mod ipc_stream;
mod optimize;
use self::insert::{RemoteWriteExec, WriteOp};
@@ -61,15 +62,15 @@ use crate::{
},
};
use arrow_array::{LargeBinaryArray, RecordBatch, RecordBatchReader};
use arrow_ipc::reader::{FileReader, StreamReader};
use arrow_schema::{ArrowError, DataType, SchemaRef};
use arrow_ipc::reader::FileReader;
use arrow_schema::{DataType, SchemaRef};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use datafusion_common::DataFusionError;
use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
use datafusion_physical_plan::{ExecutionPlan, RecordBatchStream, SendableRecordBatchStream};
use futures::{StreamExt, TryStreamExt};
use http::header::CONTENT_TYPE;
use http::header::{ACCEPT, CONTENT_TYPE};
use http::{HeaderName, StatusCode};
use lance::arrow::json::{JsonDataType, JsonSchema};
use lance::dataset::refs::TagContents;
@@ -91,6 +92,10 @@ const MIN_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-ve
const MIN_TIMESTAMP_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-timestamp");
const MIN_READ_VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-min-read-version");
const VERSION_HEADER: HeaderName = HeaderName::from_static("x-lancedb-version");
/// Asks for stream framing, which is decoded as it arrives. Servers that do not
/// stream query results ignore this and answer with file framing.
const QUERY_ACCEPT: &str =
"application/vnd.apache.arrow.stream, application/vnd.apache.arrow.file;q=0.9";
const METRIC_TYPE_KEY: &str = "metric_type";
const INDEX_TYPE_KEY: &str = "index_type";
const SCHEMA_CACHE_TTL: Duration = Duration::from_secs(30);
@@ -1155,25 +1160,30 @@ impl<S: HttpSend> RemoteTable<S> {
.map(str::to_owned);
let framing = resolve_arrow_ipc_framing(content_type.as_deref(), request_id)?;
// Buffer the whole body. File framing keeps its footer at the end, so /query
// cannot decode incrementally. Stream framing could, via
// arrow_ipc::reader::StreamDecoder, but fetch_blobs concatenates every batch
// before returning, so no caller would see data sooner.
let body = response.bytes().await.err_to_http(request_id.into())?;
type IpcBatchIterator =
Box<dyn Iterator<Item = std::result::Result<RecordBatch, ArrowError>> + Send>;
let (schema, batches): (SchemaRef, IpcBatchIterator) = match framing {
match framing {
ArrowIpcFraming::Stream => {
let reader = StreamReader::try_new(Cursor::new(body), None)?;
(reader.schema(), Box::new(reader))
let table_version = response
.headers()
.get(&VERSION_HEADER)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse().ok());
ipc_stream::read_ipc_stream(
response.bytes_stream(),
request_id.to_string(),
table_version,
)
.await
}
ArrowIpcFraming::File => {
// File framing keeps its footer at the end, so the whole body is
// needed before anything can be decoded.
let body = response.bytes().await.err_to_http(request_id.into())?;
let reader = FileReader::try_new(Cursor::new(body), None)?;
(reader.schema(), Box::new(reader))
let schema = reader.schema();
let stream = futures::stream::iter(reader).map_err(DataFusionError::from);
Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream)))
}
};
let stream = futures::stream::iter(batches).map_err(DataFusionError::from);
Ok(Box::pin(RecordBatchStreamAdapter::new(schema, stream)))
}
}
fn apply_query_params(
@@ -1544,8 +1554,15 @@ impl<S: HttpSend> RemoteTable<S> {
) -> Result<Vec<Pin<Box<dyn RecordBatchStream + Send>>>> {
let mut request = self
.client
.post(&format!("/v1/table/{}/query/", self.identifier));
.post(&format!("/v1/table/{}/query/", self.identifier))
.header(ACCEPT, QUERY_ACCEPT);
// The timeout bounds the whole query, including reading the response, as
// the server's own deadline for this request does. A deadline too far
// away to represent is never reached.
let deadline = options
.timeout
.and_then(|timeout| Some((tokio::time::Instant::now().checked_add(timeout)?, timeout)));
if let Some(timeout) = options.timeout {
// Also send to server, so it can abort the query if it takes too long.
// (If it doesn't fit into u64, it's not worth sending anyways.)
@@ -1569,28 +1586,28 @@ impl<S: HttpSend> RemoteTable<S> {
});
let streams = futures::future::try_join_all(futures);
let streams = if let Some(timeout) = options.timeout {
let timeout_future = tokio::time::sleep(timeout);
tokio::pin!(timeout_future);
tokio::pin!(streams);
tokio::select! {
_ = &mut timeout_future => {
return Err(Error::Other {
message: format!("Query timeout after {} ms", timeout.as_millis()),
source: None,
})
}
result = &mut streams => {
result?
}
}
let streams = if let Some((deadline, timeout)) = deadline {
tokio::time::timeout_at(deadline, streams)
.await
.map_err(|_| Error::Other {
message: format!("Query timeout after {} ms", timeout.as_millis()),
source: None,
})??
} else {
streams.await?
};
Ok(streams
.into_iter()
.map(|stream| restore_projection_order(stream, &query.base().select))
.map(|stream| {
let stream = restore_projection_order(stream, &query.base().select);
match deadline {
Some((deadline, timeout)) => {
Box::pin(TimeoutStream::with_deadline(stream, timeout, deadline))
}
None => stream,
}
})
.collect())
}
@@ -1714,8 +1731,9 @@ fn schema_from_description(schema: JsonSchema) -> Result<SchemaRef> {
)))
}
/// How a response body frames its Arrow IPC payload. `/query` answers with file framing
/// and `fetch_blobs` with stream framing, so the reader is picked per response.
/// How a response body frames its Arrow IPC payload. `fetch_blobs` answers with stream
/// framing, and `/query` with stream framing only on servers that stream query results,
/// so the reader is picked per response.
enum ArrowIpcFraming {
File,
Stream,
@@ -4439,6 +4457,7 @@ mod tests {
BinaryArray, Int32Array, Int64Array, RecordBatch, RecordBatchIterator, StringArray,
StructArray, record_batch,
};
use arrow_ipc::reader::StreamReader;
use arrow_schema::{DataType, Field, Schema};
use chrono::{DateTime, Utc};
use futures::{StreamExt, TryFutureExt, TryStreamExt, future::BoxFuture};
@@ -7093,25 +7112,36 @@ mod tests {
assert_eq!(blobs.value(0), b"alpha");
}
// Read as a stream, a file's leading magic declares a message longer than the
// whole body, so the body ends before the stream does.
#[rstest]
#[case(ARROW_STREAM_CONTENT_TYPE, write_ipc_file(&one_row_blob_batch("image")))]
#[case(ARROW_STREAM_CONTENT_TYPE, write_ipc_file(&one_row_blob_batch("image")), true)]
#[case(
ARROW_FILE_CONTENT_TYPE,
write_ipc_stream_uncompressed(&one_row_blob_batch("image"))
write_ipc_stream_uncompressed(&one_row_blob_batch("image")),
false
)]
#[tokio::test]
async fn test_fetch_blobs_fails_when_the_body_contradicts_the_content_type(
#[case] content_type: &'static str,
#[case] body: Vec<u8>,
#[case] ends_early: bool,
) {
let table = table_with_fetch_blobs_content_type(Some(content_type), body);
let error = table.fetch_blobs("image", &[10]).await.unwrap_err();
assert!(
matches!(error, Error::Arrow { .. }),
"expected an Arrow decode failure, got {error}"
);
if ends_early {
assert!(
matches!(error, Error::ResponseInterrupted { batches: 0, .. }),
"expected an incomplete stream, got {error}"
);
} else {
assert!(
matches!(error, Error::Arrow { .. }),
"expected an Arrow decode failure, got {error}"
);
}
}
#[tokio::test]
@@ -11042,6 +11072,7 @@ mod tests {
serde_json::json!({
"column": "quality",
"where": "id % 2 = 0",
"publication_interval_rows": 60,
"error_policy": "skip",
"max_failed_fraction": 0.01,
"max_failed_rows": 50,
@@ -11058,6 +11089,7 @@ mod tests {
});
let options = RefreshColumnOptions::default()
.where_clause("id % 2 = 0")
.publication_interval_rows(60)
.error_policy(FunctionErrorPolicy::Skip)
.max_failed_fraction(0.01)
.max_failed_rows(50)
@@ -11105,6 +11137,10 @@ mod tests {
RefreshColumnOptions::default().max_executor_processes_per_worker(0),
"max_executor_processes_per_worker",
),
(
RefreshColumnOptions::default().publication_interval_rows(0),
"publication_interval_rows",
),
] {
let error = table
.refresh_column_async_with_options("quality", options)
+729
View File
@@ -0,0 +1,729 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
//! Incremental decoding of response bodies that use Arrow IPC stream framing.
use arrow_array::RecordBatch;
use arrow_buffer::Buffer;
use arrow_ipc::reader::StreamDecoder;
use bytes::Bytes;
use datafusion_common::DataFusionError;
use datafusion_physical_plan::SendableRecordBatchStream;
use datafusion_physical_plan::stream::RecordBatchStreamAdapter;
use futures::stream::BoxStream;
use futures::{Stream, StreamExt, TryStreamExt};
use crate::error::{BoxError, Error, Result};
/// Decode an Arrow IPC stream from a response body as its chunks arrive.
///
/// Only the current chunk and the decoder's state are held, so memory is bounded
/// by the size of a batch rather than the size of the result. This waits for the
/// first batch, or for the end of an empty result, so a body that fails before
/// any data arrives fails the request itself.
///
/// A complete body ends with the end-of-stream marker; the server aborts the body
/// without it when the query fails after sending headers. A body that ends early,
/// even between messages, is reported as [`Error::ResponseInterrupted`] and never
/// as a short result.
pub(super) async fn read_ipc_stream<E>(
chunks: impl Stream<Item = std::result::Result<Bytes, E>> + Send + 'static,
request_id: String,
table_version: Option<u64>,
) -> Result<SendableRecordBatchStream>
where
E: Into<BoxError> + 'static,
{
let mut body = IpcStreamBody {
chunks: chunks.map_err(Into::into).boxed(),
chunk: Buffer::default(),
decoder: StreamDecoder::new(),
finished: false,
request_id,
table_version,
batches: 0,
rows: 0,
};
let first = body.next_batch().await?;
// The schema is the first message, so only a body holding nothing but the
// end-of-stream marker can complete without one.
let schema = body.decoder.schema().ok_or_else(|| Error::Http {
source: "Arrow IPC stream ended without a schema".into(),
request_id: body.request_id.clone(),
status_code: None,
})?;
let rest = futures::stream::try_unfold(body, |mut body| async move {
Ok(body.next_batch().await?.map(|batch| (batch, body)))
});
let batches = futures::stream::iter(first.map(Ok))
.chain(rest)
.map_err(|error: Error| DataFusionError::External(Box::new(error)));
Ok(Box::pin(RecordBatchStreamAdapter::new(schema, batches)))
}
struct IpcStreamBody {
chunks: BoxStream<'static, std::result::Result<Bytes, BoxError>>,
/// The part of the current chunk that has not been decoded yet.
chunk: Buffer,
decoder: StreamDecoder,
/// Set once the body has ended with the end-of-stream marker.
finished: bool,
request_id: String,
table_version: Option<u64>,
batches: u64,
rows: u64,
}
impl IpcStreamBody {
/// Decode until the next batch is complete. Returns `None` once the body
/// has ended with the end-of-stream marker.
async fn next_batch(&mut self) -> Result<Option<RecordBatch>> {
while !self.finished {
if self.chunk.is_empty() {
match self.chunks.next().await {
Some(Ok(chunk)) => self.chunk = chunk.into(),
Some(Err(error)) => return Err(self.interrupted(error)),
None if read_end_of_stream(&mut self.decoder) => self.finished = true,
None => {
return Err(self.interrupted(
"the response ended before the Arrow end-of-stream marker".into(),
));
}
}
continue;
}
// Decoding stops after each batch, keeping the rest of the chunk.
if let Some(batch) = self.decoder.decode(&mut self.chunk)? {
self.batches += 1;
self.rows += batch.num_rows() as u64;
return Ok(Some(batch));
}
}
Ok(None)
}
fn interrupted(&self, source: BoxError) -> Error {
Error::ResponseInterrupted {
request_id: self.request_id.clone(),
batches: self.batches,
rows: self.rows,
table_version: self.table_version,
source: source.into(),
}
}
}
/// Whether the decoder has read the end-of-stream marker.
///
/// [`StreamDecoder::finish`] also accepts input that stops between messages,
/// because the Arrow format lets a writer end a stream by closing it. A decoder
/// that has read the marker rejects any further input, which is the only way
/// its API tells the two apart.
fn read_end_of_stream(decoder: &mut StreamDecoder) -> bool {
decoder.finish().is_ok() && decoder.decode(&mut Buffer::from_slice_ref([0u8])).is_err()
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use arrow_array::builder::StringDictionaryBuilder;
use arrow_array::types::Int8Type;
use arrow_array::{ArrayRef, Int32Array, StringArray};
use arrow_ipc::CompressionType;
use arrow_ipc::writer::{DictionaryHandling, FileWriter, IpcWriteOptions, StreamWriter};
use arrow_schema::{DataType, Field, Schema, SchemaRef};
use lance::arrow::json::JsonSchema;
use rstest::rstest;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::mpsc;
use super::*;
use crate::query::{ExecutableQuery, QueryExecutionOptions};
use crate::remote::client::{ClientConfig, RetryConfig};
use crate::remote::{ARROW_FILE_CONTENT_TYPE, ARROW_STREAM_CONTENT_TYPE};
use crate::{Table, connect};
/// Three batches of two rows under a schema with metadata. The second batch's
/// dictionary extends the first one's, which writers can send as a delta, and
/// the third replaces it.
fn batches() -> Vec<RecordBatch> {
let schema = Arc::new(Schema::new_with_metadata(
vec![
Field::new("id", DataType::Int32, false),
Field::new_dictionary("label", DataType::Int8, DataType::Utf8, false),
],
HashMap::from([("origin".to_string(), "test".to_string())]),
));
let labels: [(&[&str], [&str; 2]); 3] = [
(&["a", "b"], ["a", "b"]),
(&["a", "b", "c"], ["c", "a"]),
(&["d"], ["d", "d"]),
];
labels
.into_iter()
.enumerate()
.map(|(i, (dictionary, values))| {
let dictionary = StringArray::from(dictionary.to_vec());
let mut label =
StringDictionaryBuilder::<Int8Type>::new_with_dictionary(2, &dictionary)
.unwrap();
values
.into_iter()
.for_each(|value| label.append_value(value));
let id = Int32Array::from(vec![2 * i as i32, 2 * i as i32 + 1]);
RecordBatch::try_new(
schema.clone(),
vec![Arc::new(id) as ArrayRef, Arc::new(label.finish())],
)
.unwrap()
})
.collect()
}
/// An IPC stream cut where the server cuts it: after the schema, after each
/// batch with its dictionaries, and after the end-of-stream marker.
fn messages(
schema: &Schema,
batches: &[RecordBatch],
options: IpcWriteOptions,
) -> Vec<Vec<u8>> {
let mut writer = StreamWriter::try_new_with_options(Vec::new(), schema, options).unwrap();
let mut messages = vec![std::mem::take(writer.get_mut())];
for batch in batches {
writer.write(batch).unwrap();
messages.push(std::mem::take(writer.get_mut()));
}
writer.finish().unwrap();
messages.push(std::mem::take(writer.get_mut()));
messages
}
fn chunks(body: &[u8], size: usize) -> Vec<std::io::Result<Bytes>> {
body.chunks(size)
.map(|chunk| Ok(Bytes::copy_from_slice(chunk)))
.collect()
}
/// The schema, the batches yielded, and the error that ended the stream.
async fn read(
chunks: Vec<std::io::Result<Bytes>>,
) -> (Option<SchemaRef>, Vec<RecordBatch>, Option<Error>) {
let stream =
match read_ipc_stream(futures::stream::iter(chunks), "request".into(), Some(7)).await {
Ok(stream) => stream,
Err(error) => return (None, vec![], Some(error)),
};
let schema = stream.schema();
let results = stream.collect::<Vec<_>>().await;
let (batches, errors): (Vec<_>, Vec<_>) = results.into_iter().partition(|r| r.is_ok());
assert!(errors.len() <= 1, "the stream ends at its first error");
let error = errors
.into_iter()
.next()
.map(|e| Error::from(e.unwrap_err()));
let batches = batches.into_iter().map(|r| r.unwrap()).collect();
(Some(schema), batches, error)
}
fn assert_interrupted(error: Option<Error>, expected_batches: u64, expected_rows: u64) {
match error {
Some(Error::ResponseInterrupted {
request_id,
batches,
rows,
table_version,
..
}) => {
assert_eq!(request_id, "request");
assert_eq!((batches, rows), (expected_batches, expected_rows));
assert_eq!(table_version, Some(7));
}
other => panic!("expected an interrupted response, got {other:?}"),
}
}
// One-byte chunks split every message; a single chunk holds them all.
#[rstest]
#[case(1)]
#[case(7)]
#[case(usize::MAX)]
#[tokio::test]
async fn decodes_any_chunking(#[case] chunk_size: usize) {
let input = batches();
let body = messages(&input[0].schema(), &input, IpcWriteOptions::default()).concat();
let (schema, output, error) = read(chunks(&body, chunk_size)).await;
assert!(error.is_none(), "{error:?}");
assert_eq!(schema.unwrap(), input[0].schema());
assert_eq!(output, input);
}
#[rstest]
#[case(IpcWriteOptions::default().with_dictionary_handling(DictionaryHandling::Delta))]
#[case(IpcWriteOptions::default().try_with_compression(Some(CompressionType::LZ4_FRAME)).unwrap())]
#[case(IpcWriteOptions::default().try_with_compression(Some(CompressionType::ZSTD)).unwrap())]
#[tokio::test]
async fn decodes_dictionary_deltas_and_compressed_batches(#[case] options: IpcWriteOptions) {
let input = batches();
let body = messages(&input[0].schema(), &input, options).concat();
let (_, output, error) = read(chunks(&body, 5)).await;
assert!(error.is_none(), "{error:?}");
assert_eq!(output, input);
}
/// The server answers an empty result with the schema and the end-of-stream marker.
#[tokio::test]
async fn empty_result_keeps_its_schema() {
let schema = batches()[0].schema();
let body = messages(&schema, &[], IpcWriteOptions::default()).concat();
let (decoded, output, error) = read(chunks(&body, 3)).await;
assert!(error.is_none(), "{error:?}");
assert_eq!(decoded.unwrap(), schema);
assert!(output.is_empty());
}
#[tokio::test]
async fn body_ending_without_end_of_stream_is_interrupted() {
let input = batches();
let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default());
let complete = messages[..messages.len() - 1].concat();
let after_first_batch = messages[..2].concat().len();
// Where the body stops, and how many batches it holds by then.
for (end, delivered) in [
(complete.len(), 3), // between messages, after the last batch
(complete.len() - 3, 2), // inside the last batch
(after_first_batch, 1), // between messages
(messages[0].len(), 0), // after the schema
(messages[0].len() / 2, 0), // inside the schema
(0, 0), // an empty body
] {
let (_, output, error) = read(chunks(&complete[..end], 4)).await;
assert_eq!(output, input[..delivered], "body cut at {end}");
assert_interrupted(error, delivered as u64, 2 * delivered as u64);
}
}
#[tokio::test]
async fn body_error_is_interrupted() {
let input = batches();
let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default());
let mut body = chunks(&messages[..2].concat(), usize::MAX);
body.push(Err(std::io::Error::other("connection reset")));
let (_, output, error) = read(body).await;
assert_eq!(output, input[..1]);
let message = error.as_ref().map(ToString::to_string).unwrap_or_default();
assert!(message.contains("connection reset"), "{message}");
assert_interrupted(error, 1, 2);
}
#[tokio::test]
async fn malformed_body_is_an_arrow_error() {
let input = batches();
let messages = messages(&input[0].schema(), &input, IpcWriteOptions::default());
// A message whose metadata is not a flatbuffer.
let garbage = [&[0xff; 4][..], &8u32.to_le_bytes(), &[0xab; 8]].concat();
// Anything after the end-of-stream marker.
let trailing = [messages.concat(), vec![0]].concat();
for body in [[messages[0].clone(), garbage].concat(), trailing] {
let (_, _, error) = read(chunks(&body, usize::MAX)).await;
assert!(matches!(error, Some(Error::Arrow { .. })), "{error:?}");
}
}
/// What the test server does next for a query request.
enum Reply {
/// A complete response with this status and an empty body.
Status(u16),
/// Headers of a chunked body with this content type.
Head(Option<&'static str>),
Chunk(Vec<u8>),
/// The last chunk, ending the body cleanly.
End,
/// Close the connection in the middle of the body.
Abort,
}
struct Server {
table: Table,
replies: mpsc::UnboundedSender<Reply>,
/// Headers of each query request received.
queries: Arc<Mutex<Vec<HashMap<String, String>>>>,
}
impl Server {
fn reply(&self, replies: impl IntoIterator<Item = Reply>) {
replies
.into_iter()
.for_each(|reply| self.replies.send(reply).unwrap());
}
}
/// Serve table `t` over HTTP. Query requests are answered, in order, by the
/// replies the test sends.
async fn serve() -> Server {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let (replies, mut pending) = mpsc::unbounded_channel();
let queries = Arc::new(Mutex::new(Vec::new()));
let received = queries.clone();
tokio::spawn(async move {
loop {
let (mut socket, _) = listener.accept().await.unwrap();
let (path, headers) = read_request(&mut socket).await;
if path.ends_with("/describe/") {
let schema = Schema::new(vec![
Field::new("id", DataType::Int32, false),
Field::new(
"vector",
DataType::new_fixed_size_list(DataType::Float32, 2, true),
false,
),
]);
let body = serde_json::json!({
"version": 7,
"schema": JsonSchema::try_from(&schema).unwrap(),
})
.to_string();
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
socket.write_all(response.as_bytes()).await.unwrap();
continue;
}
received.lock().unwrap().push(headers);
while let Some(reply) = pending.recv().await {
let last = !matches!(reply, Reply::Head(_) | Reply::Chunk(_));
let bytes = match reply {
Reply::Status(status) => format!(
"HTTP/1.1 {status} Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
)
.into_bytes(),
Reply::Head(content_type) => format!(
"HTTP/1.1 200 OK\r\n{}Transfer-Encoding: chunked\r\n\
x-lancedb-version: 7\r\nConnection: close\r\n\r\n",
content_type
.map(|value| format!("Content-Type: {value}\r\n"))
.unwrap_or_default()
)
.into_bytes(),
Reply::Chunk(chunk) => {
[format!("{:x}\r\n", chunk.len()).into_bytes(), chunk, b"\r\n".into()]
.concat()
}
Reply::End => b"0\r\n\r\n".to_vec(),
Reply::Abort => break,
};
// The client may have stopped reading.
if socket.write_all(&bytes).await.is_err() || last {
break;
}
}
}
});
let db = connect("db://test")
.api_key("key")
.region("us-east-1")
.host_override(&format!("http://{address}"))
.client_config(ClientConfig {
retry_config: RetryConfig {
backoff_factor: Some(0.0),
backoff_jitter: Some(0.0),
..Default::default()
},
..Default::default()
})
.execute()
.await
.unwrap();
let table = db.open_table("t").execute().await.unwrap();
Server {
table,
replies,
queries,
}
}
async fn read_request(socket: &mut TcpStream) -> (String, HashMap<String, String>) {
let mut request = Vec::new();
let mut buf = [0; 4096];
let head_end = loop {
let n = socket.read(&mut buf).await.unwrap();
assert!(n > 0, "connection closed before the request head");
request.extend_from_slice(&buf[..n]);
if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") {
break end + 4;
}
};
let head = String::from_utf8(request[..head_end].to_vec()).unwrap();
let mut lines = head.lines();
let path = lines.next().unwrap().split(' ').nth(1).unwrap().to_string();
let headers: HashMap<_, _> = lines
.filter_map(|line| line.split_once(':'))
.map(|(name, value)| (name.to_ascii_lowercase(), value.trim().to_string()))
.collect();
let length: usize = headers
.get("content-length")
.map_or(0, |length| length.parse().unwrap());
while request.len() < head_end + length {
let n = socket.read(&mut buf).await.unwrap();
assert!(n > 0, "connection closed before the request body");
request.extend_from_slice(&buf[..n]);
}
(path, headers)
}
/// The query batches as the server sends them: `id` only.
fn id_messages() -> Vec<Vec<u8>> {
let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
let batches: Vec<_> = (0..3)
.map(|i| {
RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![i]))])
.unwrap()
})
.collect();
messages(&schema, &batches, IpcWriteOptions::default())
}
fn ids(batch: &RecordBatch) -> Vec<i32> {
batch["id"]
.as_any()
.downcast_ref::<Int32Array>()
.unwrap()
.values()
.to_vec()
}
#[tokio::test]
async fn first_batch_arrives_before_the_rest_of_the_body() {
let server = serve().await;
let messages = id_messages();
server.reply([
Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)),
Reply::Chunk(messages[..2].concat()),
]);
// The server sends the rest only after the first batch has been read.
let (results, first) = tokio::time::timeout(Duration::from_secs(10), async {
let mut results = server.table.query().execute().await.unwrap();
let first = results.next().await.unwrap().unwrap();
(results, first)
})
.await
.expect("the first batch must not wait for the whole body");
assert_eq!(ids(&first), [0]);
server.reply([Reply::Chunk(messages[2..].concat()), Reply::End]);
let rest = results.try_collect::<Vec<_>>().await.unwrap();
assert_eq!(rest.iter().flat_map(ids).collect::<Vec<_>>(), [1, 2]);
let queries = server.queries.lock().unwrap();
assert_eq!(queries.len(), 1);
assert_eq!(queries[0]["accept"], super::super::QUERY_ACCEPT);
}
/// A server abort, and a proxy that turns it into a clean end of the body,
/// both fail the query after the batches already read. Neither is retried.
#[rstest]
#[case::abort(Reply::Abort, true)]
#[case::clean_end(Reply::End, false)]
#[tokio::test]
async fn interrupted_body_is_typed_and_not_retried(
#[case] end: Reply,
#[case] transport_error: bool,
) {
let server = serve().await;
let messages = id_messages();
server.reply([
Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)),
Reply::Chunk(messages[..2].concat()),
end,
]);
let mut results = server.table.query().execute().await.unwrap();
assert_eq!(ids(&results.next().await.unwrap().unwrap()), [0]);
let error = results.next().await.unwrap().unwrap_err();
assert!(results.next().await.is_none());
let Error::ResponseInterrupted {
request_id,
batches,
rows,
table_version,
source,
} = error
else {
panic!("expected an interrupted response, got {error:?}");
};
assert!(!request_id.is_empty());
assert_eq!((batches, rows, table_version), (1, 1, Some(7)));
assert_eq!(source.is::<reqwest::Error>(), transport_error, "{source}");
assert_eq!(server.queries.lock().unwrap().len(), 1);
}
/// Vector queries run through a DataFusion plan, which must keep the error's type.
#[tokio::test]
async fn vector_query_keeps_the_interruption_type() {
let server = serve().await;
let messages = id_messages();
server.reply([
Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)),
Reply::Chunk(messages[..2].concat()),
Reply::Abort,
]);
let results = server
.table
.query()
.nearest_to(&[0.0f32, 0.0])
.unwrap()
.execute()
.await
.unwrap();
let error = results.try_collect::<Vec<_>>().await.unwrap_err();
assert!(
matches!(error, Error::ResponseInterrupted { batches: 1, .. }),
"{error:?}"
);
}
/// A server without multi-vector support gets a request per vector, and the
/// plan merging the responses shares an error between its partitions.
#[tokio::test]
async fn multi_vector_query_keeps_the_interruption() {
let server = serve().await;
let messages = id_messages();
// Which vector gets which response does not matter.
server.reply([
Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)),
Reply::Chunk(messages.concat()),
Reply::End,
Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)),
Reply::Chunk(messages[..2].concat()),
Reply::Abort,
]);
let results = server
.table
.query()
.nearest_to(&[0.0f32, 0.0])
.unwrap()
.add_query_vector(&[1.0f32, 1.0])
.unwrap()
.execute()
.await
.unwrap();
let error = results.try_collect::<Vec<_>>().await.unwrap_err();
let Error::ResponseInterrupted {
request_id,
batches,
rows,
table_version,
source,
} = error
else {
panic!("expected an interrupted response, got {error:?}");
};
assert!(!request_id.is_empty());
assert_eq!((batches, rows, table_version), (1, 1, Some(7)));
assert!(source.is::<reqwest::Error>(), "{source}");
assert_eq!(server.queries.lock().unwrap().len(), 2);
}
#[tokio::test]
async fn timeout_covers_reading_the_body() {
let server = serve().await;
let messages = id_messages();
// The body stalls after the first batch.
server.reply([
Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)),
Reply::Chunk(messages[..2].concat()),
]);
let options = QueryExecutionOptions {
timeout: Some(Duration::from_millis(500)),
..Default::default()
};
let mut results = server
.table
.query()
.execute_with_options(options)
.await
.unwrap();
assert_eq!(ids(&results.next().await.unwrap().unwrap()), [0]);
let error = tokio::time::timeout(Duration::from_secs(10), results.next())
.await
.expect("the timeout must end a stalled body")
.unwrap()
.unwrap_err();
assert!(
!matches!(error, Error::ResponseInterrupted { .. }),
"{error:?}"
);
assert!(
error.to_string().contains("Query timeout after 500 ms"),
"{error}"
);
assert_eq!(
server.queries.lock().unwrap()[0]["x-request-timeout-ms"],
"500"
);
}
/// Servers that do not stream query results answer with file framing, or
/// with no content type at all.
#[rstest]
#[case(Some(ARROW_FILE_CONTENT_TYPE))]
#[case(None)]
#[tokio::test]
async fn file_framing_is_still_read(#[case] content_type: Option<&'static str>) {
let server = serve().await;
let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)]));
let batch =
RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(vec![4, 5]))])
.unwrap();
let mut writer = FileWriter::try_new(Vec::new(), &schema).unwrap();
writer.write(&batch).unwrap();
writer.finish().unwrap();
server.reply([
Reply::Head(content_type),
Reply::Chunk(writer.into_inner().unwrap()),
Reply::End,
]);
let results = server.table.query().execute().await.unwrap();
let output = results.try_collect::<Vec<_>>().await.unwrap();
assert_eq!(output, [batch]);
}
#[tokio::test]
async fn failure_before_headers_is_retried() {
let server = serve().await;
server.reply([
Reply::Status(503),
Reply::Head(Some(ARROW_STREAM_CONTENT_TYPE)),
Reply::Chunk(id_messages().concat()),
Reply::End,
]);
let results = server.table.query().execute().await.unwrap();
let output = results.try_collect::<Vec<_>>().await.unwrap();
assert_eq!(output.iter().flat_map(ids).collect::<Vec<_>>(), [0, 1, 2]);
assert_eq!(server.queries.lock().unwrap().len(), 2);
}
}
+22 -5
View File
@@ -2141,10 +2141,14 @@ impl Table {
///
/// [`RefreshColumnOptions::batch_size()`] caps rows per Function call in
/// LanceDB Enterprise and must be greater than zero when set.
/// [`RefreshColumnOptions::publication_interval_rows()`] sets an opt-in
/// row-count publication threshold for completed Function outputs; unset
/// keeps whole-fragment publication.
/// [`RefreshColumnOptions::gpu_class()`] selects a GPU pool and
/// [`RefreshColumnOptions::gpu_count()`] sets the aggregate GPU budget.
/// These options have no effect on expression-backed columns in LanceDB
/// Embedded. Remote refreshes require
/// Batch-size and GPU options have no effect on expression-backed columns
/// in LanceDB Embedded; a publication threshold is rejected there.
/// Remote refreshes require
/// [`Table::refresh_column_async_with_options`].
///
/// ```
@@ -2201,12 +2205,16 @@ impl Table {
/// Set [`RefreshColumnOptions::batch_size()`] to cap the rows each remote
/// Function call receives, for example to keep slow Functions within the
/// executor's per-call deadline. Set
/// [`RefreshColumnOptions::publication_interval_rows()`] to publish
/// completed Function outputs at a row-count threshold; unset keeps
/// whole-fragment publication. Set
/// [`RefreshColumnOptions::gpu_class()`] and
/// [`RefreshColumnOptions::gpu_count()`] to override the registered GPU
/// class or set an aggregate GPU budget for Function workers. Unset values
/// use the Function and server defaults; zero counts and malformed class
/// names are rejected before submitting a job. Embedded expression
/// refreshes ignore all three options.
/// refreshes ignore the batch-size and GPU options, and reject publication
/// thresholds and other Enterprise-only options.
///
/// ```
/// # use lancedb::{Table, table::RefreshColumnOptions};
@@ -3407,7 +3415,11 @@ impl NativeTable {
namespace_client: Option<Arc<dyn LanceNamespace>>,
pushdown_operations: HashSet<NamespaceClientPushdownOperation>,
) -> Result<Self> {
let batches = computed_columns::admit_create_source(batches)?;
let session = params.as_ref().and_then(|p| p.session.as_deref());
let batches = computed_columns::admit_create_source(
batches,
session.and_then(lance::session::Session::datafusion_session),
)?;
// Default params uses format v1.
let params = params.unwrap_or(WriteParams {
..Default::default()
@@ -3508,7 +3520,12 @@ impl NativeTable {
pushdown_operations: HashSet<NamespaceClientPushdownOperation>,
session: Option<Arc<lance::session::Session>>,
) -> Result<Self> {
let batches = computed_columns::admit_create_source(batches)?;
let batches = computed_columns::admit_create_source(
batches,
session
.as_deref()
.and_then(lance::session::Session::datafusion_session),
)?;
// Build table_id from namespace + name for the storage options provider
let mut table_id = namespace.clone();
table_id.push(name.to_string());
+24
View File
@@ -89,6 +89,30 @@ impl AddColumnsBuilder {
/// # Ok(())
/// # }
/// ```
///
/// In LanceDB Embedded, an expression can also call functions registered
/// on a DataFusion `SessionContext` attached to the connection's Lance
/// session. They are not stored with the table, so attach them on every
/// connection that opens it.
///
/// ```no_run
/// # use std::sync::Arc;
/// # use datafusion::execution::context::SessionContext;
/// # use datafusion::logical_expr::ScalarUDF;
/// # async fn declare(my_udf: ScalarUDF) -> Result<(), Box<dyn std::error::Error>> {
/// let functions = SessionContext::new();
/// functions.register_udf(my_udf);
/// let session = lance::session::Session::default().with_datafusion_session(functions);
/// let db = lancedb::connect("data/db")
/// .session(Arc::new(session))
/// .execute()
/// .await?;
/// let table = db.open_table("t").execute().await?;
/// table.add_columns().computed("y", "my_udf(x)").execute().await?;
/// table.refresh_column("y").await?;
/// # Ok(())
/// # }
/// ```
pub fn computed(mut self, name: impl Into<String>, expression: impl Into<String>) -> Self {
self.computed.push((name.into(), expression.into()));
self
+222 -38
View File
@@ -26,6 +26,7 @@ use std::collections::{BTreeSet, HashMap, HashSet};
use std::sync::Arc;
use arrow_schema::{DataType, Field as ArrowField, Fields, Schema as ArrowSchema, SchemaRef};
use datafusion::execution::context::SessionContext;
use datafusion_common::{ScalarValue, tree_node::TreeNode};
use datafusion_expr::Expr;
use datafusion_physical_plan::PhysicalExpr;
@@ -40,6 +41,7 @@ use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::function::{FUNCTION_BLOB_V2_TYPE, FunctionApplication, FunctionBinding};
use crate::materialized_view::without_declarations;
use crate::utils::resolve_arrow_field_path;
use crate::{Error, Result};
@@ -1640,8 +1642,12 @@ pub(crate) fn plan_function_application(
///
/// Paths are compared at their root: a declaration reading `metadata` is
/// invalidated by a change to `metadata.age` just as surely.
pub(crate) fn ensure_not_an_input(schema: &SchemaRef, paths: &[&str]) -> Result<()> {
ensure_not_an_input_of(schema, paths, &[])
pub(crate) fn ensure_not_an_input(
schema: &SchemaRef,
paths: &[&str],
session: Option<&SessionContext>,
) -> Result<()> {
ensure_not_an_input_of(schema, paths, &[], session)
}
/// [`ensure_not_an_input`] where `removed` names columns whose own
@@ -1651,6 +1657,7 @@ pub(crate) fn ensure_not_an_input_of(
schema: &SchemaRef,
paths: &[&str],
removed: &[&str],
session: Option<&SessionContext>,
) -> Result<()> {
// By identity, not spelling: a quoted path names the same column, while
// a path *into* one removes no declaration at all.
@@ -1668,7 +1675,7 @@ pub(crate) fn ensure_not_an_input_of(
// The expression, not stored inputs, is the source of truth; an
// expression that no longer parses proves nothing, so refuse.
let inputs = match &declaration.kind {
ComputedColumnKind::Sql { expression } => Planner::new(schema.clone())
ComputedColumnKind::Sql { expression } => session_planner(schema.clone(), session)
.parse_expr(expression)
.map(|parsed| Planner::column_names_in_expr(&parsed))
.map_err(|e| Error::InvalidInput {
@@ -1760,7 +1767,10 @@ pub(crate) fn ensure_batch_writes_no_computed_values(
/// Function declaration satisfies the binding contract, and no SQL
/// declaration reads another computed column. What passes here is what
/// `refresh_column` can execute.
pub(crate) fn ensure_declarations_are_planned(schema: &ArrowSchema) -> Result<()> {
pub(crate) fn ensure_declarations_are_planned(
schema: &ArrowSchema,
session: Option<&SessionContext>,
) -> Result<()> {
let invalid = |message: String| Error::InvalidInput { message };
// A field with any declaration key is a declaration; a partial one is
// not "no declaration", it is a broken one.
@@ -1794,7 +1804,12 @@ pub(crate) fn ensure_declarations_are_planned(schema: &ArrowSchema) -> Result<()
.filter(|f| f.name() != &column.name)
.map(|f| f.as_ref().clone())
.collect();
let bound = bind(Arc::new(ArrowSchema::new(others)), &column.name, expression)?;
let bound = bind(
Arc::new(ArrowSchema::new(others)),
&column.name,
expression,
session,
)?;
if let Some(input) = bound.roots.iter().find(|r| declared.contains(*r)) {
return Err(invalid(format!(
"computed column '{}' reads computed column '{input}'",
@@ -1944,6 +1959,17 @@ pub(crate) struct BoundExpression {
pub blob_paths: Vec<String>,
/// A directly projected Blob v2 field whose semantics the output inherits.
projected_blob_field: Option<ArrowField>,
/// Field metadata of the expression's return field, e.g. a function's
/// logical type.
return_metadata: HashMap<String, String>,
}
/// Plans against `session`'s functions when given, else Lance's defaults.
fn session_planner(schema: SchemaRef, session: Option<&SessionContext>) -> Planner {
match session {
Some(session) => Planner::new_with_session(schema, session.clone()),
None => Planner::new(schema),
}
}
fn is_direct_field_projection(expr: &Expr) -> bool {
@@ -2089,7 +2115,12 @@ fn referenced_blob_paths(schema: &ArrowSchema, inputs: &[String]) -> Result<Vec<
/// simplifier can fold a referenced column out entirely (`true OR x > 0`),
/// and the guard protecting the stored SQL has to see every column the text
/// names, not just the ones the simplified form still reads.
pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result<BoundExpression> {
pub(crate) fn bind(
schema: SchemaRef,
column: &str,
expression: &str,
session: Option<&SessionContext>,
) -> Result<BoundExpression> {
let invalid = |message: String| Error::InvalidExpression {
column: column.to_string(),
message,
@@ -2102,7 +2133,7 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result<
.into_iter()
.collect::<HashSet<_>>();
let parsing_schema = blob_runtime_schema(schema.as_ref(), &all_blob_paths);
let planner = Planner::new(parsing_schema);
let planner = session_planner(parsing_schema, session);
let parsed = planner
.parse_expr(expression)
.map_err(|e| invalid(e.to_string()))?;
@@ -2171,22 +2202,22 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result<
.map(|field| field.name().clone())
.collect();
let runtime_planner = Planner::new(runtime_schema);
let runtime_planner = session_planner(runtime_schema, session);
let optimized = runtime_planner
.optimize_expr(parsed)
.map_err(|e| invalid(e.to_string()))?;
let physical = Planner::new(read_schema.clone())
let physical = session_planner(read_schema.clone(), session)
.create_physical_expr(&optimized)
.map_err(|e| invalid(e.to_string()))?;
let data_type = physical
.data_type(read_schema.as_ref())
let return_field = physical
.return_field(read_schema.as_ref())
.map_err(|e| invalid(e.to_string()))?;
Ok(BoundExpression {
inputs,
roots,
physical,
data_type,
data_type: return_field.data_type().clone(),
blob_paths: blob_paths
.iter()
.map(|path| {
@@ -2195,6 +2226,7 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result<
})
.collect(),
projected_blob_field,
return_metadata: return_field.metadata().clone(),
})
}
@@ -2210,7 +2242,11 @@ pub(crate) fn bind(schema: SchemaRef, column: &str, expression: &str) -> Result<
/// batch may declare `a` and then `b = a + 1` in one commit. Refresh order
/// then matters, and refresh enforces it: `b` is refused while `a` still has
/// unfilled rows.
fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result<Vec<ArrowField>> {
fn plan_declarations(
schema: SchemaRef,
columns: &[(String, String)],
session: Option<&SessionContext>,
) -> Result<Vec<ArrowField>> {
if columns.is_empty() {
return Err(Error::InvalidInput {
message: "at least one computed column is required".into(),
@@ -2225,23 +2261,22 @@ fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result<
return Err(Error::ColumnAlreadyExists { name: name.clone() });
}
let bound = bind(schema.clone(), name, expression)?;
let bound = bind(schema.clone(), name, expression, session)?;
// Declared columns start entirely null, so nullability is a property
// of the declaration rather than of what the expression yields.
let computed_metadata = computed_column_metadata(expression, &bound.inputs);
let field = match bound.projected_blob_field {
Some(source) => {
let mut metadata = source.metadata().clone();
metadata.retain(|key, _| !is_declaration_key(key));
metadata.extend(computed_metadata);
source
.with_name(name)
.with_nullable(true)
.with_metadata(metadata)
let projected = match bound.projected_blob_field {
Some(source) => source.with_name(name),
None => {
ArrowField::new(name, bound.data_type, true).with_metadata(bound.return_metadata)
}
None => ArrowField::new(name, bound.data_type, true).with_metadata(computed_metadata),
};
// Keep the source's descriptive metadata, not its schema declarations.
let projected = without_declarations(&projected);
let mut metadata = projected.metadata().clone();
metadata.extend(computed_metadata);
let field = projected.with_nullable(true).with_metadata(metadata);
schema = Arc::new(ArrowSchema::new_with_metadata(
schema
.fields()
@@ -2257,8 +2292,12 @@ fn plan_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result<
Ok(fields)
}
pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result<Vec<ArrowField>> {
plan_declarations(schema, columns)
pub(crate) fn plan(
schema: SchemaRef,
columns: &[(String, String)],
session: Option<&SessionContext>,
) -> Result<Vec<ArrowField>> {
plan_declarations(schema, columns, session)
}
/// Run the schema-level checks of
@@ -2267,6 +2306,11 @@ pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result<Ve
/// every declaration. For callers that stage declarations behind other work
/// and need those rejections before any of it lands.
///
/// Expressions may call the functions of `session`, the DataFusion session
/// the table's lance session carries (see
/// [`lance::session::Session::with_datafusion_session`]); `None` allows Lance's
/// defaults only.
///
/// Only the schema is consulted. Declaring also refuses a table with an RTE
/// write spec or retained SSTables; that is table state, checked at commit.
///
@@ -2280,16 +2324,20 @@ pub(crate) fn plan(schema: SchemaRef, columns: &[(String, String)]) -> Result<Ve
/// ("a".to_string(), "x + 1".to_string()),
/// ("b".to_string(), "a * 2".to_string()),
/// ];
/// assert!(validate_declarations(schema.clone(), &declarations).is_ok());
/// assert!(validate_declarations(schema, &[("c".into(), "random()".into())]).is_err());
/// assert!(validate_declarations(schema.clone(), &declarations, None).is_ok());
/// assert!(validate_declarations(schema, &[("c".into(), "random()".into())], None).is_err());
/// ```
pub fn validate_declarations(schema: SchemaRef, columns: &[(String, String)]) -> Result<()> {
pub fn validate_declarations(
schema: SchemaRef,
columns: &[(String, String)],
session: Option<&SessionContext>,
) -> Result<()> {
ensure_not_function_bound(
schema.as_ref(),
"schema evolution",
columns.iter().map(|(name, _)| name),
)?;
plan(schema, columns).map(drop)
plan(schema, columns, session).map(drop)
}
/// Build the transform that declares `columns` against `schema`.
@@ -2302,8 +2350,9 @@ pub fn validate_declarations(schema: SchemaRef, columns: &[(String, String)]) ->
pub(crate) fn declare(
schema: SchemaRef,
columns: &[(String, String)],
session: Option<&SessionContext>,
) -> Result<NewColumnTransform> {
let fields = plan_declarations(schema, columns)?;
let fields = plan_declarations(schema, columns, session)?;
Ok(NewColumnTransform::AllNulls(Arc::new(ArrowSchema::new(
fields,
))))
@@ -2334,9 +2383,10 @@ pub(super) async fn add_foreign_kind(table: &crate::Table, name: &str, kind: &st
/// created.
pub(crate) fn admit_create_source<S: lance_datafusion::utils::StreamingWriteSource>(
batches: S,
session: Option<&SessionContext>,
) -> Result<UnfilledDeclarations<S>> {
let schema = batches.arrow_schema();
ensure_declarations_are_planned(&schema)?;
ensure_declarations_are_planned(&schema, session)?;
let declared = computed_columns(&schema)
.into_iter()
.map(|c| c.name)
@@ -2496,7 +2546,7 @@ mod tests {
)]),
));
let declarations = vec![("a".to_string(), "x + 1".to_string())];
assert!(super::validate_declarations(schema, &declarations).is_err());
assert!(super::validate_declarations(schema, &declarations, None).is_err());
}
#[test]
@@ -2588,7 +2638,7 @@ mod tests {
}
}
use arrow_array::record_batch;
use arrow_array::{RecordBatch, record_batch};
use arrow_schema::{DataType, TimeUnit};
use futures::TryStreamExt;
use lance::dataset::ColumnAlteration;
@@ -2618,6 +2668,137 @@ mod tests {
computed_columns(table.schema().await.unwrap().as_ref())
}
/// Echoes an Int32 and tags its return field, like a function with a
/// logical type.
#[derive(Debug, PartialEq, Eq, Hash)]
struct Tagged(datafusion_expr::Signature);
impl datafusion_expr::ScalarUDFImpl for Tagged {
fn name(&self) -> &str {
"tagged"
}
fn signature(&self) -> &datafusion_expr::Signature {
&self.0
}
fn return_type(&self, _: &[DataType]) -> datafusion_common::Result<DataType> {
Ok(DataType::Int32)
}
fn return_field_from_args(
&self,
_: datafusion_expr::ReturnFieldArgs,
) -> datafusion_common::Result<arrow_schema::FieldRef> {
Ok(Arc::new(
ArrowField::new("tagged", DataType::Int32, true)
.with_metadata(HashMap::from([("tag".into(), "yes".into())])),
))
}
fn invoke_with_args(
&self,
args: datafusion_expr::ScalarFunctionArgs,
) -> datafusion_common::Result<datafusion_expr::ColumnarValue> {
Ok(args.args[0].clone())
}
}
#[tokio::test]
#[cfg_attr(
not(feature = "experimental-functions"),
ignore = "requires experimental-functions"
)]
async fn test_declarations_plan_against_the_session_functions() {
let functions = SessionContext::new();
functions.register_udf(datafusion_expr::ScalarUDF::new_from_impl(Tagged(
datafusion_expr::Signature::exact(
vec![DataType::Int32],
datafusion_expr::Volatility::Immutable,
),
)));
let session =
Arc::new(lance::session::Session::default().with_datafusion_session(functions));
let conn = connect("memory://")
.session(session)
.execute()
.await
.unwrap();
let batch = record_batch!(("x", Int32, [1, 2, 3]), ("y", Int32, [4, 5, 6])).unwrap();
let table = conn
.create_table("session_functions", batch)
.execute()
.await
.unwrap();
add_computed(&table, &[("t".into(), "tagged(x)".into())])
.await
.unwrap();
let schema = table.schema().await.unwrap();
assert_eq!(
schema.field_with_name("t").unwrap().metadata().get("tag"),
Some(&"yes".to_string())
);
table.refresh_column("t").await.unwrap();
// Dropping a column re-plans every declaration on the table.
table.drop_columns(&["y"]).await.unwrap();
let batches = table
.query()
.select(Select::columns(&["t"]))
.execute()
.await
.unwrap()
.try_collect::<Vec<_>>()
.await
.unwrap();
let expected = record_batch!(("t", Int32, [1, 2, 3])).unwrap();
assert_eq!(batches[0].column(0).as_ref(), expected.column(0).as_ref());
let plain = table_with_ints("no_session").await;
let err = add_computed(&plain, &[("t".into(), "tagged(x)".into())])
.await
.unwrap_err();
assert!(err.to_string().contains("tagged"), "{err}");
}
/// A projection keeps its source's descriptive metadata, not its schema
/// declarations: a copy of the primary key is not a primary key.
#[tokio::test]
#[cfg_attr(
not(feature = "experimental-functions"),
ignore = "requires experimental-functions"
)]
async fn test_projecting_the_primary_key_drops_its_declaration() {
let conn = connect("memory://").execute().await.unwrap();
let ints = record_batch!(("x", Int32, [1, 2, 3])).unwrap();
let schema = ArrowSchema::new(vec![
ArrowField::new("x", DataType::Int32, false)
.with_metadata(HashMap::from([("note".into(), "kept".into())])),
]);
let batch = RecordBatch::try_new(Arc::new(schema), ints.columns().to_vec()).unwrap();
let table = conn
.create_table("key_projection", batch)
.execute()
.await
.unwrap();
table.set_unenforced_primary_key(["x"]).await.unwrap();
add_computed(&table, &[("copy".into(), "x".into())])
.await
.unwrap();
let schema = table.schema().await.unwrap();
let copy = schema.field_with_name("copy").unwrap();
assert!(
!copy
.metadata()
.keys()
.any(|key| key.starts_with("lance-schema:")),
"{copy:?}"
);
assert_eq!(copy.metadata().get("note"), Some(&"kept".to_string()));
}
#[tokio::test]
#[cfg_attr(
not(feature = "experimental-functions"),
@@ -2658,6 +2839,7 @@ mod tests {
("first".to_string(), "image".to_string()),
("second".to_string(), "first".to_string()),
],
None,
)
.unwrap();
@@ -2680,6 +2862,7 @@ mod tests {
let fields = plan(
schema,
&[("payload".to_string(), "coalesce(image, image)".to_string())],
None,
)
.unwrap();
@@ -2914,7 +3097,8 @@ mod tests {
assert!(
validate_declarations(
table.schema().await.unwrap(),
&[("e".into(), "random()".into())]
&[("e".into(), "random()".into())],
None,
)
.is_err()
);
@@ -4803,7 +4987,7 @@ mod tests {
let schema = declare_plan(&schema, &downstream, "fb_downstream");
ensure_supported_function_metadata(&schema).unwrap();
ensure_declarations_are_planned(&schema).unwrap();
ensure_declarations_are_planned(&schema, None).unwrap();
let bindings = function_bindings(&schema).unwrap();
assert!(
computed_function_inputs(&schema, &bindings[0])
@@ -4868,7 +5052,7 @@ mod tests {
let base = ArrowSchema::new(vec![ArrowField::new("x", DataType::Int32, true)]);
let mut fields = base.fields().to_vec();
fields.extend(
plan(Arc::new(base), &[("doubled".into(), "x * 2".into())])
plan(Arc::new(base), &[("doubled".into(), "x * 2".into())], None)
.unwrap()
.into_iter()
.map(Arc::new),
@@ -4887,7 +5071,7 @@ mod tests {
.is_none_or(|metadata| !metadata.keys().any(|key| is_declaration_key(key)))
);
let schema = Arc::new(declare_plan(&schema, &downstream, "fb_downstream"));
ensure_declarations_are_planned(&schema).unwrap();
ensure_declarations_are_planned(&schema, None).unwrap();
let batch = RecordBatch::try_new(
schema,
vec![
+31 -1
View File
@@ -100,6 +100,14 @@ pub struct RefreshColumnOptions {
/// effect on expression-backed columns in LanceDB Embedded.
#[serde(skip_serializing_if = "Option::is_none")]
pub batch_size: Option<usize>,
/// Opt-in row-count threshold for publishing completed Function outputs.
///
/// Must be greater than zero. `None` keeps whole-fragment publication.
/// Actual publication boundaries can be larger than this threshold because
/// they also depend on completed work and Function batching. LanceDB Embedded
/// rejects this option.
#[serde(skip_serializing_if = "Option::is_none")]
pub publication_interval_rows: Option<u64>,
/// GPU class for Function workers in LanceDB Enterprise.
///
/// `None` keeps the Function's registered class, or the deployment default
@@ -174,6 +182,13 @@ impl RefreshColumnOptions {
self
}
/// Use `rows` as the opt-in publication threshold for completed Function
/// outputs. The actual publication boundary can be larger than this value.
pub fn publication_interval_rows(mut self, rows: u64) -> Self {
self.publication_interval_rows = Some(rows);
self
}
/// Request Function workers from `gpu_class`.
pub fn gpu_class(mut self, gpu_class: impl Into<String>) -> Self {
self.gpu_class = Some(gpu_class.into());
@@ -201,6 +216,10 @@ impl RefreshColumnOptions {
"max_executor_processes_per_worker",
self.max_executor_processes_per_worker.is_some(),
),
(
"publication_interval_rows",
self.publication_interval_rows.is_some(),
),
]
.into_iter()
.find_map(|(name, set)| set.then_some(name))
@@ -253,6 +272,11 @@ impl RefreshColumnOptions {
message: "batch_size must be greater than zero".into(),
});
}
if self.publication_interval_rows == Some(0) {
return Err(Error::InvalidInput {
message: "publication_interval_rows must be greater than zero".into(),
});
}
if let Some(gpu_class) = &self.gpu_class {
validate_gpu_class_name(gpu_class)?;
}
@@ -308,6 +332,7 @@ async fn execute_refresh_column_with_source(
schema.clone(),
column,
&expression,
dataset.session().datafusion_session(),
)?);
ensure_inputs_filled(&dataset, &schema, column, &bound).await?;
let field = dataset
@@ -490,7 +515,12 @@ async fn ensure_inputs_filled(
),
});
};
let input_bound = super::computed_columns::bind(schema.clone(), input, expression)?;
let input_bound = super::computed_columns::bind(
schema.clone(),
input,
expression,
dataset.session().datafusion_session(),
)?;
let mut unfilled = 0u64;
for fragment in dataset.get_fragments() {
unfilled += count_fragment_gains(dataset, &fragment, &input_bound, input)
+14 -3
View File
@@ -166,7 +166,9 @@ pub(crate) async fn execute_declare(
.into(),
});
}
let transform = computed_columns::declare(table.schema().await?, columns)?;
let session = table.dataset.get().await?.session();
let transform =
computed_columns::declare(table.schema().await?, columns, session.datafusion_session())?;
let NewColumnTransform::AllNulls(schema) = transform else {
unreachable!("declarations are all-null")
};
@@ -307,7 +309,11 @@ pub(crate) async fn execute_alter_columns(
.filter(|alteration| alteration.rename.is_some() || alteration.data_type.is_some())
.map(|alteration| alteration.path.as_str())
.collect::<Vec<_>>();
computed_columns::ensure_not_an_input(&schema, &rebinding)?;
computed_columns::ensure_not_an_input(
&schema,
&rebinding,
dataset.session().datafusion_session(),
)?;
let retyped = alterations
.iter()
.filter(|alteration| alteration.data_type.is_some())
@@ -344,7 +350,12 @@ pub(crate) async fn execute_drop_columns(
let dropped = names.iter().map(String::as_str).collect::<Vec<_>>();
ensure_not_embedding_column(&schema, "drop", dropped.iter().copied())?;
computed_columns::ensure_not_bound_by(&unbinding.retained, "schema evolution", &dropped)?;
computed_columns::ensure_not_an_input_of(&schema, &dropped, &dropped)?;
computed_columns::ensure_not_an_input_of(
&schema,
&dropped,
&dropped,
dataset.session().datafusion_session(),
)?;
if !unbinding.is_noop() {
// The retirement commits before the projection, so the whole
+16
View File
@@ -680,6 +680,22 @@ impl TimeoutStream {
Box::pin(Self::new(inner, timeout))
}
/// Like [`Self::new`], but the stream expires at `deadline` rather than
/// `timeout` after its first poll. `timeout` is only used in the error.
pub fn with_deadline(
inner: SendableRecordBatchStream,
timeout: std::time::Duration,
deadline: tokio::time::Instant,
) -> Self {
Self {
inner,
state: TimeoutState::Started {
deadline: Box::pin(tokio::time::sleep_until(deadline)),
timeout,
},
}
}
fn timeout_error(timeout: &std::time::Duration) -> DataFusionError {
DataFusionError::Execution(format!("Query timeout after {} ms", timeout.as_millis()))
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "lance-linalg"
version = "15.0.0-beta.15"
version = "15.0.0-beta.16"
publish = false
edition = { workspace = true }
license = { workspace = true }
+2 -2
View File
@@ -1,5 +1,5 @@
This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.15`
(commit `a826a940d550ee1f3bb5b470c3e10e670c1e38ce`), licensed under Apache-2.0.
This directory contains `rust/lance-linalg` from Lance tag `v15.0.0-beta.16`
(commit `03b7ff329e656636c581f1e3547048101990bc1f`), 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