diff --git a/.github/workflows/java-publish.yml b/.github/workflows/java-publish.yml index 094aa552a..35d052de9 100644 --- a/.github/workflows/java-publish.yml +++ b/.github/workflows/java-publish.yml @@ -39,9 +39,11 @@ jobs: distribution: temurin java-version: 8 cache: "maven" - server-id: ossrh - server-username: SONATYPE_USER - server-password: SONATYPE_TOKEN + # Betas go to Fury and stable releases to Maven Central, which limits + # how many releases an organization may publish each month. + server-id: ${{ contains(github.ref, 'beta') && 'fury' || 'ossrh' }} + server-username: ${{ contains(github.ref, 'beta') && 'FURY_TOKEN' || 'SONATYPE_USER' }} + server-password: ${{ contains(github.ref, 'beta') && 'FURY_PASSWORD' || 'SONATYPE_TOKEN' }} gpg-private-key: ${{ secrets.GPG_PRIVATE_KEY }} gpg-passphrase: MAVEN_GPG_PASSPHRASE - name: Set git config @@ -52,8 +54,16 @@ jobs: if: github.event_name == 'pull_request' run: | ./mvnw --batch-mode -DskipTests package -pl lancedb-core -am - - name: Publish - if: startsWith(github.ref, 'refs/tags/v') + - name: Publish to Fury + if: startsWith(github.ref, 'refs/tags/v') && contains(github.ref, 'beta') + run: | + ./mvnw --batch-mode -DskipTests deploy -pl lancedb-core -am -P deploy-to-fury + env: + FURY_TOKEN: ${{ secrets.FURY_TOKEN }} + # Fury authenticates with the token as the username; the password is ignored. + FURY_PASSWORD: NOPASS + - name: Publish to Maven Central + if: startsWith(github.ref, 'refs/tags/v') && !contains(github.ref, 'beta') run: | echo "use-agent" >> ~/.gnupg/gpg.conf echo "pinentry-mode loopback" >> ~/.gnupg/gpg.conf diff --git a/ci/tests/test_build_no_lock.py b/ci/tests/test_build_no_lock.py index 634e8d333..f760d2bfc 100644 --- a/ci/tests/test_build_no_lock.py +++ b/ci/tests/test_build_no_lock.py @@ -88,9 +88,11 @@ class BuildNoLockTest(unittest.TestCase): self.assertTrue((target / "fixture_cli").is_file()) # Cargo guarantees this binary for test execution, not compile-time reads. subprocess.run([str(target / "fixture_cli")], check=True) - self.assertTrue(list((target / "deps").glob("libartifact_fixture*.rlib"))) - self.assertTrue(list((target / "build").glob("*/build-script-build"))) - self.assertTrue(list((target / "build").glob("*/out/generated.rs"))) + # Cargo 1.100 nests compiler inputs in per-unit build directories and + # names the build-script executable build_script_build. + self.assertTrue(list(target.rglob("libartifact_fixture*.rlib"))) + self.assertTrue(list((target / "build").rglob("build[-_]script[-_]build"))) + self.assertTrue(list((target / "build").rglob("out/generated.rs"))) def test_link_failure_preserves_cargo_status_and_diagnostic(self): with tempfile.TemporaryDirectory(prefix=".no-lock-", dir=SCRIPT.parent) as temp: diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index 431796843..3150d94ec 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -650,6 +650,48 @@ tables; no partial handles are returned. *** +### fetchBlobRanges() + +```ts +abstract fetchBlobRanges( + column, + requests, + options?): Promise<(null | Buffer)[]> +``` + +Materializes row-specific byte ranges at the table's current checkout. +Preserves request order, duplicates, and nulls. Zero length returns an empty +buffer for a non-null blob. Invalid ranges or missing rows reject the entire +call. See [Table.fetchBlobs](Table.md#fetchblobs) for row-ID validity across versions. + +Remote tables use the batched endpoint when the server advertises support, +splitting at 1024 ranges and 64 MiB, including individual larger ranges. +Older servers use descriptor queries and BlobFile range reads. Both protocols +use one exact branch and version. Errors from an advertised endpoint propagate +without switching protocols. All output bytes occupy memory. + +#### Parameters + +* **column**: `string` + +* **requests**: readonly [`BlobRangeRequest`](../type-aliases/BlobRangeRequest.md)[] + +* **options?**: [`BlobReadOptions`](../type-aliases/BlobReadOptions.md) + +#### Returns + +`Promise`<(`null` \| `Buffer`)[]> + +#### Example + +```ts +const bytes = await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1024n }, +]); +``` + +*** + ### fetchBlobs() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 19d7ceb97..beed7c8af 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -169,6 +169,7 @@ - [BlobMode](type-aliases/BlobMode.md) - [BlobOptions](type-aliases/BlobOptions.md) - [BlobRange](type-aliases/BlobRange.md) +- [BlobRangeRequest](type-aliases/BlobRangeRequest.md) - [BlobReadOptions](type-aliases/BlobReadOptions.md) - [BlobUri](type-aliases/BlobUri.md) - [Data](type-aliases/Data.md) diff --git a/docs/src/js/type-aliases/BlobRangeRequest.md b/docs/src/js/type-aliases/BlobRangeRequest.md new file mode 100644 index 000000000..daa231260 --- /dev/null +++ b/docs/src/js/type-aliases/BlobRangeRequest.md @@ -0,0 +1,39 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / BlobRangeRequest + +# Type Alias: BlobRangeRequest + +```ts +type BlobRangeRequest: object; +``` + +One row-specific range for [Table.fetchBlobRanges](../classes/Table.md#fetchblobranges). + +## Type declaration + +### length + +```ts +length: bigint; +``` + +Number of bytes to read, as a uint64. Zero returns an empty non-null value. + +### offset + +```ts +offset: bigint; +``` + +Byte offset from the beginning of the logical blob, as a uint64. + +### rowId + +```ts +rowId: bigint | number; +``` + +A row ID from a query with row IDs enabled. diff --git a/docs/src/python/python.md b/docs/src/python/python.md index 0e7164c1a..4ce325b2f 100644 --- a/docs/src/python/python.md +++ b/docs/src/python/python.md @@ -37,6 +37,18 @@ embedding_functions`. Prefer keyword arguments for optional parameters. ::: lancedb.db.DBConnection +Use `db.server_info()` (or `await db.server_info()` on an asynchronous connection) +to include the responding server's release, Git revision, build date and Function +runtime information in a bug report. It returns a JSON-compatible dictionary and +does not submit a query or job. Configured images are distinct from the version +of an already running job. During a rolling upgrade, successive requests can +reach different query-node builds. Embedded connections and older servers without +the endpoint raise `NotImplementedError`. + +::: lancedb.server_info.ServerBuildInfo + +::: lancedb.server_info.ServerInfo + Resource listings return iterators. Use `list(db.list_tables())` to collect all table names. `db.list_tables().tables` is a list of the first page; `limit` controls its page size and `page_token` resumes at a saved token. The same @@ -615,6 +627,20 @@ remain available, as do LanceDB Enterprise operations. The same feature requirement applies to LanceDB Embedded SQL computed-column declaration and refresh; ordinary eager `add_columns` transforms remain available. +Pass a complete defining SQL query with `query=` to use grouping, Functions +in `FROM`, or `UNNEST`: + +```python +view = db.create_materialized_view( + "events_by_kind", + query="SELECT kind, count(*) AS n FROM events GROUP BY kind", +) +``` + +`query` is mutually exclusive with `source`, `select`, `where`, and `limit`. +It is also accepted by asynchronous connections and `create_materialized_view_async`. +The backend SQL parser determines which query shapes are supported. + In LanceDB Enterprise, creation accepts `auto_refresh_enabled` and `auto_refresh_interval_seconds`: diff --git a/docs/web/feature-engineering/materialized-views.mdx b/docs/web/feature-engineering/materialized-views.mdx index 0f9494c9f..617eb7525 100644 --- a/docs/web/feature-engineering/materialized-views.mdx +++ b/docs/web/feature-engineering/materialized-views.mdx @@ -20,19 +20,19 @@ In SQL this is [`CREATE MATERIALIZED VIEW`](/sql/ddl/materialized-view#create). ## Create a view {#create} A materialized view is defined by a SQL query, so it is created with one. -From Python, run the statement on an [Enterprise connection](/basics/catalog#enterprise) -with [`execute_query`](/basics/sql#sql-from-python); the SQL is the same -either way: +From Python, pass the defining query to `create_materialized_view` on an +[Enterprise connection](/basics/catalog#enterprise): ```python Python icon="python" -db.execute_query(""" - CREATE MATERIALIZED VIEW frames_captioned AS - SELECT frame_id, video_id, ts, caption - FROM frames - WHERE selected = true -""").read_all() -view = db.open_materialized_view("frames_captioned") +view = db.create_materialized_view( + "frames_captioned", + query=""" + SELECT frame_id, video_id, ts, caption + FROM frames + WHERE selected = true + """, +) ``` ```sql SQL icon="database" @@ -43,9 +43,11 @@ WHERE selected = true ``` -`execute_query` returns once the result stream is readable, not once the -statement has finished, so `.read_all()` waits out the full creation before -the next line opens it. +`create_materialized_view` waits for creation and initial population, then +returns the view handle. Use `create_materialized_view_async` to submit a job +and wait for it separately. Both methods accept `query=` on synchronous and +asynchronous connections. `query` cannot be combined with `source`, `select`, +`where`, or `limit`; put those clauses in the query itself. The query defines the view: here, the `frames` table's `frame_id`, `video_id`, `ts` and `caption` columns, filtered to the frames selected for diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 031342fbc..bf6bf3edd 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -736,6 +736,10 @@ The other fetch methods load bytes directly: | Whole payloads for a set of rows | `fetch_blobs` | `fetchBlobs` | `fetch_blobs` | | Byte slices across many rows in one call | `fetch_blob_ranges` | Not available. Use `fetchBlobFiles` and `readRanges`. | `fetch_blob_ranges` | +{/* Draft for the TypeScript cross-row Blob range release. Replace the row above: +| Byte slices across many rows in one call | `fetch_blob_ranges` | `fetchBlobRanges` | `fetch_blob_ranges` | +*/} + - `fetch_blobs` returns the full bytes for each row ID in order. Null blobs produce null entries, and empty blobs produce empty byte strings. - `fetch_blob_files` loads bytes when you call `read`, `read_range`, or @@ -759,6 +763,21 @@ The other fetch methods load bytes directly: +{/* Draft for the TypeScript cross-row Blob range release. + +Upcoming-release draft: TypeScript adds `fetchBlobRanges` for cross-row slices. +Until that SDK release is available, use `fetchBlobFiles` and `readRanges`. +Server-side batching requires a deployment with the validated range capability; +older servers continue using the descriptor and Range path selected before the +read. An error from the selected batched endpoint is returned without fallback. +A batched call keeps the native snapshot identity from its first range response +across every partition and requires each serving node to verify it. Missing identity +support or a replaced/deleted snapshot fails the whole call; upgrade all serving +nodes before selecting the batched endpoint with a new SDK. +Custom TypeScript `Table` subclasses must implement the new abstract method. + +*/} + Python and Rust read slices across rows with `fetch_blob_ranges`. On a handle, `read_ranges` reads more than one slice of one blob. Python takes `(offset, length)` pairs, TypeScript takes `{ start, end }` ranges with an @@ -770,6 +789,14 @@ exclusive `end`, and Rust takes `start..end` ranges: + {/* Draft for the TypeScript cross-row Blob range release. + {`// Upcoming-release draft: slices from more than one row. +const slices = await blobTable.fetchBlobRanges("image", [ + { rowId: rowIds[0]!, offset: 0n, length: 6n }, + { rowId: rowIds[1]!, offset: 7n, length: 5n }, +]); +`}{"\n"} + */} {TsBlobApiRanges} diff --git a/java/README.md b/java/README.md index fd163b9f1..85e7e85ba 100644 --- a/java/README.md +++ b/java/README.md @@ -1,5 +1,39 @@ # LanceDB Java Enterprise Client +## Installation + +Stable releases of `com.lancedb:lancedb-core` are published to Maven Central. + +Beta releases are published to `https://maven.fury.io/lancedb/` instead. They +depend on Lance beta releases, which are published to `https://maven.lance.org`. +To use a beta, add both repositories alongside Maven Central: + +```xml + + + lancedb + https://maven.fury.io/lancedb/ + + + lance + https://maven.lance.org + + +``` + +For Gradle: + +```kotlin +repositories { + mavenCentral() + maven { url = uri("https://maven.fury.io/lancedb/") } + maven { url = uri("https://maven.lance.org") } +} +``` + +Use an explicit version, including the full `-beta.N` suffix. Beta versions are +Maven releases, not `SNAPSHOT` versions. + ## Configuration and Initialization ### LanceDB Cloud (legacy) diff --git a/java/pom.xml b/java/pom.xml index 87d309a01..148f7b102 100644 --- a/java/pom.xml +++ b/java/pom.xml @@ -318,6 +318,15 @@ + + deploy-to-fury + + + fury + https://maven.fury.io/lancedb/ + + + deploy-to-ossrh diff --git a/nodejs/__test__/blob_ranges.test.ts b/nodejs/__test__/blob_ranges.test.ts new file mode 100644 index 000000000..7d2fab566 --- /dev/null +++ b/nodejs/__test__/blob_ranges.test.ts @@ -0,0 +1,589 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { createHash } from "crypto"; +import { getEventListeners } from "events"; +import { createReadStream } from "fs"; +import * as http from "http"; +import { AddressInfo } from "net"; +import { + Table as ArrowTable, + Binary, + Field, + LargeBinary, + Struct, + Uint8, + Uint32, + Uint64, + Utf8, + tableToIPC, + vectorFromArray, +} from "apache-arrow"; +import { BlobRangeRequest, Connection, Table, connect } from "../lancedb"; + +jest.setTimeout(30000); + +const IDENTITY = `v1:${"a".repeat(64)}`; +const MIB = 1024 * 1024; +type Range = { + // biome-ignore lint/style/useNamingConvention: Matches the server JSON contract. + row_id: number; + offset: number; + length: number; +}; +type Request = { + column: string; + branch: string | null; + version: number | null; + ranges: Range[]; + identity?: string; +}; + +function payload(row: number, offset: number, length: number, version: number) { + const bytes = Buffer.alloc(length); + for (let i = 0; i < length; i++) { + bytes[i] = (row * 17 + ((offset + i) % 251) + version) % 251; + } + return bytes; +} + +async function withRangeServer( + run: (db: Connection, calls: Request[], paths: string[]) => Promise, + fault?: string | number, + capability: string | null = "1", + onStall?: () => void, +) { + let takes = 0; + const calls: Request[] = []; + const paths: string[] = []; + const server = http.createServer((req, res) => { + req.setTimeout(15000); + paths.push(req.url ?? ""); + if ( + req.url === "/v1/table/test/describe/" || + req.url === "/v1/table/test/branches/list/" + ) { + res.writeHead(200, { + "Content-Type": "application/json", + "phalanx-version": "1.13.0-beta.0", + ...(req.url.endsWith("/describe/") && capability !== null + ? { "x-lancedb-blob-ranges": capability } + : {}), + }); + const response = req.url.endsWith("branches/list/") + ? { + branches: { + experiment: { + parentBranch: null, + parentVersion: 1, + createAt: 1, + manifestSize: 1, + }, + }, + } + : { version: 8, schema: { fields: [] } }; + res.end(JSON.stringify(response)); + return; + } + if (capability !== "1" && req.method === "GET") { + const url = new URL(req.url!, "http://localhost"); + expect(url.searchParams.get("branch")).toBe("experiment"); + expect(url.searchParams.get("version")).toBe("3"); + const [start, end] = req.headers.range!.slice(6).split("-").map(Number); + const bytes = Buffer.from("alpha").subarray(start, end + 1); + res + .writeHead(206, { + "Content-Range": `bytes ${start}-${end}/5`, + "Content-Length": bytes.length, + "x-lancedb-version": "3", + }) + .end(bytes); + return; + } + expect(req.method).toBe("POST"); + expect(req.url).toBe( + capability === "1" + ? "/v1/table/test/fetch_blob_ranges/" + : "/v1/table/test/query/", + ); + const chunks: Buffer[] = []; + let size = 0; + req.on("data", (chunk: Buffer) => { + size += chunk.length; + expect(size).toBeLessThanOrEqual(256 * 1024); + chunks.push(chunk); + }); + req.on("end", () => { + if (capability !== "1") { + const body = JSON.parse(Buffer.concat(chunks).toString()) as { + branch: string; + version: number; + filter: string; + }; + expect(body.branch).toBe("experiment"); + expect(body.version).toBe(3); + takes++; + const ids = (body.filter.match(/\d+/g) ?? []) + .map(Number) + .filter((id) => [10, 20, 40].includes(id)) + .reverse(); + const descriptor = new Struct([ + new Field("kind", new Uint8(), false), + new Field("position", new Uint64(), false), + new Field("size", new Uint64(), false), + new Field("blob_id", new Uint32(), false), + new Field("blob_uri", new Utf8(), false), + ]); + const arrow = new ArrowTable({ + image: vectorFromArray( + ids.map((id) => + id === 20 + ? null + : { + kind: 0, + position: 0n, + size: id === 40 ? 0n : 5n, + // biome-ignore lint/style/useNamingConvention: Arrow descriptor field. + blob_id: 0, + // biome-ignore lint/style/useNamingConvention: Arrow descriptor field. + blob_uri: "", + }, + ), + descriptor, + ), + _rowid: vectorFromArray(ids.map(BigInt), new Uint64()), + }); + expect(takes).toBeGreaterThan(0); + res + .writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + "x-lancedb-version": "3", + }) + .end(tableToIPC(arrow, "stream")); + return; + } + const body = JSON.parse(Buffer.concat(chunks).toString()) as Request; + body.identity = req.headers["x-lancedb-query-snapshot"] as + | string + | undefined; + calls.push(body); + expect(body.column).toBe("image"); + expect(body.branch).toBe("experiment"); + expect(body.ranges.length).toBeLessThanOrEqual(1024); + expect( + body.ranges.reduce((sum, range) => sum + range.length, 0), + ).toBeLessThanOrEqual(64 * MIB); + const version = body.version ?? (calls.length === 1 ? 7 : 8); + const failure = + calls.length > 1 || String(fault).startsWith("first-") + ? fault + : undefined; + if (failure === "recreated" || failure === "gone") { + res + .writeHead(failure === "recreated" ? 400 : 404) + .end("query snapshot identity mismatch: source gone or replaced"); + return; + } + if (failure === "stall" && calls.length === 2) { + res.writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + "x-lancedb-version": "7", + "x-lancedb-query-snapshot": IDENTITY, + }); + res.flushHeaders(); + onStall?.(); + return; + } + if (typeof failure === "number") { + res.writeHead(failure).end("ordinary server failure"); + return; + } + if (failure === "disconnect") { + req.socket.destroy(); + return; + } + let values = body.ranges.map((range) => + range.row_id === 20 + ? null + : payload(range.row_id, range.offset, range.length, version), + ); + if (failure === "count") values = []; + if (failure === "length") values = [Buffer.alloc(0)]; + const arrow = new ArrowTable({ + [failure === "column" ? "wrong" : "value"]: vectorFromArray( + values, + failure === "type" ? new Binary() : new LargeBinary(), + ), + }); + let ipc = tableToIPC(arrow, "stream"); + if (failure === "eos") ipc = ipc.subarray(0, ipc.length - 8); + if (failure === "body") ipc = ipc.subarray(0, Math.floor(ipc.length / 2)); + res.writeHead(200, { + "Content-Type": "application/vnd.apache.arrow.stream", + connection: "close", + "Content-Length": ipc.length + (failure === "transport" ? 10 : 0), + ...(failure === "version" ? {} : { "x-lancedb-version": version }), + ...(["missing-identity", "first-missing-identity"].includes( + String(failure), + ) + ? {} + : { + "x-lancedb-query-snapshot": + failure === "wrong-identity" + ? `v1:${"b".repeat(64)}` + : failure === "first-invalid-identity" + ? "broken" + : IDENTITY, + }), + }); + // Fragment the generated IPC payload across actual HTTP writes. + for (let i = 0; i < ipc.length; i += 8192) + res.write(ipc.subarray(i, i + 8192)); + res.end(); + }); + }); + server.listen(0, "127.0.0.1"); + await new Promise((resolve) => server.once("listening", resolve)); + const port = (server.address() as AddressInfo).port; + const db = await connect("db://dev", { + apiKey: "fake", + hostOverride: `http://127.0.0.1:${port}`, + clientConfig: { + retryConfig: { retries: 2, connectRetries: 2, readRetries: 2 }, + blobRequestConcurrency: 1, + timeoutConfig: { timeout: 20 }, + }, + }); + try { + await run(db, calls, paths); + } finally { + await new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }); + } +} + +async function open(db: Connection, version?: number): Promise { + return db.openTable("test", [], { branch: "experiment", version }); +} + +describe("fetchBlobRanges", () => { + it.each([null, "0", "2"])( + "uses old routes before data requests for capability %s", + async (capability) => { + await withRangeServer( + async (db, calls, paths) => { + // Reopening exercises both the initial and cached database describe paths. + for (let i = 0; i < 2; i++) { + const table = await open(db, 3); + const requests = [ + { rowId: 10n, offset: 1n, length: 3n }, + { rowId: 20n, offset: 0n, length: 1n }, + { rowId: 40n, offset: 0n, length: 0n }, + { rowId: 10n, offset: 5n, length: 0n }, + { rowId: 10n, offset: 1n, length: 3n }, + ]; + expect(await table.fetchBlobRanges("image", requests)).toEqual([ + Buffer.from("lph"), + null, + Buffer.alloc(0), + Buffer.alloc(0), + Buffer.from("lph"), + ]); + for (const row of [ + { rowId: 10n, offset: 4n, length: 2n }, + { rowId: 99n, offset: 0n, length: 1n }, + ]) + await expect( + table.fetchBlobRanges("image", [row]), + ).rejects.toThrow(); + const before = paths.length; + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + expect(paths).toHaveLength(before); + } + expect(calls).toHaveLength(0); + expect(paths.some((path) => path.includes("fetch_blob_ranges"))).toBe( + false, + ); + }, + undefined, + capability, + ); + }, + ); + + it("renegotiates advertised support when reopening a cached table", async () => { + await withRangeServer(async (db, calls) => { + for (let i = 0; i < 2; i++) { + const table = await open(db); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, i === 0 ? 7 : 8)]); + } + expect(calls).toHaveLength(2); + }); + }); + + it("cancels while waiting for a later response body and releases the only permit", async () => { + let markStalled!: () => void; + const stalled = new Promise((resolve) => { + markStalled = resolve; + }); + await withRangeServer( + async (db, calls) => { + const table = await open(db); + const controller = new AbortController(); + const pending = table.fetchBlobRanges( + "image", + Array.from({ length: 2049 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + { signal: controller.signal }, + ); + const rejected = expect(pending).rejects.toMatchObject({ + name: "AbortError", + }); + await stalled; + controller.abort(); + await rejected; + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0); + expect(calls).toHaveLength(2); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, 8)]); + expect(calls).toHaveLength(3); + }, + "stall", + "1", + () => markStalled(), + ); + }); + it.each([undefined, 3])( + "preserves order, nulls, duplicates and snapshot (checkout %s)", + async (version) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db, version); + const requests: BlobRangeRequest[] = Array.from( + { length: 1025 }, + (_, i) => ({ + rowId: i % 9 === 0 ? 20 : 10 + (i % 7), + offset: BigInt(i), + length: BigInt(i % 4), + }), + ); + requests.push( + { rowId: 10n, offset: 0n, length: 0n }, + { rowId: 10n, offset: 2n, length: 3n }, + { rowId: 10n, offset: 2n, length: 3n }, + ); + const result = await table.fetchBlobRanges("image", requests); + expect(result).toEqual( + requests.map((range) => + Number(range.rowId) === 20 + ? null + : payload( + Number(range.rowId), + Number(range.offset), + Number(range.length), + version ?? 7, + ), + ), + ); + expect(calls.map((body) => body.version)).toEqual([ + version ?? null, + version ?? 7, + ]); + expect( + await table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0n, length: 1n }, + ]), + ).toEqual([payload(10, 0, 1, version ?? 8)]); + expect(calls[2].version).toBe(version ?? null); + expect( + paths.filter((path) => path.endsWith("fetch_blob_ranges/")), + ).toHaveLength(3); + }); + }, + ); + + it("partitions the byte budget and reassembles one range larger than 64 MiB", async () => { + await withRangeServer(async (db, calls) => { + const table = await open(db); + const requests = [ + { rowId: 10n, offset: 3n, length: BigInt(65 * MIB) }, + { rowId: 30n, offset: 7n, length: 2n }, + ]; + const result = await table.fetchBlobRanges("image", requests); + for (const [i, range] of requests.entries()) { + expect(result[i]?.length).toBe(Number(range.length)); + expect( + createHash("sha256") + .update(result[i] as Buffer) + .digest("hex"), + ).toBe( + createHash("sha256") + .update( + payload( + Number(range.rowId), + Number(range.offset), + Number(range.length), + 7, + ), + ) + .digest("hex"), + ); + } + expect(calls).toHaveLength(2); + expect(calls.map((body) => body.version)).toEqual([null, 7]); + }); + }); + + it.each([ + "type", + "column", + "count", + "length", + "eos", + "body", + "transport", + "version", + "disconnect", + 401, + 403, + 404, + 429, + 500, + ])("rejects the whole call after a later %s failure", async (fault) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + await expect( + table.fetchBlobRanges( + "image", + Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + ), + ).rejects.toThrow(); + expect(calls).toHaveLength(2); + expect( + paths.every( + (path) => + path.endsWith("describe/") || + path.endsWith("branches/list/") || + path.endsWith("fetch_blob_ranges/"), + ), + ).toBe(true); + }, fault); + }); + + it.each(["missing-identity", "wrong-identity", "recreated", "gone"])( + "retains original identity through row and byte partitions (%s)", + async (fault) => { + for (const huge of [false, true]) { + await withRangeServer(async (db, calls) => { + const table = await open(db); + const requests = huge + ? [{ rowId: 10n, offset: 0n, length: BigInt(64 * MIB + 1) }] + : Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })); + await expect( + table.fetchBlobRanges("image", requests), + ).rejects.toThrow(); + expect(calls.map((call) => call.identity)).toEqual([ + undefined, + IDENTITY, + ]); + expect(calls.map((call) => call.version)).toEqual([null, 7]); + }, fault); + } + }, + ); + + it.each(["first-missing-identity", "first-invalid-identity"])( + "requires a first authoritative bulk identity (%s)", + async (fault) => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + const before = paths.length; + await expect( + table.fetchBlobRanges( + "image", + Array.from({ length: 1025 }, () => ({ + rowId: 10n, + offset: 0n, + length: 1n, + })), + ), + ).rejects.toThrow(/snapshot identity/); + expect(calls).toHaveLength(1); + expect(paths).toHaveLength(before + 1); + }, fault); + }, + ); + + it("validates integers, overflow and cancellation and leaves empty calls at zero I/O", async () => { + await withRangeServer(async (db, calls, paths) => { + const table = await open(db); + const before = paths.length; + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + for (const request of [ + { rowId: -1, offset: 0n, length: 1n }, + { rowId: 1.5, offset: 0n, length: 1n }, + { rowId: Number.MAX_SAFE_INTEGER + 1, offset: 0n, length: 1n }, + { rowId: -1n, offset: 0n, length: 1n }, + { rowId: 1n << 64n, offset: 0n, length: 1n }, + { rowId: 10n, offset: -1n, length: 1n }, + { rowId: 10n, offset: 0n, length: -1n }, + { rowId: 10n, offset: 0n, length: 1n << 64n }, + { rowId: 20n, offset: (1n << 64n) - 1n, length: 1n }, + ]) { + await expect( + table.fetchBlobRanges("image", [request]), + ).rejects.toThrow(); + } + // Runtime type validation must also reject a number passed as an offset. + await expect( + table.fetchBlobRanges("image", [ + { rowId: 10n, offset: 0 as unknown as bigint, length: 1n }, + ]), + ).rejects.toThrow(); + const controller = new AbortController(); + controller.abort(new Error("cancelled by caller")); + await expect( + table.fetchBlobRanges( + "image", + [{ rowId: 10n, offset: 0n, length: 1n }], + { signal: controller.signal }, + ), + ).rejects.toThrow("cancelled by caller"); + expect(paths).toHaveLength(before); + expect(calls).toHaveLength(0); + }); + }); + + it("records the loaded native artifact", async () => { + const artifacts = Object.keys(require.cache).filter( + (path) => path.endsWith(".node") && path.includes("lancedb"), + ); + expect(artifacts.length).toBeGreaterThan(0); + for (const path of artifacts) { + const hash = createHash("sha256"); + for await (const chunk of createReadStream(path)) hash.update(chunk); + console.log( + `loaded native artifact=${path} sha256=${hash.digest("hex")}`, + ); + } + }); +}); diff --git a/nodejs/__test__/table.test.ts b/nodejs/__test__/table.test.ts index b803e9043..59d6929b4 100644 --- a/nodejs/__test__/table.test.ts +++ b/nodejs/__test__/table.test.ts @@ -3019,6 +3019,43 @@ describe("when dealing with blob columns", () => { expect(bytes.map((b) => b?.toString())).toEqual(["new", "hi"]); }); + it("fetchBlobRanges reads local ranges with order, duplicates, nulls and validation", async () => { + const { table, rowIds } = await openBlobTable(); + const [alphaId, betaId, nullId] = rowIds; + const requests = [ + { rowId: betaId, offset: 1n, length: 3n }, + { rowId: alphaId, offset: 0n, length: 2n }, + { rowId: nullId, offset: 0n, length: 1n }, + { rowId: alphaId, offset: 5n, length: 0n }, + { rowId: betaId, offset: 1n, length: 3n }, + ]; + expect(await table.fetchBlobRanges("image", requests)).toEqual([ + Buffer.from("eta"), + Buffer.from("al"), + null, + Buffer.alloc(0), + Buffer.from("eta"), + ]); + expect(await table.fetchBlobRanges("image", [])).toEqual([]); + await expect( + table.fetchBlobRanges("image", [ + { rowId: alphaId, offset: 4n, length: 2n }, + ]), + ).rejects.toThrow(); + await expect( + table.fetchBlobRanges("image", [ + { rowId: (1n << 63n) - 1n, offset: 0n, length: 1n }, + ]), + ).rejects.toThrow(); + const controller = new AbortController(); + expect( + await table.fetchBlobRanges("image", requests, { + signal: controller.signal, + }), + ).toHaveLength(5); + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0); + }); + it("discovers blob columns", async () => { const { table } = await openBlobTable(); expect(await table.blobColumns()).toEqual(["image"]); diff --git a/nodejs/lancedb/blob.ts b/nodejs/lancedb/blob.ts index 67e662175..a46484314 100644 --- a/nodejs/lancedb/blob.ts +++ b/nodejs/lancedb/blob.ts @@ -305,6 +305,16 @@ export async function runWithSignal( } } +/** One row-specific range for {@link Table.fetchBlobRanges}. */ +export type BlobRangeRequest = { + /** A row ID from a query with row IDs enabled. */ + rowId: bigint | number; + /** Byte offset from the beginning of the logical blob, as a uint64. */ + offset: bigint; + /** Number of bytes to read, as a uint64. Zero returns an empty non-null value. */ + length: bigint; +}; + /** A half-open byte range `[start, end)` for {@link BlobFile.readRanges}. */ export type BlobRange = { start: bigint; diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 35697dc8c..08a254bdb 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -91,6 +91,7 @@ export type { BlobInput, BlobOptions, BlobRange, + BlobRangeRequest, BlobReadOptions, BlobUri, } from "./blob"; diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index 185088424..136eb1d6c 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -17,7 +17,12 @@ import { tableFromIPC, } from "./arrow"; -import { BlobFile, BlobReadOptions, runWithSignal } from "./blob"; +import { + BlobFile, + BlobRangeRequest, + BlobReadOptions, + runWithSignal, +} from "./blob"; import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry"; import { IndexOptions } from "./indices"; import { Job } from "./job"; @@ -683,6 +688,31 @@ export abstract class Table { options?: BlobReadOptions, ): Promise<(Buffer | null)[]>; + /** + * Materializes row-specific byte ranges at the table's current checkout. + * Preserves request order, duplicates, and nulls. Zero length returns an empty + * buffer for a non-null blob. Invalid ranges or missing rows reject the entire + * call. See {@link Table.fetchBlobs} for row-ID validity across versions. + * + * Remote tables use the batched endpoint when the server advertises support, + * splitting at 1024 ranges and 64 MiB, including individual larger ranges. + * Older servers use descriptor queries and BlobFile range reads. Both protocols + * use one exact branch and version. Errors from an advertised endpoint propagate + * without switching protocols. All output bytes occupy memory. + * + * @example + * ```ts + * const bytes = await table.fetchBlobRanges("image", [ + * { rowId: 10n, offset: 0n, length: 1024n }, + * ]); + * ``` + */ + abstract fetchBlobRanges( + column: string, + requests: readonly BlobRangeRequest[], + options?: BlobReadOptions, + ): Promise<(Buffer | null)[]>; + /** * Opens lazy blob handles for `column` at the given row IDs using the * table's current checkout. @@ -1510,6 +1540,23 @@ export class LocalTable extends Table { return values.map((value) => value ?? null); } + async fetchBlobRanges( + column: string, + requests: readonly BlobRangeRequest[], + options?: BlobReadOptions, + ): Promise<(Buffer | null)[]> { + const rowIds = rowIdsToBigInts(requests.map((request) => request.rowId)); + const ranges = requests.map((request, i) => ({ + rowId: rowIds[i], + offset: request.offset, + length: request.length, + })); + const values = await runWithSignal(options?.signal, (signal) => + this.inner.fetchBlobRanges(column, ranges, signal), + ); + return values.map((value) => value ?? null); + } + async fetchBlobFiles( column: string, rowIds: readonly (bigint | number)[], diff --git a/nodejs/src/blob.rs b/nodejs/src/blob.rs index 59cf61af6..b55154019 100644 --- a/nodejs/src/blob.rs +++ b/nodejs/src/blob.rs @@ -21,6 +21,25 @@ pub struct BlobRange { pub end: BigInt, } +#[napi(object)] +pub struct BlobRangeRequest { + pub row_id: BigInt, + pub offset: BigInt, + pub length: BigInt, +} + +impl BlobRangeRequest { + pub(crate) fn parse(self) -> napi::Result { + let row_id = parse_u64(self.row_id, "row id")?; + let offset = parse_u64(self.offset, "offset")?; + let length = parse_u64(self.length, "length")?; + offset + .checked_add(length) + .ok_or_else(|| napi::Error::from_reason("blob range offset + length overflows u64"))?; + Ok(lancedb::blob::BlobRangeRequest::new(row_id, offset, length)) + } +} + #[napi] pub struct BlobFile { inner: Arc, @@ -205,14 +224,25 @@ pub fn parse_row_ids(row_ids: Vec) -> napi::Result> { .collect() } -pub fn copy_blob_buffers(array: LargeBinaryArray) -> Vec> { - (0..array.len()) - .map(|i| { - if array.is_null(i) { - None - } else { - Some(Buffer::from(array.value(i).to_vec())) - } - }) - .collect() +pub fn copy_blob_buffers(array: LargeBinaryArray) -> napi::Result>> { + let allocation_error = + |error| napi::Error::from_reason(format!("cannot allocate blob result: {error}")); + let mut result = Vec::new(); + result + .try_reserve_exact(array.len()) + .map_err(allocation_error)?; + for value in array.iter() { + let buffer = value + .map(|value| { + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(value.len()) + .map_err(allocation_error)?; + bytes.extend_from_slice(value); + Ok::<_, napi::Error>(Buffer::from(bytes)) + }) + .transpose()?; + result.push(buffer); + } + Ok(result) } diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 7076bbec1..f6abeb553 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -17,7 +17,7 @@ use napi::bindgen_prelude::*; use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi_derive::napi; -use crate::blob::{BlobFile, copy_blob_buffers, parse_row_ids, spawn_abortable}; +use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable}; use crate::error::NapiErrorExt; use crate::index::Index; use crate::job::JobFailureInfo; @@ -420,7 +420,32 @@ impl Table { .fetch_blobs(column.as_str(), &row_ids) .await .default_error()?; - Ok(copy_blob_buffers(array)) + copy_blob_buffers(array) + }) + } + + #[napi(catch_unwind)] + pub fn fetch_blob_ranges<'env>( + &self, + env: &'env Env, + column: String, + requests: Vec, + signal: Option, + ) -> napi::Result>>> { + let mut ranges = Vec::new(); + ranges.try_reserve_exact(requests.len()).map_err(|error| { + napi::Error::from_reason(format!("cannot allocate blob range requests: {error}")) + })?; + for request in requests { + ranges.push(request.parse()?); + } + let table = self.inner_ref()?.clone(); + spawn_abortable(env, signal, async move { + let array = table + .fetch_blob_ranges(column.as_str(), ranges) + .await + .default_error()?; + copy_blob_buffers(array) }) } diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 956806cde..5897ddd0c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -185,6 +185,7 @@ class Connection(object): limit: Optional[int], ) -> list[str]: ... # Deprecated: Use list_tables instead async def open_job(self, job_id: str) -> Job: ... + async def server_info(self) -> str: ... async def list_gpu_classes(self) -> list[GpuClass]: ... async def create_function_async( self, request_json: str, namespace_path: Optional[List[str]] = None @@ -348,24 +349,28 @@ class Connection(object): async def create_materialized_view( self, name: str, - source: str, + source: Optional[str] = None, projections: Optional[List[Tuple[str, str]]] = None, filter: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + *, + query: Optional[str] = None, ) -> Table: ... async def create_materialized_view_async( self, name: str, - source: str, + source: Optional[str] = None, projections: Optional[List[Tuple[str, str]]] = None, filter: Optional[str] = None, limit: Optional[int] = None, with_no_data: bool = False, auto_refresh_enabled: Optional[bool] = None, auto_refresh_interval_seconds: Optional[float] = None, + *, + query: Optional[str] = None, ) -> Job: ... def list_materialized_views( self, *, page_token: Optional[str] = None, page_limit: Optional[int] = None diff --git a/python/python/lancedb/db.py b/python/python/lancedb/db.py index 59fa5b4c6..7d690abe3 100644 --- a/python/python/lancedb/db.py +++ b/python/python/lancedb/db.py @@ -58,6 +58,7 @@ from lance_namespace import ( from lance_namespace.errors import NamespaceNotEmptyError, TableNotFoundError from . import __version__ +from .server_info import ServerInfo from ._lancedb import _append_doc_url, connect as lancedb_connect # type: ignore from .functions import FunctionVersion, FunctionDefinition from .graph import ( @@ -78,6 +79,7 @@ from .materialized_view import ( MaterializedViewSource, SelectArg, normalize_select, + _validate_create_materialized_view, ) from .secrets import ( EnvVarSecret, @@ -697,8 +699,9 @@ class DBConnection(EnforceOverrides): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -721,8 +724,12 @@ class DBConnection(EnforceOverrides): ---------- name: str The name of the view. - source: str - The name of the source table. + source: str, optional + The name of the source table. Required when ``query`` is omitted. + query: str, optional + The complete defining SQL query, including any GROUP BY or FROM + Function. Mutually exclusive with ``source``, ``select``, ``where`` + and ``limit``. Supported query shapes depend on the backend. select: list or dict, optional The view's columns: column names, ``(alias, SQL expression)`` pairs, or a dict of the same. Omitting it selects every source @@ -744,6 +751,13 @@ class DBConnection(EnforceOverrides): Returns ------- MaterializedView + + Examples + -------- + >>> view = db.create_materialized_view( # doctest: +SKIP + ... "events_by_kind", + ... query="SELECT kind, count(*) AS n FROM events GROUP BY kind", + ... ) """ raise NotImplementedError( _append_doc_url( @@ -755,8 +769,9 @@ class DBConnection(EnforceOverrides): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -1476,6 +1491,22 @@ class DBConnection(EnforceOverrides): ) ) + def server_info(self) -> ServerInfo: + """Return the responding server's build and Function runtime information. + + This call submits no query, Function, or job. The response is a + JSON-compatible dictionary, convenient to include in a bug report:: + + info = db.server_info() + print(info["query_node"]) # release, git_sha, build_date + + Requires System Usage permission. Embedded connections and older + servers without this endpoint raise ``NotImplementedError``. + Different calls can reach different builds during a rolling upgrade. + Configured images do not identify the version of a running job. + """ + raise NotImplementedError("Server build discovery requires a remote connection") + def list_gpu_classes(self) -> List[GpuClass]: """List the operator-configured Function GPU classes. @@ -2091,8 +2122,9 @@ class LanceDBConnection(DBConnection): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -2127,6 +2159,7 @@ class LanceDBConnection(DBConnection): self._conn.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -2141,8 +2174,9 @@ class LanceDBConnection(DBConnection): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -2154,6 +2188,7 @@ class LanceDBConnection(DBConnection): self._conn.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, @@ -3373,8 +3408,9 @@ class AsyncConnection(object): async def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -3390,9 +3426,15 @@ class AsyncConnection(object): See [DBConnection.create_materialized_view][lancedb.DBConnection.create_materialized_view]. """ - source, native_options = await self._materialized_view_source( - source, select, where, limit - ) + _validate_create_materialized_view(source, query, select, where, limit) + if source is not None: + source, native_options = await self._materialized_view_source( + source, select, where, limit + ) + else: + native_options = {} + if query is not None: + native_options["query"] = query inner = await self._inner.create_materialized_view( name, source, @@ -3409,8 +3451,9 @@ class AsyncConnection(object): async def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -3424,9 +3467,15 @@ class AsyncConnection(object): Enterprise, creation uses SQL; ``job_type`` is ``"query"`` and ``id`` identifies that query on this connection. """ - source, native_options = await self._materialized_view_source( - source, select, where, limit - ) + _validate_create_materialized_view(source, query, select, where, limit) + if source is not None: + source, native_options = await self._materialized_view_source( + source, select, where, limit + ) + else: + native_options = {} + if query is not None: + native_options["query"] = query inner = await self._inner.create_materialized_view_async( name, source, @@ -3653,6 +3702,12 @@ class AsyncConnection(object): """ return _opened_job(await self._inner.open_job(job_id)) + async def server_info(self) -> ServerInfo: + """Read the responding server's build information. See + [DBConnection.server_info][lancedb.db.DBConnection.server_info]. + """ + return json.loads(await self._inner.server_info()) + async def list_gpu_classes(self) -> List[GpuClass]: """List configured Function GPU classes. See [DBConnection.list_gpu_classes][lancedb.db.DBConnection.list_gpu_classes]. diff --git a/python/python/lancedb/materialized_view.py b/python/python/lancedb/materialized_view.py index 7b8c8c6a4..dc04f89f8 100644 --- a/python/python/lancedb/materialized_view.py +++ b/python/python/lancedb/materialized_view.py @@ -134,6 +134,16 @@ def _quote_identifier(name: str) -> str: return f"`{escaped}`" +def _validate_create_materialized_view(source, query, select, where, limit): + if query is not None: + if any(value is not None for value in (source, select, where, limit)): + raise ValueError( + "query cannot be combined with source, select, where or limit" + ) + elif source is None: + raise ValueError("either source or query must be provided") + + def normalize_select(select: SelectArg) -> Optional[List[Tuple[str, str]]]: """``select`` items may be a column name, an ``(alias, expression)`` pair, or a dict of the same. A bare name projects itself and is quoted, so any diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index aa9025641..72dc78c8b 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -696,8 +696,9 @@ class LanceNamespaceDBConnection(DBConnection): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -715,6 +716,7 @@ class LanceNamespaceDBConnection(DBConnection): self._inner.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -730,8 +732,9 @@ class LanceNamespaceDBConnection(DBConnection): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -743,6 +746,7 @@ class LanceNamespaceDBConnection(DBConnection): self._inner.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, @@ -1339,8 +1343,9 @@ class AsyncLanceNamespaceDBConnection: async def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -1352,6 +1357,7 @@ class AsyncLanceNamespaceDBConnection: view = await self._inner.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -1366,8 +1372,9 @@ class AsyncLanceNamespaceDBConnection: async def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: "SelectArg" = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -1379,6 +1386,7 @@ class AsyncLanceNamespaceDBConnection: return await self._inner.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, diff --git a/python/python/lancedb/remote/db.py b/python/python/lancedb/remote/db.py index a06af5d62..db3ab554c 100644 --- a/python/python/lancedb/remote/db.py +++ b/python/python/lancedb/remote/db.py @@ -4,6 +4,8 @@ from __future__ import annotations +from lancedb.server_info import ServerInfo + from dataclasses import replace from datetime import timedelta import json @@ -790,8 +792,9 @@ class RemoteDBConnection(DBConnection): def create_materialized_view( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -805,6 +808,7 @@ class RemoteDBConnection(DBConnection): self._conn.create_materialized_view( name, source, + query=query, select=select, where=where, limit=limit, @@ -826,8 +830,9 @@ class RemoteDBConnection(DBConnection): def create_materialized_view_async( self, name: str, - source: MaterializedViewSource, + source: Optional[MaterializedViewSource] = None, *, + query: Optional[str] = None, select: SelectArg = None, where: Optional[str] = None, limit: Optional[int] = None, @@ -839,6 +844,7 @@ class RemoteDBConnection(DBConnection): self._conn.create_materialized_view_async( name, source, + query=query, select=select, where=where, limit=limit, @@ -966,6 +972,13 @@ class RemoteDBConnection(DBConnection): """ return Job(LOOP.run(self._conn.open_job(job_id))) + @override + def server_info(self) -> ServerInfo: + """Read the responding server's build information. See + [DBConnection.server_info][lancedb.db.DBConnection.server_info]. + """ + return LOOP.run(self._conn.server_info()) + @override def list_gpu_classes(self) -> List[GpuClass]: """List configured Function GPU classes. See diff --git a/python/python/lancedb/server_info.py b/python/python/lancedb/server_info.py new file mode 100644 index 000000000..d53c6c380 --- /dev/null +++ b/python/python/lancedb/server_info.py @@ -0,0 +1,33 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Remote server build information returned as JSON-compatible dictionaries.""" + +from typing import Optional, TypedDict + + +class ServerBuildInfo(TypedDict): + """Immutable identity compiled into a server executable.""" + + release: str + git_sha: str + build_date: Optional[str] + + +class ServerInfo(TypedDict): + """The responding query node and its configured Function runtime. + + ``query_node`` can be ``None`` when the executable has no build metadata. + ``build_date`` is a UTC RFC 3339 timestamp when known. During a rolling + upgrade, separate requests can reach different query-node builds. + Configured images do not establish the version of a running job. + """ + + query_node: Optional[ServerBuildInfo] + lance_version: str + lancedb_version: str + function_worker_protocol_version: int + configured_query_node_image: Optional[str] + configured_job_worker_image: Optional[str] + configured_sql_job_image: Optional[str] + configured_gpu_worker_image: Optional[str] diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 3161eda30..5f0af7a66 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -2661,8 +2661,12 @@ class Table(ABC): results are returned. Row IDs can be obtained from a query with ``with_row_id(True)``. - LanceDB Enterprise reads the requested ranges through version-pinned blob - handles using HTTP byte-range requests. + LanceDB Enterprise uses the batched endpoint when the server advertises + support, partitioning at 1024 ranges and 64 MiB, including individual + larger ranges. Older servers use descriptor queries and BlobFile range + reads. Both protocols read one exact branch and version without changing + the table's checkout. Errors from an advertised endpoint propagate without + switching protocols. The final output occupies memory. """ @abstractmethod @@ -8652,6 +8656,10 @@ class AsyncTable: column: str, requests: Sequence[Sequence[int]], ) -> pa.LargeBinaryArray: + """Materialize row-specific byte ranges. + + See [Table.fetch_blob_ranges][lancedb.table.Table.fetch_blob_ranges]. + """ return await self._inner.fetch_blob_ranges(column, list(requests)) async def fetch_blob_files( diff --git a/python/python/tests/test_blob_ranges.py b/python/python/tests/test_blob_ranges.py new file mode 100644 index 000000000..c65dfb8ae --- /dev/null +++ b/python/python/tests/test_blob_ranges.py @@ -0,0 +1,380 @@ +# SPDX-License-Identifier: Apache-2.0 +# SPDX-FileCopyrightText: Copyright The LanceDB Authors + +"""Exercise the public sync/async range APIs over bounded loopback HTTP.""" + +import asyncio +import hashlib +import json +from pathlib import Path +import socket +import threading + +import lancedb._lancedb as native +import pyarrow as pa +import pytest + +from lancedb.remote.errors import HttpError, TableNotFoundError +from test_remote_db import mock_lancedb_connection + +MIB = 1024 * 1024 +IDENTITY = "v1:" + "a" * 64 +ROUTE = "/v1/table/test/fetch_blob_ranges/" + + +def payload(row, offset, length, version): + pattern = bytes((row * 17 + i + version) % 251 for i in range(251)) + start = offset % 251 + return (pattern * ((start + length + 250) // 251))[start : start + length] + + +class RangeServer: + def __init__(self, fault=None): + self.fault = fault + self.calls = [] + self.fetches = [] + self.identities = [] + self.stalled = threading.Event() + self.release = threading.Event() + + def __call__(self, request): + request.connection.settimeout(15) + size = int(request.headers.get("Content-Length", 0)) + assert size <= 256 * 1024 + body = json.loads(request.rfile.read(size) or b"{}") + self.calls.append((request.command, request.path, body)) + if request.path in ( + "/v1/table/test/describe/", + "/v1/table/test/branches/list/", + ): + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.send_header("phalanx-version", "1.13.0-beta.0") + if request.path.endswith("/describe/"): + request.send_header("x-lancedb-blob-ranges", "1") + request.end_headers() + response = ( + { + "branches": { + "experiment": { + "parentBranch": None, + "parentVersion": 1, + "createAt": 1, + "manifestSize": 1, + } + } + } + if request.path.endswith("branches/list/") + else {"version": 8, "schema": {"fields": []}} + ) + request.wfile.write(json.dumps(response).encode()) + return + assert (request.command, request.path) == ("POST", ROUTE) + self.fetches.append(body) + self.identities.append(request.headers.get("x-lancedb-query-snapshot")) + assert body["column"] == "image" + assert body["branch"] == "experiment" + ranges = body["ranges"] + assert len(ranges) <= 1024 + assert sum(r["length"] for r in ranges) <= 64 * MIB + version = body["version"] or (7 if len(self.fetches) == 1 else 8) + values = [ + None + if r["row_id"] == 20 + else payload(r["row_id"], r["offset"], r["length"], version) + for r in ranges + ] + fault = ( + self.fault + if len(self.fetches) > 1 or str(self.fault).startswith("first-") + else None + ) + if fault in ("recreated", "gone"): + request.send_response(400 if fault == "recreated" else 404) + request.end_headers() + request.wfile.write( + b"query snapshot identity mismatch: source gone or replaced" + ) + return + if fault == "stall" and len(self.fetches) == 2: + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + request.send_header("x-lancedb-version", str(version)) + request.send_header("x-lancedb-query-snapshot", IDENTITY) + request.end_headers() + request.wfile.flush() + self.stalled.set() + assert self.release.wait(15), "test did not release stalled response" + return + if fault == "structured400": + request.send_response(400) + request.send_header("x-lancedb-error-code", "invalid_input") + request.end_headers() + request.wfile.write(b'{"error":"range exceeds blob size"}') + return + if isinstance(fault, int): + request.send_response(fault) + request.end_headers() + request.wfile.write(b"ordinary server failure") + return + if fault == "disconnect": + request.connection.shutdown(socket.SHUT_RDWR) + return + column = "wrong" if fault == "column" else "value" + data_type = pa.binary() if fault == "type" else pa.large_binary() + if fault == "count": + values = [] + elif fault == "length": + values = [b""] + batch = pa.table({column: pa.array(values, type=data_type)}) + sink = pa.BufferOutputStream() + with pa.ipc.new_stream(sink, batch.schema) as writer: + writer.write_table(batch, max_chunksize=257) + ipc = sink.getvalue().to_pybytes() + if fault == "eos": + ipc = ipc[:-8] + elif fault == "body": + ipc = ipc[: len(ipc) // 2] + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + if fault != "version": + request.send_header("x-lancedb-version", str(version)) + if fault not in ("missing-identity", "first-missing-identity"): + identity = ( + "broken" + if fault == "first-invalid-identity" + else "v1:" + "b" * 64 + if fault == "wrong-identity" + else IDENTITY + ) + request.send_header("x-lancedb-query-snapshot", identity) + request.send_header( + "Content-Length", str(len(ipc) + (10 if fault == "transport" else 0)) + ) + request.end_headers() + for i in range(0, len(ipc), 8192): + request.wfile.write(ipc[i : i + 8192]) + + +async def fetch(table, requests, use_async): + result = table.fetch_blob_ranges("image", requests) + return await result if use_async else result + + +def api(db, use_async, version=None): + table = db.open_table("test", branch="experiment", version=version) + return table._table if use_async else table + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("version", [None, 3]) +async def test_range_sdk_order_snapshot_and_overwrite(use_async, version): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + table = api(db, use_async, version) + requests = [(20 if i % 9 == 0 else 10 + i % 7, i, i % 4) for i in range(1025)] + requests += [(10, 0, 0), (10, 2, 3), (10, 2, 3)] + result = await fetch(table, requests, use_async) + assert isinstance(result, pa.LargeBinaryArray) + assert result.to_pylist() == [ + None if row == 20 else payload(row, offset, length, version or 7) + for row, offset, length in requests + ] + assert [b["version"] for b in handler.fetches] == [version, version or 7] + result = await fetch(table, [(10, 0, 1)], use_async) + assert result.to_pylist() == [payload(10, 0, 1, version or 8)] + assert handler.fetches[-1]["version"] == version + assert len(handler.fetches) == 3 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_cached_reopen_negotiates_capability(use_async): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + for version in (7, 8): + table = api(db, use_async) + result = await fetch(table, [(10, 0, 1)], use_async) + assert result.to_pylist() == [payload(10, 0, 1, version)] + assert len(handler.fetches) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_large_single_and_aggregate_budget(use_async): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + requests = [ + (10, 3, 33 * MIB), + (30, 7, 33 * MIB), + (40, 11, 70 * MIB), + (20, 0, 2**64 - 1), + ] + # The loopback server advances latest after the first partition. + result = await fetch(table, requests, use_async) + assert len(result) == 4 + for i, (row, offset, length) in enumerate(requests[:3]): + expected = payload(row, offset, length, 7) + assert ( + hashlib.sha256(result[i].as_buffer()).digest() + == hashlib.sha256(expected).digest() + ) + assert len(result[i].as_buffer()) == length + assert result[3].as_py() is None + assert len(handler.fetches) == 3 + assert [b["version"] for b in handler.fetches] == [None, 7, 7] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize( + "fault", + [ + "type", + "column", + "count", + "length", + "eos", + "body", + "transport", + "version", + "disconnect", + 401, + 403, + 404, + 429, + 500, + ], +) +async def test_range_sdk_later_failure_rejects_entire_call(use_async, fault): + handler = RangeServer(fault=fault) + with mock_lancedb_connection( + handler, retry_config={"retries": 2, "connect_retries": 2, "read_retries": 2} + ) as db: + table = api(db, use_async) + with pytest.raises(Exception) as exc: + await fetch(table, [(10, 0, 1)] * 1025, use_async) + if fault == 404: + assert isinstance(exc.value, TableNotFoundError) + assert isinstance(exc.value.__cause__, HttpError) + assert exc.value.__cause__.status_code == 404 + else: + assert not isinstance(exc.value, ValueError) + if isinstance(fault, int): + assert exc.value.status_code == fault + assert len(handler.fetches) == 2 + assert all( + path in ("/v1/table/test/describe/", "/v1/table/test/branches/list/", ROUTE) + for _, path, _ in handler.calls + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_structured_400_preserves_value_error(use_async): + handler = RangeServer(fault="structured400") + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + with pytest.raises(ValueError, match="range exceeds blob size"): + await fetch(table, [(10, 0, 1)] * 1025, use_async) + assert len(handler.fetches) == 2 + + +@pytest.mark.asyncio +async def test_range_sdk_async_cancel_releases_only_request_permit(): + handler = RangeServer(fault="stall") + with mock_lancedb_connection(handler, blob_request_concurrency=1) as db: + table = api(db, True) + pending = asyncio.create_task(fetch(table, [(10, 0, 1)] * 2049, True)) + try: + assert await asyncio.to_thread(handler.stalled.wait, 10) + pending.cancel() + with pytest.raises(asyncio.CancelledError): + await pending + assert len(handler.fetches) == 2 + result = await asyncio.wait_for(fetch(table, [(10, 0, 1)], True), 5) + assert result.to_pylist() == [payload(10, 0, 1, 8)] + assert len(handler.fetches) == 3 + finally: + pending.cancel() + handler.release.set() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +async def test_range_sdk_integer_validation_and_empty_zero_io(use_async): + handler = RangeServer() + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + before = len(handler.calls) + assert (await fetch(table, [], use_async)).to_pylist() == [] + for request in [ + (-1, 0, 1), + (2**64, 0, 1), + (10, -1, 1), + (10, 0, -1), + (10, 0, 2**64), + (10, 0.5, 1), + (20, 2**64 - 1, 1), + (10, 0), + ]: + with pytest.raises((ValueError, OverflowError, TypeError)): + await fetch(table, [request], use_async) + assert len(handler.calls) == before + + +def test_range_sdk_loaded_artifact_identity(): + artifact = Path(native.__file__).resolve() + digest = hashlib.sha256() + with artifact.open("rb") as source: + for chunk in iter(lambda: source.read(1024 * 1024), b""): + digest.update(chunk) + print(f"loaded native artifact={artifact} sha256={digest.hexdigest()}") + assert artifact.is_file() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize( + "fault", ["missing-identity", "wrong-identity", "recreated", "gone"] +) +@pytest.mark.parametrize("huge", [False, True]) +async def test_range_sdk_original_identity_survives_every_partition( + use_async, fault, huge +): + handler = RangeServer(fault=fault) + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + requests = [(10, 0, 64 * MIB + 1)] if huge else [(10, 0, 1)] * 1025 + error = ( + ValueError + if fault == "recreated" + else TableNotFoundError + if fault == "gone" + else NotImplementedError + ) + with pytest.raises( + error, match="snapshot identity" if fault != "gone" else None + ): + await fetch(table, requests, use_async) + assert handler.identities == [None, IDENTITY] + assert len(handler.fetches) == 2 + assert [body["version"] for body in handler.fetches] == [None, 7] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("use_async", [False, True]) +@pytest.mark.parametrize("fault", ["first-missing-identity", "first-invalid-identity"]) +async def test_range_sdk_bulk_requires_identity_before_payload_acceptance( + use_async, fault +): + handler = RangeServer(fault=fault) + with mock_lancedb_connection(handler) as db: + table = api(db, use_async) + before = len(handler.calls) + with pytest.raises(NotImplementedError, match="snapshot identity"): + await fetch(table, [(10, 0, 1)] * 1025, use_async) + assert len(handler.fetches) == 1 + assert len(handler.calls) == before + 1 diff --git a/python/python/tests/test_materialized_views.py b/python/python/tests/test_materialized_views.py index bf964102b..1ea0c1cb9 100644 --- a/python/python/tests/test_materialized_views.py +++ b/python/python/tests/test_materialized_views.py @@ -10,6 +10,7 @@ import lancedb import pytest import pyarrow as pa from lancedb.db import AsyncConnection +from lancedb.exceptions import JobFailedError from lancedb.materialized_view import MaterializedViewDefinition from lancedb.remote.db import RemoteDBConnection from utils import start_server_thread @@ -175,7 +176,8 @@ async def test_remote_refresh_reports_unknown_metrics( assert not any("count_rows" in path for path in requests) -def test_sync_remote_create_uses_public_async_connection(): +@pytest.mark.parametrize("query", [None, "SELECT name FROM people WHERE age >= 18"]) +def test_sync_remote_create_uses_public_async_connection(query): calls = [] class StubAsyncTable: @@ -190,6 +192,7 @@ def test_sync_remote_create_uses_public_async_connection(): name, source, *, + query=None, select=None, where=None, limit=None, @@ -201,6 +204,7 @@ def test_sync_remote_create_uses_public_async_connection(): ( name, source, + query, select, where, limit, @@ -219,18 +223,24 @@ def test_sync_remote_create_uses_public_async_connection(): db.db_name = "example" db.serialize = lambda: "{}" - view = db.create_materialized_view( - "adults", - "people", - select=["name"], - where="age >= 18", - limit=10, - with_no_data=True, - auto_refresh_enabled=True, - auto_refresh_interval_seconds=0.5, - ) + if query is None: + view = db.create_materialized_view( + "adults", + "people", + select=["name"], + where="age >= 18", + limit=10, + with_no_data=True, + auto_refresh_enabled=True, + auto_refresh_interval_seconds=0.5, + ) + assert calls == [ + ("adults", "people", None, ["name"], "age >= 18", 10, True, True, 0.5) + ] + else: + view = db.create_materialized_view("adults", query=query) + assert calls == [("adults", None, query, None, None, None, False, None, None)] assert view.name == "adults" - assert calls == [("adults", "people", ["name"], "age >= 18", 10, True, True, 0.5)] db.drop_materialized_view("adults", namespace_path=["analytics"]) assert calls[-1] == ("drop", "adults", ["analytics"]) @@ -790,3 +800,144 @@ def test_embedded_explicitly_disabled_refresh_is_supported(tmp_path): db = make_db(tmp_path) view = db.create_materialized_view("mv", "people", auto_refresh_enabled=False) assert view.table.count_rows() == 3 + + +@pytest.mark.experimental_functions +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("namespace", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize( + "query, expected", + [ + ( + "SELECT kind, count(*) AS n FROM events GROUP BY kind", + [{"kind": "a", "n": 2}, {"kind": "b", "n": 1}], + ), + ( + "SELECT id, tag FROM events, UNNEST(tags) AS tag", + [{"id": 1, "tag": "x"}, {"id": 1, "tag": "y"}, {"id": 3, "tag": "z"}], + ), + ], +) +async def test_query_defined_materialized_view( + tmp_path, sync, namespace, background, query, expected +): + if namespace: + connect = lancedb.connect_namespace if sync else lancedb.connect_namespace_async + db = connect("dir", {"root": str(tmp_path)}, storage_options=STABLE_ROW_IDS) + elif sync: + db = lancedb.connect(tmp_path, storage_options=STABLE_ROW_IDS) + else: + db = await lancedb.connect_async(tmp_path, storage_options=STABLE_ROW_IDS) + rows = [ + {"id": 1, "kind": "a", "tags": ["x", "y"]}, + {"id": 2, "kind": "a", "tags": []}, + {"id": 3, "kind": "b", "tags": ["z"]}, + ] + if sync: + db.create_table("events", rows, storage_options=STABLE_ROW_IDS) + if background: + db.create_materialized_view_async("result", query=query).wait() + view = db.open_materialized_view("result") + else: + view = db.create_materialized_view("result", query=query) + actual = view.table.to_arrow().to_pylist() + assert view.definition.query == query + view.refresh() + refreshed = view.table.to_arrow().to_pylist() + else: + await db.create_table("events", rows, storage_options=STABLE_ROW_IDS) + if background: + job = await db.create_materialized_view_async("result", query=query) + await job.wait() + view = await db.open_materialized_view("result") + else: + view = await db.create_materialized_view("result", query=query) + actual = (await view.table.to_arrow()).to_pylist() + assert (await view.definition()).query == query + await view.refresh() + refreshed = (await view.table.to_arrow()).to_pylist() + assert sorted(actual, key=str) == sorted(expected, key=str) + assert sorted(refreshed, key=str) == sorted(expected, key=str) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize("background", [False, True]) +@pytest.mark.parametrize( + "clauses", + [{"source": "people"}, {"select": []}, {"select": {}}, {"where": ""}, {"limit": 0}], +) +async def test_query_rejects_source_clauses_before_submission( + sync, background, clauses +): + connect = lancedb.connect if sync else lancedb.connect_async + db = connect("db://dev", api_key="fake", host_override="http://127.0.0.1:1") + if not sync: + db = await db + create = ( + db.create_materialized_view_async if background else db.create_materialized_view + ) + with pytest.raises(ValueError, match="query cannot be combined"): + if sync: + create("invalid", query="SELECT * FROM people", **clauses) + else: + await create("invalid", query="SELECT * FROM people", **clauses) + with pytest.raises(ValueError, match="either source or query"): + if sync: + create("missing") + else: + await create("missing") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("sync", [False, True]) +@pytest.mark.parametrize( + "query", + [ + "SELECT kind, count(*) AS n FROM events GROUP BY kind", + "SELECT id, c.text FROM docs, chunk(body) AS c", + "SELECT id, tag FROM events, UNNEST(tags) AS tag", + "SELECT a.id FROM a JOIN b ON a.id = b.id", + ], +) +async def test_remote_create_forwards_defining_query(sync, query): + native = CapturingCreateConnection() + db = AsyncConnection(native) + if sync: + remote = RemoteDBConnection.__new__(RemoteDBConnection) + remote._conn = db + job = remote.create_materialized_view_async("result", query=query) + job.wait() + else: + job = await db.create_materialized_view_async("result", query=query) + await job.wait() + assert native.calls[0][0:2] == ("result", None) + assert native.calls[0][2]["query"] == query + + +@pytest.mark.experimental_functions +@pytest.mark.parametrize("background", [False, True]) +def test_query_with_no_data_and_invalid_query(tmp_path, background): + db = make_db(tmp_path) + query = "SELECT name FROM people WHERE age >= 18" + if background: + db.create_materialized_view_async( + "adults", query=query, with_no_data=True + ).wait() + view = db.open_materialized_view("adults") + else: + view = db.create_materialized_view("adults", query=query, with_no_data=True) + assert view.table.count_rows() == 0 + view.refresh() + assert view.table.count_rows() == 2 + create = ( + db.create_materialized_view_async if background else db.create_materialized_view + ) + error = JobFailedError if background else ValueError + with pytest.raises(error, match="unsupported clause"): + result = create("invalid", query="SELECT * FROM people ORDER BY age") + if background: + result.wait() + assert "invalid" not in db.table_names() diff --git a/python/python/tests/test_remote_db.py b/python/python/tests/test_remote_db.py index 561a0f900..ca2516fda 100644 --- a/python/python/tests/test_remote_db.py +++ b/python/python/tests/test_remote_db.py @@ -5466,6 +5466,7 @@ def blob_remote_table( *, server_version=Version("0.5.0"), location=None, + range_capability=None, version_header="1", framing="file", requests=None, @@ -5487,6 +5488,8 @@ def blob_remote_table( request.send_response(200) request.send_header("Content-Type", "application/json") request.send_header("phalanx-version", str(server_version)) + if range_capability is not None: + request.send_header("x-lancedb-blob-ranges", range_capability) request.end_headers() response = dict(BLOB_DESCRIBE_RESPONSE) response["version"] = body.get("version") or state["version"] @@ -5594,6 +5597,42 @@ def blob_remote_table( writer_factory = pa.ipc.new_file if framing == "file" else pa.ipc.new_stream with writer_factory(request.wfile, response_table.schema) as writer: writer.write_table(response_table, max_chunksize=1) + elif ( + range_capability == "1" + and request.path == "/v1/table/test/fetch_blob_ranges/" + ): + size = int(request.headers["Content-Length"]) + body = json.loads(request.rfile.read(size)) + payloads = {10: b"alpha", 20: None, 30: b"gamma", 40: b""} + values = [] + for item in body["ranges"]: + row, offset, length = ( + item[key] for key in ("row_id", "offset", "length") + ) + error = None + if row not in payloads: + error = "only 1 exist" + elif payloads[row] is not None and offset + length > len(payloads[row]): + error = "range exceeds blob size" + if error: + request.send_response(400) + request.end_headers() + request.wfile.write(error.encode()) + return + payload = payloads[row] + values.append( + None if payload is None else payload[offset : offset + length] + ) + response_table = pa.table( + {"value": pa.array(values, type=pa.large_binary())} + ) + request.send_response(200) + request.send_header("Content-Type", "application/vnd.apache.arrow.stream") + request.send_header("x-lancedb-version", "1") + request.send_header("x-lancedb-query-snapshot", "v1:" + "a" * 64) + request.end_headers() + with pa.ipc.new_stream(request.wfile, response_table.schema) as writer: + writer.write_table(response_table) elif request.path == "/v1/table/test/fetch_blobs/": content_len = int(request.headers.get("Content-Length", 0)) body = json.loads(request.rfile.read(content_len)) @@ -5901,8 +5940,11 @@ def test_sync_remote_blob_pandas_avoids_storage_access( @pytest.mark.asyncio @pytest.mark.parametrize("use_async", [False, True]) -async def test_remote_fetch_blob_ranges(use_async): - with blob_remote_table() as remote_table: +@pytest.mark.parametrize("range_capability", [None, "0", "2", "1"]) +async def test_remote_fetch_blob_ranges(use_async, range_capability): + with blob_remote_table( + server_version="1.13.0-beta.0", range_capability=range_capability + ) as remote_table: table = remote_table._table if use_async else remote_table requests = [ (30, 2, 3), @@ -6497,6 +6539,93 @@ def test_remote_job_handle_reports_its_own_detail(): } +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize("known_build", [False, True]) +@pytest.mark.asyncio +async def test_remote_server_info(is_async, known_build): + requests = [] + expected = { + "query_node": { + "release": "1.2.3", + "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + } + if known_build + else None, + "lance_version": "5.0.0", + "lancedb_version": "0.42.0", + "function_worker_protocol_version": 25, + "configured_query_node_image": "example.invalid/query:configured", + "configured_job_worker_image": "example.invalid/cpu:configured", + "configured_sql_job_image": "example.invalid/cli:configured", + "configured_gpu_worker_image": "example.invalid/worker:configured", + } + + def handler(request): + requests.append((request.command, request.path)) + request.send_response(200) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write(json.dumps(expected).encode()) + + if is_async: + async with mock_lancedb_connection_async(handler) as db: + actual = await db.server_info() + else: + with mock_lancedb_connection(handler) as db: + actual = db.server_info() + + assert actual == expected + assert json.loads(json.dumps(actual)) == expected + assert requests == [("GET", "/v1/server/info")] + + +@pytest.mark.parametrize("is_async", [False, True]) +@pytest.mark.parametrize("status", [404, 403]) +@pytest.mark.asyncio +async def test_remote_server_info_errors(is_async, status): + requests = [] + + def handler(request): + requests.append((request.command, request.path)) + request.send_response(status) + request.send_header("Content-Type", "application/json") + request.end_headers() + request.wfile.write( + json.dumps( + { + "error": "discovery unavailable", + "server": { + "release": "1.2.3", + "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + }, + } + ).encode() + ) + + expected_error = NotImplementedError if status == 404 else HttpError + with pytest.raises(expected_error) as caught: + if is_async: + async with mock_lancedb_connection_async(handler) as db: + await db.server_info() + else: + with mock_lancedb_connection(handler) as db: + db.server_info() + + if status == 404: + assert "/v1/server/info" in str(caught.value) + else: + # Permission responses do not carry the input-error classifier header. + # The native HTTP error and Python conversion must retain provenance. + assert "discovery unavailable" in str(caught.value) + assert "1.2.3" in str(caught.value) + assert "0123456789ab" in str(caught.value) + assert "2024-01-01T00:00:00Z" in str(caught.value) + assert caught.value.status_code == 403 + assert requests == [("GET", "/v1/server/info")] + + @pytest.mark.parametrize("is_async", [False, True]) @pytest.mark.asyncio async def test_remote_list_gpu_classes(is_async): diff --git a/python/src/connection.rs b/python/src/connection.rs index 1a99c1372..a32c00be1 100644 --- a/python/src/connection.rs +++ b/python/src/connection.rs @@ -26,6 +26,7 @@ use lancedb::{ database::{CreateTableMode, Database, ReadConsistency}, function::{GpuClass as LanceGpuClass, RefreshColumnResult}, graph::PropertyGraphDefinition, + materialized_view::CreateMaterializedViewBuilder, }; use pyo3::{ Bound, FromPyObject, Py, PyAny, PyRef, PyResult, Python, @@ -34,6 +35,27 @@ use pyo3::{ types::{PyAnyMethods, PyDict, PyDictMethods, PyList}, }; +fn materialized_view_builder( + connection: &LanceConnection, + name: String, + source: Option, + query: Option, + has_clauses: bool, +) -> PyResult { + match (source, query) { + (None, Some(query)) if !has_clauses => { + Ok(connection.create_materialized_view_from_query(name, query)) + } + (Some(source), None) => Ok(connection.create_materialized_view(name, source)), + (None, None) => Err(PyValueError::new_err( + "either source or query must be provided", + )), + _ => Err(PyValueError::new_err( + "query cannot be combined with source, select, where or limit", + )), + } +} + #[pyclass] pub struct Connection { inner: Option, @@ -483,21 +505,29 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] pub fn create_materialized_view( self_: PyRef<'_, Self>, name: String, - source: String, + source: Option, projections: Option>, filter: Option, limit: Option, with_no_data: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, + query: Option, ) -> PyResult> { let inner = self_.get_inner()?.clone(); + let builder = materialized_view_builder( + &inner, + name, + source, + query, + projections.is_some() || filter.is_some() || limit.is_some(), + )?; future_into_py(self_.py(), async move { - let mut builder = inner.create_materialized_view(name, source); + let mut builder = builder; if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } @@ -520,21 +550,29 @@ impl Connection { } #[allow(clippy::too_many_arguments)] - #[pyo3(signature = (name, source, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None))] + #[pyo3(signature = (name, source=None, projections=None, filter=None, limit=None, with_no_data=false, auto_refresh_enabled=None, auto_refresh_interval_seconds=None, *, query=None))] pub fn create_materialized_view_async( self_: PyRef<'_, Self>, name: String, - source: String, + source: Option, projections: Option>, filter: Option, limit: Option, with_no_data: bool, auto_refresh_enabled: Option, auto_refresh_interval_seconds: Option, + query: Option, ) -> PyResult> { let inner = self_.get_inner()?.clone(); + let builder = materialized_view_builder( + &inner, + name, + source, + query, + projections.is_some() || filter.is_some() || limit.is_some(), + )?; future_into_py(self_.py(), async move { - let mut builder = inner.create_materialized_view(name, source); + let mut builder = builder; if let Some(enabled) = auto_refresh_enabled { builder = builder.auto_refresh_enabled(enabled); } @@ -1285,6 +1323,14 @@ impl Connection { )) } + pub fn server_info(self_: PyRef<'_, Self>) -> PyResult> { + let inner = self_.get_inner()?.clone(); + future_into_py(self_.py(), async move { + let info = inner.server_info().await.infer_error()?; + serde_json::to_string(&info).map_err(|error| PyValueError::new_err(error.to_string())) + }) + } + pub fn list_gpu_classes(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.get_inner()?.clone(); future_into_py(self_.py(), async move { diff --git a/rust/lancedb/src/blob.rs b/rust/lancedb/src/blob.rs index ead1f2410..82f502250 100644 --- a/rust/lancedb/src/blob.rs +++ b/rust/lancedb/src/blob.rs @@ -356,7 +356,7 @@ impl BlobFile { /// /// `row_id` is obtained from a query with row ids enabled. /// `offset` and `length` are relative to the beginning of the logical blob. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] pub struct BlobRangeRequest { /// Row id of the blob value to read. pub row_id: u64, diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index fa35dc459..cc398e32b 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -1303,6 +1303,24 @@ impl Connection { self.database().list_gpu_classes().await } + /// Read the responding server's build and Function runtime information. + /// + /// This request does not submit a query, Function, or job. It requires + /// System Usage permission. Embedded databases and older servers without + /// `GET /v1/server/info` return [`Error::NotSupported`]. During a rolling + /// upgrade, separate requests can report different query-node builds. + /// + /// ```no_run + /// # async fn example(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let info = db.server_info().await?; + /// println!("{:?}", info.query_node); + /// # Ok(()) + /// # } + /// ``` + pub async fn server_info(&self) -> Result { + self.database().server_info().await + } + /// List server-side jobs across the database's tables. /// /// Results are fetched lazily, one page at a time. See [`Listing`] diff --git a/rust/lancedb/src/database.rs b/rust/lancedb/src/database.rs index 7b4859faa..23ed9fc3d 100644 --- a/rust/lancedb/src/database.rs +++ b/rust/lancedb/src/database.rs @@ -479,6 +479,13 @@ pub trait Database: async fn list_gpu_classes(&self) -> Result> { gpu_class_catalog_not_supported() } + + /// Read the responding remote server's build identity. + async fn server_info(&self) -> Result { + Err(crate::Error::NotSupported { + message: "Server build discovery requires a remote LanceDB connection".into(), + }) + } /// Create a materialized view through a remote catalog and return its /// initial-population job. Local connections use the native declaration /// path directly. diff --git a/rust/lancedb/src/error.rs b/rust/lancedb/src/error.rs index 89ad7a229..6aed94d71 100644 --- a/rust/lancedb/src/error.rs +++ b/rust/lancedb/src/error.rs @@ -64,6 +64,8 @@ impl RemoteResourceIdentity { #[derive(Debug, Clone, Default, PartialEq, Eq)] #[non_exhaustive] pub struct RemoteErrorMetadata { + /// Build of the executable that produced the error, when reported. + pub server: Option, /// Machine-readable input error code, when available. pub error_code: Option, /// SQL job that failed, when the request ran in an isolated job. @@ -84,6 +86,8 @@ impl RemoteErrorMetadata { .map(str::to_owned) }; Self { + server: header("x-lancedb-server-build") + .and_then(|value| serde_json::from_str(&value).ok()), error_code: header("x-lancedb-error-code"), job_id: header("x-lancedb-sql-job-id"), job_request_id: header("x-job-request-id"), @@ -119,7 +123,7 @@ pub(crate) fn parse_flight_resource_identity(value: &str) -> Option, @@ -131,17 +135,28 @@ impl HttpErrorSource { pub(crate) fn new( message: String, response_body: Option<&str>, - metadata: RemoteErrorMetadata, + mut metadata: RemoteErrorMetadata, ) -> Self { let details = response_body.and_then(parse_http_error_details); + let body = + response_body.and_then(|body| serde_json::from_str::(body).ok()); + if metadata.server.is_none() { + metadata.server = body + .as_ref() + .and_then(|body| body.get("server").cloned()) + .and_then(|server| serde_json::from_value(server).ok()); + } let message = if metadata.error_code.is_some() { - response_body - .and_then(|body| serde_json::from_str::(body).ok()) + body.as_ref() .and_then(|body| body.get("error")?.as_str().map(str::to_owned)) .unwrap_or(message) } else { message }; + let message = match &metadata.server { + Some(server) => format!("{message} [server: {server}]"), + None => message, + }; Self { message, details, @@ -317,6 +332,18 @@ impl Display for JobFailure { } } +fn server_build_suffix(_source: &(dyn std::error::Error + Send + Sync + 'static)) -> String { + #[cfg(feature = "remote")] + if let Some(server) = _source + .downcast_ref::() + .and_then(Error::remote_error_metadata) + .and_then(|metadata| metadata.server.as_ref()) + { + return format!(" [server: {server}]"); + } + String::new() +} + #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { @@ -324,7 +351,7 @@ pub enum Error { InvalidTableName { name: String, reason: String }, #[snafu(display("Invalid input, {message}"))] InvalidInput { message: String }, - #[snafu(display("Table '{name}' was not found"))] + #[snafu(display("Table '{name}' was not found{}", server_build_suffix(source.as_ref())))] TableNotFound { name: String, source: BoxError }, #[snafu(display( "Table '{name}' exists but could not be loaded (it may be corrupt or incomplete): {source}" @@ -385,8 +412,8 @@ pub enum Error { }, #[snafu(display("Job{} was cancelled", job_id.as_ref().map(|id| format!(" {id}")).unwrap_or_default()))] JobCancelled { job_id: Option }, - #[snafu(display("Job '{job_id}' was not found"))] - JobNotFound { job_id: String }, + #[snafu(display("Job '{job_id}' was not found{}", server_build_suffix(source.as_ref())))] + JobNotFound { job_id: String, source: BoxError }, // 3rd party / external errors #[snafu(display("object_store error: {source}"))] @@ -576,7 +603,7 @@ impl Error { match self { Self::Http { status_code, .. } => *status_code, Self::Retry { status_code, .. } => *status_code, - Self::TableNotFound { source, .. } => { + Self::TableNotFound { source, .. } | Self::JobNotFound { source, .. } => { source.downcast_ref::().and_then(Self::status_code) } Self::JobFailed { failure, .. } => { @@ -623,7 +650,7 @@ impl Error { Self::Retry { source, .. } => source .downcast_ref::() .and_then(Self::remote_error_metadata), - Self::TableNotFound { source, .. } => source + Self::TableNotFound { source, .. } | Self::JobNotFound { source, .. } => source .downcast_ref::() .and_then(Self::remote_error_metadata), Self::JobFailed { failure, .. } => failure @@ -635,9 +662,35 @@ impl Error { } } - /// A copy of an error that other partitions of a DataFusion plan still hold. - /// Only an interrupted response can be copied, because it shares its source. - fn clone_shared(&self) -> Option { + /// Copy supported errors without flattening sources retained by a shared plan + /// or schema cache. + pub(crate) fn clone_shared(&self) -> Option { + #[cfg(feature = "remote")] + match self { + Self::Http { + source, + request_id, + status_code, + } => { + return source + .downcast_ref::() + .map(|source| Self::Http { + source: Box::new(source.clone()), + request_id: request_id.clone(), + status_code: *status_code, + }); + } + Self::TableNotFound { name, source } => { + return source + .downcast_ref::() + .and_then(Self::clone_shared) + .map(|source| Self::TableNotFound { + name: name.clone(), + source: Box::new(source), + }); + } + _ => {} + } #[cfg(feature = "remote")] if let Self::ResponseInterrupted { request_id, diff --git a/rust/lancedb/src/lib.rs b/rust/lancedb/src/lib.rs index 0f02d90cf..9f800d593 100644 --- a/rust/lancedb/src/lib.rs +++ b/rust/lancedb/src/lib.rs @@ -216,6 +216,7 @@ pub mod query; pub mod remote; pub mod rerankers; pub mod secrets; +pub mod server_info; pub mod sql; pub mod storage_integration; pub mod table; diff --git a/rust/lancedb/src/materialized_view.rs b/rust/lancedb/src/materialized_view.rs index bd7fbb942..9920cd893 100644 --- a/rust/lancedb/src/materialized_view.rs +++ b/rust/lancedb/src/materialized_view.rs @@ -1574,14 +1574,15 @@ async fn prepare_with( } /// Builds a materialized view. Created by -/// [`Connection::create_materialized_view`]. +/// [`Connection::create_materialized_view`] or +/// [`Connection::create_materialized_view_from_query`]. pub struct CreateMaterializedViewBuilder { connection: Connection, name: String, namespace: Vec, - source: String, + input: MaterializedViewInput, source_namespace: Vec, - projections: Vec<(String, String)>, + projections: Option>, filter: Option, limit: Option, with_no_data: bool, @@ -1589,6 +1590,11 @@ pub struct CreateMaterializedViewBuilder { auto_refresh_interval_seconds: Option, } +enum MaterializedViewInput { + Source(String), + Query(String), +} + fn source_sql_identifier( namespace_path: &[String], source: &str, @@ -1609,14 +1615,14 @@ fn source_sql_identifier( } impl CreateMaterializedViewBuilder { - pub(crate) fn new(connection: Connection, name: String, source: String) -> Self { + fn new(connection: Connection, name: String, input: MaterializedViewInput) -> Self { Self { connection, name, namespace: Vec::new(), - source, + input, source_namespace: Vec::new(), - projections: Vec::new(), + projections: None, filter: None, limit: None, with_no_data: false, @@ -1644,10 +1650,12 @@ impl CreateMaterializedViewBuilder { mut self, columns: impl IntoIterator, impl Into)>, ) -> Self { - self.projections = columns - .into_iter() - .map(|(output, expression)| (output.into(), expression.into())) - .collect(); + self.projections = Some( + columns + .into_iter() + .map(|(output, expression)| (output.into(), expression.into())) + .collect(), + ); self } @@ -1697,22 +1705,38 @@ impl CreateMaterializedViewBuilder { } fn query(&self) -> Result { + if let MaterializedViewInput::Query(query) = &self.input { + if !self.source_namespace.is_empty() + || self.projections.is_some() + || self.filter.is_some() + || self.limit.is_some() + { + return Err(Error::InvalidInput { + message: "a defining query cannot be combined with source_namespace, select, only_if or limit".into(), + }); + } + return Ok(query.clone()); + } + let MaterializedViewInput::Source(source) = &self.input else { + unreachable!() + }; fn quote(name: &str) -> String { format!("\"{}\"", name.replace('"', "\"\"")) } - let projection = if self.projections.is_empty() { - "*".to_string() - } else { - self.projections - .iter() - .map(|(output, expression)| format!("{expression} AS {}", quote(output))) - .collect::>() - .join(", ") - }; + let projection = + if let Some(projections) = self.projections.as_ref().filter(|p| !p.is_empty()) { + projections + .iter() + .map(|(output, expression)| format!("{expression} AS {}", quote(output))) + .collect::>() + .join(", ") + } else { + "*".to_string() + }; let source = source_sql_identifier( &self.source_namespace, - &self.source, + source, self.connection.uri().starts_with("db://"), ); let mut query = format!("SELECT {projection} FROM {source}"); @@ -1775,19 +1799,33 @@ impl CreateMaterializedViewBuilder { .to_string(), }); } - let source = self - .connection - .open_table(&self.source) - .namespace(self.source_namespace.clone()) - .execute() - .await?; - let prepared = prepare_declaration( - &source, - (!self.projections.is_empty()).then_some(self.projections.as_slice()), - self.filter.as_deref(), - self.limit, - ) - .await?; + let prepared = match &self.input { + MaterializedViewInput::Source(name) => { + let source = self + .connection + .open_table(name) + .namespace(self.source_namespace.clone()) + .execute() + .await?; + prepare_declaration( + &source, + self.projections.as_deref().filter(|p| !p.is_empty()), + self.filter.as_deref(), + self.limit, + ) + .await? + } + MaterializedViewInput::Query(_) => { + let definition = MaterializedViewDefinition::from_sql(&self.query()?)?; + let source = self + .connection + .open_table(&definition.source_table) + .namespace(definition.source_namespace.clone()) + .execute() + .await?; + prepare_definition(&source, definition).await? + } + }; let view = prepared.create_in(&self.namespace, &self.name).await?; if !self.with_no_data { view.refresh().execute().await?; @@ -2067,7 +2105,41 @@ impl Connection { name: impl Into, source: impl Into, ) -> CreateMaterializedViewBuilder { - CreateMaterializedViewBuilder::new(self.clone(), name.into(), source.into()) + CreateMaterializedViewBuilder::new( + self.clone(), + name.into(), + MaterializedViewInput::Source(source.into()), + ) + } + + /// Define a materialized view using a complete SQL query. + /// + /// Embedded connections parse the query with + /// [`MaterializedViewDefinition::from_sql`]. Remote connections send the + /// query to the server, which determines the supported SQL syntax. + /// Put projections, predicates and limits in the query rather than using + /// the builder's source-specific methods. + /// + /// ```no_run + /// # #![recursion_limit = "256"] + /// # async fn create(db: &lancedb::Connection) -> lancedb::Result<()> { + /// let view = db.create_materialized_view_from_query( + /// "events_by_kind", + /// "SELECT kind, count(*) AS n FROM events GROUP BY kind", + /// ).execute().await?; + /// # Ok(()) + /// # } + /// ``` + pub fn create_materialized_view_from_query( + &self, + name: impl Into, + query: impl Into, + ) -> CreateMaterializedViewBuilder { + CreateMaterializedViewBuilder::new( + self.clone(), + name.into(), + MaterializedViewInput::Query(query.into()), + ) } /// Open the materialized view named `name`. @@ -2229,6 +2301,65 @@ mod tests { ); } + #[tokio::test] + async fn query_builder_rejects_source_clauses() { + let conn = connect("memory://").execute().await.unwrap(); + let builder = || conn.create_materialized_view_from_query("mv", "SELECT * FROM src"); + for invalid in [ + builder().select([("x", "x")]), + builder().select(Vec::<(String, String)>::new()), + builder().only_if("x > 0"), + builder().limit(0), + builder().source_namespace(vec!["ns".into()]), + ] { + assert!(matches!(invalid.query(), Err(Error::InvalidInput { .. }))); + } + } + + #[tokio::test] + #[cfg_attr( + not(feature = "experimental-functions"), + ignore = "requires experimental-functions" + )] + async fn create_from_query_supports_grouping_and_background_population() { + let conn = connect("memory://").execute().await.unwrap(); + conn.create_table( + "src", + record_batch!(("kind", Utf8, ["a", "a", "b"])).unwrap(), + ) + .execute() + .await + .unwrap(); + let query = "SELECT kind, count(*) AS n FROM src GROUP BY kind"; + let view = conn + .create_materialized_view_from_query("groups", query) + .with_no_data(true) + .execute() + .await + .unwrap(); + assert_eq!(view.definition_sql(), query); + assert_eq!(view.table().count_rows(None).await.unwrap(), 0); + view.refresh().execute().await.unwrap(); + assert_eq!(view.table().count_rows(None).await.unwrap(), 2); + conn.create_materialized_view_from_query("background", query) + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap(); + assert_eq!( + conn.open_materialized_view("background") + .await + .unwrap() + .table() + .count_rows(None) + .await + .unwrap(), + 2 + ); + } + #[test] fn sql_definition_defaults_share_one_metadata_value() { let metadata = HashMap::from([( diff --git a/rust/lancedb/src/remote/db.rs b/rust/lancedb/src/remote/db.rs index b562f41df..92523ec34 100644 --- a/rust/lancedb/src/remote/db.rs +++ b/rust/lancedb/src/remote/db.rs @@ -1242,16 +1242,39 @@ impl Database for RemoteDatabase { let handle = super::job::RemoteJob::new(self.client.clone(), job_id.to_string()); match crate::job::JobHandle::describe(&handle).await { Ok(description) => Ok(Job::opened(Box::new(handle), description)), - Err(Error::Http { - status_code: Some(StatusCode::NOT_FOUND), - .. - }) => Err(Error::JobNotFound { + Err( + error @ Error::Http { + status_code: Some(StatusCode::NOT_FOUND), + .. + }, + ) => Err(Error::JobNotFound { job_id: job_id.to_string(), + source: Box::new(error), }), Err(err) => Err(err), } } + async fn server_info(&self) -> Result { + let req = self.client.get("/v1/server/info"); + let (request_id, response) = self.client.send(req).await?; + let response = match self.client.check_response(&request_id, response).await { + Ok(response) => response, + Err(Error::Http { + status_code: Some(StatusCode::NOT_FOUND), + .. + }) => { + return Err(Error::NotSupported { + message: "Server build discovery requires a newer LanceDB server; \ + GET /v1/server/info returned 404 Not Found" + .into(), + }); + } + Err(error) => return Err(error), + }; + response.json().await.err_to_http(request_id) + } + async fn list_gpu_classes(&self) -> Result> { #[derive(serde::Deserialize)] struct Response { @@ -1655,9 +1678,9 @@ impl Database for RemoteDatabase { let (request_id, rsp) = self.client.send_with_retry(req, None, true).await?; let rsp = RemoteTable::::handle_table_not_found(&request.name, rsp, &request_id).await?; - self.client.check_response(&request_id, rsp).await?; + let rsp = self.client.check_response(&request_id, rsp).await?; - Ok(Arc::new(RemoteTable::new_with_sql_client( + let table = Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), self.db_name.clone(), request.name, @@ -1665,7 +1688,9 @@ impl Database for RemoteDatabase { identifier, version, self.sql_client.clone(), - ))) + )); + table.seed_blob_ranges_capability(rsp.headers()); + Ok(table) } else { // Describe the table to confirm it exists before moving on. let req = self @@ -1676,6 +1701,7 @@ impl Database for RemoteDatabase { RemoteTable::::handle_table_not_found(&request.name, rsp, &request_id).await?; let rsp = self.client.check_response(&request_id, rsp).await?; let version = parse_server_version(&request_id, &rsp)?; + let describe_headers = rsp.headers().clone(); let describe_body = rsp.text().await.ok(); let table = Arc::new(RemoteTable::new_with_sql_client( self.client.clone(), @@ -1686,6 +1712,7 @@ impl Database for RemoteDatabase { version.clone(), self.sql_client.clone(), )); + table.seed_blob_ranges_capability(&describe_headers); // This describe already carries the schema, so hand it to the table // instead of making the first schema read fetch it again. A version or // branch pin applied after this invalidates the cache. @@ -4151,6 +4178,106 @@ mod tests { } } + #[tokio::test] + async fn test_server_info_preserves_remote_provenance() { + let conn = Connection::new_with_handler(|request| { + assert_eq!(request.method(), &reqwest::Method::GET); + assert_eq!(request.url().path(), "/v1/server/info"); + http::Response::builder().status(200).body(serde_json::json!({ + "query_node": { "release": "1.2.3", "git_sha": "0123456789ab", "build_date": "2024-01-01T00:00:00Z" }, + "lance_version": "5.0.0", + "lancedb_version": "0.42.0", + "function_worker_protocol_version": 25, + "configured_gpu_worker_image": "example.invalid/worker:configured", + "future_component": "ignored" + }).to_string()).unwrap() + }); + let info = conn.server_info().await.unwrap(); + let build = info.query_node.unwrap(); + assert_eq!(build.release, "1.2.3"); + assert_eq!(build.git_sha, "0123456789ab"); + assert_eq!(build.build_date.as_deref(), Some("2024-01-01T00:00:00Z")); + assert_eq!(info.function_worker_protocol_version, 25); + assert_eq!( + info.configured_gpu_worker_image.as_deref(), + Some("example.invalid/worker:configured") + ); + } + + #[tokio::test] + async fn test_server_info_error_provenance_survives_classification() { + for target in ["table", "job", "masked"] { + let conn = Connection::new_with_handler(move |_| { + let server = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + }); + if target == "masked" { + http::Response::builder() + .status(500) + .header("x-lancedb-server-build", server.to_string()) + .body("Internal server error".to_string()) + .unwrap() + } else { + http::Response::builder() + .status(404) + .body(serde_json::json!({"error": "missing", "server": server}).to_string()) + .unwrap() + } + }); + let error = match target { + "table" => conn.open_table("missing").execute().await.unwrap_err(), + "job" => conn.open_job("missing").await.unwrap_err(), + _ => conn.server_info().await.unwrap_err(), + }; + match target { + "table" => assert!(matches!(&error, Error::TableNotFound { .. })), + "job" => assert!(matches!(&error, Error::JobNotFound { .. })), + _ => assert_eq!( + error.status_code(), + Some(http::StatusCode::INTERNAL_SERVER_ERROR) + ), + } + let server = error + .remote_error_metadata() + .unwrap() + .server + .as_ref() + .unwrap(); + assert_eq!(server.git_sha, "0123456789ab"); + assert_eq!(server.release, "1.2.3"); + let message = error.to_string(); + assert!(message.contains("0123456789ab"), "{message}"); + assert!(message.contains("2024-01-01T00:00:00Z"), "{message}"); + } + } + + #[tokio::test] + async fn test_server_info_distinguishes_unsupported_from_denied() { + for status in [404, 403] { + let conn = Connection::new_with_handler(move |_| { + http::Response::builder() + .status(status) + .body("unavailable") + .unwrap() + }); + let error = conn.server_info().await.unwrap_err(); + if status == 404 { + assert!( + matches!(error, Error::NotSupported { message } if message.contains("/v1/server/info")) + ); + } else { + assert!(matches!( + error, + Error::Http { + status_code: Some(http::StatusCode::FORBIDDEN), + .. + } + )); + } + } + } + #[tokio::test] async fn test_list_gpu_classes_reports_configured_hardware() { let conn = Connection::new_with_handler(|request| { @@ -4364,7 +4491,7 @@ mod tests { }); let err = conn.open_job("nope").await.unwrap_err(); assert!( - matches!(&err, Error::JobNotFound { job_id } if job_id == "nope"), + matches!(&err, Error::JobNotFound { job_id, .. } if job_id == "nope"), "{err:?}" ); } diff --git a/rust/lancedb/src/remote/sql.rs b/rust/lancedb/src/remote/sql.rs index 949b078e3..9c34f8f90 100644 --- a/rust/lancedb/src/remote/sql.rs +++ b/rust/lancedb/src/remote/sql.rs @@ -1797,6 +1797,11 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro .map(str::to_owned) }; let metadata = crate::error::RemoteErrorMetadata { + server: status + .metadata() + .get_bin("x-lancedb-server-build-bin") + .and_then(|value| value.to_bytes().ok()) + .and_then(|value| serde_json::from_slice(&value).ok()), error_code: header("x-lancedb-error-code"), job_id: header(SQL_JOB_ID_METADATA_KEY), job_request_id: header("x-job-request-id"), @@ -1805,8 +1810,12 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro .and_then(crate::error::parse_flight_resource_identity), }; let sql_job_id = metadata.job_id.clone(); + let mut message = status.message().to_owned(); + if let Some(server) = &metadata.server { + message.push_str(&format!(" [server: {server}]")); + } let error = Error::Sql { - message: status.message().into(), + message: message.clone(), request_id: request_id.into(), grpc_code: status.code() as i32, metadata: Box::new(metadata), @@ -1816,7 +1825,7 @@ pub(super) fn sql_status_error(request_id: &str, status: &tonic::Status) -> Erro job_id: Some(sql_job_id.clone()), failure: Box::new(JobFailure { phase: None, - message: Some(status.message().into()), + message: Some(message), traceback: None, retryable: None, sql_job_id: Some(sql_job_id), diff --git a/rust/lancedb/src/remote/sql_test.rs b/rust/lancedb/src/remote/sql_test.rs index d94defac4..d25c72830 100644 --- a/rust/lancedb/src/remote/sql_test.rs +++ b/rust/lancedb/src/remote/sql_test.rs @@ -33,6 +33,53 @@ use crate::remote::table::RemoteTable; use crate::storage_integration::{CreateStorageIntegrationRequest, SecretReference}; use crate::table::BaseTable; +#[test] +fn server_info_survives_flight_error_and_job_wrapping() { + for with_job in [false, true] { + let mut status = tonic::Status::invalid_argument("invalid query"); + status + .metadata_mut() + .insert("x-lancedb-error-code", "invalid_query".parse().unwrap()); + let build = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", "build_date": "2024-01-01T00:00:00Z" + }) + .to_string(); + status.metadata_mut().insert_bin( + "x-lancedb-server-build-bin", + tonic::metadata::MetadataValue::from_bytes(build.as_bytes()), + ); + if with_job { + status + .metadata_mut() + .insert(SQL_JOB_ID_METADATA_KEY, "job-original".parse().unwrap()); + } + let error = sql_status_error("request-original", &status); + let text = error.to_string(); + assert!(text.contains("invalid query"), "{text}"); + assert!(text.contains("1.2.3"), "{text}"); + assert!(text.contains("0123456789ab"), "{text}"); + assert!(text.contains("2024-01-01T00:00:00Z"), "{text}"); + assert_eq!( + error.remote_error_metadata().unwrap().error_code.as_deref(), + Some("invalid_query") + ); + match error { + Error::JobFailed { job_id, .. } if with_job => { + assert_eq!(job_id.as_deref(), Some("job-original")) + } + Error::Sql { + grpc_code, + request_id, + .. + } if !with_job => { + assert_eq!(grpc_code, tonic::Code::InvalidArgument as i32); + assert_eq!(request_id, "request-original"); + } + other => panic!("unexpected error classification: {other}"), + } + } +} + #[derive(Debug, Default)] struct DelayedHeaderProvider { delay_next: AtomicBool, @@ -1090,6 +1137,61 @@ async fn catalog_connections_use_explicit_sql_endpoint_and_database_scope() { server.await.unwrap().unwrap(); } +#[tokio::test] +async fn remote_query_builder_sends_the_complete_query() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let incoming = futures::stream::try_unfold(listener, |listener| async { + let (socket, _) = listener.accept().await?; + Ok::<_, std::io::Error>(Some((socket, listener))) + }); + let service = TestSqlService { + adaptive: true, + ..Default::default() + }; + let statements = service.statements.clone(); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let server = tokio::spawn( + tonic::transport::Server::builder() + .add_service(FlightServiceServer::new(service)) + .serve_with_incoming_shutdown(incoming, async { + let _ = shutdown_rx.await; + }), + ); + let connection = crate::connect("db://analytics") + .region("us-east-1") + .api_key("test-key") + .host_override("http://127.0.0.1:1") + .sql_host_override(&format!("grpc://{address}")) + .execute() + .await + .unwrap(); + for query in [ + "SELECT kind, count(*) AS n FROM events GROUP BY kind", + "SELECT id, c.text FROM docs, chunk(body) AS c", + "SELECT id, tag FROM events, UNNEST(tags) AS tag", + "SELECT a.id FROM a JOIN b ON a.id = b.id", + ] { + connection + .create_materialized_view_from_query("result", query) + .auto_refresh_enabled(false) + .execute_async() + .await + .unwrap() + .wait() + .await + .unwrap(); + assert_eq!( + statements.lock().unwrap().last().unwrap(), + &format!( + "CREATE MATERIALIZED VIEW \"result\" WITH (auto_refresh_enabled = false) AS {query}" + ) + ); + } + shutdown_tx.send(()).unwrap(); + server.await.unwrap().unwrap(); +} + #[tokio::test] async fn remote_create_uses_sql_and_preserves_options_and_namespace() { for defer in [false, true] { diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index d560a4802..dcceb4260 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -86,6 +86,7 @@ use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; use std::io::Cursor; use std::pin::Pin; +use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, SystemTime}; use tokio::sync::RwLock; @@ -634,6 +635,8 @@ pub struct RemoteTable { version: Arc>>, location: RwLock>, schema_cache: BackgroundCache, + // Only a successful describe can opt into the batched range protocol. + blob_ranges_supported: Arc, // WAL-PK-FUSION: delete, with its initializers below. wal_pk_fusion: PkFusionMemory, freshness: Arc>, @@ -881,6 +884,7 @@ impl RemoteTable { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -888,6 +892,15 @@ impl RemoteTable { } } + pub(super) fn seed_blob_ranges_capability(&self, headers: &http::HeaderMap) { + self.blob_ranges_supported.store( + headers + .get("x-lancedb-blob-ranges") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); + } + /// Seed the schema cache from a `describe` body the caller already fetched. /// /// Best effort. `open_table` succeeds today without reading this body, so a @@ -918,6 +931,7 @@ impl RemoteTable { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: self.blob_ranges_supported.clone(), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch, @@ -1067,6 +1081,7 @@ impl RemoteTable { }; let response = self.check_table_response(&request_id, response).await?; + self.seed_blob_ranges_capability(response.headers()); match response.text().await { Ok(body) => { @@ -1924,7 +1939,7 @@ fn base_media_type(content_type: &str) -> &str { fn unwrap_shared_error(arc: Arc) -> Error { match Arc::try_unwrap(arc) { Ok(err) => err, - Err(arc) => match &*arc { + Err(arc) => arc.clone_shared().unwrap_or_else(|| match &*arc { Error::TableNotFound { name, source } => Error::TableNotFound { name: name.clone(), source: source.to_string().into(), @@ -1932,7 +1947,7 @@ fn unwrap_shared_error(arc: Arc) -> Error { _ => Error::Runtime { message: arc.to_string(), }, - }, + }), } } @@ -1943,6 +1958,7 @@ async fn fetch_schema( read_snapshot: ReadSnapshot, branch: Option, freshness: Arc>, + blob_ranges_supported: Arc, ) -> Result { let mut body = serde_json::json!({ "version": read_snapshot.version }); if let Some(branch) = &branch { @@ -1955,20 +1971,18 @@ async fn fetch_schema( let (request_id, response) = client.send_with_retry(request, None, true).await?; - if response.status() == StatusCode::NOT_FOUND { - let body = response.text().await.ok().unwrap_or_default(); - return Err(Error::TableNotFound { - name: table_name.to_string(), - source: Box::new(Error::Http { - source: body.into(), - request_id, - status_code: Some(StatusCode::NOT_FOUND), - }), - }); - } + let response = + RemoteTable::::handle_table_not_found(table_name, response, &request_id).await?; let response = client.check_response(&request_id, response).await?; freshness_headers.observe_headers(&freshness, response.headers()); + blob_ranges_supported.store( + response + .headers() + .get("x-lancedb-blob-ranges") + .is_some_and(|value| value == "1"), + AtomicOrdering::Relaxed, + ); let body = response.text().await.map_err(|e| { let status_code = e.status(); Error::Http { @@ -2026,6 +2040,7 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2054,6 +2069,7 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2091,6 +2107,7 @@ mod test_utils { version: Arc::new(RwLock::new(None)), location: RwLock::new(None), schema_cache: BackgroundCache::new(SCHEMA_CACHE_TTL, SCHEMA_CACHE_REFRESH_WINDOW), + blob_ranges_supported: Arc::new(AtomicBool::new(false)), wal_pk_fusion: PkFusionMemory::default(), freshness: Arc::new(Mutex::new(FreshnessState::default())), branch: None, @@ -2885,6 +2902,7 @@ impl BaseTable for RemoteTable { let table_name = self.name.clone(); let branch = self.branch.clone(); let freshness = self.freshness.clone(); + let blob_ranges_supported = self.blob_ranges_supported.clone(); match self .schema_cache @@ -2896,6 +2914,7 @@ impl BaseTable for RemoteTable { read_snapshot, branch, freshness, + blob_ranges_supported, ) .await }) @@ -4894,6 +4913,49 @@ mod tests { assert_eq!(schema, expected); } + #[tokio::test] + async fn test_server_info_survives_schema_cache_errors() { + let expected = crate::server_info::ServerBuildInfo { + release: "1.2.3".into(), + git_sha: "0123456789ab".into(), + build_date: Some("2024-01-01T00:00:00Z".into()), + }; + for header_only in [false, true] { + let table = Table::new_with_handler("my_table", move |request| { + assert_eq!(request.url().path(), "/v1/table/my_table/describe/"); + let server = serde_json::json!({ + "release": "1.2.3", "git_sha": "0123456789ab", + "build_date": "2024-01-01T00:00:00Z", + }); + let response = http::Response::builder().status(404); + if header_only { + response + .header("x-lancedb-server-build", server.to_string()) + .body("missing".to_string()) + .unwrap() + } else { + response + .body(serde_json::json!({"error": "missing", "server": server}).to_string()) + .unwrap() + } + }); + let original = Arc::new(table.schema().await.unwrap_err()); + // Keep another reader's reference alive to exercise the shared result. + let shared = unwrap_shared_error(original.clone()); + for error in [original.as_ref(), &shared] { + assert!(matches!(error, Error::TableNotFound { name, .. } if name == "my_table")); + assert_eq!(error.status_code(), Some(StatusCode::NOT_FOUND)); + assert_eq!( + error + .remote_error_metadata() + .and_then(|metadata| metadata.server.as_ref()), + Some(&expected), + ); + assert!(error.to_string().contains("0123456789ab")); + } + } + } + #[tokio::test] async fn test_count_rows() { let table = Table::new_with_handler("my_table", |request| { diff --git a/rust/lancedb/src/remote/table/blobs.rs b/rust/lancedb/src/remote/table/blobs.rs index a0051c955..3367d2218 100644 --- a/rust/lancedb/src/remote/table/blobs.rs +++ b/rust/lancedb/src/remote/table/blobs.rs @@ -35,11 +35,13 @@ use crate::table::{AnyQuery, BaseTable}; use super::{ FreshnessHeaders, FreshnessState, QUERY_SNAPSHOT_HEADER, ReadSnapshot, RemoteTable, VERSION_HEADER, check_query_snapshot_response, freshness_headers_snapshot, + valid_query_snapshot_identity, }; // The Cloud route rejects larger row-id lists. Its separate 64 MiB byte limit // is handled by splitting a rejected request below. const MAX_FETCH_BLOBS_ROW_IDS: usize = 1024; +const MAX_FETCH_BLOB_RANGE_BYTES: u64 = 64 * 1024 * 1024; fn is_fetch_blobs_byte_limit_error(error: &Error) -> bool { matches!(error, Error::Http { @@ -599,7 +601,7 @@ impl RemoteTable { read_snapshot.version = Some(self.describe_read_snapshot(read_snapshot).await?.version); } let mut pending: Vec<&[u64]> = row_ids.chunks(MAX_FETCH_BLOBS_ROW_IDS).rev().collect(); - let mut blobs = BlobAccumulator::new(row_ids.len()); + let mut blobs = BlobAccumulator::new(row_ids.len())?; while let Some(ids) = pending.pop() { match self .fetch_blobs_chunk(column, ids, read_snapshot, &mut blobs) @@ -642,7 +644,7 @@ impl RemoteTable { } } - Ok(blobs.finish()) + Ok(blobs.finish()?) } async fn fetch_blobs_chunk( @@ -725,11 +727,88 @@ impl RemoteTable { Ok(()) } - /// Materialize ranges through version-pinned handles, preserving nulls and order. + /// Materialize ranges using the protocol advertised by a successful describe. pub(super) async fn fetch_blob_ranges_impl( &self, column: &str, requests: &[BlobRangeRequest], + ) -> Result { + let mut blobs = BlobAccumulator::new(requests.len())?; + if requests.is_empty() { + return Ok(blobs.finish()?); + } + for request in requests { + request + .offset + .checked_add(request.length) + .ok_or_else(|| Error::InvalidInput { + message: "blob range offset + length overflows u64".into(), + })?; + } + self.reject_list_blob_path_if_known(column).await?; + if !self.blob_ranges_supported.load(Ordering::Relaxed) { + return self.fetch_blob_ranges_legacy(column, requests).await; + } + // Select the protocol before issuing data requests. An advertised endpoint + // failing in a mixed deployment must fail truthfully, without fallback. + let mut snapshot = self.snapshot_read_state().await; + let mut identity = self.expected_query_snapshot.clone(); + let mut index = 0; + let mut consumed = 0; + let mut ranges = Vec::new(); + ranges + .try_reserve_exact(MAX_FETCH_BLOBS_ROW_IDS) + .map_err(|error| Error::InvalidInput { + message: format!("cannot allocate blob range requests: {error}"), + })?; + while index < requests.len() { + ranges.clear(); + let continuation = consumed != 0; + let mut budget = MAX_FETCH_BLOB_RANGE_BYTES; + while index < requests.len() && ranges.len() < MAX_FETCH_BLOBS_ROW_IDS { + let request = requests[index]; + let remaining = request.length - consumed; + if budget == 0 && remaining != 0 { + break; + } + let length = remaining.min(budget); + // The full range was checked above; all subranges fit within it. + ranges.push(BlobRangeRequest::new( + request.row_id, + request.offset + consumed, + length, + )); + consumed += length; + budget -= length; + if consumed == request.length { + index += 1; + consumed = 0; + } else { + break; + } + } + let array = self + .fetch_blob_ranges_chunk(column, &ranges, &mut snapshot, &mut identity) + .await?; + // A null has no bytes to partition. Avoid sending arbitrarily many + // empty fragments for a null with a very large requested length. + if consumed != 0 && array.is_null(array.len() - 1) { + index += 1; + consumed = 0; + } + if continuation { + blobs.append_continuation(&array)?; + } else { + blobs.append(&array)?; + } + } + Ok(blobs.finish()?) + } + + async fn fetch_blob_ranges_legacy( + &self, + column: &str, + requests: &[BlobRangeRequest], ) -> Result { let row_ids = requests .iter() @@ -738,16 +817,12 @@ impl RemoteTable { let files = self.fetch_blob_files_impl(column, &row_ids).await?; let mut builder = LargeBinaryBuilder::with_capacity(requests.len(), 0); for (file, request) in files.into_iter().zip(requests) { - let end = - request - .offset - .checked_add(request.length) - .ok_or_else(|| Error::InvalidInput { - message: "blob range offset + length overflows u64".into(), - })?; match file { Some(file) => { - let bytes = file.read_range(request.offset..end).await?; + // Overflow was checked before selecting either protocol. + let bytes = file + .read_range(request.offset..request.offset + request.length) + .await?; builder.append_value(bytes); } None => builder.append_null(), @@ -756,6 +831,162 @@ impl RemoteTable { Ok(builder.finish()) } + async fn fetch_blob_ranges_chunk( + &self, + column: &str, + ranges: &[BlobRangeRequest], + snapshot: &mut ReadSnapshot, + identity: &mut Option, + ) -> Result { + let _permit = self + .client + .blob_request_semaphore + .clone() + .acquire_owned() + .await + .expect("blob request semaphore is never closed"); + let body = serde_json::json!({ + "column": column, + "version": snapshot.version, + "branch": self.branch, + "ranges": ranges, + }); + let request = self + .client + .post(&format!("/v1/table/{}/fetch_blob_ranges/", self.identifier)) + .json(&body); + let request = if let Some(expected) = identity.as_deref() { + request.header(super::QUERY_SNAPSHOT_HEADER, expected) + } else { + request + }; + let (request_id, response) = self + .send_with_freshness(request, false, snapshot.freshness) + .await?; + // The range operation defines 400 as invalid input. Let the established + // checker decode structured/plain server errors before normalizing it. + let response = self + .check_table_response(&request_id, response) + .await + .map_err(|error| { + if let Error::Http { + source, + request_id, + status_code: Some(StatusCode::BAD_REQUEST), + } = error + { + Error::InvalidInput { + message: format!("fetch_blob_ranges (request {request_id}): {source}"), + } + } else { + error + } + })?; + let invalid = |message: String| Error::Http { + source: format!("fetch_blob_ranges: {message}").into(), + request_id: request_id.clone(), + status_code: None, + }; + let version = response.headers().get(&VERSION_HEADER) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()) + .filter(|version| *version != 0) + .ok_or_else(|| invalid("missing or invalid x-lancedb-version; a server supporting the batched range endpoint is required".into()))?; + if snapshot.version.is_some_and(|expected| expected != version) { + return Err(invalid(format!( + "response version {version} differs from requested version {:?}", + snapshot.version + ))); + } + // Do not decode or accept any payload before establishing/verifying the + // identity. A later partition can never replace the original expectation. + check_query_snapshot_response(identity.as_deref(), &response)?; + if identity.is_none() { + let actual = response.headers().get(super::QUERY_SNAPSHOT_HEADER) + .and_then(|value| value.to_str().ok()) + .filter(|value| valid_query_snapshot_identity(value)) + .ok_or_else(|| Error::NotSupported { + message: "Batched Blob ranges require a snapshot identity; upgrade every serving node".into(), + })?; + *identity = Some(actual.to_owned()); + } + snapshot.version = Some(version); + // This endpoint's contract is stream framing. Keep the bounded, fallible + // IPC path from #4979 instead of buffering an Arrow file response. + let content_type = response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + if !content_type + .split(';') + .next() + .unwrap_or("") + .trim() + .eq_ignore_ascii_case(crate::remote::ARROW_STREAM_CONTENT_TYPE) + { + return Err(invalid(format!( + "expected Arrow IPC stream, got '{content_type}'" + ))); + } + let mut stream = super::ipc_stream::read_ipc_stream( + response.bytes_stream(), + request_id.clone(), + Some(version), + ) + .await?; + let schema = stream.schema(); + if !matches!( + schema + .field_with_name("value") + .map(|field| field.data_type()), + Ok(DataType::LargeBinary) + ) { + return Err(invalid( + "response requires a LargeBinary column named 'value'".into(), + )); + } + let mut blobs = BlobAccumulator::new(ranges.len())?; + let mut rows = 0usize; + let mut bytes = 0u64; + while let Some(batch) = stream.try_next().await? { + let array = batch + .column_by_name("value") + .and_then(|column| column.as_any().downcast_ref::()) + .ok_or_else(|| { + invalid("response requires a LargeBinary column named 'value'".into()) + })?; + let end = rows + .checked_add(array.len()) + .filter(|end| *end <= ranges.len()) + .ok_or_else(|| invalid("response has more rows than requested".into()))?; + let offsets = array.value_offsets(); + bytes = bytes + .checked_add((offsets[array.len()] - offsets[0]) as u64) + .filter(|bytes| *bytes <= MAX_FETCH_BLOB_RANGE_BYTES) + .ok_or_else(|| invalid("response exceeds 64 MiB of range bytes".into()))?; + for (i, range) in ranges[rows..end].iter().enumerate() { + if array.is_valid(i) && array.value_length(i) as u64 != range.length { + return Err(invalid(format!( + "row {} returned {} bytes for requested length {}", + rows + i, + array.value_length(i), + range.length + ))); + } + } + blobs.append(array)?; + rows = end; + } + if rows != ranges.len() { + return Err(invalid(format!( + "returned {rows} rows for {} ranges", + ranges.len() + ))); + } + Ok(blobs.finish()?) + } + /// Open seekable handles for `row_ids`. /// /// Descriptors for the requested rows come from one `_rowid` take query per @@ -1666,10 +1897,155 @@ mod tests { let error = table.fetch_blob_ranges("image", &ranges).await.unwrap_err(); assert!(error.to_string().contains(message), "{error}"); // Missing rows and invalid ranges fail without reading any bytes. - assert_eq!(requests.lock().unwrap().len(), 1); + assert!(matches!(error, Error::InvalidInput { .. })); + assert_eq!( + requests.lock().unwrap().len(), + usize::from(!message.contains("overflows")) + ); } } + #[tokio::test] + async fn remote_blob_ranges_keep_producing_query_identity_from_first_request() { + const IDENTITY: &str = + "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let calls = Arc::new(StdMutex::new(Vec::new())); + let captured = calls.clone(); + let table = RemoteTable::new_mock( + "my_table".into(), + move |request| { + assert_eq!( + request.url().path(), + "/v1/table/my_table/fetch_blob_ranges/" + ); + assert_eq!( + request.headers()[super::super::QUERY_SNAPSHOT_HEADER], + IDENTITY + ); + let body: serde_json::Value = + serde_json::from_slice(request.body().unwrap().as_bytes().unwrap()).unwrap(); + assert_eq!(body["version"], 42); + let rows = body["ranges"].as_array().unwrap().len(); + captured.lock().unwrap().push(rows); + let batch = RecordBatch::try_from_iter([( + "value", + Arc::new(LargeBinaryArray::from(vec![Some(b"A".as_slice()); rows])) + as Arc, + )]) + .unwrap(); + let mut bytes = Vec::new(); + let mut writer = + arrow_ipc::writer::StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "42") + .header(super::super::QUERY_SNAPSHOT_HEADER, IDENTITY) + .body(bytes) + .unwrap() + }, + Some(Version::new(1, 13, 0)), + ); + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + let snapshot = table + .query_snapshot_with_identity(42, IDENTITY) + .await + .unwrap(); + let ranges = snapshot + .fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1); 1025]) + .await + .unwrap(); + assert_eq!( + ranges, + LargeBinaryArray::from(vec![Some(b"A".as_slice()); 1025]) + ); + assert_eq!(*calls.lock().unwrap(), [1024, 1]); + assert!(table.snapshot_read_state().await.version.is_none()); + } + + #[tokio::test] + async fn remote_blob_ranges_cancel_releases_the_only_request_permit() { + use std::sync::atomic::AtomicUsize; + let entered = Arc::new(tokio::sync::Notify::new()); + let started = entered.clone(); + let calls = Arc::new(AtomicUsize::new(0)); + let captured = calls.clone(); + let table = Arc::new(RemoteTable::new_mock_with_version_and_config( + "my_table".into(), + move |request| { + assert!(request.url().path().ends_with("/fetch_blob_ranges/")); + if captured.fetch_add(1, Ordering::SeqCst) == 0 { + started.notify_one(); + http::Response::builder() + .status(200) + .header("content-type", "application/vnd.apache.arrow.stream") + .header(VERSION_HEADER, "7") + .header( + super::super::QUERY_SNAPSHOT_HEADER, + format!("v1:{}", "a".repeat(64)), + ) + .body(reqwest::Body::wrap_stream(futures::stream::pending::< + std::result::Result, + >())) + .unwrap() + } else { + http::Response::builder() + .status(400) + .header("x-lancedb-error-code", "invalid_input") + .body(reqwest::Body::from( + r#"{"error":"range exceeds blob size"}"#, + )) + .unwrap() + } + }, + Some(Version::new(1, 13, 0)), + crate::remote::ClientConfig { + blob_request_concurrency: Some(1), + ..Default::default() + }, + )); + let mut headers = http::HeaderMap::new(); + headers.insert("x-lancedb-blob-ranges", "1".parse().unwrap()); + table.seed_blob_ranges_capability(&headers); + let reader_table = table.clone(); + let reader = tokio::spawn(async move { + reader_table + .fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1); 1025]) + .await + }); + tokio::time::timeout(Duration::from_secs(5), entered.notified()) + .await + .unwrap(); + reader.abort(); + assert!(reader.await.unwrap_err().is_cancelled()); + let error = tokio::time::timeout( + Duration::from_secs(5), + table.fetch_blob_ranges("image", &[BlobRangeRequest::new(10, 0, 1)]), + ) + .await + .unwrap() + .unwrap_err(); + assert!(matches!(error, Error::InvalidInput { .. })); + assert!(error.to_string().contains("range exceeds blob size")); + assert_eq!(calls.load(Ordering::SeqCst), 2); + } + + #[tokio::test] + async fn remote_blob_ranges_reject_overflow_before_http() { + let (table, requests) = mock_take_blob_table(vec![], Some("7")); + let error = table + .fetch_blob_ranges("image", &[BlobRangeRequest::new(20, u64::MAX, 1)]) + .await + .unwrap_err(); + assert!(error.to_string().contains("overflows u64"), "{error}"); + assert!(requests.lock().unwrap().is_empty()); + } + #[tokio::test] async fn remote_blob_ranges_accept_empty_requests_without_http() { let (table, requests) = mock_take_blob_table(vec![], Some("7")); diff --git a/rust/lancedb/src/remote/table/blobs/aggregate.rs b/rust/lancedb/src/remote/table/blobs/aggregate.rs index e8e794fa0..68bc20c88 100644 --- a/rust/lancedb/src/remote/table/blobs/aggregate.rs +++ b/rust/lancedb/src/remote/table/blobs/aggregate.rs @@ -6,75 +6,143 @@ use std::collections::VecDeque; use arrow_array::{Array, LargeBinaryArray}; -use arrow_buffer::{Buffer, MutableBuffer, NullBufferBuilder, OffsetBuffer}; +use arrow_buffer::{BooleanBuffer, Buffer, NullBuffer, OffsetBuffer}; use arrow_schema::ArrowError; +fn allocation_error(error: impl std::fmt::Display) -> ArrowError { + ArrowError::ComputeError(format!("cannot allocate blob result: {error}")) +} + pub(super) struct BlobAccumulator { offsets: Vec, - nulls: NullBufferBuilder, + validity: Vec, values: VecDeque, bytes: i64, + has_nulls: bool, } impl BlobAccumulator { - pub(super) fn new(rows: usize) -> Self { - let mut offsets = Vec::with_capacity(rows + 1); + pub(super) fn new(rows: usize) -> Result { + let capacity = rows + .checked_add(1) + .ok_or_else(|| allocation_error("row count overflow"))?; + let mut offsets = Vec::new(); + offsets + .try_reserve_exact(capacity) + .map_err(allocation_error)?; offsets.push(0); - Self { + let mut validity = Vec::new(); + let validity_bytes = rows / 8 + usize::from(!rows.is_multiple_of(8)); + validity + .try_reserve_exact(validity_bytes) + .map_err(allocation_error)?; + Ok(Self { offsets, - nulls: NullBufferBuilder::new(rows), + validity, values: VecDeque::new(), bytes: 0, - } + has_nulls: false, + }) } pub(super) fn append(&mut self, array: &LargeBinaryArray) -> Result<(), ArrowError> { + self.append_inner(array, false) + } + + /// The first value continues the preceding response's final logical range. + pub(super) fn append_continuation( + &mut self, + array: &LargeBinaryArray, + ) -> Result<(), ArrowError> { + self.append_inner(array, true) + } + + fn append_inner( + &mut self, + array: &LargeBinaryArray, + continuation: bool, + ) -> Result<(), ArrowError> { + let rows = self.offsets.len() - 1; + if continuation + && (rows == 0 + || array.is_empty() + || (self.validity[(rows - 1) / 8] & (1 << ((rows - 1) % 8)) != 0) + != array.is_valid(0)) + { + return Err(ArrowError::ComputeError( + "inconsistent nulls in split blob range".into(), + )); + } let offsets = array.value_offsets(); let start = offsets[0]; let length = offsets[array.len()] - start; let total = self.bytes.checked_add(length).ok_or_else(|| { - ArrowError::ComputeError("fetch_blobs result exceeds i64 byte offsets".into()) + ArrowError::ComputeError("blob result exceeds i64 byte offsets".into()) })?; - self.offsets.extend( - offsets[1..] - .iter() - .map(|offset| self.bytes + (*offset - start)), - ); - if let Some(nulls) = array.nulls() { - self.nulls.append_buffer(nulls); - } else { - self.nulls.append_n_non_nulls(array.len()); - } + let skip = usize::from(continuation); + self.offsets + .try_reserve(array.len() - skip) + .map_err(allocation_error)?; + let new_rows = rows + .checked_add(array.len() - skip) + .ok_or_else(|| allocation_error("row count overflow"))?; + let validity_bytes = new_rows / 8 + usize::from(new_rows % 8 != 0); + self.validity + .try_reserve(validity_bytes - self.validity.len()) + .map_err(allocation_error)?; + self.validity.resize(validity_bytes, 0); if length != 0 { + self.values.try_reserve(1).map_err(allocation_error)?; self.values.push_back( array .values() .slice_with_length(start as usize, length as usize), ); } + if continuation { + *self.offsets.last_mut().unwrap() = self.bytes + (offsets[1] - start); + } + self.offsets.extend( + offsets[1 + skip..] + .iter() + .map(|offset| self.bytes + (*offset - start)), + ); + for i in skip..array.len() { + let row = rows + i - skip; + if array.is_valid(i) { + self.validity[row / 8] |= 1 << (row % 8); + } else { + self.has_nulls = true; + } + } self.bytes = total; Ok(()) } - pub(super) fn finish(mut self) -> LargeBinaryArray { + pub(super) fn finish(mut self) -> Result { let values = match self.values.len() { 0 => Buffer::default(), 1 => self.values.pop_front().unwrap(), _ => { - let mut values = MutableBuffer::new(self.bytes as usize); - // Do not retain all decoded batches alongside the final allocation. + let length = usize::try_from(self.bytes).map_err(allocation_error)?; + let mut values = Vec::new(); + values.try_reserve_exact(length).map_err(allocation_error)?; // Drop each source allocation immediately after copying its bytes. while let Some(chunk) = self.values.pop_front() { values.extend_from_slice(&chunk); } - values.into() + Buffer::from_vec(values) } }; - LargeBinaryArray::new( + let rows = self.offsets.len() - 1; + let nulls = self + .has_nulls + .then(|| NullBuffer::new(BooleanBuffer::new(Buffer::from_vec(self.validity), 0, rows))); + Ok(LargeBinaryArray::new( OffsetBuffer::new(self.offsets.into()), values, - self.nulls.finish(), - ) + nulls, + )) } } @@ -85,9 +153,9 @@ mod tests { #[test] fn single_buffer_is_not_copied() { let array = LargeBinaryArray::from(vec![Some(b"alpha".as_slice()), None, Some(b"")]); - let mut result = BlobAccumulator::new(3); + let mut result = BlobAccumulator::new(3).unwrap(); result.append(&array).unwrap(); - let output = result.finish(); + let output = result.finish().unwrap(); assert_eq!(output.values().as_ptr(), array.values().as_ptr()); assert_eq!(output, array); } @@ -101,21 +169,27 @@ mod tests { Some(b""), Some(b"beta"), ]); - let mut result = BlobAccumulator::new(6); + let mut result = BlobAccumulator::new(6).unwrap(); result.append(&array.slice(1, 3)).unwrap(); result.append(&array.slice(4, 1)).unwrap(); result.append(&array.slice(2, 2)).unwrap(); assert_eq!( - result.finish(), + result.finish().unwrap(), LargeBinaryArray::from(vec![ Some(b"alpha".as_slice()), None, Some(b""), Some(b"beta"), None, - Some(b""), + Some(b"") ]) ); - assert_eq!(BlobAccumulator::new(0).finish().len(), 0); + assert_eq!(BlobAccumulator::new(0).unwrap().finish().unwrap().len(), 0); + } + + #[test] + fn impossible_capacity_is_an_error() { + assert!(BlobAccumulator::new(usize::MAX).is_err()); + assert!(BlobAccumulator::new(usize::MAX / 2).is_err()); } } diff --git a/rust/lancedb/src/server_info.rs b/rust/lancedb/src/server_info.rs new file mode 100644 index 000000000..48daf508b --- /dev/null +++ b/rust/lancedb/src/server_info.rs @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Remote server provenance for diagnostics without submitting a query or job. + +use serde::{Deserialize, Serialize}; +use std::fmt; + +/// Immutable identity compiled into a server executable. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ServerBuildInfo { + /// Release of this executable. + pub release: String, + /// Git revision used to build the executable. + pub git_sha: String, + /// UTC RFC 3339 build timestamp, when known. + pub build_date: Option, +} + +impl fmt::Display for ServerBuildInfo { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "{} (git {}, built {})", + self.release, + self.git_sha, + self.build_date.as_deref().unwrap_or("unknown") + ) + } +} + +/// Identity of the query node that answered a discovery request. +/// +/// Different requests can reach different versions during a rolling upgrade. +/// Configured images do not establish which version a running job uses. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ServerInfo { + /// The responding executable; absent if its identity was not initialized. + pub query_node: Option, + /// Lance library linked into the responding server. + pub lance_version: String, + /// LanceDB library linked into the responding server. + pub lancedb_version: String, + /// Function worker protocol supported by this server build. + pub function_worker_protocol_version: u16, + /// Configured query-node image, not an independently observed digest. + pub configured_query_node_image: Option, + /// Default CPU/job worker image; existing jobs can retain earlier pins. + pub configured_job_worker_image: Option, + /// CLI image configured for newly launched SQL jobs. + pub configured_sql_job_image: Option, + /// Configured GPU worker image, not an observation of a running worker. + pub configured_gpu_worker_image: Option, +} diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index db68ab290..4959b2842 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1452,8 +1452,13 @@ impl Table { /// ranges for the same blob. The output has the same length and order as /// the requests. Null blobs produce null output slots; empty ranges on /// non-null blobs produce empty byte strings. - /// LanceDB Enterprise tables read through version-pinned [`BlobFile`] handles using - /// HTTP byte-range requests. + /// LanceDB Enterprise uses the batched endpoint when the server advertises + /// support, splitting calls at 1024 ranges and 64 MiB of requested bytes. + /// Individual larger ranges are partitioned and reassembled into one result. + /// Older servers use descriptor queries and [`Self::fetch_blob_files`] range + /// reads. Both protocols read one exact branch and version without changing + /// this handle's checkout. The final materialized output still occupies memory. + /// Errors from an advertised endpoint propagate without switching protocols. /// /// `_rowid` values stay valid after compaction when the table has stable /// row ids. One missing or deleted row id rejects the whole request; no @@ -1486,10 +1491,14 @@ impl Table { column: impl AsRef, requests: impl IntoIterator, ) -> Result { - let requests = requests.into_iter().collect::>(); - self.inner - .fetch_blob_ranges(column.as_ref(), &requests) - .await + let mut ranges = Vec::new(); + for request in requests { + ranges.try_reserve(1).map_err(|error| Error::InvalidInput { + message: format!("cannot allocate blob range requests: {error}"), + })?; + ranges.push(request); + } + self.inner.fetch_blob_ranges(column.as_ref(), &ranges).await } /// Open lazy [`BlobFile`] handles for the given row ids. diff --git a/rust/lancedb/src/table/datafusion.rs b/rust/lancedb/src/table/datafusion.rs index 81df7d300..22ec5caeb 100644 --- a/rust/lancedb/src/table/datafusion.rs +++ b/rust/lancedb/src/table/datafusion.rs @@ -4,6 +4,7 @@ //! This module contains adapters to allow LanceDB tables to be used as DataFusion table providers. mod blob_coerce; +mod blob_materialize; mod blob_nulls; pub mod cast; pub mod insert; @@ -31,7 +32,7 @@ use lance_core::{ datatypes::{Projection, Schema as LanceSchema}, }; -use super::{AnyQuery, BaseTable}; +use super::{AnyQuery, BaseTable, NativeTableExt}; use crate::{ Error, Result, query::{QueryExecutionOptions, QueryFilter, QueryRequest, Select}, @@ -199,7 +200,8 @@ impl ExecutionPlan for MetadataEraserExec { pub enum BlobSchema { /// Expose Blob v2 descriptors (`kind`, `position`, `size`, `blob_id`, `blob_uri`) /// and legacy v1 descriptors (`position`, `size`). Scans support all blob fields; - /// SQL INSERT into Blob v2 tables is unsupported. + /// SQL INSERT SELECT materializes descriptors from a single native-table + /// snapshot; remote and Realtime/MemWAL sources are not supported. #[default] Read, /// Expose Blob v2 write inputs (`data`, `uri`, `position`, `size`) and legacy @@ -213,9 +215,33 @@ pub enum BlobSchema { /// /// Defaults to [`BlobSchema::Read`], matching the descriptor schema produced by /// scans without fetching blob bytes. Use [`Self::with_blob_schema`] to enable -/// SQL INSERT into blob columns. Legacy v1 blobs expose descriptors in read mode -/// and `LargeBinary` inputs in write mode; write-mode descriptor scans fail with -/// a schema mismatch. Tables without blob columns behave the same in both modes. +/// SQL INSERT with logical blob inputs. In read mode, INSERT SELECT can copy +/// Blob v2 descriptors from a single native-table snapshot into target-owned +/// payloads, including projections, filters, sorting, and limits. JOIN, UNION, +/// aggregation, and computed descriptors fail during planning because their +/// source row addresses cannot be established safely. Legacy v1 blobs expose +/// descriptors in read mode and `LargeBinary` inputs in write mode; write-mode +/// descriptor scans fail with a schema mismatch. Tables without blob columns +/// behave the same in both modes. +/// Descriptor copying requires a native source table; remote and Realtime/MemWAL +/// sources are not supported by this materialization path. +/// +/// With read adapters registered as `source` and `target`, copying blobs needs +/// no payload UDF or explicit system columns: +/// +/// ```sql +/// INSERT INTO target SELECT * FROM source WHERE id > 10; +/// ``` +/// +/// The target owns the copied payloads independently of subsequent source +/// compaction or deletion. External URI references retain their external +/// storage semantics and remain subject to the target's registered external +/// bases; copying a descriptor does not authorize a new external location. +/// +/// Materialization allocates payload bytes for each input batch outside the +/// DataFusion memory pool. For large blobs, configure a conservative +/// `SessionConfig::with_batch_size`; the pool limit alone does not bound these +/// allocations, and a single blob can still exceed that limit. #[derive(Debug)] pub struct BaseTableAdapter { table: Arc, @@ -440,13 +466,55 @@ impl TableProvider for BaseTableAdapter { ..Default::default() }; - let plan = self - .table - .create_plan(&AnyQuery::Query(query), options) + // The scan and any later INSERT rewrite must use the same snapshot, + // even if the live table advances between planning and execution. + let projects_descriptors = match projection { + Some(indices) => indices + .iter() + .any(|index| blob_nulls::has_descriptor(provider_schema.field(*index))), + None => provider_schema + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)), + }; + let snapshot = if self.blob_schema == BlobSchema::Read + && self.table.as_native().is_some() + && projects_descriptors + { + Some( + self.table + .query_snapshot() + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?, + ) + } else { + None + }; + let source = snapshot.as_ref().unwrap_or(&self.table); + let plan = source + .create_plan(&AnyQuery::Query(query.clone()), options.clone()) .map_err(|err| DataFusionError::External(err.into())) .await?; let plan = blob_nulls::mask_plan(plan)?; - let plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + let mut plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + if let Some(snapshot) = snapshot + && plan + .schema() + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)) + { + let dataset = snapshot + .as_native() + .unwrap() + .dataset + .get() + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?; + plan = Arc::new(blob_materialize::BlobScanExec::new( + plan, snapshot, dataset, query, options, + )); + } if self.blob_schema == BlobSchema::Write { let schema = match projection { Some(projection) => Arc::new(provider_schema.project(projection)?), @@ -509,17 +577,30 @@ impl TableProvider for BaseTableAdapter { input: Arc, insert_op: InsertOp, ) -> DataFusionResult> { + let has_descriptors = input + .schema() + .fields() + .iter() + .any(|field| blob_nulls::has_descriptor(field)) + || (blob_materialize::has_source_scan(&input) + && input + .schema() + .fields() + .iter() + .any(|field| blob_materialize::has_descriptor(field))); if self.blob_schema == BlobSchema::Read && self .schema .fields() .iter() .any(|field| blob_nulls::has_descriptor(field)) + && !has_descriptors { return Err(DataFusionError::NotImplemented( "SQL INSERT into Blob v2 tables requires BlobSchema::Write".into(), )); } + let input = blob_materialize::materialize(input, self.write_schema.as_ref()).await?; let mode = match insert_op { InsertOp::Append => WriteMode::Append, InsertOp::Overwrite => WriteMode::Overwrite, diff --git a/rust/lancedb/src/table/datafusion/blob_materialize.rs b/rust/lancedb/src/table/datafusion/blob_materialize.rs new file mode 100644 index 000000000..22d0a023d --- /dev/null +++ b/rust/lancedb/src/table/datafusion/blob_materialize.rs @@ -0,0 +1,615 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +//! Preserve scan provenance until INSERT can materialize source-owned blobs. +//! +//! External descriptors remain references and must satisfy the destination's +//! existing external-base policy; source authorization grants no target trust. + +use std::fmt; +use std::sync::Arc; + +use arrow_array::RecordBatch; +use arrow_schema::{DataType, Field, Schema, SchemaRef}; +use datafusion_common::{DataFusionError, Result, tree_node::TreeNodeRecursion}; +use datafusion_execution::{SendableRecordBatchStream, TaskContext}; +use datafusion_functions::core::getfield::GetFieldFunc; +use datafusion_physical_expr::{ + PhysicalExpr, ScalarFunctionExpr, + expressions::{CastExpr, Column, Literal}, +}; +use datafusion_physical_plan::{ + DisplayAs, DisplayFormatType, ExecutionPlan, ExecutionPlanProperties, PlanProperties, + coalesce_partitions::CoalescePartitionsExec, + execution_plan::{ChildrenPropertiesMode, ReplaceChildrenOptions}, + filter::FilterExec, + limit::{GlobalLimitExec, LocalLimitExec}, + projection::ProjectionExec, + repartition::RepartitionExec, + sorts::{sort::SortExec, sort_preserving_merge::SortPreservingMergeExec}, + stream::RecordBatchStreamAdapter, +}; +use futures::{FutureExt, TryStreamExt, future::BoxFuture}; +use lance::{Dataset, dataset::BlobV2BatchRewritePlan}; +use lance_core::{ + ROW_ADDR, + datatypes::{BlobV2Layout, Schema as LanceSchema}, +}; + +use super::{BaseTable, MetadataEraserExec, blob_nulls}; +use crate::{ + query::{QueryExecutionOptions, QueryRequest, Select}, + table::AnyQuery, +}; + +const HIDDEN_ROW_ADDR: &str = "__lancedb_blob_rowaddr"; + +// Expressions such as CASE can retain the descriptor layout while dropping +// extension metadata. They still require proven provenance before writing. +pub(super) fn has_descriptor(field: &Field) -> bool { + contains_layout(field.data_type(), BlobV2Layout::Descriptor) +} + +fn descriptor_for_target(input: &Field, target: &Field) -> bool { + if crate::blob::is_blob(target) { + return matches!(input.data_type(), DataType::Struct(fields) + if BlobV2Layout::classify(fields) == Some(BlobV2Layout::Descriptor)); + } + match (input.data_type(), target.data_type()) { + (DataType::Struct(input), DataType::Struct(target)) => target.iter().any(|target| { + input + .find(target.name()) + .is_some_and(|(_, input)| descriptor_for_target(input, target)) + }), + ( + DataType::List(input) | DataType::LargeList(input) | DataType::FixedSizeList(input, _), + DataType::List(target) + | DataType::LargeList(target) + | DataType::FixedSizeList(target, _), + ) => descriptor_for_target(input, target), + _ => false, + } +} + +fn contains_layout(data_type: &DataType, layout: BlobV2Layout) -> bool { + match data_type { + DataType::Struct(fields) => { + BlobV2Layout::classify(fields) == Some(layout) + || fields + .iter() + .any(|field| contains_layout(field.data_type(), layout)) + } + DataType::List(item) | DataType::LargeList(item) | DataType::FixedSizeList(item, _) => { + contains_layout(item.data_type(), layout) + } + _ => false, + } +} + +pub(super) fn has_source_scan(input: &Arc) -> bool { + input.downcast_ref::().is_some() + || input.children().iter().any(|child| has_source_scan(child)) +} + +#[expect( + deprecated, + reason = "DataFusion 55 still accepts CoalesceBatchesExec plans" +)] +fn preserves_row_identity(input: &Arc) -> bool { + input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input.downcast_ref::().is_some() + || input + .downcast_ref::() + .is_some() + || input.downcast_ref::().is_some() +} + +fn provenance_error(detail: impl fmt::Display) -> DataFusionError { + DataFusionError::Plan(format!( + "Blob INSERT SELECT requires descriptors from one source table snapshot with an \ + unambiguous row address; {detail}. JOIN, UNION, aggregation, and computed blob \ + descriptors are not supported" + )) +} + +/// A transparent scan boundary. It retains the snapshot and scan request, rather +/// than exposing a system column to SELECT * or fetching any payloads on reads. +#[derive(Debug)] +pub(super) struct BlobScanExec { + input: Arc, + source: Arc, + dataset: Arc, + query: QueryRequest, + options: QueryExecutionOptions, +} + +impl BlobScanExec { + pub(super) fn new( + input: Arc, + source: Arc, + dataset: Arc, + query: QueryRequest, + options: QueryExecutionOptions, + ) -> Self { + Self { + input, + source, + dataset, + query, + options, + } + } + + async fn with_row_address(&self) -> Result { + let mut query = self.query.clone(); + let Select::Columns(columns) = &mut query.select else { + return Err(provenance_error( + "source scan has no explicit column projection", + )); + }; + if !columns.iter().any(|name| name == ROW_ADDR) { + columns.push(ROW_ADDR.to_owned()); + } + let plan = self + .source + .create_plan(&AnyQuery::Query(query), self.options.clone()) + .await + .map_err(|error| DataFusionError::External(Box::new(error)))?; + let plan = blob_nulls::mask_plan(plan)?; + let plan: Arc = Arc::new(MetadataEraserExec::new(plan)); + let schema = plan.schema(); + let mut projection: Vec<(Arc, String)> = self + .input + .schema() + .fields() + .iter() + .map(|field| { + Ok(( + Arc::new(Column::new(field.name(), schema.index_of(field.name())?)) as _, + field.name().clone(), + )) + }) + .collect::>()?; + projection.push(( + Arc::new(Column::new(ROW_ADDR, schema.index_of(ROW_ADDR)?)), + HIDDEN_ROW_ADDR.into(), + )); + Ok(Provenance { + plan: Arc::new(ProjectionExec::try_new(projection, plan)?), + dataset: self.dataset.clone(), + fields: self + .input + .schema() + .fields() + .iter() + .map(|field| Some(field.name().clone())) + .collect(), + }) + } +} + +impl DisplayAs for BlobScanExec { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "BlobScanExec: version={}", + self.dataset.version().version + ) + } +} + +impl ExecutionPlan for BlobScanExec { + fn apply_expressions( + &self, + _: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + fn name(&self) -> &str { + "BlobScanExec" + } + fn properties(&self) -> &Arc { + self.input.properties() + } + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + fn maintains_input_order(&self) -> Vec { + vec![true] + } + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + let [input]: [_; 1] = children + .try_into() + .map_err(|_| provenance_error("invalid scan children"))?; + Ok(Arc::new(Self::new( + input, + self.source.clone(), + self.dataset.clone(), + self.query.clone(), + self.options.clone(), + ))) + } + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + self.input.execute(partition, context) + } +} + +struct Provenance { + plan: Arc, + dataset: Arc, + // Source field path for each output column, before the hidden address. + fields: Vec>, +} + +fn source_field(expr: &Arc, fields: &[Option]) -> Option { + if let Some(column) = expr.downcast_ref::() { + return fields.get(column.index()).cloned().flatten(); + } + let call = expr.downcast_ref::()?; + call.fun().inner().downcast_ref::()?; + let (root, path) = call.args().split_first()?; + let mut source = source_field(root, fields)?; + for component in path { + let name = component + .downcast_ref::()? + .value() + .try_as_str() + .flatten()?; + source.push('.'); + source.push_str(name); + } + Some(source) +} + +fn with_provenance(input: Arc) -> BoxFuture<'static, Result> { + async move { + if let Some(scan) = input.downcast_ref::() { + return scan.with_row_address().await; + } + let children = input.children(); + // An explicit allowlist keeps row identity from silently propagating + // through a future operator that changes cardinality or column meaning. + if children.len() != 1 || !preserves_row_identity(&input) { + return Err(provenance_error(format!( + "cannot establish provenance through {}", + input.name() + ))); + } + let mut provenance = with_provenance(children[0].clone()).await?; + if let Some(projection) = input.downcast_ref::() { + let fields = projection + .expr() + .iter() + .map(|expr| source_field(&expr.expr, &provenance.fields)) + .collect(); + let mut expressions: Vec<(Arc, String)> = projection + .expr() + .iter() + .map(|expr| (expr.expr.clone(), expr.alias.clone())) + .collect(); + expressions.push(( + Arc::new(Column::new( + HIDDEN_ROW_ADDR, + provenance.plan.schema().fields().len() - 1, + )), + HIDDEN_ROW_ADDR.into(), + )); + provenance.plan = Arc::new(ProjectionExec::try_new(expressions, provenance.plan)?); + provenance.fields = fields; + } else { + if input.schema() != children[0].schema() { + return Err(provenance_error(format!( + "{} changes the source schema", + input.name() + ))); + } + provenance.plan = input.replace_children( + vec![provenance.plan], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + )?; + } + Ok(provenance) + } + .boxed() +} + +/// Defer only a container coercion whose Blob leaves retain their named paths. +/// Descriptor leaves are atomic: casting their members is never provenance. +fn can_defer_blob_cast(source: &Field, cast_type: &DataType, target: &Field) -> bool { + if crate::blob::is_blob(target) { + let (DataType::Struct(source), DataType::Struct(cast)) = (source.data_type(), cast_type) + else { + return false; + }; + return BlobV2Layout::classify(source) == Some(BlobV2Layout::Descriptor) + && (BlobV2Layout::classify(cast) == Some(BlobV2Layout::Logical) + || (BlobV2Layout::classify(cast) == Some(BlobV2Layout::Descriptor) + && source.len() == cast.len() + && source.iter().zip(cast).all(|(source, cast)| { + source.name() == cast.name() && source.data_type() == cast.data_type() + }))); + } + match (source.data_type(), cast_type, target.data_type()) { + (DataType::Struct(source), DataType::Struct(cast), DataType::Struct(target)) => { + source.len() == cast.len() + && source.len() == target.len() + && target.iter().all(|target| { + source + .find(target.name()) + .zip(cast.find(target.name())) + .is_some_and(|((_, source), (_, cast))| { + can_defer_blob_cast(source, cast.data_type(), target) + }) + }) + } + (DataType::List(source), DataType::List(cast), DataType::List(target)) + | (DataType::LargeList(source), DataType::LargeList(cast), DataType::LargeList(target)) => { + can_defer_blob_cast(source, cast.data_type(), target) + } + ( + DataType::FixedSizeList(source, source_len), + DataType::FixedSizeList(cast, cast_len), + DataType::FixedSizeList(target, target_len), + ) => { + source_len == cast_len + && source_len == target_len + && can_defer_blob_cast(source, cast.data_type(), target) + } + _ => !has_descriptor(source) && cast_type == target.data_type(), + } +} + +pub(super) async fn materialize( + input: Arc, + target_schema: &Schema, +) -> Result> { + if !target_schema + .fields() + .iter() + .any(|field| crate::blob::field_tree_has_blob_v2(field)) + { + return Ok(input); + } + // INSERT may cast containers for metadata, field order, scalar siblings, + // or a Write adapter's logical layout. Bind the original Blob leaves and + // materialize before applying the target coercion. Other expressions still + // have to pass the Column/GetField provenance checks below. + let input = if let Some(projection) = input.downcast_ref::() { + let mut changed = false; + let expressions = projection + .expr() + .iter() + .map(|projected| { + let mut expr = projected.expr.clone(); + if let Some(cast) = expr.downcast_ref::() + && let Ok(target) = target_schema.field_with_name(&projected.alias) + && crate::blob::field_tree_has_blob_v2(target) + && let source = cast + .expr() + .return_field(projection.input().schema().as_ref())? + && has_descriptor(&source) + { + if !can_defer_blob_cast( + &source, + &cast.data_type(projection.input().schema().as_ref())?, + target, + ) { + return Err(provenance_error(format!( + "cast of column '{}' does not preserve Blob leaf identity", + projected.alias + ))); + } + expr = cast.expr().clone(); + changed = true; + } + Ok((expr, projected.alias.clone())) + }) + .collect::>>()?; + if changed { + Arc::new(ProjectionExec::try_new( + expressions, + projection.input().clone(), + )?) as Arc + } else { + input + } + } else { + input + }; + let rewrite_columns: Vec = input + .schema() + .fields() + .iter() + .map(|field| { + target_schema + .field_with_name(field.name()) + .is_ok_and(|target| descriptor_for_target(field, target)) + }) + .collect(); + if !rewrite_columns.iter().any(|rewrite| *rewrite) { + return Ok(input); + } + let provenance = with_provenance(input.clone()).await?; + let mut source_schema = LanceSchema::default(); + let mut expressions: Vec<(Arc, String)> = Vec::new(); + for (index, (field, source)) in input + .schema() + .fields() + .iter() + .zip(&provenance.fields) + .enumerate() + { + let name = format!("__lancedb_blob_column_{index}"); + if rewrite_columns[index] { + let source = source.as_ref().ok_or_else(|| { + provenance_error(format!("column '{}' has no source", field.name())) + })?; + let mut source_field = provenance + .dataset + .schema() + .field(source) + .ok_or_else(|| provenance_error(format!("source field '{source}' is missing")))? + .clone(); + if !crate::blob::field_tree_has_blob_v2(&Field::from(&source_field)) { + return Err(provenance_error(format!( + "source field '{source}' is not a Blob v2 column" + ))); + } + source_field.name = name.clone(); + source_schema.fields.push(source_field); + } + expressions.push((Arc::new(Column::new(field.name(), index)), name)); + } + expressions.push(( + Arc::new(Column::new(HIDDEN_ROW_ADDR, provenance.fields.len())), + ROW_ADDR.into(), + )); + let plan: Arc = + Arc::new(ProjectionExec::try_new(expressions, provenance.plan)?); + // preserve_managed=false forces even managed source payloads to become + // target-owned bytes instead of retaining source storage references. + let rewrite = Arc::new(BlobV2BatchRewritePlan::try_new( + &source_schema, + plan.schema().as_ref(), + false, + false, + )?); + let schema = Arc::new(Schema::new( + rewrite + .output_schema() + .fields() + .iter() + .zip(input.schema().fields()) + .map(|(rewritten, original)| rewritten.as_ref().clone().with_name(original.name())) + .collect::>(), + )); + let plan = Arc::new(MaterializeBlobsExec::new( + plan, + provenance.dataset, + rewrite, + schema, + )); + super::cast::cast_to_table_schema(plan, target_schema) + .map_err(|error| DataFusionError::External(Box::new(error))) +} + +struct MaterializeBlobsExec { + input: Arc, + dataset: Arc, + rewrite: Arc, + schema: SchemaRef, + properties: Arc, +} + +impl fmt::Debug for MaterializeBlobsExec { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MaterializeBlobsExec") + .field("input", &self.input) + .finish_non_exhaustive() + } +} + +impl MaterializeBlobsExec { + fn new( + input: Arc, + dataset: Arc, + rewrite: Arc, + schema: SchemaRef, + ) -> Self { + // Rewriting changes column types; descriptor equivalences/orderings do + // not describe the resulting payload structs. + let properties = Arc::new(PlanProperties::new( + datafusion_physical_expr::EquivalenceProperties::new(schema.clone()), + datafusion_physical_expr::Partitioning::UnknownPartitioning( + input.output_partitioning().partition_count(), + ), + input.properties().emission_type, + input.properties().boundedness, + )); + Self { + input, + dataset, + rewrite, + schema, + properties, + } + } +} + +impl DisplayAs for MaterializeBlobsExec { + fn fmt_as(&self, _: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "MaterializeBlobsExec") + } +} + +impl ExecutionPlan for MaterializeBlobsExec { + fn apply_expressions( + &self, + _: &mut dyn FnMut(&Arc) -> Result, + ) -> Result { + Ok(TreeNodeRecursion::Continue) + } + fn name(&self) -> &str { + "MaterializeBlobsExec" + } + fn properties(&self) -> &Arc { + &self.properties + } + fn children(&self) -> Vec<&Arc> { + vec![&self.input] + } + fn maintains_input_order(&self) -> Vec { + vec![true] + } + fn with_new_children( + self: Arc, + children: Vec>, + ) -> Result> { + let [input]: [_; 1] = children + .try_into() + .map_err(|_| provenance_error("invalid rewrite children"))?; + Ok(Arc::new(Self::new( + input, + self.dataset.clone(), + self.rewrite.clone(), + self.schema.clone(), + ))) + } + fn execute( + &self, + partition: usize, + context: Arc, + ) -> Result { + let dataset = self.dataset.clone(); + let rewrite = self.rewrite.clone(); + let schema = self.schema.clone(); + let stream = self + .input + .execute(partition, context)? + .and_then(move |batch| { + let dataset = dataset.clone(); + let rewrite = rewrite.clone(); + let schema = schema.clone(); + async move { + let batch = rewrite.transform_batch(&dataset, batch).await?; + Ok(RecordBatch::try_new(schema, batch.columns().to_vec())?) + } + }); + Ok(Box::pin(RecordBatchStreamAdapter::new( + self.schema.clone(), + stream, + ))) + } +} diff --git a/rust/lancedb/src/table/datafusion/insert.rs b/rust/lancedb/src/table/datafusion/insert.rs index ec1e603d2..a2d5f34c9 100644 --- a/rust/lancedb/src/table/datafusion/insert.rs +++ b/rust/lancedb/src/table/datafusion/insert.rs @@ -195,6 +195,7 @@ impl ExecutionPlan for InsertExec { context: Arc, ) -> DataFusionResult { let input_stream = self.input.execute(partition, context)?; + let input_plan = self.input.clone(); let dataset = self.dataset.clone(); let mut write_params = self.write_params.clone(); let partial_transactions = self.partial_transactions.clone(); @@ -227,6 +228,9 @@ impl ExecutionPlan for InsertExec { )); let stream = futures::stream::once(async move { + // Source blob snapshots must outlive the final target commit, not + // only the consumption of the input stream. + let _input_plan = input_plan; if let Some(tracker) = tracker && write_params.write_progress.is_none() { diff --git a/rust/lancedb/src/table/freshness.rs b/rust/lancedb/src/table/freshness.rs index 477020fc3..645653a46 100644 --- a/rust/lancedb/src/table/freshness.rs +++ b/rust/lancedb/src/table/freshness.rs @@ -1879,6 +1879,8 @@ pub async fn preserve_function_freshness( pending_fill.retain(|id, _| live.contains(id)); state.signatures.retain(|id, _| live.contains(id)); state.row_state.retain(|id, _| live.contains(id)); + state.failure_coverage.retain(|id, _| live.contains(id)); + state.failed_rows.retain(|id, _| live.contains(id)); state.basis.clear(); let reference = write_sidecar(dataset, &state.normalize()?).await?; let fill_reference = if pending_fill.is_empty() { @@ -3029,6 +3031,101 @@ mod tests { } } + #[tokio::test] + async fn function_write_prunes_outcomes_for_replaced_fragments() { + let table = fresh_function_table().await; + let mut dataset = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .as_ref() + .clone(); + let inputs = fields_for_paths(dataset.schema(), &["title".into(), "body".into()]).unwrap(); + let signatures = signatures_for(&dataset, &[0, 1], &inputs).unwrap(); + let failures = FailureEvidence { + known_rows: BTreeMap::from([ + (0, RoaringBitmap::from_iter([0, 1])), + (1, RoaringBitmap::from_iter([0, 1])), + ]), + failed_rows: BTreeMap::from([(1, RoaringBitmap::from_iter([1]))]), + }; + for column in ["search_text", "search_token_count"] { + record_freshness_with_failures( + &mut dataset, + None, + column, + "fb_01K3TEXT", + &inputs, + signatures.clone(), + &failures, + ) + .await + .unwrap(); + } + + // Replace all of fragment 0, insert one uncomputed row, and leave + // fragment 1 (including its retained failure evidence) untouched. + let source = arrow_array::record_batch!( + ("title", Utf8, ["a", "b", "e"]), + ("spare", Int32, [1, 1, 1]) + ) + .unwrap(); + let mut merge = + MergeInsertBuilder::try_new(Arc::new(dataset), vec!["title".into()]).unwrap(); + merge.when_matched(WhenMatched::UpdateAll); + merge.when_not_matched(WhenNotMatched::InsertAll); + let (merged, stats) = merge + .try_build() + .unwrap() + .execute_reader(Box::new(RecordBatchIterator::new( + [Ok(source.clone())], + source.schema(), + ))) + .await + .unwrap(); + let mut dataset = merged.as_ref().clone(); + assert!(!dataset.get_fragments().iter().any(|f| f.id() == 0)); + assert!(dataset.get_fragments().iter().any(|f| f.id() == 1)); + preserve_function_freshness( + &mut dataset, + FunctionWrite::Merge { + source_schema: &source.schema(), + on: &["title".into()], + num_inserted_rows: stats.num_inserted_rows, + }, + ) + .await + .unwrap(); + + let reopened = dataset + .checkout_version(dataset.version().version) + .await + .unwrap(); + for column in ["search_text", "search_token_count"] { + let StrictFreshness::Certified { + staleness, + failures, + } = strict_freshness_against(&reopened, column, "fb_01K3TEXT", &inputs) + .await + .unwrap() + else { + panic!("the preserved sidecar should retain failure evidence"); + }; + assert_eq!( + failures.known_rows, + BTreeMap::from([(1, RoaringBitmap::from_iter([0, 1]))]) + ); + assert_eq!( + failures.failed_rows, + BTreeMap::from([(1, RoaringBitmap::from_iter([1]))]) + ); + assert_eq!(staleness.pending_fill.len(), 1); + } + } + #[rstest::rstest] #[case::same_definition(false)] #[case::changed_definition(true)] diff --git a/rust/lancedb/tests/datafusion_blob_schema.rs b/rust/lancedb/tests/datafusion_blob_schema.rs index d51c182f6..5af3122ab 100644 --- a/rust/lancedb/tests/datafusion_blob_schema.rs +++ b/rust/lancedb/tests/datafusion_blob_schema.rs @@ -571,66 +571,701 @@ async fn legacy_blob_write_mode_rejects_descriptor_scans_and_keeps_scalar_scans( } #[tokio::test] -async fn copying_non_null_descriptors_between_tables_commits_no_rows() { +async fn copying_descriptors_materializes_payloads_and_preserves_snapshot() { + use std::collections::HashMap; + use std::num::NonZeroUsize; + + use lancedb::blob::{BlobOptions, blob_with_options}; + use lancedb::table::OptimizeAction; + + for managed in [false, true] { + for mode in [BlobSchema::Read, BlobSchema::Write] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let payload = blob_with_options( + "payload", + true, + BlobOptions { + inline_size_threshold: Some(8), + dedicated_size_threshold: NonZeroUsize::new(32), + }, + ); + let values: Vec> = vec![ + Some(b"hi"), + Some(&[2; 16]), + Some(&[3; 64]), + None, + Some(b""), + Some(b"skip"), + ]; + let schema = Arc::new(Schema::new_with_metadata( + vec![Field::new("id", DataType::Int64, false), payload], + HashMap::from([("lance.blob.managed".into(), managed.to_string())]), + )); + let batch = RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from(vec![1, 2, 3, 4, 5, 6])), + blob_inputs(values.clone()), + ], + ) + .unwrap(); + let source = db.create_table("docs", batch).execute().await.unwrap(); + let ctx = SessionContext::new_with_config( + SessionConfig::new() + .with_batch_size(2) + .with_target_partitions(2), + ); + register(&ctx, &source, BlobSchema::Read).await; + // Descriptor queries and SELECT * retain their original read schema. + let sizes = sql(&ctx, "SELECT payload.size FROM docs ORDER BY id").await; + assert_eq!( + sizes + .column(0) + .as_primitive::() + .value(2), + 64 + ); + assert_eq!(sql(&ctx, "SELECT * FROM docs").await.num_columns(), 2); + let kinds = sql(&ctx, "SELECT payload.kind FROM docs ORDER BY id").await; + let kinds = kinds + .column(0) + .as_primitive::(); + if !managed { + assert_eq!( + kinds.value(0), + lance_core::datatypes::BlobKind::Inline as u8 + ); + assert_eq!( + kinds.value(1), + lance_core::datatypes::BlobKind::Packed as u8 + ); + assert_eq!( + kinds.value(2), + lance_core::datatypes::BlobKind::Dedicated as u8 + ); + } else { + assert_eq!( + kinds.value(2), + lance_core::datatypes::BlobKind::Managed as u8 + ); + } + let (_destination_tmp, destination) = empty_table(vec![ + blob("copied", true), + Field::new("id", DataType::Int64, false), + ]) + .await; + let writer = BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode); + ctx.register_table("destination", Arc::new(writer)).unwrap(); + let plan = ctx.sql("INSERT INTO destination (id, copied) SELECT id + 10, payload AS copied FROM docs WHERE id > 0 AND (payload.size IS NULL OR payload.size < 100) ORDER BY id DESC LIMIT 5 OFFSET 1") + .await.unwrap().create_physical_plan().await.unwrap(); + // A live-table change after planning must not change the source + // version used to decode the descriptors in this insert. + source.delete("id = 1").await.unwrap(); + datafusion_physical_plan::collect(plan, ctx.task_ctx()) + .await + .unwrap(); + assert_eq!(destination.count_rows(None).await.unwrap(), 5); + source.optimize(OptimizeAction::All).await.unwrap(); + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let reader = BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_system_columns(&[ROW_ID]) + .unwrap(); + ctx.register_table("copied_rows", Arc::new(reader)).unwrap(); + let ids = sql(&ctx, "SELECT _rowid FROM copied_rows ORDER BY id").await; + let ids = ids + .column(0) + .as_primitive::() + .values(); + assert_eq!( + destination.fetch_blobs("copied", ids).await.unwrap(), + LargeBinaryArray::from(values[..5].to_vec()) + ); + } + } +} + +#[tokio::test] +async fn copying_nested_descriptors_preserves_parent_nulls_and_field_identity() { + use arrow_array::Int32Array; + use lancedb::blob::{BlobOptions, blob_with_options}; + + for difference in ["metadata", "order", "scalar"] { + for mode in [BlobSchema::Read, BlobSchema::Write] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let children = vec![ + Arc::new(Field::new("note", DataType::Utf8, true)), + Arc::new(Field::new("rank", DataType::Int32, true)), + Arc::new(blob_with_options( + "clip", + true, + BlobOptions { + inline_size_threshold: Some(8), + ..Default::default() + }, + )), + ]; + let extra_field = Field::new("extra", DataType::Struct(children.clone().into()), true); + let extra = StructArray::new( + children.into(), + vec![ + Arc::new(StringArray::from(vec![ + Some("a"), + Some("hidden"), + Some("c"), + ])), + Arc::new(Int32Array::from(vec![1, 2, 3])), + blob_inputs(vec![Some(b"hi"), Some(b"hidden"), Some(b"")]), + ], + Some(NullBuffer::from(vec![true, false, true])), + ); + let batch = RecordBatch::try_new( + Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + extra_field, + ])), + vec![Arc::new(Int64Array::from(vec![1, 2, 3])), Arc::new(extra)], + ) + .unwrap(); + let source = db.create_table("docs", batch).execute().await.unwrap(); + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + let mut target_children = vec![ + Field::new("note", DataType::Utf8, true), + Field::new( + "rank", + if difference == "scalar" { + DataType::Int64 + } else { + DataType::Int32 + }, + true, + ), + blob("clip", true), + ]; + if difference == "order" { + target_children.swap(0, 2); + } + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + Field::new("extra", DataType::Struct(target_children.into()), true), + blob("flattened", true), + ]) + .await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode), + ), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + for expression in [ + "CASE WHEN id = 1 THEN extra ELSE NULL END", + "named_struct('note', extra.note, 'rank', extra.rank, 'clip', extra.clip)", + ] { + let query = format!( + "INSERT INTO destination SELECT id, {expression} AS extra, extra.clip AS flattened FROM docs" + ); + let error = planning_error(&ctx, &query).await; + assert!( + error.contains("one source table snapshot"), + "{difference}, {mode:?}: {error}" + ); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + } + sql(&ctx, "INSERT INTO destination SELECT id, extra, extra.clip AS flattened FROM docs ORDER BY id DESC").await; + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let ids = row_ids(&ctx, &destination).await; + let expected = + LargeBinaryArray::from(vec![Some(b"hi".as_slice()), None, Some(b"".as_slice())]); + assert_eq!( + destination.fetch_blobs("extra.clip", &ids).await.unwrap(), + expected, + "{difference}, {mode:?}" + ); + assert_eq!( + destination.fetch_blobs("flattened", &ids).await.unwrap(), + expected + ); + let nested = sql(&ctx, "SELECT extra FROM read_docs ORDER BY id").await; + let extra = nested.column(0).as_struct(); + assert!(extra.is_null(1)); + assert_eq!( + extra + .column_by_name("note") + .unwrap() + .as_string::() + .value(2), + "c" + ); + let rank = extra.column_by_name("rank").unwrap(); + if difference == "scalar" { + assert_eq!( + rank.as_primitive::() + .value(2), + 3 + ); + } else { + assert_eq!( + rank.as_primitive::() + .value(2), + 3 + ); + } + } + } +} + +#[tokio::test] +async fn ordinary_descriptor_shaped_structs_remain_plain_data() { + let fields = vec![ + Field::new("id", DataType::Int64, false), + Field::new( + "raw", + DataType::Struct( + vec![ + Field::new("kind", DataType::UInt8, true), + Field::new("position", DataType::UInt64, true), + Field::new("size", DataType::UInt64, true), + Field::new("blob_id", DataType::UInt32, true), + Field::new("blob_uri", DataType::Utf8, true), + ] + .into(), + ), + true, + ), + ]; + let (source_tmp, source) = empty_table(fields.clone()).await; + let (_destination_tmp, destination) = empty_table(fields).await; + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + sql(&ctx, "INSERT INTO docs VALUES (1, named_struct('kind', 1, 'position', 2, 'size', 3, 'blob_id', 4, 'blob_uri', 'plain data'))").await; + let expected = sql(&ctx, "SELECT * FROM docs").await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap(), + ), + ) + .unwrap(); + sql(&ctx, "INSERT INTO destination SELECT * FROM docs").await; + std::fs::remove_dir_all(source_tmp.path()).unwrap(); + let actual = sql(&ctx, "SELECT * FROM destination").await; + assert_eq!(actual.columns(), expected.columns()); +} + +#[tokio::test] +async fn ambiguous_descriptor_sources_fail_during_planning_without_writing() { let (_tmp, source) = empty_table(vec![ Field::new("id", DataType::Int64, false), blob("payload", true), ]) .await; - let ctx = SessionContext::new_with_config( - SessionConfig::new() - .with_batch_size(1) - .with_target_partitions(1), - ); + let ctx = SessionContext::new(); register(&ctx, &source, BlobSchema::Write).await; sql( &ctx, "INSERT INTO docs SELECT 1, named_struct('data', X'6869', 'uri', NULL)", ) .await; - sql(&ctx, "INSERT INTO docs VALUES (2, NULL)").await; register(&ctx, &source, BlobSchema::Read).await; - let (_dest_tmp, destination) = empty_table( - source - .schema() - .await - .unwrap() - .fields() - .iter() - .map(|f| f.as_ref().clone()) - .collect(), - ) + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) .await; let writer = BaseTableAdapter::try_new(destination.base_table().clone()) .await - .unwrap() - .with_blob_schema(BlobSchema::Write); + .unwrap(); ctx.register_table("destination", Arc::new(writer)).unwrap(); let version = destination.version().await.unwrap(); - // The null row is valid and reaches the writer before the non-null - // descriptor. Even if it is written to a fragment, it must not be committed. - let plan = ctx - .sql("INSERT INTO destination SELECT id, payload FROM docs ORDER BY id DESC") + for select in [ + "SELECT a.id, a.payload FROM docs a JOIN docs b ON a.id = b.id", + "SELECT id, payload FROM docs UNION ALL SELECT id, payload FROM docs", + "SELECT id, payload FROM docs GROUP BY id, payload", + "SELECT id, CASE WHEN id = 1 THEN payload ELSE NULL END AS payload FROM docs", + ] { + let query = format!("INSERT INTO destination {select}"); + let error = planning_error(&ctx, &query).await; + assert!( + error.contains("one source table snapshot"), + "{query}: {error}" + ); + } + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + assert_eq!(destination.version().await.unwrap(), version); +} + +#[tokio::test] +async fn external_descriptor_copy_obeys_destination_bases_and_preserves_ranges() { + use lance::dataset::WriteParams; + use lance_core::datatypes::BlobKind; + use lance_table::format::BasePath; + use lancedb::table::WriteOptions; + + let external_tmp = tempdir().unwrap(); + let payload = b"0123456789abcdef"; + let path = external_tmp.path().join("payload.bin"); + std::fs::write(&path, payload).unwrap(); + let uri = url::Url::from_file_path(&path).unwrap().to_string(); + let base_uri = url::Url::from_directory_path(external_tmp.path()) + .unwrap() + .to_string(); + let base = |id| BasePath { + id, + name: Some("external".into()), + path: base_uri.clone(), + is_dataset_root: false, + }; + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ])); + let DataType::Struct(children) = schema.field(1).data_type().clone() else { + unreachable!() + }; + let input = RecordBatch::try_new( + schema.clone(), + vec![ + Arc::new(Int64Array::from(vec![1, 2])), + Arc::new(StructArray::new( + children, + vec![ + Arc::new(LargeBinaryArray::from(vec![ + None, + Some(b"inline".as_slice()), + ])), + Arc::new(StringArray::from(vec![Some(uri.as_str()), None])), + Arc::new(UInt64Array::from(vec![Some(4), None])), + Arc::new(UInt64Array::from(vec![Some(6), None])), + ], + None, + )), + ], + ) + .unwrap(); + for source_registered in [false, true] { + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let source = db + .create_empty_table("source", schema.clone()) + .write_options(WriteOptions { + lance_write_params: Some(WriteParams { + initial_bases: source_registered.then(|| vec![base(7)]), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + source + .add(input.clone()) + .allow_external_blob_outside_bases(!source_registered) + .execute() + .await + .unwrap(); + for mode in [BlobSchema::Read, BlobSchema::Write] { + let ctx = SessionContext::new(); + register(&ctx, &source, BlobSchema::Read).await; + let descriptor = sql(&ctx, "SELECT payload.blob_id FROM docs WHERE id = 1").await; + assert_eq!( + descriptor + .column(0) + .as_primitive::() + .value(0), + if source_registered { 7 } else { 0 } + ); + for authorized in [false, true] { + let destination_tmp = tempdir().unwrap(); + let destination_db = connect(destination_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let destination = destination_db + .create_empty_table("destination", schema.clone()) + .write_options(WriteOptions { + lance_write_params: Some(WriteParams { + initial_bases: authorized.then(|| vec![base(11)]), + ..Default::default() + }), + }) + .execute() + .await + .unwrap(); + ctx.deregister_table("destination").unwrap(); + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(mode), + ), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + let result = ctx + .sql("INSERT INTO destination SELECT * FROM docs ORDER BY id") + .await + .unwrap() + .collect() + .await; + if !authorized { + let error = result.unwrap_err().to_string(); + assert!( + error.contains("outside registered external bases"), + "{error}" + ); + let reopened = destination_db + .open_table("destination") + .execute() + .await + .unwrap(); + assert_eq!(reopened.version().await.unwrap(), version); + assert_eq!(reopened.count_rows(None).await.unwrap(), 0); + // A logical URI input has the same destination authorization boundary. + ctx.register_table( + "logical_target", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap() + .with_blob_schema(BlobSchema::Write), + ), + ) + .unwrap(); + let error = ctx.sql(&format!("INSERT INTO logical_target SELECT 3, named_struct('data', NULL, 'uri', '{uri}')")).await.unwrap().collect().await.unwrap_err().to_string(); + assert!( + error.contains("allow_external_blob_outside_bases"), + "{error}" + ); + destination.checkout_latest().await.unwrap(); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + } else { + result.unwrap(); + let ids = row_ids(&ctx, &destination).await; + let descriptor = sql(&ctx, "SELECT payload.kind, payload.blob_id, payload.blob_uri, payload.position, payload.size FROM read_docs WHERE id = 1").await; + assert_eq!( + descriptor + .column(0) + .as_primitive::() + .value(0), + BlobKind::External as u8 + ); + assert_eq!( + descriptor + .column(1) + .as_primitive::() + .value(0), + 11 + ); + assert_eq!( + descriptor.column(2).as_string::().value(0), + "payload.bin" + ); + assert_eq!( + descriptor + .column(3) + .as_primitive::() + .value(0), + 4 + ); + assert_eq!( + descriptor + .column(4) + .as_primitive::() + .value(0), + 6 + ); + assert_eq!( + destination.fetch_blobs("payload", &ids).await.unwrap(), + LargeBinaryArray::from(vec![ + Some(&payload[4..10]), + Some(b"inline".as_slice()) + ]) + ); + let files = destination.fetch_blob_files("payload", &ids).await.unwrap(); + let file = files[0].as_ref().unwrap(); + assert_eq!(file.uri(), Some("payload.bin")); + let dataset = destination.dataset().unwrap().get().await.unwrap(); + let registered = &dataset.manifest().base_paths[&11]; + let resolved = + url::Url::parse(&format!("{}/", registered.path.trim_end_matches('/'))) + .unwrap() + .join(file.uri().unwrap()) + .unwrap(); + assert_eq!(resolved.as_str(), uri); + assert_eq!(file.position(), Some(4)); + assert_eq!(file.size(), 6); + } + } + } + } +} + +#[tokio::test] +async fn source_payload_failure_after_written_partition_does_not_commit() { + use datafusion_physical_plan::{ + ExecutionPlanProperties, + execution_plan::{ChildrenPropertiesMode, ReplaceChildrenOptions}, + union::UnionExec, + }; + use futures::TryStreamExt; + use lancedb::blob::{BlobOptions, blob_with_options}; + use std::num::NonZeroUsize; + + let source_tmp = tempdir().unwrap(); + let db = connect(source_tmp.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int64, false), + blob_with_options( + "payload", + true, + BlobOptions { + inline_size_threshold: Some(0), + dedicated_size_threshold: NonZeroUsize::new(1), + }, + ), + ])); + let source = db + .create_table( + "docs", + RecordBatch::try_new( + schema, + vec![ + Arc::new(Int64Array::from(vec![1, 2])), + blob_inputs(vec![Some(&[1; 64]), Some(&[2; 64])]), + ], + ) + .unwrap(), + ) + .execute() + .await + .unwrap(); + let (_destination_tmp, destination) = empty_table(vec![ + Field::new("id", DataType::Int64, false), + blob("payload", true), + ]) + .await; + let ctx = SessionContext::new_with_config( + SessionConfig::new() + .with_target_partitions(1) + .with_batch_size(1), + ); + register(&ctx, &source, BlobSchema::Read).await; + ctx.register_table( + "destination", + Arc::new( + BaseTableAdapter::try_new(destination.base_table().clone()) + .await + .unwrap(), + ), + ) + .unwrap(); + let first = ctx + .sql("INSERT INTO destination SELECT * FROM docs WHERE id = 1") .await .unwrap() .create_physical_plan() .await .unwrap(); - let error = datafusion_physical_plan::collect(plan, ctx.task_ctx()) + let second = ctx + .sql("INSERT INTO destination SELECT * FROM docs WHERE id = 2") .await - .unwrap_err(); - assert!(error.to_string().contains("blob"), "{error}"); + .unwrap() + .create_physical_plan() + .await + .unwrap(); + assert_eq!(first.name(), "InsertExec"); + assert_eq!(second.name(), "InsertExec"); + // Combine already validated SQL inputs only to control partition scheduling: + // finish one real uncommitted write before faulting the next payload read. + let input = UnionExec::try_new(vec![ + first.children()[0].clone(), + second.children()[0].clone(), + ]) + .unwrap(); + assert_eq!(input.output_partitioning().partition_count(), 2); + let insert = first + .replace_children( + vec![input], + ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute), + ) + .unwrap(); + let version = destination.version().await.unwrap(); + let batches: Vec = insert + .execute(0, ctx.task_ctx()) + .unwrap() + .try_collect() + .await + .unwrap(); + assert_eq!( + batches[0] + .column(0) + .as_primitive::() + .value(0), + 1 + ); assert_eq!(destination.count_rows(None).await.unwrap(), 0); assert_eq!(destination.version().await.unwrap(), version); - sql( - &ctx, - "INSERT INTO destination SELECT id, payload FROM docs WHERE payload IS NULL", - ) - .await; - let ids = row_ids(&ctx, &destination).await; - assert_eq!(ids.len(), 1); - assert_eq!( - destination.fetch_blobs("payload", &ids).await.unwrap(), - LargeBinaryArray::from(vec![None::<&[u8]>]) + let dataset = destination.dataset().unwrap().get().await.unwrap(); + let data_dir = _destination_tmp.path().join("docs.lance").join("data"); + assert!( + std::fs::read_dir(data_dir).unwrap().next().is_some(), + "first partition must have written a data file" ); + let ids = row_ids(&ctx, &source).await; + let files = source.fetch_blob_files("payload", &ids).await.unwrap(); + let file = files[1].as_ref().unwrap(); + assert_eq!( + file.kind(), + Some(lance_core::datatypes::BlobKind::Dedicated) + ); + let missing_path = std::path::Path::new("/").join(file.data_path().unwrap().as_ref()); + drop(files); + std::fs::remove_file(&missing_path).unwrap(); + let error = insert + .execute(1, ctx.task_ctx()) + .unwrap() + .try_collect::>() + .await + .unwrap_err() + .to_string(); + assert!( + error.contains(missing_path.file_name().unwrap().to_str().unwrap()), + "{error}" + ); + // Check both the live handle and an independently reopened manifest. + destination.checkout_latest().await.unwrap(); + assert_eq!(destination.version().await.unwrap(), version); + assert_eq!(destination.count_rows(None).await.unwrap(), 0); + let reopened = lance::Dataset::open(dataset.uri()).await.unwrap(); + assert_eq!(reopened.version().version, version); + assert_eq!(reopened.count_rows(None).await.unwrap(), 0); } diff --git a/rust/lancedb/tests/remote_blob_ranges.rs b/rust/lancedb/tests/remote_blob_ranges.rs new file mode 100644 index 000000000..51c49fe09 --- /dev/null +++ b/rust/lancedb/tests/remote_blob_ranges.rs @@ -0,0 +1,634 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +#![cfg(feature = "remote")] + +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use arrow_array::{Array, ArrayRef, LargeBinaryArray, RecordBatch, StringArray}; +use arrow_ipc::writer::StreamWriter; +use lancedb::Table; +use lancedb::blob::BlobRangeRequest; +use lancedb::remote::{ClientConfig, RetryConfig, TimeoutConfig}; +use serde_json::{Value, json}; +use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; +use tokio::net::TcpListener; + +const MIB: u64 = 1024 * 1024; +const IDENTITY: &str = "v1:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; +const ROUTE: &str = "/v1/table/test/fetch_blob_ranges/"; + +struct Reply { + status: u16, + version: Option, + body: Vec, + declared_extra: usize, + identity: Option<&'static str>, +} + +fn ipc(column: &str, values: ArrayRef) -> Vec { + let batch = RecordBatch::try_from_iter([(column, values)]).unwrap(); + let mut body = Vec::new(); + let mut writer = StreamWriter::try_new(&mut body, &batch.schema()).unwrap(); + // Multiple batches exercise response assembly as well as HTTP partitions. + let mid = batch.num_rows() / 2; + writer.write(&batch.slice(0, mid)).unwrap(); + writer + .write(&batch.slice(mid, batch.num_rows() - mid)) + .unwrap(); + writer.finish().unwrap(); + drop(writer); + body +} + +fn legacy_reply(path: &str, body: &Value, takes: usize) -> Reply { + use arrow_array::{StructArray, UInt8Array, UInt32Array, UInt64Array}; + let version = body["version"] + .as_u64() + .unwrap_or(if takes == 1 { 7 } else { 8 }); + if path.ends_with("/query/") { + assert_eq!(body["branch"], "experiment"); + assert_eq!(body["columns"], json!(["image"])); + let filter = body["filter"].as_str().unwrap(); + let ids = filter + .split_once('(') + .unwrap() + .1 + .trim_end_matches(')') + .split(',') + .map(|id| id.trim().parse::().unwrap()) + .filter(|id| [10, 20, 30, 40].contains(id)) + .rev() + .collect::>(); + let fields = lance_core::datatypes::BLOB_V2_DESC_FIELDS.clone(); + let descriptors = StructArray::new( + fields, + vec![ + Arc::new(UInt8Array::from(vec![0; ids.len()])), + Arc::new(UInt64Array::from(vec![0; ids.len()])), + Arc::new(UInt64Array::from( + ids.iter() + .map(|id| if *id == 40 { 0 } else { 5 }) + .collect::>(), + )), + Arc::new(UInt32Array::from(vec![0; ids.len()])), + Arc::new(StringArray::from(vec![""; ids.len()])), + ], + Some(ids.iter().map(|id| *id != 20).collect()), + ); + let batch = RecordBatch::try_from_iter([ + ("image", Arc::new(descriptors) as ArrayRef), + ("_rowid", Arc::new(UInt64Array::from(ids)) as ArrayRef), + ]) + .unwrap(); + let mut bytes = Vec::new(); + let mut writer = StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(&batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + Reply { + status: 200, + version: Some(version), + body: bytes, + declared_extra: 0, + identity: Some(IDENTITY), + } + } else { + assert!(path.contains("branch=experiment"), "{path}"); + let version = path + .split("version=") + .nth(1) + .unwrap() + .split('&') + .next() + .unwrap() + .parse::() + .unwrap(); + let range = body["range"] + .as_str() + .unwrap() + .strip_prefix("bytes=") + .unwrap(); + let (start, end) = range.split_once('-').unwrap(); + let start = start.parse::().unwrap(); + let end = end.parse::().unwrap(); + let payload = if version == 8 { b"ALPHA" } else { b"alpha" }; + Reply { + status: 206, + version: Some(version), + body: payload[start..=end].to_vec(), + declared_extra: 0, + identity: Some(IDENTITY), + } + } +} + +fn reply(values: Vec>>, version: u64) -> Reply { + Reply { + status: 200, + version: Some(version), + body: ipc( + "value", + Arc::new(LargeBinaryArray::from_iter( + values.iter().map(|v| v.as_deref()), + )), + ), + declared_extra: 0, + identity: Some(IDENTITY), + } +} + +fn byte(row: u64, offset: u64, version: u64) -> u8 { + ((row * 17 + offset % 251 + version) % 251) as u8 +} + +fn serve_ranges(body: &Value, version: u64) -> Reply { + assert_eq!(body["column"], "image"); + let ranges = body["ranges"].as_array().unwrap(); + assert!(ranges.len() <= 1024); + assert!( + ranges + .iter() + .map(|r| r["length"].as_u64().unwrap()) + .sum::() + <= 64 * MIB + ); + let values = ranges + .iter() + .map(|r| { + let row = r["row_id"].as_u64().unwrap(); + let offset = r["offset"].as_u64().unwrap(); + let length = r["length"].as_u64().unwrap(); + (row != 20).then(|| { + (offset..offset + length) + .map(|i| byte(row, i, version)) + .collect() + }) + }) + .collect(); + reply(values, version) +} + +struct Server { + url: String, + calls: Arc>>, + task: tokio::task::JoinHandle<()>, + identities: Arc>>>, +} + +impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl Server { + async fn new(handler: impl Fn(&Value, usize) -> Reply + Send + Sync + 'static) -> Self { + Self::with_capability(handler, Some("1")).await + } + + async fn with_capability( + handler: impl Fn(&Value, usize) -> Reply + Send + Sync + 'static, + capability: Option<&'static str>, + ) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let calls = Arc::new(Mutex::new(Vec::new())); + let captured = calls.clone(); + let identities = Arc::new(Mutex::new(Vec::new())); + let captured_identities = identities.clone(); + let task = tokio::spawn(async move { + let mut fetches = 0; + let mut takes = 0; + loop { + let (socket, _) = listener.accept().await.unwrap(); + let captured = captured.clone(); + let result = tokio::time::timeout(Duration::from_secs(20), async { + let mut socket = BufReader::new(socket); + let mut line = String::new(); + socket.read_line(&mut line).await?; + let path = line.split_whitespace().nth(1).unwrap().to_string(); + let method = line.split_whitespace().next().unwrap().to_string(); + let mut range = String::new(); + let mut length = 0; + let mut identity = None; + loop { + line.clear(); + socket.read_line(&mut line).await?; + assert!(line.len() <= 16384); + if line == "\r\n" { break; } + if let Some((name, value)) = line.split_once(':') { + if name.eq_ignore_ascii_case("content-length") { + length = value.trim().parse::().unwrap(); + } + if name.eq_ignore_ascii_case("x-lancedb-query-snapshot") { identity = Some(value.trim().to_owned()); } + if name.eq_ignore_ascii_case("range") { range = value.trim().to_string(); } + } + } + assert!(length <= 256 * 1024); + let mut bytes = vec![0; length]; + socket.read_exact(&mut bytes).await?; + let body = if method == "GET" { json!({"range": range}) } else if bytes.is_empty() { json!({}) } else { serde_json::from_slice(&bytes).unwrap() }; + captured.lock().unwrap().push((path.clone(), body.clone())); + let response = if path == "/v1/table/test/describe/" { + Reply { status: 200, version: None, body: serde_json::to_vec(&json!({"version": 8, "schema": {"fields": []}})).unwrap(), declared_extra: 0, identity: None } + } else if path == "/v1/table/test/branches/list/" { + Reply { status: 200, version: None, body: br#"{"branches":{"experiment":{"parentBranch":null,"parentVersion":1,"createAt":1,"manifestSize":1}}}"#.to_vec(), declared_extra: 0, identity: None } + } else if capability != Some("1") { + assert_ne!(path, ROUTE, "unknown capability must select old routes first"); + takes += usize::from(path.ends_with("/query/")); + legacy_reply(&path, &body, takes) + } else { + assert_eq!(path, ROUTE, "unexpected legacy or fallback request"); + fetches += 1; + captured_identities.lock().unwrap().push(identity); + handler(&body, fetches) + }; + if response.status == 0 { return Ok::<_, std::io::Error>(()); } + let version = response.version.map(|v| format!("x-lancedb-version: {v}\r\n")).unwrap_or_default(); + let capability = if path.ends_with("/describe/") { capability.map(|value| format!("x-lancedb-blob-ranges: {value}\r\n")).unwrap_or_default() } else { String::new() }; + let content_type = if path == ROUTE || path.ends_with("/query/") { "application/vnd.apache.arrow.stream" } else { "application/json" }; + let content_range = if method == "GET" { format!("Content-Range: {}/5\r\n", body["range"].as_str().unwrap().replace("bytes=", "bytes ")) } else { String::new() }; + let identity = if path == ROUTE { response.identity.map(|id| format!("x-lancedb-query-snapshot: {id}\r\n")).unwrap_or_default() } else { String::new() }; + let header = format!("HTTP/1.1 {} Response\r\nContent-Type: {content_type}\r\nphalanx-version: 1.13.0-beta.0\r\n{capability}{version}{identity}{content_range}Content-Length: {}\r\nConnection: close\r\n\r\n", response.status, response.body.len() + response.declared_extra); + socket.write_all(header.as_bytes()).await?; + for chunk in response.body.chunks(8192) { socket.write_all(chunk).await?; } + socket.shutdown().await?; + Ok(()) + }).await; + // A client rejecting a malformed schema may close the body early. + assert!(result.is_ok(), "loopback request timed out"); + } + }); + Self { + url, + calls, + task, + identities, + } + } + + async fn table(&self, version: Option) -> Table { + let db = lancedb::connect("db://dev") + .api_key("fake") + .region("us-east-1") + .host_override(&self.url) + .client_config(ClientConfig { + retry_config: RetryConfig { + retries: Some(2), + connect_retries: Some(2), + read_retries: Some(2), + ..Default::default() + }, + timeout_config: TimeoutConfig { + timeout: Some(Duration::from_secs(30)), + ..Default::default() + }, + ..Default::default() + }) + .execute() + .await + .unwrap(); + let mut open = db.open_table("test").branch("experiment"); + if let Some(version) = version { + open = open.version(version); + } + open.execute().await.unwrap() + } +} + +#[tokio::test] +async fn public_ranges_work_on_old_routes_only_servers() { + for capability in [None, Some("0"), Some("2")] { + for checkout in [None, Some(3)] { + let server = Server::with_capability( + |_, _| panic!("new endpoint must not be requested"), + capability, + ) + .await; + let table = server.table(checkout).await; + let cloned = table.clone(); + let ranges = [ + BlobRangeRequest::new(10, 1, 3), + BlobRangeRequest::new(20, 0, 1), + BlobRangeRequest::new(40, 0, 0), + BlobRangeRequest::new(10, 5, 0), + BlobRangeRequest::new(10, 1, 3), + ]; + let result = cloned.fetch_blob_ranges("image", ranges).await.unwrap(); + assert_eq!( + result, + LargeBinaryArray::from(vec![ + Some(b"lph".as_slice()), + None, + Some(b"".as_slice()), + Some(b"".as_slice()), + Some(b"lph".as_slice()) + ]) + ); + let result = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap(); + assert_eq!( + result.value(0), + if checkout.is_none() { b"A" } else { b"a" } + ); + for ranges in [ + vec![BlobRangeRequest::new(10, 4, 2)], + vec![BlobRangeRequest::new(99, 0, 1)], + ] { + assert!(matches!( + table.fetch_blob_ranges("image", ranges).await.unwrap_err(), + lancedb::Error::InvalidInput { .. } + )); + } + assert!( + !server + .calls + .lock() + .unwrap() + .iter() + .any(|(path, _)| path == ROUTE) + ); + } + } +} + +#[tokio::test] +async fn public_ranges_keep_order_nulls_and_snapshot_without_pinning_live_handle() { + for checkout in [None, Some(3)] { + let server = Server::new(move |body, call| { + assert_eq!(body["branch"], "experiment"); + let expected = checkout.or((call > 1 && call < 3).then_some(7)); + assert_eq!(body["version"].as_u64(), expected); + serve_ranges( + body, + body["version"] + .as_u64() + .unwrap_or(if call == 1 { 7 } else { 8 }), + ) + }) + .await; + let table = server.table(checkout).await; + let mut requests = (0..1025) + .map(|i| BlobRangeRequest::new(if i % 9 == 0 { 20 } else { 10 + i % 7 }, i, i % 4)) + .collect::>(); + requests.extend([ + BlobRangeRequest::new(10, 0, 0), + BlobRangeRequest::new(10, 2, 3), + BlobRangeRequest::new(10, 2, 3), + ]); + let result = table + .fetch_blob_ranges("image", requests.clone()) + .await + .unwrap(); + assert_eq!(result.len(), requests.len()); + for (i, request) in requests.iter().enumerate() { + assert_eq!(result.is_null(i), request.row_id == 20); + if request.row_id != 20 { + let expected = (request.offset..request.offset + request.length) + .map(|j| byte(request.row_id, j, checkout.unwrap_or(7))) + .collect::>(); + assert_eq!(result.value(i), expected); + } + } + let next = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 0, 1)]) + .await + .unwrap(); + assert_eq!(next.value(0), [byte(10, 0, checkout.unwrap_or(8))]); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 3 + ); + } +} + +#[tokio::test] +async fn public_ranges_partition_bytes_and_reassemble_large_single_range() { + let server = Server::new(|body, call| { + assert_eq!(body["version"].as_u64(), (call > 1).then_some(7)); + serve_ranges(body, 7) + }) + .await; + let table = server.table(None).await; + let requests = [ + BlobRangeRequest::new(10, 3, 33 * MIB), + BlobRangeRequest::new(30, 7, 33 * MIB), + BlobRangeRequest::new(40, 11, 70 * MIB), + BlobRangeRequest::new(20, 0, u64::MAX), + ]; + let result = table.fetch_blob_ranges("image", requests).await.unwrap(); + assert_eq!(result.len(), 4); + for (i, request) in requests[..3].iter().enumerate() { + assert_eq!(result.value_length(i) as u64, request.length); + assert!( + result + .value(i) + .iter() + .enumerate() + .all(|(j, value)| *value == byte(request.row_id, request.offset + j as u64, 7)) + ); + } + assert!(result.is_null(3)); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 3 + ); +} + +#[tokio::test] +async fn public_ranges_reject_malformed_responses_and_http_failures_without_fallback() { + for case in 0..16 { + let server = Server::new(move |body, call| { + let mut response = serve_ranges(body, 7); + // Fail after one successful partition to prove no partial success. + if call == 1 { + return response; + } + match case { + 0 => response.body = ipc("value", Arc::new(StringArray::from(vec!["bad"]))), + 1 => { + response.body = ipc( + "wrong", + Arc::new(LargeBinaryArray::from(vec![Some(b"a".as_slice())])), + ) + } + 2 => response = reply(vec![], 7), + 3 => response = reply(vec![Some(vec![1]), Some(vec![2])], 7), + 4 => response.body.truncate(response.body.len() - 8), + 5 => response.body.truncate(response.body.len() / 2), + 6 => response.declared_extra = 10, + 7 => response = reply(vec![Some(vec![])], 7), + 8 => response.version = None, + 9 => response.version = Some(8), + 10..=14 => { + response.status = [401, 403, 404, 429, 500][case - 10]; + response.body = b"ordinary failure".to_vec(); + } + 15 => response.status = 0, + _ => unreachable!(), + } + response + }) + .await; + let table = server.table(None).await; + let requests = vec![BlobRangeRequest::new(10, 0, 1); 1025]; + assert!( + table.fetch_blob_ranges("image", requests).await.is_err(), + "case {case}" + ); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 2, + "case {case}" + ); + } +} + +#[tokio::test] +async fn public_ranges_validate_locally_and_propagate_server_range_errors() { + let server = Server::new(|_, _| Reply { + status: 400, + version: None, + body: b"range exceeds blob size or missing row".to_vec(), + declared_extra: 0, + identity: Some(IDENTITY), + }) + .await; + let table = server.table(None).await; + let before = server.calls.lock().unwrap().len(); + assert_eq!(table.fetch_blob_ranges("image", []).await.unwrap().len(), 0); + assert!( + table + .fetch_blob_ranges("image", [BlobRangeRequest::new(20, u64::MAX, 1)]) + .await + .unwrap_err() + .to_string() + .contains("overflows u64") + ); + assert_eq!(server.calls.lock().unwrap().len(), before); + let error = table + .fetch_blob_ranges("image", [BlobRangeRequest::new(10, 9, 2)]) + .await + .unwrap_err(); + assert!(matches!(error, lancedb::Error::InvalidInput { .. })); + assert!(error.to_string().contains("range exceeds")); +} + +#[tokio::test] +async fn public_ranges_require_original_identity_on_every_partition() { + for huge in [false, true] { + for case in 0..5 { + let server = Server::new(move |body, call| { + let mut response = serve_ranges(body, 7); + if call == 2 { + response.identity = match case { + 0 => None, // Old serving node ignores the precondition. + 1 => Some("invalid"), + _ => Some( + "v1:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + ), + }; + if case == 3 || case == 4 { + response.status = if case == 3 { 400 } else { 404 }; + response.body = + b"query snapshot identity mismatch: gone or replaced".to_vec(); + } else { + // Identity verification must win over malformed payload. + response.body = b"not Arrow".to_vec(); + } + } + response + }) + .await; + let table = server.table(None).await; + let requests = if huge { + vec![BlobRangeRequest::new(10, 0, 64 * MIB + 1)] + } else { + vec![BlobRangeRequest::new(10, 0, 1); 1025] + }; + let error = table + .fetch_blob_ranges("image", requests) + .await + .unwrap_err(); + if case < 3 { + assert!( + matches!(error, lancedb::Error::NotSupported { .. }), + "{error}" + ); + assert!(error.to_string().contains("snapshot identity"), "{error}"); + } else if case == 3 { + assert!( + matches!(error, lancedb::Error::InvalidInput { .. }), + "{error}" + ); + } else { + assert!( + matches!(error, lancedb::Error::TableNotFound { .. }), + "{error}" + ); + } + assert_eq!( + *server.identities.lock().unwrap(), + [None, Some(IDENTITY.into())] + ); + assert_eq!( + server + .calls + .lock() + .unwrap() + .iter() + .filter(|(path, _)| path == ROUTE) + .count(), + 2 + ); + } + } +} + +#[tokio::test] +async fn public_ranges_cannot_establish_identity_from_numeric_version_or_describe() { + for identity in [None, Some("invalid"), Some("v2:unsupported")] { + let server = Server::new(move |_, call| { + assert_eq!(call, 1, "no failure fallback, replay or second partition"); + let mut response = reply(vec![Some(b"A".to_vec()); 1024], 7); + response.identity = identity; + response.body = b"not Arrow".to_vec(); + response + }) + .await; + let table = server.table(None).await; + let before = server.calls.lock().unwrap().len(); + let error = table + .fetch_blob_ranges("image", vec![BlobRangeRequest::new(10, 0, 1); 1025]) + .await + .unwrap_err(); + assert!( + matches!(error, lancedb::Error::NotSupported { .. }), + "{error}" + ); + assert!(error.to_string().contains("snapshot identity"), "{error}"); + assert_eq!(server.calls.lock().unwrap().len(), before + 1); + } +}