Elffuss BraidHub

kikocis/lancedb public

main · 18.2 KiBRawPermalink
1import { Schema } from "apache-arrow";
2// Copyright 2024 Lance Developers.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16import * as arrow13 from "apache-arrow-13";
17import * as arrow14 from "apache-arrow-14";
18import * as arrow15 from "apache-arrow-15";
19import * as arrow16 from "apache-arrow-16";
20import * as arrow17 from "apache-arrow-17";
21
22import {
23 convertToTable,
24 fromTableToBuffer,
25 makeArrowTable,
26 makeEmptyTable,
27} from "../lancedb/arrow";
28import {
29 EmbeddingFunction,
30 FieldOptions,
31 FunctionOptions,
32} from "../lancedb/embedding/embedding_function";
33import { EmbeddingFunctionConfig } from "../lancedb/embedding/registry";
34
35// biome-ignore lint/suspicious/noExplicitAny: skip
36function sampleRecords(): Array<Record<string, any>> {
37 return [
38 {
39 binary: Buffer.alloc(5),
40 boolean: false,
41 number: 7,
42 string: "hello",
43 struct: { x: 0, y: 0 },
44 list: ["anime", "action", "comedy"],
45 },
46 ];
47}
48describe.each([arrow13, arrow14, arrow15, arrow16, arrow17])(
49 "Arrow",
50 (
51 arrow:
52 | typeof arrow13
53 | typeof arrow14
54 | typeof arrow15
55 | typeof arrow16
56 | typeof arrow17,
57 ) => {
58 type ApacheArrow =
59 | typeof arrow13
60 | typeof arrow14
61 | typeof arrow15
62 | typeof arrow16
63 | typeof arrow17;
64 const {
65 Schema,
66 Field,
67 Binary,
68 Bool,
69 Utf8,
70 Float64,
71 Struct,
72 List,
73 Int32,
74 Int64,
75 Float,
76 Float16,
77 Float32,
78 FixedSizeList,
79 Precision,
80 tableFromIPC,
81 DataType,
82 Dictionary,
83 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
84 } = <any>arrow;
85 type Schema = ApacheArrow["Schema"];
86 type Table = ApacheArrow["Table"];
87
88 // Helper method to verify various ways to create a table
89 async function checkTableCreation(
90 tableCreationMethod: (
91 records: Record<string, unknown>[],
92 recordsReversed: Record<string, unknown>[],
93 schema: Schema,
94 ) => Promise<Table>,
95 infersTypes: boolean,
96 ): Promise<void> {
97 const records = sampleRecords();
98 const recordsReversed = [
99 {
100 list: ["anime", "action", "comedy"],
101 struct: { x: 0, y: 0 },
102 string: "hello",
103 number: 7,
104 boolean: false,
105 binary: Buffer.alloc(5),
106 },
107 ];
108 const schema = new Schema([
109 new Field("binary", new Binary(), false),
110 new Field("boolean", new Bool(), false),
111 new Field("number", new Float64(), false),
112 new Field("string", new Utf8(), false),
113 new Field(
114 "struct",
115 new Struct([
116 new Field("x", new Float64(), false),
117 new Field("y", new Float64(), false),
118 ]),
119 ),
120 new Field(
121 "list",
122 new List(new Field("item", new Utf8(), false)),
123 false,
124 ),
125 ]);
126
127 const table = (await tableCreationMethod(
128 records,
129 recordsReversed,
130 schema,
131 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
132 )) as any;
133 schema.fields.forEach(
134 (
135 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
136 field: { name: any; type: { toString: () => any } },
137 idx: string | number,
138 ) => {
139 const actualField = table.schema.fields[idx];
140 // Type inference always assumes nullable=true
141 if (infersTypes) {
142 expect(actualField.nullable).toBe(true);
143 } else {
144 expect(actualField.nullable).toBe(false);
145 }
146 expect(table.getChild(field.name)?.type.toString()).toEqual(
147 field.type.toString(),
148 );
149 expect(table.getChildAt(idx)?.type.toString()).toEqual(
150 field.type.toString(),
151 );
152 },
153 );
154 }
155
156 describe("The function makeArrowTable", function () {
157 it("will use data types from a provided schema instead of inference", async function () {
158 const schema = new Schema([
159 new Field("a", new Int32()),
160 new Field("b", new Float32()),
161 new Field(
162 "c",
163 new FixedSizeList(3, new Field("item", new Float16())),
164 ),
165 new Field("d", new Int64()),
166 ]);
167 const table = makeArrowTable(
168 [
169 { a: 1, b: 2, c: [1, 2, 3], d: 9 },
170 { a: 4, b: 5, c: [4, 5, 6], d: 10 },
171 { a: 7, b: 8, c: [7, 8, 9], d: null },
172 ],
173 { schema },
174 );
175
176 const buf = await fromTableToBuffer(table);
177 expect(buf.byteLength).toBeGreaterThan(0);
178
179 const actual = tableFromIPC(buf);
180 expect(actual.numRows).toBe(3);
181 const actualSchema = actual.schema;
182 expect(actualSchema).toEqual(schema);
183 });
184
185 it("will assume the column `vector` is FixedSizeList<Float32> by default", async function () {
186 const schema = new Schema([
187 new Field("a", new Float(Precision.DOUBLE), true),
188 new Field("b", new Float(Precision.DOUBLE), true),
189 new Field(
190 "vector",
191 new FixedSizeList(
192 3,
193 new Field("item", new Float(Precision.SINGLE), true),
194 ),
195 true,
196 ),
197 ]);
198 const table = makeArrowTable([
199 { a: 1, b: 2, vector: [1, 2, 3] },
200 { a: 4, b: 5, vector: [4, 5, 6] },
201 { a: 7, b: 8, vector: [7, 8, 9] },
202 ]);
203
204 const buf = await fromTableToBuffer(table);
205 expect(buf.byteLength).toBeGreaterThan(0);
206
207 const actual = tableFromIPC(buf);
208 expect(actual.numRows).toBe(3);
209 const actualSchema = actual.schema;
210 expect(actualSchema).toEqual(schema);
211 });
212
213 it("can support multiple vector columns", async function () {
214 const schema = new Schema([
215 new Field("a", new Float(Precision.DOUBLE), true),
216 new Field("b", new Float(Precision.DOUBLE), true),
217 new Field(
218 "vec1",
219 new FixedSizeList(3, new Field("item", new Float16(), true)),
220 true,
221 ),
222 new Field(
223 "vec2",
224 new FixedSizeList(3, new Field("item", new Float16(), true)),
225 true,
226 ),
227 ]);
228 const table = makeArrowTable(
229 [
230 { a: 1, b: 2, vec1: [1, 2, 3], vec2: [2, 4, 6] },
231 { a: 4, b: 5, vec1: [4, 5, 6], vec2: [8, 10, 12] },
232 { a: 7, b: 8, vec1: [7, 8, 9], vec2: [14, 16, 18] },
233 ],
234 {
235 vectorColumns: {
236 vec1: { type: new Float16() },
237 vec2: { type: new Float16() },
238 },
239 },
240 );
241
242 const buf = await fromTableToBuffer(table);
243 expect(buf.byteLength).toBeGreaterThan(0);
244
245 const actual = tableFromIPC(buf);
246 expect(actual.numRows).toBe(3);
247 const actualSchema = actual.schema;
248 expect(actualSchema).toEqual(schema);
249 });
250
251 it("will allow different vector column types", async function () {
252 const table = makeArrowTable([{ fp16: [1], fp32: [1], fp64: [1] }], {
253 vectorColumns: {
254 fp16: { type: new Float16() },
255 fp32: { type: new Float32() },
256 fp64: { type: new Float64() },
257 },
258 });
259
260 expect(
261 table.getChild("fp16")?.type.children[0].type.toString(),
262 ).toEqual(new Float16().toString());
263 expect(
264 table.getChild("fp32")?.type.children[0].type.toString(),
265 ).toEqual(new Float32().toString());
266 expect(
267 table.getChild("fp64")?.type.children[0].type.toString(),
268 ).toEqual(new Float64().toString());
269 });
270
271 it("will use dictionary encoded strings if asked", async function () {
272 const table = makeArrowTable([{ str: "hello" }]);
273 expect(DataType.isUtf8(table.getChild("str")?.type)).toBe(true);
274
275 const tableWithDict = makeArrowTable([{ str: "hello" }], {
276 dictionaryEncodeStrings: true,
277 });
278 expect(DataType.isDictionary(tableWithDict.getChild("str")?.type)).toBe(
279 true,
280 );
281
282 const schema = new Schema([
283 new Field("str", new Dictionary(new Utf8(), new Int32())),
284 ]);
285
286 const tableWithDict2 = makeArrowTable([{ str: "hello" }], { schema });
287 expect(
288 DataType.isDictionary(tableWithDict2.getChild("str")?.type),
289 ).toBe(true);
290 });
291
292 it("will infer data types correctly", async function () {
293 await checkTableCreation(
294 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
295 async (records) => (<any>makeArrowTable)(records),
296 true,
297 );
298 });
299
300 it("will allow a schema to be provided", async function () {
301 await checkTableCreation(
302 async (records, _, schema) =>
303 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
304 (<any>makeArrowTable)(records, { schema }),
305 false,
306 );
307 });
308
309 it("will use the field order of any provided schema", async function () {
310 await checkTableCreation(
311 async (_, recordsReversed, schema) =>
312 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
313 (<any>makeArrowTable)(recordsReversed, { schema }),
314 false,
315 );
316 });
317
318 it("will make an empty table", async function () {
319 await checkTableCreation(
320 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
321 async (_, __, schema) => (<any>makeArrowTable)([], { schema }),
322 false,
323 );
324 });
325 });
326
327 class DummyEmbedding extends EmbeddingFunction<string> {
328 toJSON(): Partial<FunctionOptions> {
329 return {};
330 }
331
332 async computeSourceEmbeddings(data: string[]): Promise<number[][]> {
333 return data.map(() => [0.0, 0.0]);
334 }
335
336 ndims(): number {
337 return 2;
338 }
339
340 embeddingDataType() {
341 return new Float16();
342 }
343 }
344
345 class DummyEmbeddingWithNoDimension extends EmbeddingFunction<string> {
346 toJSON(): Partial<FunctionOptions> {
347 return {};
348 }
349
350 embeddingDataType() {
351 return new Float16();
352 }
353
354 async computeSourceEmbeddings(data: string[]): Promise<number[][]> {
355 return data.map(() => [0.0, 0.0]);
356 }
357 }
358 const dummyEmbeddingConfig: EmbeddingFunctionConfig = {
359 sourceColumn: "string",
360 function: new DummyEmbedding(),
361 };
362
363 const dummyEmbeddingConfigWithNoDimension: EmbeddingFunctionConfig = {
364 sourceColumn: "string",
365 function: new DummyEmbeddingWithNoDimension(),
366 };
367
368 describe("convertToTable", function () {
369 it("will infer data types correctly", async function () {
370 await checkTableCreation(
371 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
372 async (records) => await (<any>convertToTable)(records),
373 true,
374 );
375 });
376
377 it("will allow a schema to be provided", async function () {
378 await checkTableCreation(
379 async (records, _, schema) =>
380 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
381 await (<any>convertToTable)(records, undefined, { schema }),
382 false,
383 );
384 });
385
386 it("will use the field order of any provided schema", async function () {
387 await checkTableCreation(
388 async (_, recordsReversed, schema) =>
389 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
390 await (<any>convertToTable)(recordsReversed, undefined, { schema }),
391 false,
392 );
393 });
394
395 it("will make an empty table", async function () {
396 await checkTableCreation(
397 async (_, __, schema) =>
398 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
399 await (<any>convertToTable)([], undefined, { schema }),
400 false,
401 );
402 });
403
404 it("will apply embeddings", async function () {
405 const records = sampleRecords();
406 const table = await convertToTable(records, dummyEmbeddingConfig);
407 expect(DataType.isFixedSizeList(table.getChild("vector")?.type)).toBe(
408 true,
409 );
410 expect(
411 table.getChild("vector")?.type.children[0].type.toString(),
412 ).toEqual(new Float16().toString());
413 });
414
415 it("will fail if missing the embedding source column", async function () {
416 await expect(
417 convertToTable([{ id: 1 }], dummyEmbeddingConfig),
418 ).rejects.toThrow("'string' was not present");
419 });
420
421 it("use embeddingDimension if embedding missing from table", async function () {
422 const schema = new Schema([new Field("string", new Utf8(), false)]);
423 // Simulate getting an empty Arrow table (minus embedding) from some other source
424 // In other words, we aren't starting with records
425 const table = makeEmptyTable(schema);
426
427 // If the embedding specifies the dimension we are fine
428 await fromTableToBuffer(table, dummyEmbeddingConfig);
429
430 // We can also supply a schema and should be ok
431 const schemaWithEmbedding = new Schema([
432 new Field("string", new Utf8(), false),
433 new Field(
434 "vector",
435 new FixedSizeList(2, new Field("item", new Float16(), false)),
436 false,
437 ),
438 ]);
439 await fromTableToBuffer(
440 table,
441 dummyEmbeddingConfigWithNoDimension,
442 schemaWithEmbedding,
443 );
444
445 // Otherwise we will get an error
446 await expect(
447 fromTableToBuffer(table, dummyEmbeddingConfigWithNoDimension),
448 ).rejects.toThrow("does not specify `embeddingDimension`");
449 });
450
451 it("will apply embeddings to an empty table", async function () {
452 const schema = new Schema([
453 new Field("string", new Utf8(), false),
454 new Field(
455 "vector",
456 new FixedSizeList(2, new Field("item", new Float16(), false)),
457 false,
458 ),
459 ]);
460 const table = await convertToTable([], dummyEmbeddingConfig, {
461 schema,
462 });
463 expect(DataType.isFixedSizeList(table.getChild("vector")?.type)).toBe(
464 true,
465 );
466 expect(
467 table.getChild("vector")?.type.children[0].type.toString(),
468 ).toEqual(new Float16().toString());
469 });
470
471 it("will complain if embeddings present but schema missing embedding column", async function () {
472 const schema = new Schema([new Field("string", new Utf8(), false)]);
473 await expect(
474 convertToTable([], dummyEmbeddingConfig, { schema }),
475 ).rejects.toThrow("column vector was missing");
476 });
477
478 it("will provide a nice error if run twice", async function () {
479 const records = sampleRecords();
480 const table = await convertToTable(records, dummyEmbeddingConfig);
481
482 // fromTableToBuffer will try and apply the embeddings again
483 await expect(
484 fromTableToBuffer(table, dummyEmbeddingConfig),
485 ).rejects.toThrow("already existed");
486 });
487 });
488
489 describe("makeEmptyTable", function () {
490 it("will make an empty table", async function () {
491 await checkTableCreation(
492 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
493 async (_, __, schema) => (<any>makeEmptyTable)(schema),
494 false,
495 );
496 });
497 });
498
499 describe("when using two versions of arrow", function () {
500 it("can still import data", async function () {
501 const schema = new arrow13.Schema([
502 new arrow13.Field("id", new arrow13.Int32()),
503 new arrow13.Field(
504 "vector",
505 new arrow13.FixedSizeList(
506 1024,
507 new arrow13.Field("item", new arrow13.Float32(), true),
508 ),
509 ),
510 new arrow13.Field(
511 "struct",
512 new arrow13.Struct([
513 new arrow13.Field(
514 "nested",
515 new arrow13.Dictionary(
516 new arrow13.Utf8(),
517 new arrow13.Int32(),
518 1,
519 true,
520 ),
521 ),
522 new arrow13.Field(
523 "ts_with_tz",
524 new arrow13.TimestampNanosecond("some_tz"),
525 ),
526 new arrow13.Field(
527 "ts_no_tz",
528 new arrow13.TimestampNanosecond(null),
529 ),
530 ]),
531 ),
532 // biome-ignore lint/suspicious/noExplicitAny: skip
533 ]) as any;
534 schema.metadataVersion = arrow13.MetadataVersion.V5;
535 const table = makeArrowTable([], { schema });
536
537 const buf = await fromTableToBuffer(table);
538 expect(buf.byteLength).toBeGreaterThan(0);
539 const actual = tableFromIPC(buf);
540 const actualSchema = actual.schema;
541 expect(actualSchema.fields.length).toBe(3);
542
543 // Deep equality gets hung up on some very minor unimportant differences
544 // between arrow version 13 and 15 which isn't really what we're testing for
545 // and so we do our own comparison that just checks name/type/nullability
546 function compareFields(lhs: arrow13.Field, rhs: arrow13.Field) {
547 expect(lhs.name).toEqual(rhs.name);
548 expect(lhs.nullable).toEqual(rhs.nullable);
549 expect(lhs.typeId).toEqual(rhs.typeId);
550 if ("children" in lhs.type && lhs.type.children !== null) {
551 const lhsChildren = lhs.type.children as arrow13.Field[];
552 lhsChildren.forEach((child: arrow13.Field, idx) => {
553 compareFields(child, rhs.type.children[idx]);
554 });
555 }
556 }
557 // biome-ignore lint/suspicious/noExplicitAny: <explanation>
558 actualSchema.fields.forEach((field: any, idx: string | number) => {
559 compareFields(field, actualSchema.fields[idx]);
560 });
561 });
562 });
563 },
564);