From 1c0118015c43344e5e1a585a1018fae7cb681feb Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 27 Nov 2026 00:16:29 +0800 Subject: [PATCH] feat(nodejs): open source-bearing blob descriptors (#5238) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add `Table.openBlobFile` and `Table.openBlobFiles` for source-bearing SQL `blob_descriptor` results, matching the existing Rust and Python APIs. The TypeScript methods forward the descriptor to the shared Rust opener instead of reimplementing routing. That keeps the 10 MiB direct-read threshold, pinned snapshot identity, resolver refresh, and 503 single-shot proxy fallback identical to `fetchBlobFiles` and the other public Blob V2 entries. Descriptor fields remain the snake_case shape returned by Arrow/SQL; the wrapper converts unsigned 64-bit values to `bigint` at the NAPI boundary and returns `null` for null descriptors. Existing custom `Table` subclasses keep working through a default "not supported" implementation. Validation: - `pnpm tsc` - `pnpm lint` - `pnpm test --runInBand __test__/blob_open.test.ts __test__/blob_ranges.test.ts __test__/remote_blob_snapshot.test.ts` — 65 passed - focused Rust core tests for direct opens, threshold routing, snapshot preservation, and 503 fallback — passed The docs also update the TypeScript cross-row range table and example; `fetchBlobRanges` was already implemented but was still documented as unavailable. --- docs/src/js/classes/Table.md | 61 +++++ docs/src/js/globals.md | 2 + docs/src/js/interfaces/BlobDescriptor.md | 59 ++++ .../src/js/interfaces/BlobDescriptorSource.md | 66 +++++ docs/web-tests/blob-v2/ts/multimodal.test.ts | 12 +- docs/web/management/table.mdx | 33 +-- docs/web/snippets/multimodal.mdx | 2 +- docs/web/sql/dql/blob-descriptor.mdx | 27 ++ nodejs/__test__/blob_open.test.ts | 257 ++++++++++++++++++ nodejs/lancedb/blob.ts | 74 +++++ nodejs/lancedb/index.ts | 1 + nodejs/lancedb/table.ts | 57 ++++ nodejs/src/blob.rs | 57 +++- nodejs/src/table.rs | 20 +- 14 files changed, 692 insertions(+), 36 deletions(-) create mode 100644 docs/src/js/interfaces/BlobDescriptor.md create mode 100644 docs/src/js/interfaces/BlobDescriptorSource.md create mode 100644 nodejs/__test__/blob_open.test.ts diff --git a/docs/src/js/classes/Table.md b/docs/src/js/classes/Table.md index afd2b897f..ad20d1e0a 100644 --- a/docs/src/js/classes/Table.md +++ b/docs/src/js/classes/Table.md @@ -1229,6 +1229,67 @@ rows depending on how they match. *** +### openBlobFile() + +```ts +openBlobFile(_descriptor, _options?): Promise +``` + +Opens a lazy handle from a source-bearing SQL `blob_descriptor` result. + +The descriptor's source pins the table version, branch, column and row +identity, so opening does not change this table's checkout. Null +descriptors return `null`. Payload bytes load only when the returned +handle is read. Pass BlobReadOptions.signal to cancel the open. + +#### Parameters + +* **\_descriptor**: `null` \| [`BlobDescriptor`](../interfaces/BlobDescriptor.md) + +* **\_options?**: [`BlobReadOptions`](../type-aliases/BlobReadOptions.md) + +#### Returns + +`Promise`<`null` \| [`BlobFile`](BlobFile.md)> + +#### Example + +```ts +const rows = await table + .query() + .select({ video: "blob_descriptor(video)" }) + .toArray(); +const handle = await table.openBlobFile(rows[0].video); +if (handle) { + const header = await handle.readRange(0n, 16n); + await handle.close(); +} +``` + +*** + +### openBlobFiles() + +```ts +openBlobFiles(descriptors, options?): AsyncGenerator +``` + +Opens source-bearing descriptors in iteration order, preserving nulls. +Handles open lazily as the iterable advances. Close each non-null handle +after use. + +#### Parameters + +* **descriptors**: `Iterable`<`null` \| [`BlobDescriptor`](../interfaces/BlobDescriptor.md)> + +* **options?**: [`BlobReadOptions`](../type-aliases/BlobReadOptions.md) + +#### Returns + +`AsyncGenerator`<`null` \| [`BlobFile`](BlobFile.md), `any`, `unknown`> + +*** + ### optimize() ```ts diff --git a/docs/src/js/globals.md b/docs/src/js/globals.md index 33fbe1176..e98ddccaf 100644 --- a/docs/src/js/globals.md +++ b/docs/src/js/globals.md @@ -63,6 +63,8 @@ - [AddDataOptions](interfaces/AddDataOptions.md) - [AddResult](interfaces/AddResult.md) - [AlterColumnsResult](interfaces/AlterColumnsResult.md) +- [BlobDescriptor](interfaces/BlobDescriptor.md) +- [BlobDescriptorSource](interfaces/BlobDescriptorSource.md) - [BranchColumnChange](interfaces/BranchColumnChange.md) - [BranchColumnSummary](interfaces/BranchColumnSummary.md) - [BranchDiff](interfaces/BranchDiff.md) diff --git a/docs/src/js/interfaces/BlobDescriptor.md b/docs/src/js/interfaces/BlobDescriptor.md new file mode 100644 index 000000000..7576b856f --- /dev/null +++ b/docs/src/js/interfaces/BlobDescriptor.md @@ -0,0 +1,59 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / BlobDescriptor + +# Interface: BlobDescriptor + +A source-bearing Blob V2 descriptor accepted by [Table.openBlobFile](../classes/Table.md#openblobfile). +Query results expose these fields as an Arrow struct. The source pins the +table version, branch, column and row identity used to open the handle. + +## Properties + +### blob\_id + +```ts +blob_id: number; +``` + +*** + +### blob\_uri + +```ts +blob_uri: string; +``` + +*** + +### kind + +```ts +kind: number; +``` + +*** + +### position + +```ts +position: number | bigint; +``` + +*** + +### size + +```ts +size: number | bigint; +``` + +*** + +### source + +```ts +source: BlobDescriptorSource; +``` diff --git a/docs/src/js/interfaces/BlobDescriptorSource.md b/docs/src/js/interfaces/BlobDescriptorSource.md new file mode 100644 index 000000000..994adec39 --- /dev/null +++ b/docs/src/js/interfaces/BlobDescriptorSource.md @@ -0,0 +1,66 @@ +[**@lancedb/lancedb**](../README.md) • **Docs** + +*** + +[@lancedb/lancedb](../globals.md) / BlobDescriptorSource + +# Interface: BlobDescriptorSource + +A source-bearing Blob V2 descriptor returned by the SQL `blob_descriptor` +function. Field names match the descriptor object/Arrow struct shape. + +## Properties + +### branch? + +```ts +optional branch: null | string; +``` + +*** + +### column + +```ts +column: string; +``` + +*** + +### committed\_at\_micros + +```ts +committed_at_micros: number | bigint; +``` + +*** + +### row\_is\_address + +```ts +row_is_address: boolean; +``` + +*** + +### row\_reference + +```ts +row_reference: number | bigint; +``` + +*** + +### uri + +```ts +uri: string; +``` + +*** + +### version + +```ts +version: number | bigint; +``` diff --git a/docs/web-tests/blob-v2/ts/multimodal.test.ts b/docs/web-tests/blob-v2/ts/multimodal.test.ts index b253ee9b2..c3ba5b9e7 100644 --- a/docs/web-tests/blob-v2/ts/multimodal.test.ts +++ b/docs/web-tests/blob-v2/ts/multimodal.test.ts @@ -78,16 +78,14 @@ test("blob column tutorial", async () => { assert.equal(payloads.length, 2); // --8<-- [start:blob_api_ranges] - const [secondImage] = await blobTable.fetchBlobFiles("image", [rowIds[1]!]); - const parts = await secondImage!.readRanges([ - { start: 0n, end: 6n }, - { start: 7n, end: 12n }, + const slices = await blobTable.fetchBlobRanges("image", [ + { rowId: rowIds[0]!, offset: 0n, length: 6n }, + { rowId: rowIds[1]!, offset: 7n, length: 5n }, ]); - await secondImage!.close(); // --8<-- [end:blob_api_ranges] assert.deepEqual( - parts.map((part) => part.toString("utf8")), - ["second", "image"], + slices.map((slice) => slice!.toString("utf8")), + ["inline", "image"], ); // --8<-- [start:blob_api_bytes_mode] diff --git a/docs/web/management/table.mdx b/docs/web/management/table.mdx index 8c42f2122..fef2a5707 100644 --- a/docs/web/management/table.mdx +++ b/docs/web/management/table.mdx @@ -819,11 +819,7 @@ The other fetch methods load bytes directly: | Need | Python | TypeScript | Rust | | --- | --- | --- | --- | | Whole payloads for a set of rows | `fetch_blobs` | `fetchBlobs` | `fetch_blobs` | -| Byte slices across many rows in one call | `fetch_blob_ranges` | Not available. Use `fetchBlobFiles` and `readRanges`. | `fetch_blob_ranges` | - -{/* Draft for the TypeScript cross-row Blob range release. Replace the row above: | Byte slices across many rows in one call | `fetch_blob_ranges` | `fetchBlobRanges` | `fetch_blob_ranges` | -*/} - `fetch_blobs` returns the full bytes for each row ID in order. Null blobs produce null entries, and empty blobs produce empty byte strings. @@ -848,22 +844,17 @@ The other fetch methods load bytes directly: -{/* Draft for the TypeScript cross-row Blob range release. -Upcoming-release draft: TypeScript adds `fetchBlobRanges` for cross-row slices. -Until that SDK release is available, use `fetchBlobFiles` and `readRanges`. -Server-side batching requires a deployment with the validated range capability; -older servers continue using the descriptor and Range path selected before the -read. An error from the selected batched endpoint is returned without fallback. -A batched call keeps the native snapshot identity from its first range response -across every partition and requires each serving node to verify it. Missing identity -support or a replaced/deleted snapshot fails the whole call; upgrade all serving -nodes before selecting the batched endpoint with a new SDK. -Custom TypeScript `Table` subclasses must implement the new abstract method. +TypeScript `fetchBlobRanges` uses the batched `/fetch_blob_ranges` endpoint when +the server advertises the range capability; older servers use descriptor queries +and Range reads. An error from the selected endpoint is returned without +fallback. The call keeps the native snapshot identity from its first response +across every partition, so missing identity support or a replaced snapshot fails +the whole call. Upgrade every serving node before selecting the batched endpoint +with a new SDK. -*/} -Python and Rust read slices across rows with `fetch_blob_ranges`. On a handle, +All three SDKs read slices across rows with the range API. On a handle, `read_ranges` reads more than one slice of one blob. Python takes `(offset, length)` pairs, TypeScript takes `{ start, end }` ranges with an exclusive `end`, and Rust takes `start..end` ranges: @@ -874,14 +865,6 @@ exclusive `end`, and Rust takes `start..end` ranges: - {/* Draft for the TypeScript cross-row Blob range release. - {`// Upcoming-release draft: slices from more than one row. -const slices = await blobTable.fetchBlobRanges("image", [ - { rowId: rowIds[0]!, offset: 0n, length: 6n }, - { rowId: rowIds[1]!, offset: 7n, length: 5n }, -]); -`}{"\n"} - */} {TsBlobApiRanges} diff --git a/docs/web/snippets/multimodal.mdx b/docs/web/snippets/multimodal.mdx index 19180dfd0..db8059e07 100644 --- a/docs/web/snippets/multimodal.mdx +++ b/docs/web/snippets/multimodal.mdx @@ -42,7 +42,7 @@ export const TsBlobApiFiles = "const rows = await blobTable\n .query()\n .sele export const TsBlobApiIngest = "const blobTable = await db.createEmptyTable(\"photos\", blobSchema, {\n mode: \"overwrite\",\n});\n\nawait blobTable.add([\n { id: 1n, label: \"door\", image: Buffer.from(\"inline_image_bytes\") },\n { id: 2n, label: \"window\", image: Buffer.from(\"second_image_bytes\") },\n]);\n"; -export const TsBlobApiRanges = "const [secondImage] = await blobTable.fetchBlobFiles(\"image\", [rowIds[1]!]);\nconst parts = await secondImage!.readRanges([\n { start: 0n, end: 6n },\n { start: 7n, end: 12n },\n]);\nawait secondImage!.close();\n"; +export const TsBlobApiRanges = "const slices = await blobTable.fetchBlobRanges(\"image\", [\n { rowId: rowIds[0]!, offset: 0n, length: 6n },\n { rowId: rowIds[1]!, offset: 7n, length: 5n },\n]);\n"; export const TsBlobApiSchema = "const blobSchema = new arrow.Schema([\n new arrow.Field(\"id\", new arrow.Int64()),\n new arrow.Field(\"label\", new arrow.Utf8()),\n lancedb.blob(\"image\"),\n]);\n"; diff --git a/docs/web/sql/dql/blob-descriptor.mdx b/docs/web/sql/dql/blob-descriptor.mdx index 7ba83311c..49b4fe391 100644 --- a/docs/web/sql/dql/blob-descriptor.mdx +++ b/docs/web/sql/dql/blob-descriptor.mdx @@ -27,6 +27,33 @@ rows = db.execute_query("SELECT id, blob_descriptor(video) AS descriptor FROM vi with table.open_blob_file(rows[0]["descriptor"]) as reader: payload = reader.read() ``` + +```typescript TypeScript icon="typescript" +const rows = await table + .query() + .select({ descriptor: "blob_descriptor(video)" }) + .toArray(); +const reader = await table.openBlobFile(rows[0].descriptor); +if (reader) { + const payload = await reader.read(); + await reader.close(); +} +``` + +```rust Rust icon="rust" +use lancedb::{blob::BlobDescriptor, Table}; + +async fn read_descriptor( + table: &Table, + descriptor: &BlobDescriptor, +) -> lancedb::Result<()> { + let reader = table.open_blob_file(descriptor).await?; + let payload = reader.read().await?; + println!("{} bytes", payload.len()); + reader.close().await?; + Ok(()) +} +``` A descriptor is pinned to the table version it was read at: it keeps diff --git a/nodejs/__test__/blob_open.test.ts b/nodejs/__test__/blob_open.test.ts new file mode 100644 index 000000000..34d1c764c --- /dev/null +++ b/nodejs/__test__/blob_open.test.ts @@ -0,0 +1,257 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Copyright The LanceDB Authors + +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { + type BlobDescriptor, + type Connection, + type Table, + connect, +} from "../lancedb"; + +jest.setTimeout(15000); + +const IDENTITY = `v1:${"a".repeat(64)}`; +const MIB = 1024 * 1024; + +function descriptor(size: bigint): BlobDescriptor { + return { + kind: 2, + position: 0n, + size, + // biome-ignore lint/style/useNamingConvention: Matches the descriptor. + blob_id: 1, + // biome-ignore lint/style/useNamingConvention: Matches the descriptor. + blob_uri: "", + source: { + uri: "s3://fixture/table.lance", + version: 46n, + // biome-ignore lint/style/useNamingConvention: Matches the descriptor. + committed_at_micros: 1795627189287568n, + branch: null, + column: "image", + // biome-ignore lint/style/useNamingConvention: Matches the descriptor. + row_reference: 0n, + // biome-ignore lint/style/useNamingConvention: Matches the descriptor. + row_is_address: false, + }, + }; +} + +async function readBody(req: import("node:http").IncomingMessage) { + const chunks: Buffer[] = []; + for await (const chunk of req) { + chunks.push(chunk as Buffer); + } + return Buffer.concat(chunks).toString(); +} + +async function withOpenServer( + run: ( + db: Connection, + table: Table, + state: { + directStatus: number; + blobLocationsCalls: number; + objectCalls: number; + proxyCalls: number; + lastLocationBody: Record | undefined; + }, + ) => Promise, + size: bigint = 10n * BigInt(MIB), +) { + let port = 0; + const state = { + directStatus: 200, + blobLocationsCalls: 0, + objectCalls: 0, + proxyCalls: 0, + lastLocationBody: undefined as Record | undefined, + }; + const payload = Buffer.alloc(Number(size), 0x61); + const server = createServer(async (req, res) => { + const url = req.url ?? ""; + if (url === "/v1/table/test/describe/") { + res.writeHead(200, { + "content-type": "application/json", + "phalanx-version": "1.15.0-beta.0", + "x-lancedb-blob-locations": "1", + }); + res.end(JSON.stringify({ version: 46, schema: { fields: [] } })); + return; + } + if (url === "/v1/table/test/blob_locations/") { + state.blobLocationsCalls++; + const body = JSON.parse(await readBody(req)) as Record; + state.lastLocationBody = body; + if (state.directStatus !== 200) { + res.writeHead(state.directStatus).end("resolver unavailable"); + return; + } + res.writeHead(200, { + "content-type": "application/json", + "x-lancedb-version": "46", + "x-lancedb-query-snapshot": IDENTITY, + }); + res.end( + JSON.stringify({ + sources: [ + { + url: `http://127.0.0.1:${port}/object?signature=test`, + // biome-ignore lint/style/useNamingConvention: Matches the resolver response. + expires_at_unix_secs: 4102444800, + }, + ], + items: [ + { + kind: "presigned", + // biome-ignore lint/style/useNamingConvention: Matches the resolver response. + source_index: 0, + offset: 0, + size: Number(size), + }, + ], + }), + ); + return; + } + if (url.startsWith("/object")) { + state.objectCalls++; + const range = req.headers.range ?? ""; + const match = /^bytes=(\d+)-(\d+)$/.exec(range); + if (match === null) { + res.writeHead(416).end(); + return; + } + const start = Number(match[1]); + const end = Number(match[2]); + const body = payload.subarray(start, end + 1); + res.writeHead(206, { + "content-range": `bytes ${start}-${end}/${size}`, + "content-length": body.length, + "x-lancedb-version": "46", + "x-lancedb-query-snapshot": IDENTITY, + connection: "close", + }); + res.end(body); + return; + } + if (url.startsWith("/v1/table/test/blob/image/0/bytes")) { + state.proxyCalls++; + const range = req.headers.range ?? ""; + const match = /^bytes=(\d+)-(\d+)$/.exec(range); + if (match === null) { + res.writeHead(416).end(); + return; + } + const start = Number(match[1]); + const end = Number(match[2]); + const body = payload.subarray(start, end + 1); + res.writeHead(206, { + "content-range": `bytes ${start}-${end}/${size}`, + "content-length": body.length, + "x-lancedb-version": "46", + "x-lancedb-query-snapshot": IDENTITY, + connection: "close", + }); + res.end(body); + return; + } + res.writeHead(404).end(`unexpected request: ${req.method} ${url}`); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + port = (server.address() as AddressInfo).port; + const db = await connect("db://dev", { + apiKey: "fake", + hostOverride: `http://127.0.0.1:${port}`, + clientConfig: { timeoutConfig: { timeout: 10 } }, + }); + const table = await db.openTable("test"); + try { + await run(db, table, state); + } finally { + await new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }); + } +} + +describe("openBlobFile", () => { + it("opens a large descriptor through the direct resolver and reads bytes", async () => { + await withOpenServer(async (_db, table, state) => { + const handle = (await table.openBlobFile(descriptor(10n * BigInt(MIB))))!; + expect(handle).not.toBeNull(); + // Below the per-read threshold the same handle stays on the proxy. + expect(await handle.readRange(0n, 4n)).toEqual(Buffer.alloc(4, 0x61)); + expect(state.proxyCalls).toBe(1); + expect(state.objectCalls).toBe(0); + const large = await handle.readRange(0n, 10n * BigInt(MIB)); + expect(large.length).toBe(10 * MIB); + expect(large.equals(Buffer.alloc(10 * MIB, 0x61))).toBe(true); + expect(state.blobLocationsCalls).toBe(1); + expect(state.objectCalls).toBe(1); + expect(state.proxyCalls).toBe(1); + expect(state.lastLocationBody).toMatchObject({ + version: 46, + // biome-ignore lint/style/useNamingConvention: Matches the resolver body. + row_ids: [0], + // biome-ignore lint/style/useNamingConvention: Matches the resolver body. + source_uri: "s3://fixture/table.lance", + // biome-ignore lint/style/useNamingConvention: Matches the resolver body. + source_commit_micros: 1795627189287568, + // biome-ignore lint/style/useNamingConvention: Matches the resolver body. + row_is_address: false, + }); + await handle.close(); + }); + }); + + it("falls back to the proxy when the resolver returns 503", async () => { + await withOpenServer(async (_db, table, state) => { + state.directStatus = 503; + const handle = (await table.openBlobFile(descriptor(10n * BigInt(MIB))))!; + expect(handle).not.toBeNull(); + const large = await handle.readRange(0n, 10n * BigInt(MIB)); + expect(large.length).toBe(10 * MIB); + expect(large.equals(Buffer.alloc(10 * MIB, 0x61))).toBe(true); + expect(state.blobLocationsCalls).toBe(1); + expect(state.objectCalls).toBe(0); + expect(state.proxyCalls).toBe(1); + await handle.close(); + }); + }); + + it("keeps descriptors below the direct threshold on the proxy path", async () => { + await withOpenServer(async (_db, table, state) => { + const handle = (await table.openBlobFile(descriptor(BigInt(MIB))))!; + expect(await handle.readRange(0n, 4n)).toEqual(Buffer.alloc(4, 0x61)); + expect(state.blobLocationsCalls).toBe(0); + expect(state.objectCalls).toBe(0); + expect(state.proxyCalls).toBe(1); + await handle.close(); + }, BigInt(MIB)); + }); + + it("preserves nulls and order in openBlobFiles", async () => { + await withOpenServer(async (_db, table, state) => { + const handles = []; + for await (const handle of table.openBlobFiles([ + null, + descriptor(10n * BigInt(MIB)), + null, + ])) { + handles.push(handle); + } + expect(handles[0]).toBeNull(); + expect(handles[1]).not.toBeNull(); + expect(handles[2]).toBeNull(); + expect(await handles[1]!.readRange(0n, 4n)).toEqual( + Buffer.alloc(4, 0x61), + ); + expect(state.blobLocationsCalls).toBe(1); + await handles[1]!.close(); + }); + }); +}); diff --git a/nodejs/lancedb/blob.ts b/nodejs/lancedb/blob.ts index be26f6121..0a67165b1 100644 --- a/nodejs/lancedb/blob.ts +++ b/nodejs/lancedb/blob.ts @@ -310,6 +310,80 @@ export class BlobFile { } } +/** + * A source-bearing Blob V2 descriptor returned by the SQL `blob_descriptor` + * function. Field names match the descriptor object/Arrow struct shape. + */ +export interface BlobDescriptorSource { + uri: string; + version: bigint | number; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + committed_at_micros: bigint | number; + branch?: string | null; + column: string; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + row_reference: bigint | number; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + row_is_address: boolean; +} + +/** + * A source-bearing Blob V2 descriptor accepted by {@link Table.openBlobFile}. + * Query results expose these fields as an Arrow struct. The source pins the + * table version, branch, column and row identity used to open the handle. + */ +export interface BlobDescriptor { + kind: number; + position: bigint | number; + size: bigint | number; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + blob_id: number; + // biome-ignore lint/style/useNamingConvention: Matches the SQL descriptor field. + blob_uri: string; + source: BlobDescriptorSource; +} + +function descriptorBigInt(value: bigint | number, field: string): bigint { + if (typeof value === "bigint") { + if (value < 0n) { + throw new TypeError(`blob descriptor ${field} cannot be negative`); + } + return value; + } + if (!Number.isSafeInteger(value) || value < 0) { + throw new TypeError( + `blob descriptor ${field} must be a non-negative safe integer or bigint`, + ); + } + return BigInt(value); +} + +/** @ignore */ +export function toNativeBlobDescriptor(descriptor: BlobDescriptor) { + return { + kind: descriptor.kind, + position: descriptorBigInt(descriptor.position, "position"), + size: descriptorBigInt(descriptor.size, "size"), + blobId: descriptor.blob_id, + blobUri: descriptor.blob_uri, + source: { + uri: descriptor.source.uri, + version: descriptorBigInt(descriptor.source.version, "source.version"), + committedAtMicros: descriptorBigInt( + descriptor.source.committed_at_micros, + "source.committed_at_micros", + ), + branch: descriptor.source.branch ?? undefined, + column: descriptor.source.column, + rowReference: descriptorBigInt( + descriptor.source.row_reference, + "source.row_reference", + ), + rowIsAddress: descriptor.source.row_is_address, + }, + }; +} + /** Options for blob reads. */ export type BlobReadOptions = { /** diff --git a/nodejs/lancedb/index.ts b/nodejs/lancedb/index.ts index 88f1bd921..58e1f0cde 100644 --- a/nodejs/lancedb/index.ts +++ b/nodejs/lancedb/index.ts @@ -93,6 +93,7 @@ export { } from "./arrow"; export { blob, isBlobField, BlobFile } from "./blob"; +export type { BlobDescriptor, BlobDescriptorSource } from "./blob"; export type { BlobData, BlobInput, diff --git a/nodejs/lancedb/table.ts b/nodejs/lancedb/table.ts index a599bac2b..1bbcb4ac5 100644 --- a/nodejs/lancedb/table.ts +++ b/nodejs/lancedb/table.ts @@ -35,10 +35,12 @@ import { } from "./arrow"; import { + BlobDescriptor, BlobFile, BlobRangeRequest, BlobReadOptions, runWithSignal, + toNativeBlobDescriptor, } from "./blob"; import { EmbeddingFunctionConfig, getRegistry } from "./embedding/registry"; import { @@ -871,6 +873,48 @@ export abstract class Table { options?: BlobReadOptions, ): Promise<(BlobFile | null)[]>; + /** + * Opens a lazy handle from a source-bearing SQL `blob_descriptor` result. + * + * The descriptor's source pins the table version, branch, column and row + * identity, so opening does not change this table's checkout. Null + * descriptors return `null`. Payload bytes load only when the returned + * handle is read. Pass {@link BlobReadOptions.signal} to cancel the open. + * + * @example + * ```ts + * const rows = await table + * .query() + * .select({ video: "blob_descriptor(video)" }) + * .toArray(); + * const handle = await table.openBlobFile(rows[0].video); + * if (handle) { + * const header = await handle.readRange(0n, 16n); + * await handle.close(); + * } + * ``` + */ + async openBlobFile( + _descriptor: BlobDescriptor | null, + _options?: BlobReadOptions, + ): Promise { + throw new Error("openBlobFile is not supported on this table type"); + } + + /** + * Opens source-bearing descriptors in iteration order, preserving nulls. + * Handles open lazily as the iterable advances. Close each non-null handle + * after use. + */ + async *openBlobFiles( + descriptors: Iterable, + options?: BlobReadOptions, + ): AsyncGenerator { + for (const descriptor of descriptors) { + yield await this.openBlobFile(descriptor, options); + } + } + /** * Create a search query to find the nearest neighbors * of the given query @@ -1936,6 +1980,19 @@ export class LocalTable extends Table { ); } + async openBlobFile( + descriptor: BlobDescriptor | null, + options?: BlobReadOptions, + ): Promise { + if (descriptor == null) { + return null; + } + const file = await runWithSignal(options?.signal, (signal) => + this.inner.openBlobFile(toNativeBlobDescriptor(descriptor), signal), + ); + return BlobFile.fromNative(file); + } + query(): Query { return new Query(this.inner); } diff --git a/nodejs/src/blob.rs b/nodejs/src/blob.rs index b55154019..c1bc50d09 100644 --- a/nodejs/src/blob.rs +++ b/nodejs/src/blob.rs @@ -8,13 +8,66 @@ use std::sync::atomic::{AtomicBool, Ordering}; use arrow_array::{Array, LargeBinaryArray}; use futures::future::abortable; -use lancedb::blob::BlobFile as LanceBlobFile; +use lancedb::blob::{ + BlobDescriptor as LanceBlobDescriptor, BlobDescriptorSource as LanceBlobDescriptorSource, + BlobFile as LanceBlobFile, +}; use napi::Env; use napi::bindgen_prelude::*; use napi_derive::napi; use crate::error::convert_error; +#[napi(object)] +pub struct BlobDescriptorInputSource { + pub uri: String, + pub version: BigInt, + pub committed_at_micros: BigInt, + pub branch: Option, + pub column: String, + pub row_reference: BigInt, + pub row_is_address: bool, +} + +#[napi(object)] +pub struct BlobDescriptorInput { + pub kind: u32, + pub position: BigInt, + pub size: BigInt, + pub blob_id: u32, + pub blob_uri: String, + pub source: BlobDescriptorInputSource, +} + +impl BlobDescriptorInput { + pub(crate) fn into_descriptor(self) -> napi::Result { + Ok(LanceBlobDescriptor { + kind: u8::try_from(self.kind).map_err(|_| { + napi::Error::from_reason("blob descriptor kind must be between 0 and 255") + })?, + position: parse_u64(self.position, "blob descriptor position")?, + size: parse_u64(self.size, "blob descriptor size")?, + blob_id: self.blob_id, + blob_uri: self.blob_uri, + source: LanceBlobDescriptorSource { + uri: self.source.uri, + version: parse_u64(self.source.version, "blob descriptor source version")?, + committed_at_micros: parse_u64( + self.source.committed_at_micros, + "blob descriptor source committed_at_micros", + )?, + branch: self.source.branch, + column: self.source.column, + row_reference: parse_u64( + self.source.row_reference, + "blob descriptor source row_reference", + )?, + row_is_address: self.source.row_is_address, + }, + }) + } +} + #[napi(object)] pub struct BlobRange { pub start: BigInt, @@ -202,7 +255,7 @@ fn bigint_range(start: BigInt, end: BigInt) -> napi::Result> { Ok(start..end) } -fn parse_u64(value: BigInt, name: &str) -> napi::Result { +pub(crate) fn parse_u64(value: BigInt, name: &str) -> napi::Result { let (negative, value, lossless) = value.get_u64(); if negative { return Err(napi::Error::from_reason(format!( diff --git a/nodejs/src/table.rs b/nodejs/src/table.rs index 098b7ce0b..536be3cd5 100644 --- a/nodejs/src/table.rs +++ b/nodejs/src/table.rs @@ -19,7 +19,10 @@ use napi::bindgen_prelude::*; use napi::threadsafe_function::{ThreadsafeFunction, ThreadsafeFunctionCallMode}; use napi_derive::napi; -use crate::blob::{BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, spawn_abortable}; +use crate::blob::{ + BlobDescriptorInput, BlobFile, BlobRangeRequest, copy_blob_buffers, parse_row_ids, + spawn_abortable, +}; use crate::error::{NapiErrorExt, convert_error}; use crate::index::Index; use crate::iterator::RecordBatchIterator; @@ -626,6 +629,21 @@ impl Table { }) } + #[napi(catch_unwind)] + pub fn open_blob_file<'env>( + &self, + env: &'env Env, + descriptor: BlobDescriptorInput, + signal: Option, + ) -> napi::Result> { + let descriptor = descriptor.into_descriptor()?; + let table = self.inner_ref()?.clone(); + spawn_abortable(env, signal, async move { + let file = table.open_blob_file(&descriptor).await.default_error()?; + Ok(BlobFile::new(file)) + }) + } + #[napi(catch_unwind)] pub fn vector_search(&self, vector: Float32Array) -> napi::Result { self.query()?.nearest_to(vector)