feat(nodejs): open source-bearing blob descriptors (#5238)

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.
This commit is contained in:
Xuanwo
2026-11-27 00:16:29 +08:00
committed by GitHub
parent 85dcf3a3c5
commit 1c0118015c
14 changed files with 692 additions and 36 deletions
+257
View File
@@ -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<string, unknown> | undefined;
},
) => Promise<void>,
size: bigint = 10n * BigInt(MIB),
) {
let port = 0;
const state = {
directStatus: 200,
blobLocationsCalls: 0,
objectCalls: 0,
proxyCalls: 0,
lastLocationBody: undefined as Record<string, unknown> | 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<string, unknown>;
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<void>((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<void>((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();
});
});
});
+74
View File
@@ -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 = {
/**
+1
View File
@@ -93,6 +93,7 @@ export {
} from "./arrow";
export { blob, isBlobField, BlobFile } from "./blob";
export type { BlobDescriptor, BlobDescriptorSource } from "./blob";
export type {
BlobData,
BlobInput,
+57
View File
@@ -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<BlobFile | null> {
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<BlobDescriptor | null>,
options?: BlobReadOptions,
): AsyncGenerator<BlobFile | null> {
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<BlobFile | null> {
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);
}
+55 -2
View File
@@ -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<String>,
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<LanceBlobDescriptor> {
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<Range<u64>> {
Ok(start..end)
}
fn parse_u64(value: BigInt, name: &str) -> napi::Result<u64> {
pub(crate) fn parse_u64(value: BigInt, name: &str) -> napi::Result<u64> {
let (negative, value, lossless) = value.get_u64();
if negative {
return Err(napi::Error::from_reason(format!(
+19 -1
View File
@@ -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<AbortSignal>,
) -> napi::Result<PromiseRaw<'env, BlobFile>> {
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<VectorQuery> {
self.query()?.nearest_to(vector)