diff --git a/.bumpversion.toml b/.bumpversion.toml index 8d67bac3c..fec283ac1 100644 --- a/.bumpversion.toml +++ b/.bumpversion.toml @@ -1,5 +1,5 @@ [tool.bumpversion] -current_version = "0.42.0-beta.36" +current_version = "0.42.0-beta.37" parse = """(?x) (?P0|[1-9]\\d*)\\. (?P0|[1-9]\\d*)\\. diff --git a/Cargo.lock b/Cargo.lock index 6ce7d3fe8..685c843c7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3885,8 +3885,8 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" [[package]] name = "fsst" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-array", "rand 0.9.5", @@ -5364,8 +5364,8 @@ checksum = "e037a2e1d8d5fdbd49b16a4ea09d5d6401c1f29eca5ff29d03d3824dba16256a" [[package]] name = "lance" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arc-swap", "arrow", @@ -5441,8 +5441,8 @@ dependencies = [ [[package]] name = "lance-arrow" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-array", "arrow-buffer", @@ -5465,8 +5465,8 @@ dependencies = [ [[package]] name = "lance-bitpacking" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrayref", "crunchy", @@ -5476,8 +5476,8 @@ dependencies = [ [[package]] name = "lance-core" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-array", "arrow-buffer", @@ -5515,8 +5515,8 @@ dependencies = [ [[package]] name = "lance-datafusion" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow", "arrow-array", @@ -5547,8 +5547,8 @@ dependencies = [ [[package]] name = "lance-datafusion-exec" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow", "arrow-array", @@ -5574,8 +5574,8 @@ dependencies = [ [[package]] name = "lance-datagen" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow", "arrow-array", @@ -5592,8 +5592,8 @@ dependencies = [ [[package]] name = "lance-derive" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "proc-macro2", "quote", @@ -5602,8 +5602,8 @@ dependencies = [ [[package]] name = "lance-encoding" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-arith", "arrow-array", @@ -5637,8 +5637,8 @@ dependencies = [ [[package]] name = "lance-file" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-arith", "arrow-array", @@ -5668,8 +5668,8 @@ dependencies = [ [[package]] name = "lance-geo" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-array", "arrow-schema", @@ -5700,8 +5700,8 @@ dependencies = [ [[package]] name = "lance-index" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arc-swap", "arrow", @@ -5773,8 +5773,8 @@ dependencies = [ [[package]] name = "lance-index-core" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-array", "arrow-schema", @@ -5797,8 +5797,8 @@ dependencies = [ [[package]] name = "lance-io" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow", "arrow-array", @@ -5843,8 +5843,8 @@ dependencies = [ [[package]] name = "lance-jsonb" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "byteorder", "ethnum", @@ -5861,7 +5861,7 @@ dependencies = [ [[package]] name = "lance-linalg" -version = "16.0.0-beta.3" +version = "16.0.0-beta.4" dependencies = [ "approx", "argminmax 0.7.1", @@ -5883,8 +5883,8 @@ dependencies = [ [[package]] name = "lance-namespace" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow", "async-trait", @@ -5898,8 +5898,8 @@ dependencies = [ [[package]] name = "lance-namespace-impls" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arc-swap", "arrow", @@ -5953,8 +5953,8 @@ dependencies = [ [[package]] name = "lance-select" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-array", "arrow-buffer", @@ -5968,8 +5968,8 @@ dependencies = [ [[package]] name = "lance-table" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow", "arrow-array", @@ -6010,8 +6010,8 @@ dependencies = [ [[package]] name = "lance-table-runtime" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-array", "arrow-buffer", @@ -6055,8 +6055,8 @@ dependencies = [ [[package]] name = "lance-testing" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "arrow-array", "arrow-schema", @@ -6069,8 +6069,8 @@ dependencies = [ [[package]] name = "lance-tokenizer" -version = "16.0.0-beta.3" -source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.3#a93690c0a82ad8ea5e0dd621e3a311a5fce9a487" +version = "16.0.0-beta.4" +source = "git+https://github.com/lance-format/lance.git?tag=v16.0.0-beta.4#1686234925dde0289409fa31ff615d724943ccb6" dependencies = [ "frostem", "icu_segmenter", @@ -6083,7 +6083,7 @@ dependencies = [ [[package]] name = "lancedb" -version = "0.42.0-beta.36" +version = "0.42.0-beta.37" dependencies = [ "ahash", "anyhow", @@ -6194,7 +6194,7 @@ dependencies = [ [[package]] name = "lancedb-cli" -version = "0.42.0-beta.36" +version = "0.42.0-beta.37" dependencies = [ "anyhow", "arrow-array", @@ -6237,7 +6237,7 @@ dependencies = [ [[package]] name = "lancedb-nodejs" -version = "0.42.0-beta.36" +version = "0.42.0-beta.37" dependencies = [ "arrow-array", "arrow-buffer", @@ -6263,7 +6263,7 @@ dependencies = [ [[package]] name = "lancedb-python" -version = "0.42.0-beta.36" +version = "0.42.0-beta.37" dependencies = [ "arc-swap", "arrow", diff --git a/Cargo.toml b/Cargo.toml index 4d09bf2a8..954516f62 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,20 +20,20 @@ categories = ["database-implementations"] rust-version = "1.98.0" [workspace.dependencies] -lance = { "version" = "=16.0.0-beta.3", default-features = false, "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-core = { "version" = "=16.0.0-beta.3", "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-datagen = { "version" = "=16.0.0-beta.3", "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-file = { "version" = "=16.0.0-beta.3", "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-io = { "version" = "=16.0.0-beta.3", default-features = false, "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-index = { "version" = "=16.0.0-beta.3", "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-jsonb = { "version" = "=16.0.0-beta.3", "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace = { "version" = "=16.0.0-beta.3", "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-namespace-impls = { "version" = "=16.0.0-beta.3", default-features = false, "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-table = { "version" = "=16.0.0-beta.3", "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-testing = { "version" = "=16.0.0-beta.3", "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-datafusion = { "version" = "=16.0.0-beta.3", "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-encoding = { "version" = "=16.0.0-beta.3", "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } -lance-arrow = { "version" = "=16.0.0-beta.3", "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance = { "version" = "=16.0.0-beta.4", default-features = false, "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-core = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-datagen = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-file = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-io = { "version" = "=16.0.0-beta.4", default-features = false, "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-index = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-jsonb = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-namespace-impls = { "version" = "=16.0.0-beta.4", default-features = false, "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-table = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-testing = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-datafusion = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-encoding = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } +lance-arrow = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } lancedb = { path = "rust/lancedb", default-features = false } ahash = "0.8" anyhow = "1" diff --git a/docs/src/java/java.md b/docs/src/java/java.md index 36d3f2031..d392faec8 100644 --- a/docs/src/java/java.md +++ b/docs/src/java/java.md @@ -14,7 +14,7 @@ Add the following dependency to your `pom.xml`: com.lancedb lancedb-core - 0.42.0-beta.36 + 0.42.0-beta.37 ``` diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index afd2b897f..ad20d1e0a 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1229,6 +1229,67 @@ rows depending on how they match. *** +### openBlobFile() + +```ts +openBlobFile(_descriptor, _options?): Promise +``` + +Opens a lazy handle from a source-bearing SQL `blob_descriptor` result. + +The descriptor's source pins the table version, branch, column and row +identity, so opening does not change this table's checkout. Null +descriptors return `null`. Payload bytes load only when the returned +handle is read. Pass BlobReadOptions.signal to cancel the open. + +#### Parameters + +* **\_descriptor**: `null` \| [`BlobDescriptor`](../interfaces/BlobDescriptor.md) + +* **\_options?**: [`BlobReadOptions`](../type-aliases/BlobReadOptions.md) + +#### Returns + +`Promise`<`null` \| [`BlobFile`](BlobFile.md)> + +#### Example + +```ts +const rows = await table + .query() + .select({ video: "blob_descriptor(video)" }) + .toArray(); +const handle = await table.openBlobFile(rows[0].video); +if (handle) { + const header = await handle.readRange(0n, 16n); + await handle.close(); +} +``` + +*** + +### openBlobFiles() + +```ts +openBlobFiles(descriptors, options?): AsyncGenerator +``` + +Opens source-bearing descriptors in iteration order, preserving nulls. +Handles open lazily as the iterable advances. Close each non-null handle +after use. + +#### Parameters + +* **descriptors**: `Iterable`<`null` \| [`BlobDescriptor`](../interfaces/BlobDescriptor.md)> + +* **options?**: [`BlobReadOptions`](../type-aliases/BlobReadOptions.md) + +#### Returns + +`AsyncGenerator`<`null` \| [`BlobFile`](BlobFile.md), `any`, `unknown`> + +*** + ### optimize() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 33fbe1176..e98ddccaf 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -63,6 +63,8 @@ - [AddDataOptions](interfaces/AddDataOptions.md) - [AddResult](interfaces/AddResult.md) - [AlterColumnsResult](interfaces/AlterColumnsResult.md) +- [BlobDescriptor](interfaces/BlobDescriptor.md) +- [BlobDescriptorSource](interfaces/BlobDescriptorSource.md) - [BranchColumnChange](interfaces/BranchColumnChange.md) - [BranchColumnSummary](interfaces/BranchColumnSummary.md) - [BranchDiff](interfaces/BranchDiff.md) diff --git a/docs/src/js/interfaces/BlobDescriptor.md b/docs/src/js/interfaces/BlobDescriptor.md new file mode 100644 index 000000000..7576b856f --- /dev/null +++ b/docs/src/js/interfaces/BlobDescriptor.md @@ -0,0 +1,59 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / BlobDescriptor + +# Interface: BlobDescriptor + +A source-bearing Blob V2 descriptor accepted by [Table.openBlobFile](../classes/Table.md#openblobfile). +Query results expose these fields as an Arrow struct. The source pins the +table version, branch, column and row identity used to open the handle. + +## Properties + +### blob\_id + +```ts +blob_id: number; +``` + +*** + +### blob\_uri + +```ts +blob_uri: string; +``` + +*** + +### kind + +```ts +kind: number; +``` + +*** + +### position + +```ts +position: number | bigint; +``` + +*** + +### size + +```ts +size: number | bigint; +``` + +*** + +### source + +```ts +source: BlobDescriptorSource; +``` diff --git a/docs/src/js/interfaces/BlobDescriptorSource.md b/docs/src/js/interfaces/BlobDescriptorSource.md new file mode 100644 index 000000000..994adec39 --- /dev/null +++ b/docs/src/js/interfaces/BlobDescriptorSource.md @@ -0,0 +1,66 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / BlobDescriptorSource + +# Interface: BlobDescriptorSource + +A source-bearing Blob V2 descriptor returned by the SQL `blob_descriptor` +function. Field names match the descriptor object/Arrow struct shape. + +## Properties + +### branch? + +```ts +optional branch: null | string; +``` + +*** + +### column + +```ts +column: string; +``` + +*** + +### committed\_at\_micros + +```ts +committed_at_micros: number | bigint; +``` + +*** + +### row\_is\_address + +```ts +row_is_address: boolean; +``` + +*** + +### row\_reference + +```ts +row_reference: number | bigint; +``` + +*** + +### uri + +```ts +uri: string; +``` + +*** + +### version + +```ts +version: number | bigint; +``` diff --git a/docs/web-tests/blob-v2/ts/multimodal.test.ts b/docs/web-tests/blob-v2/ts/multimodal.test.ts index b253ee9b2..c3ba5b9e7 100644 --- a/docs/web-tests/blob-v2/ts/multimodal.test.ts +++ b/docs/web-tests/blob-v2/ts/multimodal.test.ts @@ -78,16 +78,14 @@ test("blob column tutorial", async () => { assert.equal(payloads.length, 2); // --8<-- [start:blob_api_ranges] - const [secondImage] = await blobTable.fetchBlobFiles("image", [rowIds[1]!]); - const parts = await secondImage!.readRanges([ - { start: 0n, end: 6n }, - { start: 7n, end: 12n }, + const slices = await blobTable.fetchBlobRanges("image", [ + { rowId: rowIds[0]!, offset: 0n, length: 6n }, + { rowId: rowIds[1]!, offset: 7n, length: 5n }, ]); - await secondImage!.close(); // --8<-- [end:blob_api_ranges] assert.deepEqual( - parts.map((part) => part.toString("utf8")), - ["second", "image"], + slices.map((slice) => slice!.toString("utf8")), + ["inline", "image"], ); // --8<-- [start:blob_api_bytes_mode] diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 8c42f2122..fef2a5707 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -819,11 +819,7 @@ The other fetch methods load bytes directly: | Need | Python | TypeScript | Rust | | --- | --- | --- | --- | | Whole payloads for a set of rows | `fetch_blobs` | `fetchBlobs` | `fetch_blobs` | -| Byte slices across many rows in one call | `fetch_blob_ranges` | Not available. Use `fetchBlobFiles` and `readRanges`. | `fetch_blob_ranges` | - -{/* Draft for the TypeScript cross-row Blob range release. Replace the row above: | Byte slices across many rows in one call | `fetch_blob_ranges` | `fetchBlobRanges` | `fetch_blob_ranges` | -*/} - `fetch_blobs` returns the full bytes for each row ID in order. Null blobs produce null entries, and empty blobs produce empty byte strings. @@ -848,22 +844,17 @@ The other fetch methods load bytes directly: -{/* Draft for the TypeScript cross-row Blob range release. -Upcoming-release draft: TypeScript adds `fetchBlobRanges` for cross-row slices. -Until that SDK release is available, use `fetchBlobFiles` and `readRanges`. -Server-side batching requires a deployment with the validated range capability; -older servers continue using the descriptor and Range path selected before the -read. An error from the selected batched endpoint is returned without fallback. -A batched call keeps the native snapshot identity from its first range response -across every partition and requires each serving node to verify it. Missing identity -support or a replaced/deleted snapshot fails the whole call; upgrade all serving -nodes before selecting the batched endpoint with a new SDK. -Custom TypeScript `Table` subclasses must implement the new abstract method. +TypeScript `fetchBlobRanges` uses the batched `/fetch_blob_ranges` endpoint when +the server advertises the range capability; older servers use descriptor queries +and Range reads. An error from the selected endpoint is returned without +fallback. The call keeps the native snapshot identity from its first response +across every partition, so missing identity support or a replaced snapshot fails +the whole call. Upgrade every serving node before selecting the batched endpoint +with a new SDK. -*/} -Python and Rust read slices across rows with `fetch_blob_ranges`. On a handle, +All three SDKs read slices across rows with the range API. On a handle, `read_ranges` reads more than one slice of one blob. Python takes `(offset, length)` pairs, TypeScript takes `{ start, end }` ranges with an exclusive `end`, and Rust takes `start..end` ranges: @@ -874,14 +865,6 @@ exclusive `end`, and Rust takes `start..end` ranges: - {/* Draft for the TypeScript cross-row Blob range release. - {`// Upcoming-release draft: slices from more than one row. -const slices = await blobTable.fetchBlobRanges("image", [ - { rowId: rowIds[0]!, offset: 0n, length: 6n }, - { rowId: rowIds[1]!, offset: 7n, length: 5n }, -]); -`}{"\n"} - */} {TsBlobApiRanges} diff --git a/docs/web/snippets/multimodal.mdx b/docs/web/snippets/multimodal.mdx index 19180dfd0..db8059e07 100644 --- a/docs/web/snippets/multimodal.mdx +++ b/docs/web/snippets/multimodal.mdx @@ -42,7 +42,7 @@ export const TsBlobApiFiles = "const rows = await blobTable\n .query()\n .sele export const TsBlobApiIngest = "const blobTable = await db.createEmptyTable(\"photos\", blobSchema, {\n mode: \"overwrite\",\n});\n\nawait blobTable.add([\n { id: 1n, label: \"door\", image: Buffer.from(\"inline_image_bytes\") },\n { id: 2n, label: \"window\", image: Buffer.from(\"second_image_bytes\") },\n]);\n"; -export const TsBlobApiRanges = "const [secondImage] = await blobTable.fetchBlobFiles(\"image\", [rowIds[1]!]);\nconst parts = await secondImage!.readRanges([\n { start: 0n, end: 6n },\n { start: 7n, end: 12n },\n]);\nawait secondImage!.close();\n"; +export const TsBlobApiRanges = "const slices = await blobTable.fetchBlobRanges(\"image\", [\n { rowId: rowIds[0]!, offset: 0n, length: 6n },\n { rowId: rowIds[1]!, offset: 7n, length: 5n },\n]);\n"; export const TsBlobApiSchema = "const blobSchema = new arrow.Schema([\n new arrow.Field(\"id\", new arrow.Int64()),\n new arrow.Field(\"label\", new arrow.Utf8()),\n lancedb.blob(\"image\"),\n]);\n"; diff --git a/docs/web/sql/dql/blob-descriptor.mdx b/docs/web/sql/dql/blob-descriptor.mdx index 7ba83311c..49b4fe391 100644 --- a/docs/web/sql/dql/blob-descriptor.mdx +++ b/docs/web/sql/dql/blob-descriptor.mdx @@ -27,6 +27,33 @@ rows = db.execute_query("SELECT id, blob_descriptor(video) AS descriptor FROM vi with table.open_blob_file(rows[0]["descriptor"]) as reader: payload = reader.read() ``` + +```typescript TypeScript icon="typescript" +const rows = await table + .query() + .select({ descriptor: "blob_descriptor(video)" }) + .toArray(); +const reader = await table.openBlobFile(rows[0].descriptor); +if (reader) { + const payload = await reader.read(); + await reader.close(); +} +``` + +```rust Rust icon="rust" +use lancedb::{blob::BlobDescriptor, Table}; + +async fn read_descriptor( + table: &Table, + descriptor: &BlobDescriptor, +) -> lancedb::Result<()> { + let reader = table.open_blob_file(descriptor).await?; + let payload = reader.read().await?; + println!("{} bytes", payload.len()); + reader.close().await?; + Ok(()) +} +``` A descriptor is pinned to the table version it was read at: it keeps diff --git a/java/lancedb-core/pom.xml b/java/lancedb-core/pom.xml index 2942ad115..250dcbda8 100644 --- a/java/lancedb-core/pom.xml +++ b/java/lancedb-core/pom.xml @@ -8,7 +8,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.36 + 0.42.0-beta.37 ../pom.xml diff --git a/java/pom.xml b/java/pom.xml index 035fe0273..a0a2a6ee3 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -6,7 +6,7 @@ com.lancedb lancedb-parent - 0.42.0-beta.36 + 0.42.0-beta.37 pom ${project.artifactId} LanceDB Java SDK Parent POM @@ -28,7 +28,7 @@ UTF-8 15.0.0 - 16.0.0-beta.3 + 16.0.0-beta.4 2.18.12 false 2.30.0 diff --git a/nodejs/Cargo.toml b/nodejs/Cargo.toml index 15cd7390e..2c44d4471 100644 --- a/nodejs/Cargo.toml +++ b/nodejs/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "lancedb-nodejs" edition.workspace = true -version = "0.42.0-beta.36" +version = "0.42.0-beta.37" publish = false license.workspace = true description.workspace = true diff --git a/nodejs/__test__/blob_open.test.ts b/nodejs/__test__/blob_open.test.ts new file mode 100644 index 000000000..34d1c764c --- /dev/null +++ b/nodejs/__test__/blob_open.test.ts @@ -0,0 +1,257 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { + type BlobDescriptor, + type Connection, + type Table, + connect, +} from "../lancedb"; + +jest.setTimeout(15000); + +const IDENTITY = `v1:${"a".repeat(64)}`; +const MIB = 1024 * 1024; + +function descriptor(size: bigint): BlobDescriptor { + return { + kind: 2, + position: 0n, + size, + // biome-ignore lint/style/useNamingConvention: Matches the descriptor. + blob_id: 1, + // biome-ignore lint/style/useNamingConvention: Matches the descriptor. + blob_uri: "", + source: { + uri: "s3://fixture/table.lance", + version: 46n, + // biome-ignore lint/style/useNamingConvention: Matches the descriptor. + committed_at_micros: 1795627189287568n, + branch: null, + column: "image", + // biome-ignore lint/style/useNamingConvention: Matches the descriptor. + row_reference: 0n, + // biome-ignore lint/style/useNamingConvention: Matches the descriptor. + row_is_address: false, + }, + }; +} + +async function readBody(req: import("node:http").IncomingMessage) { + const chunks: Buffer[] = []; + for await (const chunk of req) { + chunks.push(chunk as Buffer); + } + return Buffer.concat(chunks).toString(); +} + +async function withOpenServer( + run: ( + db: Connection, + table: Table, + state: { + directStatus: number; + blobLocationsCalls: number; + objectCalls: number; + proxyCalls: number; + lastLocationBody: Record | undefined; + }, + ) => Promise, + size: bigint = 10n * BigInt(MIB), +) { + let port = 0; + const state = { + directStatus: 200, + blobLocationsCalls: 0, + objectCalls: 0, + proxyCalls: 0, + lastLocationBody: undefined as Record | undefined, + }; + const payload = Buffer.alloc(Number(size), 0x61); + const server = createServer(async (req, res) => { + const url = req.url ?? ""; + if (url === "/v1/table/test/describe/") { + res.writeHead(200, { + "content-type": "application/json", + "phalanx-version": "1.15.0-beta.0", + "x-lancedb-blob-locations": "1", + }); + res.end(JSON.stringify({ version: 46, schema: { fields: [] } })); + return; + } + if (url === "/v1/table/test/blob_locations/") { + state.blobLocationsCalls++; + const body = JSON.parse(await readBody(req)) as Record; + state.lastLocationBody = body; + if (state.directStatus !== 200) { + res.writeHead(state.directStatus).end("resolver unavailable"); + return; + } + res.writeHead(200, { + "content-type": "application/json", + "x-lancedb-version": "46", + "x-lancedb-query-snapshot": IDENTITY, + }); + res.end( + JSON.stringify({ + sources: [ + { + url: `http://127.0.0.1:${port}/object?signature=test`, + // biome-ignore lint/style/useNamingConvention: Matches the resolver response. + expires_at_unix_secs: 4102444800, + }, + ], + items: [ + { + kind: "presigned", + // biome-ignore lint/style/useNamingConvention: Matches the resolver response. + source_index: 0, + offset: 0, + size: Number(size), + }, + ], + }), + ); + return; + } + if (url.startsWith("/object")) { + state.objectCalls++; + const range = req.headers.range ?? ""; + const match = /^bytes=(\d+)-(\d+)$/.exec(range); + if (match === null) { + res.writeHead(416).end(); + return; + } + const start = Number(match[1]); + const end = Number(match[2]); + const body = payload.subarray(start, end + 1); + res.writeHead(206, { + "content-range": `bytes ${start}-${end}/${size}`, + "content-length": body.length, + "x-lancedb-version": "46", + "x-lancedb-query-snapshot": IDENTITY, + connection: "close", + }); + res.end(body); + return; + } + if (url.startsWith("/v1/table/test/blob/image/0/bytes")) { + state.proxyCalls++; + const range = req.headers.range ?? ""; + const match = /^bytes=(\d+)-(\d+)$/.exec(range); + if (match === null) { + res.writeHead(416).end(); + return; + } + const start = Number(match[1]); + const end = Number(match[2]); + const body = payload.subarray(start, end + 1); + res.writeHead(206, { + "content-range": `bytes ${start}-${end}/${size}`, + "content-length": body.length, + "x-lancedb-version": "46", + "x-lancedb-query-snapshot": IDENTITY, + connection: "close", + }); + res.end(body); + return; + } + res.writeHead(404).end(`unexpected request: ${req.method} ${url}`); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + port = (server.address() as AddressInfo).port; + const db = await connect("db://dev", { + apiKey: "fake", + hostOverride: `http://127.0.0.1:${port}`, + clientConfig: { timeoutConfig: { timeout: 10 } }, + }); + const table = await db.openTable("test"); + try { + await run(db, table, state); + } finally { + await new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }); + } +} + +describe("openBlobFile", () => { + it("opens a large descriptor through the direct resolver and reads bytes", async () => { + await withOpenServer(async (_db, table, state) => { + const handle = (await table.openBlobFile(descriptor(10n * BigInt(MIB))))!; + expect(handle).not.toBeNull(); + // Below the per-read threshold the same handle stays on the proxy. + expect(await handle.readRange(0n, 4n)).toEqual(Buffer.alloc(4, 0x61)); + expect(state.proxyCalls).toBe(1); + expect(state.objectCalls).toBe(0); + const large = await handle.readRange(0n, 10n * BigInt(MIB)); + expect(large.length).toBe(10 * MIB); + expect(large.equals(Buffer.alloc(10 * MIB, 0x61))).toBe(true); + expect(state.blobLocationsCalls).toBe(1); + expect(state.objectCalls).toBe(1); + expect(state.proxyCalls).toBe(1); + expect(state.lastLocationBody).toMatchObject({ + version: 46, + // biome-ignore lint/style/useNamingConvention: Matches the resolver body. + row_ids: [0], + // biome-ignore lint/style/useNamingConvention: Matches the resolver body. + source_uri: "s3://fixture/table.lance", + // biome-ignore lint/style/useNamingConvention: Matches the resolver body. + source_commit_micros: 1795627189287568, + // biome-ignore lint/style/useNamingConvention: Matches the resolver body. + row_is_address: false, + }); + await handle.close(); + }); + }); + + it("falls back to the proxy when the resolver returns 503", async () => { + await withOpenServer(async (_db, table, state) => { + state.directStatus = 503; + const handle = (await table.openBlobFile(descriptor(10n * BigInt(MIB))))!; + expect(handle).not.toBeNull(); + const large = await handle.readRange(0n, 10n * BigInt(MIB)); + expect(large.length).toBe(10 * MIB); + expect(large.equals(Buffer.alloc(10 * MIB, 0x61))).toBe(true); + expect(state.blobLocationsCalls).toBe(1); + expect(state.objectCalls).toBe(0); + expect(state.proxyCalls).toBe(1); + await handle.close(); + }); + }); + + it("keeps descriptors below the direct threshold on the proxy path", async () => { + await withOpenServer(async (_db, table, state) => { + const handle = (await table.openBlobFile(descriptor(BigInt(MIB))))!; + expect(await handle.readRange(0n, 4n)).toEqual(Buffer.alloc(4, 0x61)); + expect(state.blobLocationsCalls).toBe(0); + expect(state.objectCalls).toBe(0); + expect(state.proxyCalls).toBe(1); + await handle.close(); + }, BigInt(MIB)); + }); + + it("preserves nulls and order in openBlobFiles", async () => { + await withOpenServer(async (_db, table, state) => { + const handles = []; + for await (const handle of table.openBlobFiles([ + null, + descriptor(10n * BigInt(MIB)), + null, + ])) { + handles.push(handle); + } + expect(handles[0]).toBeNull(); + expect(handles[1]).not.toBeNull(); + expect(handles[2]).toBeNull(); + expect(await handles[1]!.readRange(0n, 4n)).toEqual( + Buffer.alloc(4, 0x61), + ); + expect(state.blobLocationsCalls).toBe(1); + await handles[1]!.close(); + }); + }); +}); diff --git a/nodejs/lancedb/blob.ts b/nodejs/lancedb/blob.ts index be26f6121..0a67165b1 100644 --- a/nodejs/lancedb/blob.ts +++ b/nodejs/lancedb/blob.ts @@ -310,6 +310,80 @@ export class BlobFile { } } +/** + * A source-bearing Blob V2 descriptor returned by the SQL `blob_descriptor` + * function. Field names match the descriptor object/Arrow struct shape. + */ +export interface BlobDescriptorSource { + uri: string; + version: bigint | number; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + committed_at_micros: bigint | number; + branch?: string | null; + column: string; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + row_reference: bigint | number; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + row_is_address: boolean; +} + +/** + * A source-bearing Blob V2 descriptor accepted by {@link Table.openBlobFile}. + * Query results expose these fields as an Arrow struct. The source pins the + * table version, branch, column and row identity used to open the handle. + */ +export interface BlobDescriptor { + kind: number; + position: bigint | number; + size: bigint | number; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + blob_id: number; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + blob_uri: string; + source: BlobDescriptorSource; +} + +function descriptorBigInt(value: bigint | number, field: string): bigint { + if (typeof value === "bigint") { + if (value < 0n) { + throw new TypeError(`blob descriptor ${field} cannot be negative`); + } + return value; + } + if (!Number.isSafeInteger(value) || value < 0) { + throw new TypeError( + `blob descriptor ${field} must be a non-negative safe integer or bigint`, + ); + } + return BigInt(value); +} + +/** @ignore */ +export function toNativeBlobDescriptor(descriptor: BlobDescriptor) { + return { + kind: descriptor.kind, + position: descriptorBigInt(descriptor.position, "position"), + size: descriptorBigInt(descriptor.size, "size"), + blobId: descriptor.blob_id, + blobUri: descriptor.blob_uri, + source: { + uri: descriptor.source.uri, + version: descriptorBigInt(descriptor.source.version, "source.version"), + committedAtMicros: descriptorBigInt( + descriptor.source.committed_at_micros, + "source.committed_at_micros", + ), + branch: descriptor.source.branch ?? undefined, + column: descriptor.source.column, + rowReference: descriptorBigInt( + descriptor.source.row_reference, + "source.row_reference", + ), + rowIsAddress: descriptor.source.row_is_address, + }, + }; +} + /** Options for blob reads. */ export type BlobReadOptions = { /** diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 88f1bd921..58e1f0cde 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -93,6 +93,7 @@ export { } from "./arrow"; export { blob, isBlobField, BlobFile } from "./blob"; +export type { BlobDescriptor, BlobDescriptorSource } from "./blob"; export type { BlobData, BlobInput, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index a599bac2b..1bbcb4ac5 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -35,10 +35,12 @@ import { } from "./arrow"; import { + BlobDescriptor, BlobFile, BlobRangeRequest, BlobReadOptions, runWithSignal, + toNativeBlobDescriptor, } from "./blob"; import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry"; import { @@ -871,6 +873,48 @@ export abstract class Table { options?: BlobReadOptions, ): Promise<(BlobFile | null)[]>; + /** + * Opens a lazy handle from a source-bearing SQL `blob_descriptor` result. + * + * The descriptor's source pins the table version, branch, column and row + * identity, so opening does not change this table's checkout. Null + * descriptors return `null`. Payload bytes load only when the returned + * handle is read. Pass {@link BlobReadOptions.signal} to cancel the open. + * + * @example + * ```ts + * const rows = await table + * .query() + * .select({ video: "blob_descriptor(video)" }) + * .toArray(); + * const handle = await table.openBlobFile(rows[0].video); + * if (handle) { + * const header = await handle.readRange(0n, 16n); + * await handle.close(); + * } + * ``` + */ + async openBlobFile( + _descriptor: BlobDescriptor | null, + _options?: BlobReadOptions, + ): Promise { + throw new Error("openBlobFile is not supported on this table type"); + } + + /** + * Opens source-bearing descriptors in iteration order, preserving nulls. + * Handles open lazily as the iterable advances. Close each non-null handle + * after use. + */ + async *openBlobFiles( + descriptors: Iterable, + options?: BlobReadOptions, + ): AsyncGenerator { + for (const descriptor of descriptors) { + yield await this.openBlobFile(descriptor, options); + } + } + /** * Create a search query to find the nearest neighbors * of the given query @@ -1936,6 +1980,19 @@ export class LocalTable extends Table { ); } + async openBlobFile( + descriptor: BlobDescriptor | null, + options?: BlobReadOptions, + ): Promise { + if (descriptor == null) { + return null; + } + const file = await runWithSignal(options?.signal, (signal) => + this.inner.openBlobFile(toNativeBlobDescriptor(descriptor), signal), + ); + return BlobFile.fromNative(file); + } + query(): Query { return new Query(this.inner); } diff --git a/nodejs/npm/darwin-arm64/package.json b/nodejs/npm/darwin-arm64/package.json index e3609922a..fc6f1a7ea 100644 --- a/nodejs/npm/darwin-arm64/package.json +++ b/nodejs/npm/darwin-arm64/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-darwin-arm64", - "version": "0.42.0-beta.36", + "version": "0.42.0-beta.37", "os": ["darwin"], "cpu": ["arm64"], "main": "lancedb.darwin-arm64.node", diff --git a/nodejs/npm/linux-arm64-gnu/package.json b/nodejs/npm/linux-arm64-gnu/package.json index a922a144c..41aa1cf3a 100644 --- a/nodejs/npm/linux-arm64-gnu/package.json +++ b/nodejs/npm/linux-arm64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-gnu", - "version": "0.42.0-beta.36", + "version": "0.42.0-beta.37", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-gnu.node", diff --git a/nodejs/npm/linux-arm64-musl/package.json b/nodejs/npm/linux-arm64-musl/package.json index ae5a4cfb1..44b9dc419 100644 --- a/nodejs/npm/linux-arm64-musl/package.json +++ b/nodejs/npm/linux-arm64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-arm64-musl", - "version": "0.42.0-beta.36", + "version": "0.42.0-beta.37", "os": ["linux"], "cpu": ["arm64"], "main": "lancedb.linux-arm64-musl.node", diff --git a/nodejs/npm/linux-x64-gnu/package.json b/nodejs/npm/linux-x64-gnu/package.json index 2cb10fd7d..48940a19f 100644 --- a/nodejs/npm/linux-x64-gnu/package.json +++ b/nodejs/npm/linux-x64-gnu/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-gnu", - "version": "0.42.0-beta.36", + "version": "0.42.0-beta.37", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-gnu.node", diff --git a/nodejs/npm/linux-x64-musl/package.json b/nodejs/npm/linux-x64-musl/package.json index c50637259..456cc5d97 100644 --- a/nodejs/npm/linux-x64-musl/package.json +++ b/nodejs/npm/linux-x64-musl/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-linux-x64-musl", - "version": "0.42.0-beta.36", + "version": "0.42.0-beta.37", "os": ["linux"], "cpu": ["x64"], "main": "lancedb.linux-x64-musl.node", diff --git a/nodejs/npm/win32-arm64-msvc/package.json b/nodejs/npm/win32-arm64-msvc/package.json index 33459cce1..f2d77f108 100644 --- a/nodejs/npm/win32-arm64-msvc/package.json +++ b/nodejs/npm/win32-arm64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-arm64-msvc", - "version": "0.42.0-beta.36", + "version": "0.42.0-beta.37", "os": [ "win32" ], diff --git a/nodejs/npm/win32-x64-msvc/package.json b/nodejs/npm/win32-x64-msvc/package.json index 6a2e9d87d..f7f192b6d 100644 --- a/nodejs/npm/win32-x64-msvc/package.json +++ b/nodejs/npm/win32-x64-msvc/package.json @@ -1,6 +1,6 @@ { "name": "@lancedb/lancedb-win32-x64-msvc", - "version": "0.42.0-beta.36", + "version": "0.42.0-beta.37", "os": ["win32"], "cpu": ["x64"], "main": "lancedb.win32-x64-msvc.node", diff --git a/nodejs/package.json b/nodejs/package.json index 4aab4e65c..4f89a79e6 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -11,7 +11,7 @@ "ann" ], "private": false, - "version": "0.42.0-beta.36", + "version": "0.42.0-beta.37", "main": "dist/index.js", "exports": { ".": "./dist/index.js", diff --git a/nodejs/src/blob.rs b/nodejs/src/blob.rs index b55154019..b8f563103 100644 --- a/nodejs/src/blob.rs +++ b/nodejs/src/blob.rs @@ -8,13 +8,66 @@ use std::sync::atomic::{AtomicBool, Ordering}; use arrow_array::{Array, LargeBinaryArray}; use futures::future::abortable; -use lancedb::blob::BlobFile as LanceBlobFile; +use lancedb::blob::{ + BlobDescriptor as LanceBlobDescriptor, BlobDescriptorSource as LanceBlobDescriptorSource, + BlobFile as LanceBlobFile, +}; use napi::Env; use napi::bindgen_prelude::*; use napi_derive::napi; use crate::error::convert_error; +#[napi(object)] +pub struct BlobDescriptorInputSource { + pub uri: String, + pub version: BigInt, + pub committed_at_micros: BigInt, + pub branch: Option, + pub column: String, + pub row_reference: BigInt, + pub row_is_address: bool, +} + +#[napi(object)] +pub struct BlobDescriptorInput { + pub kind: u32, + pub position: BigInt, + pub size: BigInt, + pub blob_id: u32, + pub blob_uri: String, + pub source: BlobDescriptorInputSource, +} + +impl BlobDescriptorInput { + pub(crate) fn into_descriptor(self) -> napi::Result { + Ok(LanceBlobDescriptor { + kind: u8::try_from(self.kind).map_err(|_| { + napi::Error::from_reason("blob descriptor kind must be between 0 and 255") + })?, + position: parse_u64(self.position, "blob descriptor position")?, + size: parse_u64(self.size, "blob descriptor size")?, + blob_id: self.blob_id, + blob_uri: self.blob_uri, + source: LanceBlobDescriptorSource { + uri: self.source.uri, + version: parse_u64(self.source.version, "blob descriptor source version")?, + committed_at_micros: parse_u64( + self.source.committed_at_micros, + "blob descriptor source committed_at_micros", + )?, + branch: self.source.branch, + column: self.source.column, + row_reference: parse_u64( + self.source.row_reference, + "blob descriptor source row_reference", + )?, + row_is_address: self.source.row_is_address, + }, + }) + } +} + #[napi(object)] pub struct BlobRange { pub start: BigInt, diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 098b7ce0b..536be3cd5 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -19,7 +19,10 @@ use napi::bindgen_prelude::*; use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi_derive::napi; -use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable}; +use crate::blob::{ + BlobDescriptorInput, BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, + spawn_abortable, +}; use crate::error::{NapiErrorExt, convert_error}; use crate::index::Index; use crate::iterator::RecordBatchIterator; @@ -626,6 +629,21 @@ impl Table { }) } + #[napi(catch_unwind)] + pub fn open_blob_file<'env>( + &self, + env: &'env Env, + descriptor: BlobDescriptorInput, + signal: Option, + ) -> napi::Result> { + let descriptor = descriptor.into_descriptor()?; + let table = self.inner_ref()?.clone(); + spawn_abortable(env, signal, async move { + let file = table.open_blob_file(&descriptor).await.default_error()?; + Ok(BlobFile::new(file)) + }) + } + #[napi(catch_unwind)] pub fn vector_search(&self, vector: Float32Array) -> napi::Result { self.query()?.nearest_to(vector) diff --git a/python/Cargo.toml b/python/Cargo.toml index 30928a3b8..c7db5fa5b 100644 --- a/python/Cargo.toml +++ b/python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-python" -version = "0.42.0-beta.36" +version = "0.42.0-beta.37" publish = false edition.workspace = true description = "Python bindings for LanceDB" diff --git a/python/pyproject.toml b/python/pyproject.toml index 99f4d8e71..b0fa12adc 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -64,7 +64,7 @@ tests = [ "polars>=0.19, <=1.32.3", "pyarrow>=16", "pyarrow-stubs>=16.0", - "pylance==16.0.0b3", + "pylance==16.0.0b4", "requests>=2.31.0", "datafusion>=54,<55", "opentelemetry-sdk>=1.30.0", diff --git a/python/python/tests/test_function_creation.py b/python/python/tests/test_function_creation.py index 0d9669693..ae5a2bf8b 100644 --- a/python/python/tests/test_function_creation.py +++ b/python/python/tests/test_function_creation.py @@ -175,6 +175,13 @@ async def test_function_index_inspection_is_separate_from_registration(with_prim def do_get(self, context, ticket): self.requests.append(ticket.ticket) + if b"DESCRIBE FUNCTION" in ticket.ticket: + assert b"FORMAT JSON" in ticket.ticket + return flight.RecordBatchStream( + pa.table( + {"description": [json.dumps(stored)]} + ).replace_schema_metadata({b"lancedb.describe.format": b"json"}) + ) return flight.RecordBatchStream( pa.table({"definition": [json.dumps(stored)]}) ) @@ -214,7 +221,8 @@ async def test_function_index_inspection_is_separate_from_registration(with_prim version = db.get_function(name, version=1) assert await async_db.get_function(name, version="1") == version assert all( - f"DESCRIBE FUNCTION \"{name}\" WITH (version = '1')".encode() in ticket + f"DESCRIBE FUNCTION \"{name}\" WITH (version = '1') FORMAT JSON".encode() + in ticket for ticket in server.requests ) assert len(server.requests) == 2 diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index 8aac9698c..22995a8e1 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -92,10 +92,13 @@ async def test_remote_refresh_reports_unknown_metrics( return flight.RecordBatchStream( pa.table( { - "name": ["view"], - "query": ["SELECT * FROM source"], + "description": [ + json.dumps( + {"name": "view", "query": "SELECT * FROM source"} + ) + ], } - ) + ).replace_schema_metadata({b"lancedb.describe.format": b"json"}) ) assert b"REFRESH MATERIALIZED VIEW" in ticket.ticket # SQL completion carries no refresh statistics. @@ -151,7 +154,8 @@ async def test_remote_refresh_reports_unknown_metrics( assert len(describes) == 2 assert len(refreshes) == 1 assert all( - b'DESCRIBE MATERIALIZED VIEW "view"' in command for command in describes + b'DESCRIBE MATERIALIZED VIEW "view" FORMAT JSON' in command + for command in describes ) (refresh,) = refreshes assert b'REFRESH MATERIALIZED VIEW "view"' in refresh diff --git a/python/python/tests/test_storage_integration.py b/python/python/tests/test_storage_integration.py index 9f01f2bc2..c96f36059 100644 --- a/python/python/tests/test_storage_integration.py +++ b/python/python/tests/test_storage_integration.py @@ -66,6 +66,11 @@ def remote_server(text_type=pa.string()): ) elif b"DROP STORAGE INTEGRATION" in command: result = pa.table({"dropped": [True]}) + elif b"DESCRIBE STORAGE INTEGRATION" in command: + assert b"FORMAT JSON" in command + result = pa.table( + {"description": [json.dumps(info)]} + ).replace_schema_metadata({b"lancedb.describe.format": b"json"}) else: if b"STORAGE_PROVIDER = 'HUGGINGFACE'" in command: info.update( diff --git a/python/uv.lock b/python/uv.lock index 16660c1de..90b13bcb2 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -1912,7 +1912,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 = ">=16.0.0b2" }, - { name = "pylance", marker = "extra == 'tests'", specifier = "==16.0.0b3" }, + { name = "pylance", marker = "extra == 'tests'", specifier = "==16.0.0b4" }, { 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" }, @@ -3649,20 +3649,20 @@ crypto = [ [[package]] name = "pylance" -version = "16.0.0b3" +version = "16.0.0b4" source = { registry = "https://pypi.fury.io/lance-format/" } dependencies = [ { name = "lance-namespace" }, { name = "pyarrow" }, ] wheels = [ - { url = "https://pypi.fury.io/lance-format/-/ver_63znt/pylance-16.0.0b3-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:17d618aa63b739ada02057755134155c0bebf5e7aff947e15f01a6a64b0e20f3" }, - { url = "https://pypi.fury.io/lance-format/-/ver_tLDwa/pylance-16.0.0b3-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9e747e226318252b6184b3d08848e5e93535fb40e872f8475e6f4cf7542bb4ab" }, - { url = "https://pypi.fury.io/lance-format/-/ver_PugEU/pylance-16.0.0b3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:41b724717279af867739ddba4d8b86224e95bed5c58f065d5cf644d05225b2fb" }, - { url = "https://pypi.fury.io/lance-format/-/ver_2h6uhZ/pylance-16.0.0b3-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:be625835a369aef8509d28a77757eaf98b33986849ff017d9d84539b19f277f9" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1zFtjX/pylance-16.0.0b3-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:169bd83f3ed715328a4b417865495ed31aac221e4370b3030dd77a1c958feb9f" }, - { url = "https://pypi.fury.io/lance-format/-/ver_i4Lal/pylance-16.0.0b3-cp310-abi3-win_amd64.whl", hash = "sha256:03b883302492c128115da7453102f18e9ecffb8ed7eaaa879bfc5700bd47236c" }, - { url = "https://pypi.fury.io/lance-format/-/ver_1MGmbF/pylance-16.0.0b3-cp310-abi3-win_arm64.whl", hash = "sha256:201f95ceec019b43c278fa7da985b54534ddf4be5f63ca2a8996d92367c11f61" }, + { url = "https://pypi.fury.io/lance-format/-/ver_oJPBj/pylance-16.0.0b4-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:495789f4c6376aed8c5ad41fd04a828910120245e7d021cc2f59651f01ec7e45" }, + { url = "https://pypi.fury.io/lance-format/-/ver_bll8w/pylance-16.0.0b4-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7579acd634b3d1513bb836d437d1f13bc4eb76625b0795e65b583007b16f223b" }, + { url = "https://pypi.fury.io/lance-format/-/ver_2d4iLq/pylance-16.0.0b4-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e5cf1c63d612ac36141399ceff30f46be16e537cd4d01562bc0453e8d79f19e8" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1X7cLu/pylance-16.0.0b4-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:b478f6ffef5a4e938e5578a6ec8f5b00866098b253daadd8f704008851d58417" }, + { url = "https://pypi.fury.io/lance-format/-/ver_pZ4HP/pylance-16.0.0b4-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:be9d95a9d22dad0371139faf982297cdd918aded1d59bc3ab4dd27394f55ba79" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1M3BoM/pylance-16.0.0b4-cp310-abi3-win_amd64.whl", hash = "sha256:1f84164d895df4522722cc7f8f10eaa42449c3c997f25476fb07ab48ef3b2969" }, + { url = "https://pypi.fury.io/lance-format/-/ver_1AAGRf/pylance-16.0.0b4-cp310-abi3-win_arm64.whl", hash = "sha256:9423e6f4edef4f4048fab6cde69dd5cf2d2acdfc6dbe6171ce720753136b6b0a" }, ] [[package]] diff --git a/rust/lancedb/Cargo.toml b/rust/lancedb/Cargo.toml index 99005cd74..2e4a88af0 100644 --- a/rust/lancedb/Cargo.toml +++ b/rust/lancedb/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb" -version = "0.42.0-beta.36" +version = "0.42.0-beta.37" 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" = "=16.0.0-beta.3", "tag" = "v16.0.0-beta.3", "git" = "https://github.com/lance-format/lance.git" } +lance-linalg = { "version" = "=16.0.0-beta.4", "tag" = "v16.0.0-beta.4", "git" = "https://github.com/lance-format/lance.git" } lance-encoding = { workspace = true } lance-arrow = { workspace = true } lance-namespace = { workspace = true } diff --git a/rust/lancedb/cli/Cargo.toml b/rust/lancedb/cli/Cargo.toml index 4d445d64c..11c70510d 100644 --- a/rust/lancedb/cli/Cargo.toml +++ b/rust/lancedb/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lancedb-cli" -version = "0.42.0-beta.36" +version = "0.42.0-beta.37" edition = "2021" license.workspace = true repository.workspace = true diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index aa8b6f23a..5036d36e6 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1049,13 +1049,13 @@ impl Database for RemoteDatabase { let name = integration_sql::object_name(name, namespace_path)?; let result = self .execute_query_async(ExecuteQueryRequest { - query: format!("DESCRIBE STORAGE INTEGRATION {name}"), + query: format!("DESCRIBE STORAGE INTEGRATION {name} FORMAT JSON"), default_namespace_path: namespace_path.to_vec(), parameters: None, options: Default::default(), }) .await?; - integration_sql::decode_info(&result.reader().await?.try_collect::>().await?) + super::sql::description(result.reader().await?.try_collect::>().await?) } async fn list_storage_integrations( diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 68f53b10e..fda450e2c 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -38,6 +38,7 @@ use crate::sql::{Query, QueryDescription, QueryHandle, QueryStatus}; mod function; pub(super) mod materialized_view; mod objects; +pub(super) use objects::description; pub(super) mod receipt; mod secret; pub(super) use secret::SecretWriteOperation; diff --git a/rust/lancedb/src/remote/sql/function.rs b/rust/lancedb/src/remote/sql/function.rs index f2a12a024..d147fb374 100644 --- a/rust/lancedb/src/remote/sql/function.rs +++ b/rust/lancedb/src/remote/sql/function.rs @@ -4,7 +4,7 @@ use super::{ SqlClient, materialized_view::quote_identifier, - objects::{definition, literal, string_lists, strings}, + objects::{definition, description, literal, string_lists, strings}, }; use crate::{ database::ExecuteQueryRequest, @@ -72,14 +72,14 @@ impl SqlClient { self.object_job( ExecuteQueryRequest { query: format!( - "DESCRIBE FUNCTION {}{version_clause}", + "DESCRIBE FUNCTION {}{version_clause} FORMAT JSON", quote_identifier(name) ), default_namespace_path: namespace.to_vec(), parameters: None, options: Default::default(), }, - definition, + description, ) .await? .wait() diff --git a/rust/lancedb/src/remote/sql/materialized_view.rs b/rust/lancedb/src/remote/sql/materialized_view.rs index c87adc9ec..b8b9fc2f7 100644 --- a/rust/lancedb/src/remote/sql/materialized_view.rs +++ b/rust/lancedb/src/remote/sql/materialized_view.rs @@ -3,11 +3,11 @@ use std::sync::Arc; -use arrow_array::{Array, RecordBatch, StringArray}; +use arrow_array::{Array, StringArray}; use futures::TryStreamExt; -use super::SqlClient; use super::receipt::ReceiptRow; +use super::{SqlClient, objects::description}; use crate::database::ExecuteQueryRequest; use crate::error::{Error, Result}; use crate::listing::{ListingOptions, ListingPage}; @@ -19,22 +19,9 @@ pub(in crate::remote) fn quote_identifier(name: &str) -> String { format!("\"{}\"", name.replace('"', "\"\"")) } -fn strings(batch: &RecordBatch, name: &str) -> Result> { - let values = batch - .column_by_name(name) - .and_then(|column| column.as_any().downcast_ref::()) - .ok_or_else(|| Error::Runtime { - message: format!("materialized-view SQL result is missing UTF-8 column '{name}'"), - })?; - if values.null_count() != 0 { - return Err(Error::Runtime { - message: format!("materialized-view SQL result contains null '{name}'"), - }); - } - Ok(values - .iter() - .map(|value| value.unwrap().to_owned()) - .collect()) +#[derive(serde::Deserialize)] +struct MaterializedViewMetadata { + query: String, } pub(in crate::remote) enum MaterializedViewJobSubmission { @@ -103,21 +90,19 @@ impl SqlClient { validate_namespace(namespace)?; let query = self .execute(ExecuteQueryRequest { - query: format!("DESCRIBE MATERIALIZED VIEW {}", quote_identifier(name)), + query: format!( + "DESCRIBE MATERIALIZED VIEW {} FORMAT JSON", + quote_identifier(name) + ), default_namespace_path: namespace.to_vec(), parameters: None, options: Default::default(), }) .await?; - let mut reader = query.reader().await?; - let mut definitions = Vec::new(); - while let Some(batch) = reader.try_next().await? { - definitions.extend(strings(&batch, "query")?); - } - let [definition_sql] = - <[String; 1]>::try_from(definitions).map_err(|_| Error::Runtime { - message: "DESCRIBE MATERIALIZED VIEW must return exactly one definition".into(), - })?; + let reader = query.reader().await?; + let metadata: MaterializedViewMetadata = + description(reader.try_collect::>().await?)?; + let definition_sql = metadata.query; let parsed_definition = MaterializedViewDefinition::from_sql(&definition_sql).ok(); Ok(MaterializedViewInfo { definition_sql, diff --git a/rust/lancedb/src/remote/sql/objects.rs b/rust/lancedb/src/remote/sql/objects.rs index 482fa46de..cbf40f576 100644 --- a/rust/lancedb/src/remote/sql/objects.rs +++ b/rust/lancedb/src/remote/sql/objects.rs @@ -154,6 +154,43 @@ pub(super) fn string_lists(batches: &[RecordBatch], name: &str) -> Result(batches: Vec) -> Result { + if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { + return Err(Error::Runtime { + message: "DESCRIBE FORMAT JSON must return exactly one document".into(), + }); + } + for batch in &batches { + if batch.num_columns() != 1 + || batch + .schema() + .metadata() + .get("lancedb.describe.format") + .map(String::as_str) + != Some("json") + || batch + .column_by_name("description") + .and_then(|column| column.as_any().downcast_ref::()) + .is_none() + { + return Err(Error::Runtime { message: "DESCRIBE FORMAT JSON requires one UTF8 description column with JSON format metadata".into() }); + } + } + let mut documents = strings(&batches, "description")?; + let document: serde_json::Value = + serde_json::from_str(&documents.remove(0)).map_err(|error| Error::Runtime { + message: format!("Invalid DESCRIBE JSON document: {error}"), + })?; + if !document.is_object() { + return Err(Error::Runtime { + message: "DESCRIBE FORMAT JSON requires an object document".into(), + }); + } + serde_json::from_value(document).map_err(|error| Error::Runtime { + message: format!("Invalid DESCRIBE metadata: {error}"), + }) +} + pub(super) fn definition(batches: Vec) -> Result { let values = strings(&batches, "definition")?; let [value]: [String; 1] = values.try_into().map_err(|_| Error::Runtime { @@ -275,3 +312,72 @@ mod tests { assert!(string_lists(&[non_list], "warnings").is_err()); } } + +#[cfg(test)] +mod description_tests { + use super::*; + + #[test] + fn descriptions_require_one_explicit_json_document() { + let document = serde_json::json!({"name":"saved", "schema":{"fields":[]}, "nullable":null}); + let batch = RecordBatch::try_new( + Arc::new( + arrow_schema::Schema::new(vec![arrow_schema::Field::new( + "description", + arrow_schema::DataType::Utf8, + false, + )]) + .with_metadata(std::collections::HashMap::from([( + "lancedb.describe.format".into(), + "json".into(), + )])), + ), + vec![Arc::new(StringArray::from(vec![document.to_string()]))], + ) + .unwrap(); + assert_eq!( + description::(vec![batch.clone()]).unwrap(), + document + ); + assert!(description::(vec![]).is_err()); + assert!(description::(vec![batch.clone(), batch.clone()]).is_err()); + let invalid = RecordBatch::try_new( + batch.schema(), + vec![Arc::new(StringArray::from(vec!["View\nname: saved"]))], + ) + .unwrap(); + assert!(description::(vec![invalid]).is_err()); + let text = RecordBatch::try_new( + Arc::new(batch.schema().as_ref().clone().with_metadata( + std::collections::HashMap::from([( + "lancedb.describe.format".into(), + "text".into(), + )]), + )), + batch.columns().to_vec(), + ) + .unwrap(); + assert!(description::(vec![text]).is_err()); + for value in ["[]", "null", "1", "\"text\""] { + let scalar = RecordBatch::try_new( + batch.schema(), + vec![Arc::new(StringArray::from(vec![value]))], + ) + .unwrap(); + assert!(description::(vec![scalar]).is_err()); + } + let null = RecordBatch::try_new( + Arc::new( + arrow_schema::Schema::new(vec![arrow_schema::Field::new( + "description", + arrow_schema::DataType::Utf8, + true, + )]) + .with_metadata(batch.schema().metadata().clone()), + ), + vec![Arc::new(StringArray::from(vec![None::<&str>]))], + ) + .unwrap(); + assert!(description::(vec![null]).is_err()); + } +} diff --git a/rust/lancedb/src/remote/sql/secret.rs b/rust/lancedb/src/remote/sql/secret.rs index 14c08e94b..ded060e93 100644 --- a/rust/lancedb/src/remote/sql/secret.rs +++ b/rust/lancedb/src/remote/sql/secret.rs @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use super::{SqlClient, materialized_view::quote_identifier, objects::strings}; +use super::{SqlClient, materialized_view::quote_identifier, objects::description}; use crate::{ database::ExecuteQueryRequest, error::{Error, Result}, @@ -9,7 +9,7 @@ use crate::{ secrets::SecretInfo, utils::{validate_namespace, validate_secret_name}, }; -use arrow_array::{Array, Int64Array, RecordBatch, StringArray}; +use arrow_array::{RecordBatch, StringArray}; use std::sync::Arc; pub(in crate::remote) enum SecretWriteOperation { @@ -18,31 +18,7 @@ pub(in crate::remote) enum SecretWriteOperation { } fn secret_info(batches: Vec) -> Result { - if batches.iter().map(RecordBatch::num_rows).sum::() != 1 { - return Err(Error::Runtime { - message: "DESCRIBE SECRET must return exactly one row".into(), - }); - } - let batch = batches.iter().find(|batch| batch.num_rows() == 1).unwrap(); - let timestamp = |name: &str| -> Result { - let values = batch - .column_by_name(name) - .and_then(|column| column.as_any().downcast_ref::()) - .ok_or_else(|| Error::Runtime { - message: format!("DESCRIBE SECRET is missing INT64 column '{name}'"), - })?; - if values.is_null(0) { - return Err(Error::Runtime { - message: format!("DESCRIBE SECRET contains null '{name}'"), - }); - } - Ok(values.value(0)) - }; - Ok(SecretInfo { - name: strings(&batches, "name")?.remove(0), - created_at_millis: timestamp("created_at_millis")?, - updated_at_millis: timestamp("updated_at_millis")?, - }) + description(batches) } impl SqlClient { @@ -100,7 +76,7 @@ impl SqlClient { validate_namespace(namespace)?; self.object_job( ExecuteQueryRequest { - query: format!("DESCRIBE SECRET {}", quote_identifier(name)), + query: format!("DESCRIBE SECRET {} FORMAT JSON", quote_identifier(name)), default_namespace_path: namespace.to_vec(), parameters: None, options: Default::default(), @@ -143,36 +119,40 @@ impl SqlClient { #[cfg(test)] mod tests { use super::*; - use arrow_array::ArrayRef; #[test] - fn decodes_native_secret_metadata() { - let batch = RecordBatch::try_from_iter(vec![ - ( - "name", - Arc::new(StringArray::from(vec!["api-key"])) as ArrayRef, - ), - ( - "created_at_millis", - Arc::new(Int64Array::from(vec![10])) as ArrayRef, - ), - ( - "updated_at_millis", - Arc::new(Int64Array::from(vec![20])) as ArrayRef, - ), - ]) + fn decodes_secret_json_metadata() { + let document = serde_json::json!({"name":"api-key", "created_at_millis":10, "updated_at_millis":20, "history":[{"generation":1,"at_millis":10}]}); + let schema = arrow_schema::Schema::new(vec![arrow_schema::Field::new( + "description", + arrow_schema::DataType::Utf8, + false, + )]) + .with_metadata(std::collections::HashMap::from([( + "lancedb.describe.format".into(), + "json".into(), + )])); + let batch = RecordBatch::try_new( + Arc::new(schema), + vec![Arc::new(StringArray::from(vec![document.to_string()]))], + ) .unwrap(); let info = secret_info(vec![batch.clone()]).unwrap(); assert_eq!(info.name, "api-key"); assert_eq!(info.created_at_millis, 10); assert_eq!(info.updated_at_millis, 20); assert!(secret_info(vec![]).is_err()); - assert!(secret_info(vec![batch.clone(), batch]).is_err()); - let missing = RecordBatch::try_from_iter(vec![( - "name", - Arc::new(StringArray::from(vec!["api-key"])) as ArrayRef, - )]) - .unwrap(); - assert!(secret_info(vec![missing]).is_err()); + assert!(secret_info(vec![batch.clone(), batch.clone()]).is_err()); + for invalid in [ + serde_json::json!({"name":"api-key"}), + serde_json::json!({"name":"api-key","created_at_millis":"10","updated_at_millis":20}), + ] { + let batch = RecordBatch::try_new( + batch.schema(), + vec![Arc::new(StringArray::from(vec![invalid.to_string()]))], + ) + .unwrap(); + assert!(secret_info(vec![batch]).is_err()); + } } } diff --git a/rust/lancedb/src/remote/sql/view.rs b/rust/lancedb/src/remote/sql/view.rs index ca09c4b5d..32a43b421 100644 --- a/rust/lancedb/src/remote/sql/view.rs +++ b/rust/lancedb/src/remote/sql/view.rs @@ -1,7 +1,11 @@ // SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Copyright The LanceDB Authors -use super::{SqlClient, materialized_view::quote_identifier, objects::strings}; +use super::{ + SqlClient, + materialized_view::quote_identifier, + objects::{description, strings}, +}; use crate::{ database::ExecuteQueryRequest, error::{Error, Result}, @@ -40,7 +44,7 @@ impl ViewDefinition { } } -fn view_description( +fn created_view_definition( batches: Vec, namespace: Vec, ) -> Result { @@ -53,11 +57,29 @@ fn view_description( } Ok(values.remove(0)) }; - let name = one("name")?; - let json: JsonArrowSchema = - serde_json::from_str(&one("schema")?).map_err(|error| Error::Runtime { - message: format!("View '{name}' has invalid schema JSON: {error}"), - })?; + let metadata = ViewMetadata { + name: one("name")?, + query: one("query")?, + schema: serde_json::from_str(&one("schema")?).map_err(|error| Error::Runtime { + message: format!("View metadata has invalid schema JSON: {error}"), + })?, + }; + view_definition(metadata, namespace) +} + +#[derive(serde::Deserialize)] +struct ViewMetadata { + name: String, + query: String, + schema: JsonArrowSchema, +} + +fn view_definition(metadata: ViewMetadata, namespace: Vec) -> Result { + let ViewMetadata { + name, + query, + schema: json, + } = metadata; let schema = lance_namespace::schema::convert_json_arrow_schema(&json).map_err(|error| { Error::Runtime { message: format!("View '{name}' has an undecodable schema: {error}"), @@ -84,7 +106,7 @@ fn view_description( Ok(ViewDefinition { name, namespace, - query: one("query")?, + query, default_database, default_namespace: default_namespace_path, schema: json, @@ -113,7 +135,7 @@ impl SqlClient { parameters: None, options: Default::default(), }, - move |batches| view_description(batches, namespace_path), + move |batches| created_view_definition(batches, namespace_path), ) .await? .wait() @@ -130,12 +152,12 @@ impl SqlClient { let namespace_path = namespace.to_vec(); self.object_job( ExecuteQueryRequest { - query: format!("DESCRIBE VIEW {}", quote_identifier(name)), + query: format!("DESCRIBE VIEW {} FORMAT JSON", quote_identifier(name)), default_namespace_path: namespace.to_vec(), parameters: None, options: Default::default(), }, - move |batches| view_description(batches, namespace_path), + move |batches| view_definition(description(batches)?, namespace_path), ) .await? .wait() diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index 770fe32fc..f14eb3cc9 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -765,6 +765,17 @@ impl FlightService for TestSqlService { } } +fn description_batch(document: serde_json::Value) -> RecordBatch { + let schema = Schema::new(vec![Field::new("description", DataType::Utf8, false)]).with_metadata( + HashMap::from([("lancedb.describe.format".into(), "json".into())]), + ); + RecordBatch::try_new( + Arc::new(schema), + vec![Arc::new(StringArray::from(vec![document.to_string()]))], + ) + .unwrap() +} + fn parameter_row() -> RecordBatch { let vector = FixedSizeListArray::from_iter_primitive::( [Some([0.1_f32, 1e-45, -0.0].map(Some))], @@ -1801,17 +1812,8 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { let (socket, _) = listener.accept().await?; Ok::<_, std::io::Error>(Some((socket, listener))) }); - let result = RecordBatch::try_from_iter(vec![ - ( - "name", - Arc::new(StringArray::from(vec!["view"])) as ArrayRef, - ), - ( - "query", - Arc::new(StringArray::from(vec!["SELECT * FROM source"])) as ArrayRef, - ), - ]) - .unwrap(); + let result = + description_batch(serde_json::json!({"name":"view", "query":"SELECT * FROM source"})); let service = TestSqlService { result, ..Default::default() @@ -1921,7 +1923,7 @@ async fn remote_refresh_omits_unknown_metrics_and_forwards_full() { assert_eq!( *statements.lock().unwrap(), [ - "DESCRIBE MATERIALIZED VIEW \"view\"", + "DESCRIBE MATERIALIZED VIEW \"view\" FORMAT JSON", "REFRESH MATERIALIZED VIEW \"view\"", "REFRESH MATERIALIZED VIEW \"view\" WITH (full = true)", "REFRESH MATERIALIZED VIEW \"view\" WITH (full = true, total_cpu_millis = 8000, total_memory_bytes = 17179869184, total_gpu_count = 2, gpu_class = 'h100', gpu_count = 2)", @@ -3216,11 +3218,8 @@ async fn remote_mv_listing_uses_server_continuation_tokens() { async fn remote_describe_materialized_view_preserves_the_sql_definition() { for defer in [false, true] { let definition = "SELECT s.x, d.label FROM source s JOIN dim d ON s.id = d.id"; - let result = RecordBatch::try_from_iter(vec![( - "query", - Arc::new(StringArray::from(vec![definition])) as ArrayRef, - )]) - .unwrap(); + let result = + description_batch(serde_json::json!({"name":"daily_sales", "query":definition})); let service = TestSqlService { adaptive: true, defer, @@ -3245,7 +3244,7 @@ async fn remote_describe_materialized_view_preserves_the_sql_definition() { assert!(info.parsed_definition.is_none()); assert_eq!( *statements.lock().unwrap(), - ["DESCRIBE MATERIALIZED VIEW \"daily_sales\""] + ["DESCRIBE MATERIALIZED VIEW \"daily_sales\" FORMAT JSON"] ); shutdown.send(()).unwrap(); } @@ -3283,6 +3282,10 @@ async fn storage_integration_methods_use_sql_with_namespace_and_typed_metadata() result: RecordBatch::try_from_iter(columns.clone()).unwrap(), adaptive: true, defer, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([( + "DESCRIBE STORAGE INTEGRATION \"raw\" FORMAT JSON".into(), + description_batch(info.clone()), + )]))), ..Default::default() }; let statements = service.statements.clone(); @@ -3310,13 +3313,14 @@ async fn storage_integration_methods_use_sql_with_namespace_and_typed_metadata() created.trust_policy["Statement"][0]["Condition"]["StringEquals"]["sts:ExternalId"], created.aws_external_id ); + let described = database + .describe_storage_integration("raw", &namespace) + .await + .unwrap(); + assert_eq!(described.aws_external_id, created.aws_external_id); assert_eq!( - database - .describe_storage_integration("raw", &namespace) - .await - .unwrap() - .aws_external_id, - created.aws_external_id + serde_json::to_value(&described).unwrap(), + serde_json::to_value(&created).unwrap() ); assert_eq!( database @@ -3347,7 +3351,10 @@ async fn storage_integration_methods_use_sql_with_namespace_and_typed_metadata() .unwrap(); let statements = statements.lock().unwrap(); assert!(statements[0].contains("STORAGE_AWS_REGION = 'us-east-1'")); - assert_eq!(statements[1], "DESCRIBE STORAGE INTEGRATION \"raw\""); + assert_eq!( + statements[1], + "DESCRIBE STORAGE INTEGRATION \"raw\" FORMAT JSON" + ); assert_eq!( statements[2], "SHOW STORAGE INTEGRATIONS IN \"platform$aws\" LIMIT 1000" @@ -3467,6 +3474,16 @@ async fn function_creation_and_description_use_sql_query_handles() { adaptive: true, defer, result, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([ + ( + "DESCRIBE FUNCTION \"embed\" WITH (version = '1') FORMAT JSON".into(), + description_batch(version_json.clone()), + ), + ( + "DESCRIBE FUNCTION \"embed\" FORMAT JSON".into(), + description_batch(version_json.clone()), + ), + ]))), ..Default::default() }; let statements = service.statements.clone(); @@ -3621,8 +3638,11 @@ async fn function_creation_and_description_use_sql_query_handles() { assert_eq!(listed_json["row_timeout_seconds"], 8.0); assert_eq!(listed_json["result_stability"], "input_and_context"); let seen = statements.lock().unwrap(); - assert_eq!(seen[1], "DESCRIBE FUNCTION \"embed\" WITH (version = '1')"); - assert_eq!(seen[2], "DESCRIBE FUNCTION \"embed\""); + assert_eq!( + seen[1], + "DESCRIBE FUNCTION \"embed\" WITH (version = '1') FORMAT JSON" + ); + assert_eq!(seen[2], "DESCRIBE FUNCTION \"embed\" FORMAT JSON"); shutdown.send(()).unwrap(); } } @@ -3888,27 +3908,16 @@ async fn secret_writes_bind_credentials_and_never_put_them_in_sql() { } #[tokio::test] async fn secret_description_uses_the_sql_metadata_projection() { - let result = RecordBatch::try_from_iter(vec![ - ( - "name", - Arc::new(StringArray::from(vec!["api-key"])) as ArrayRef, - ), - ( - "created_at_millis", - Arc::new(arrow_array::Int64Array::from(vec![1])) as ArrayRef, - ), - ( - "updated_at_millis", - Arc::new(arrow_array::Int64Array::from(vec![2])) as ArrayRef, - ), - ]) - .unwrap(); + let result = description_batch( + serde_json::json!({"name":"api-key", "created_at_millis":1, "updated_at_millis":2, "history":[]}), + ); let service = TestSqlService { adaptive: true, defer: true, result, ..Default::default() }; + let statements = service.statements.clone(); let (client, shutdown) = start_sql_service(service, ClientConfig::default()).await; let db = RemoteDatabase::new_mock(|_| -> http::Response { panic!("unexpected REST request"); @@ -3917,6 +3926,10 @@ async fn secret_description_uses_the_sql_metadata_projection() { let info = db.describe_secret("api-key", &[]).await.unwrap(); assert_eq!(info.name, "api-key"); assert_eq!(info.updated_at_millis, 2); + assert_eq!( + *statements.lock().unwrap(), + ["DESCRIBE SECRET \"api-key\" FORMAT JSON"] + ); shutdown.send(()).unwrap(); } @@ -4220,6 +4233,12 @@ async fn view_create_and_describe_return_metadata_through_sql() { adaptive: true, defer, result, + result_overrides: Arc::new(std::sync::Mutex::new(HashMap::from([( + "DESCRIBE VIEW \"adults\" FORMAT JSON".into(), + description_batch( + serde_json::json!({"name":"adults", "query":"SELECT name FROM people", "schema":serde_json::from_str::(schema).unwrap()}), + ), + )]))), ..Default::default() }; let statements = service.statements.clone(); @@ -4256,7 +4275,7 @@ async fn view_create_and_describe_return_metadata_through_sql() { [ "CREATE VIEW \"adults\" AS SELECT name FROM people", "CREATE VIEW IF NOT EXISTS \"adults\" AS SELECT replacement FROM other_people", - "DESCRIBE VIEW \"adults\"" + "DESCRIBE VIEW \"adults\" FORMAT JSON" ] ); assert!( diff --git a/rust/lancedb/vendor/lance-linalg/Cargo.toml b/rust/lancedb/vendor/lance-linalg/Cargo.toml index 1cb653ad9..cf2ab7d39 100644 --- a/rust/lancedb/vendor/lance-linalg/Cargo.toml +++ b/rust/lancedb/vendor/lance-linalg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lance-linalg" -version = "16.0.0-beta.3" +version = "16.0.0-beta.4" publish = false edition = { workspace = true } license = { workspace = true } diff --git a/rust/lancedb/vendor/lance-linalg/README.lancedb.md b/rust/lancedb/vendor/lance-linalg/README.lancedb.md index b6e85c75b..0c9047b92 100644 --- a/rust/lancedb/vendor/lance-linalg/README.lancedb.md +++ b/rust/lancedb/vendor/lance-linalg/README.lancedb.md @@ -1,5 +1,5 @@ -This directory contains `rust/lance-linalg` from Lance tag `v16.0.0-beta.3` -(commit `a93690c0a82ad8ea5e0dd621e3a311a5fce9a487`), licensed under Apache-2.0. +This directory contains `rust/lance-linalg` from Lance tag `v16.0.0-beta.4` +(commit `1686234925dde0289409fa31ff615d724943ccb6`), 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