mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
fix(node): preserve incoming Arrow schema on overwrite (#5276)
## Summary - Use the incoming Arrow schema and metadata for Arrow overwrite input, even if the previous table had automatic embeddings. - Preserve current schema conversion for append and row-object overwrite. - Resolve the incoming schema's embedding provider only when its vector column needs generation. Compute missing vectors across every Arrow batch. ## Validation - Native regression creates an embedding table, verifies that a row overwrite computes its vector, then replaces the table with a different Arrow schema and checks its metadata and stored row. The test fails on main when the SDK passes a null value to the previous embedding function. - Embedding Jest suite with the 0.42.0-beta.38 native binding: 15 passed, 1 skipped (requires an OpenAI key). TypeScript compilation with `--noEmit` and Biome checks passed. - Reopened two-batch imports preserve both precomputed vectors with no provider registered and generate vectors for both rows when inputs are missing. Both regressions failed before the follow-up. Across `embedding.test.ts` and `arrow.test.ts`, 511 passed and one OpenAI integration was skipped. TypeScript and Biome passed. Fixes https://github.com/lancedb/lancedb/issues/5275 --------- Co-authored-by: Divyam Talwar <DivyamTalwar@users.noreply.github.com> Co-authored-by: Divyam Talwar <194859478+DivyamTalwar@users.noreply.github.com>
This commit is contained in:
co-authored by
Divyam Talwar
Divyam Talwar
parent
3129573909
commit
0abc7d48be
@@ -13,9 +13,12 @@ import {
|
||||
Float64,
|
||||
Int32,
|
||||
Schema,
|
||||
Table,
|
||||
Utf8,
|
||||
fromDataToBuffer,
|
||||
makeArrowTable,
|
||||
tableFromIPC,
|
||||
tableToIPC,
|
||||
} from "../lancedb/arrow";
|
||||
import { EmbeddingFunction, LanceSchema } from "../lancedb/embedding";
|
||||
import { getRegistry, register } from "../lancedb/embedding/registry";
|
||||
@@ -139,6 +142,113 @@ describe("embedding functions", () => {
|
||||
expect(vectorsDefined).toEqual(new Array(5).fill(true));
|
||||
});
|
||||
|
||||
it("uses the incoming Arrow schema when overwriting an embedding table", async () => {
|
||||
@register("overwrite-schema")
|
||||
class TestEmbedding extends EmbeddingFunction<string> {
|
||||
ndims() {
|
||||
return 1;
|
||||
}
|
||||
embeddingDataType() {
|
||||
return new Float32();
|
||||
}
|
||||
async computeSourceEmbeddings(values: string[]) {
|
||||
return values.map((value) => [value.length]);
|
||||
}
|
||||
}
|
||||
|
||||
const db = await connect(tmpDir.name);
|
||||
const embedding = new TestEmbedding();
|
||||
const schema = LanceSchema({
|
||||
text: embedding.sourceField(new Utf8()),
|
||||
vector: embedding.vectorField(),
|
||||
});
|
||||
const table = await db.createTable("embeddings", [{ text: "old" }], {
|
||||
schema,
|
||||
});
|
||||
|
||||
await table.add([{ text: "new row" }], { mode: "overwrite" });
|
||||
const [embedded] = await table.query().toArray();
|
||||
expect([...embedded.vector]).toEqual([7]);
|
||||
expect((await table.schema()).metadata.has("embedding_functions")).toBe(
|
||||
true,
|
||||
);
|
||||
|
||||
const incoming = makeArrowTable([{ text: "fresh", vector: null }], {
|
||||
schema,
|
||||
});
|
||||
await table.add(incoming, { mode: "overwrite" });
|
||||
const reopened = await db.openTable("embeddings");
|
||||
const [fresh] = await reopened.query().toArray();
|
||||
expect(fresh.text).toBe("fresh");
|
||||
expect(fresh.vector?.toJSON()).toEqual([5]);
|
||||
|
||||
const replacementSchema = new Schema(
|
||||
[new Field("replacement", new Utf8(), true)],
|
||||
new Map([["schema-version", "v2"]]),
|
||||
);
|
||||
const replacement = makeArrowTable([{ replacement: "new schema" }], {
|
||||
schema: replacementSchema,
|
||||
});
|
||||
await table.add(replacement, { mode: "overwrite" });
|
||||
|
||||
expect(await table.schema()).toEqual(replacementSchema);
|
||||
const rows = await table.query().toArray();
|
||||
expect(rows.map((row) => row.toJSON())).toEqual([
|
||||
{ replacement: "new schema" },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(["populated", "missing"])(
|
||||
"overwrites from two Arrow IPC batches with %s vectors",
|
||||
async (vectors) => {
|
||||
class ProducerEmbedding extends EmbeddingFunction<string> {
|
||||
ndims() {
|
||||
return 2;
|
||||
}
|
||||
embeddingDataType() {
|
||||
return new Float32();
|
||||
}
|
||||
async computeSourceEmbeddings(values: string[]) {
|
||||
return values.map((value) => [value.length, value.length + 1]);
|
||||
}
|
||||
}
|
||||
if (vectors === "missing") {
|
||||
register()(ProducerEmbedding);
|
||||
}
|
||||
const embedding = new ProducerEmbedding();
|
||||
const schema = LanceSchema({
|
||||
text: embedding.sourceField(new Utf8()),
|
||||
vector: embedding.vectorField(),
|
||||
});
|
||||
const first = makeArrowTable(
|
||||
[{ text: "first", vector: vectors === "missing" ? null : [17, 18] }],
|
||||
{ schema },
|
||||
);
|
||||
const second = makeArrowTable(
|
||||
[{ text: "next", vector: vectors === "missing" ? null : [77, 78] }],
|
||||
{ schema },
|
||||
);
|
||||
const source = new Table(schema, [...first.batches, ...second.batches]);
|
||||
const incoming = tableFromIPC(tableToIPC(source, "file"));
|
||||
expect(incoming.batches).toHaveLength(2);
|
||||
|
||||
const db = await connect(tmpDir.name);
|
||||
const table = await db.createTable("arrow_import", [{ previous: true }]);
|
||||
await table.add(incoming, { mode: "overwrite" });
|
||||
const reopened = await db.openTable("arrow_import");
|
||||
expect((await reopened.schema()).metadata).toEqual(schema.metadata);
|
||||
const rows = await reopened.query().toArray();
|
||||
expect(rows).toHaveLength(2);
|
||||
expect(
|
||||
Object.fromEntries(rows.map((row) => [row.text, [...row.vector]])),
|
||||
).toEqual(
|
||||
vectors === "missing"
|
||||
? { first: [5, 6], next: [4, 5] }
|
||||
: { first: [17, 18], next: [77, 78] },
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("should be able to create an empty table with an embedding function", async () => {
|
||||
@register()
|
||||
class MockEmbeddingFunction extends EmbeddingFunction<string> {
|
||||
|
||||
+23
-28
@@ -1068,7 +1068,9 @@ async function applyEmbeddingsFromMetadata(
|
||||
schema: Schema,
|
||||
): Promise<ArrowTable> {
|
||||
const registry = getRegistry();
|
||||
const functions = await registry.parseFunctions(schema.metadata);
|
||||
const functions = parseEmbeddingMetadata(
|
||||
schema.metadata.get("embedding_functions")!,
|
||||
);
|
||||
|
||||
const columns = Object.fromEntries(
|
||||
table.schema.fields.map((field) => [
|
||||
@@ -1077,41 +1079,35 @@ async function applyEmbeddingsFromMetadata(
|
||||
]),
|
||||
);
|
||||
|
||||
for (const functionEntry of functions.values()) {
|
||||
const sourceColumn = columns[functionEntry.sourceColumn];
|
||||
const destColumn = functionEntry.vectorColumn;
|
||||
if (sourceColumn === undefined) {
|
||||
for (const { name, model, sourceColumn, vectorColumn } of functions) {
|
||||
const existingColumn = columns[vectorColumn];
|
||||
if (
|
||||
table.numRows === 0 ||
|
||||
(existingColumn && existingColumn.nullCount !== existingColumn.length)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const source = columns[sourceColumn];
|
||||
if (source === undefined) {
|
||||
throw new Error(
|
||||
`Cannot apply embedding function because the source column '${functionEntry.sourceColumn}' was not present in the data`,
|
||||
`Cannot apply embedding function because the source column '${sourceColumn}' was not present in the data`,
|
||||
);
|
||||
}
|
||||
|
||||
// Check if destination column exists and handle accordingly
|
||||
if (columns[destColumn] !== undefined) {
|
||||
const existingColumn = columns[destColumn];
|
||||
// If the column exists but is all null, we can fill it with embeddings
|
||||
if (existingColumn.nullCount !== existingColumn.length) {
|
||||
// Column has non-null values, skip embedding application
|
||||
continue;
|
||||
}
|
||||
const provider = registry.get(name);
|
||||
if (!provider) {
|
||||
throw new Error(`Function "${name}" not found in registry`);
|
||||
}
|
||||
|
||||
if (table.batches.length > 1) {
|
||||
throw new Error(
|
||||
"Internal error: `makeArrowTable` unexpectedly created a table with more than one batch",
|
||||
);
|
||||
}
|
||||
const values = sourceColumn.toArray();
|
||||
|
||||
const vectors =
|
||||
await functionEntry.function.computeSourceEmbeddings(values);
|
||||
const embedding = await provider.create(model);
|
||||
const values = source.toArray();
|
||||
const vectors = await embedding.computeSourceEmbeddings(values);
|
||||
if (vectors.length !== values.length) {
|
||||
throw new Error(
|
||||
"Embedding function did not return an embedding for each input element",
|
||||
);
|
||||
}
|
||||
let destType: DataType;
|
||||
const dtype = schema.fields.find((f) => f.name === destColumn)!.type;
|
||||
const dtype = schema.fields.find((f) => f.name === vectorColumn)!.type;
|
||||
if (isFixedSizeList(dtype)) {
|
||||
destType = sanitizeType(dtype);
|
||||
} else {
|
||||
@@ -1120,8 +1116,7 @@ async function applyEmbeddingsFromMetadata(
|
||||
dtype,
|
||||
);
|
||||
}
|
||||
const vector = makeVector(vectors, destType);
|
||||
columns[destColumn] = vector;
|
||||
columns[vectorColumn] = makeVector(vectors, destType);
|
||||
}
|
||||
|
||||
// Add any missing columns from the schema as null vectors
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
dataTypeToJson,
|
||||
fromDataToBuffer,
|
||||
fromTableToBuffer,
|
||||
isArrowTable,
|
||||
isMultiVector,
|
||||
makeEmptyTable,
|
||||
tableFromIPC,
|
||||
@@ -179,7 +180,7 @@ import {
|
||||
createAutoQuery,
|
||||
instanceOfFullTextQuery,
|
||||
} from "./query";
|
||||
import { sanitizeType } from "./sanitize";
|
||||
import { sanitizeSchema, sanitizeType } from "./sanitize";
|
||||
import { QueryParameters, toParameterBuffer } from "./sql";
|
||||
import { IntoSql, toSQL } from "./util";
|
||||
export { IndexConfig } from "./native";
|
||||
@@ -1842,7 +1843,10 @@ export class LocalTable extends Table {
|
||||
throw new Error("retries must be an integer between 0 and 255");
|
||||
}
|
||||
const mode = options?.mode ?? "append";
|
||||
const schema = await this.schema();
|
||||
const schema =
|
||||
mode === "overwrite" && isArrowTable(data)
|
||||
? sanitizeSchema(data.schema)
|
||||
: await this.schema();
|
||||
|
||||
const buffer = await fromDataToBuffer(data, undefined, schema);
|
||||
// Wrap the user callback so a thrown error doesn't surface as an
|
||||
|
||||
Reference in New Issue
Block a user