| 1 | // Copyright 2024 Lance Developers. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | import { describe } from 'mocha' |
| 16 | import { assert, expect, use as chaiUse } from 'chai' |
| 17 | import * as chaiAsPromised from 'chai-as-promised' |
| 18 | |
| 19 | import { convertToTable, fromTableToBuffer, makeArrowTable, makeEmptyTable } from '../arrow' |
| 20 | import { |
| 21 | Field, |
| 22 | FixedSizeList, |
| 23 | Float16, |
| 24 | Float32, |
| 25 | Int32, |
| 26 | tableFromIPC, |
| 27 | Schema, |
| 28 | Float64, |
| 29 | type Table, |
| 30 | Binary, |
| 31 | Bool, |
| 32 | Utf8, |
| 33 | Struct, |
| 34 | List, |
| 35 | DataType, |
| 36 | Dictionary, |
| 37 | Int64, |
| 38 | MetadataVersion |
| 39 | } from 'apache-arrow' |
| 40 | import { |
| 41 | Dictionary as OldDictionary, |
| 42 | Field as OldField, |
| 43 | FixedSizeList as OldFixedSizeList, |
| 44 | Float32 as OldFloat32, |
| 45 | Int32 as OldInt32, |
| 46 | Struct as OldStruct, |
| 47 | Schema as OldSchema, |
| 48 | TimestampNanosecond as OldTimestampNanosecond, |
| 49 | Utf8 as OldUtf8 |
| 50 | } from 'apache-arrow-old' |
| 51 | import { type EmbeddingFunction } from '../embedding/embedding_function' |
| 52 | |
| 53 | chaiUse(chaiAsPromised) |
| 54 | |
| 55 | function sampleRecords (): Array<Record<string, any>> { |
| 56 | return [ |
| 57 | { |
| 58 | binary: Buffer.alloc(5), |
| 59 | boolean: false, |
| 60 | number: 7, |
| 61 | string: 'hello', |
| 62 | struct: { x: 0, y: 0 }, |
| 63 | list: ['anime', 'action', 'comedy'] |
| 64 | } |
| 65 | ] |
| 66 | } |
| 67 | |
| 68 | // Helper method to verify various ways to create a table |
| 69 | async function checkTableCreation (tableCreationMethod: (records: any, recordsReversed: any, schema: Schema) => Promise<Table>): Promise<void> { |
| 70 | const records = sampleRecords() |
| 71 | const recordsReversed = [{ |
| 72 | list: ['anime', 'action', 'comedy'], |
| 73 | struct: { x: 0, y: 0 }, |
| 74 | string: 'hello', |
| 75 | number: 7, |
| 76 | boolean: false, |
| 77 | binary: Buffer.alloc(5) |
| 78 | }] |
| 79 | const schema = new Schema([ |
| 80 | new Field('binary', new Binary(), false), |
| 81 | new Field('boolean', new Bool(), false), |
| 82 | new Field('number', new Float64(), false), |
| 83 | new Field('string', new Utf8(), false), |
| 84 | new Field('struct', new Struct([ |
| 85 | new Field('x', new Float64(), false), |
| 86 | new Field('y', new Float64(), false) |
| 87 | ])), |
| 88 | new Field('list', new List(new Field('item', new Utf8(), false)), false) |
| 89 | ]) |
| 90 | |
| 91 | const table = await tableCreationMethod(records, recordsReversed, schema) |
| 92 | schema.fields.forEach((field, idx) => { |
| 93 | const actualField = table.schema.fields[idx] |
| 94 | assert.isFalse(actualField.nullable) |
| 95 | assert.equal(table.getChild(field.name)?.type.toString(), field.type.toString()) |
| 96 | assert.equal(table.getChildAt(idx)?.type.toString(), field.type.toString()) |
| 97 | }) |
| 98 | } |
| 99 | |
| 100 | describe('The function makeArrowTable', function () { |
| 101 | it('will use data types from a provided schema instead of inference', async function () { |
| 102 | const schema = new Schema([ |
| 103 | new Field('a', new Int32()), |
| 104 | new Field('b', new Float32()), |
| 105 | new Field('c', new FixedSizeList(3, new Field('item', new Float16()))), |
| 106 | new Field('d', new Int64()) |
| 107 | ]) |
| 108 | const table = makeArrowTable( |
| 109 | [ |
| 110 | { a: 1, b: 2, c: [1, 2, 3], d: 9 }, |
| 111 | { a: 4, b: 5, c: [4, 5, 6], d: 10 }, |
| 112 | { a: 7, b: 8, c: [7, 8, 9], d: null } |
| 113 | ], |
| 114 | { schema } |
| 115 | ) |
| 116 | |
| 117 | const buf = await fromTableToBuffer(table) |
| 118 | assert.isAbove(buf.byteLength, 0) |
| 119 | |
| 120 | const actual = tableFromIPC(buf) |
| 121 | assert.equal(actual.numRows, 3) |
| 122 | const actualSchema = actual.schema |
| 123 | assert.deepEqual(actualSchema, schema) |
| 124 | }) |
| 125 | |
| 126 | it('will assume the column `vector` is FixedSizeList<Float32> by default', async function () { |
| 127 | const schema = new Schema([ |
| 128 | new Field('a', new Float64()), |
| 129 | new Field('b', new Float64()), |
| 130 | new Field( |
| 131 | 'vector', |
| 132 | new FixedSizeList(3, new Field('item', new Float32(), true)) |
| 133 | ) |
| 134 | ]) |
| 135 | const table = makeArrowTable([ |
| 136 | { a: 1, b: 2, vector: [1, 2, 3] }, |
| 137 | { a: 4, b: 5, vector: [4, 5, 6] }, |
| 138 | { a: 7, b: 8, vector: [7, 8, 9] } |
| 139 | ]) |
| 140 | |
| 141 | const buf = await fromTableToBuffer(table) |
| 142 | assert.isAbove(buf.byteLength, 0) |
| 143 | |
| 144 | const actual = tableFromIPC(buf) |
| 145 | assert.equal(actual.numRows, 3) |
| 146 | const actualSchema = actual.schema |
| 147 | assert.deepEqual(actualSchema, schema) |
| 148 | }) |
| 149 | |
| 150 | it('can support multiple vector columns', async function () { |
| 151 | const schema = new Schema([ |
| 152 | new Field('a', new Float64()), |
| 153 | new Field('b', new Float64()), |
| 154 | new Field('vec1', new FixedSizeList(3, new Field('item', new Float16(), true))), |
| 155 | new Field('vec2', new FixedSizeList(3, new Field('item', new Float16(), true))) |
| 156 | ]) |
| 157 | const table = makeArrowTable( |
| 158 | [ |
| 159 | { a: 1, b: 2, vec1: [1, 2, 3], vec2: [2, 4, 6] }, |
| 160 | { a: 4, b: 5, vec1: [4, 5, 6], vec2: [8, 10, 12] }, |
| 161 | { a: 7, b: 8, vec1: [7, 8, 9], vec2: [14, 16, 18] } |
| 162 | ], |
| 163 | { |
| 164 | vectorColumns: { |
| 165 | vec1: { type: new Float16() }, |
| 166 | vec2: { type: new Float16() } |
| 167 | } |
| 168 | } |
| 169 | ) |
| 170 | |
| 171 | const buf = await fromTableToBuffer(table) |
| 172 | assert.isAbove(buf.byteLength, 0) |
| 173 | |
| 174 | const actual = tableFromIPC(buf) |
| 175 | assert.equal(actual.numRows, 3) |
| 176 | const actualSchema = actual.schema |
| 177 | assert.deepEqual(actualSchema, schema) |
| 178 | }) |
| 179 | |
| 180 | it('will allow different vector column types', async function () { |
| 181 | const table = makeArrowTable( |
| 182 | [ |
| 183 | { fp16: [1], fp32: [1], fp64: [1] } |
| 184 | ], |
| 185 | { |
| 186 | vectorColumns: { |
| 187 | fp16: { type: new Float16() }, |
| 188 | fp32: { type: new Float32() }, |
| 189 | fp64: { type: new Float64() } |
| 190 | } |
| 191 | } |
| 192 | ) |
| 193 | |
| 194 | assert.equal(table.getChild('fp16')?.type.children[0].type.toString(), new Float16().toString()) |
| 195 | assert.equal(table.getChild('fp32')?.type.children[0].type.toString(), new Float32().toString()) |
| 196 | assert.equal(table.getChild('fp64')?.type.children[0].type.toString(), new Float64().toString()) |
| 197 | }) |
| 198 | |
| 199 | it('will use dictionary encoded strings if asked', async function () { |
| 200 | const table = makeArrowTable([{ str: 'hello' }]) |
| 201 | assert.isTrue(DataType.isUtf8(table.getChild('str')?.type)) |
| 202 | |
| 203 | const tableWithDict = makeArrowTable([{ str: 'hello' }], { dictionaryEncodeStrings: true }) |
| 204 | assert.isTrue(DataType.isDictionary(tableWithDict.getChild('str')?.type)) |
| 205 | |
| 206 | const schema = new Schema([ |
| 207 | new Field('str', new Dictionary(new Utf8(), new Int32())) |
| 208 | ]) |
| 209 | |
| 210 | const tableWithDict2 = makeArrowTable([{ str: 'hello' }], { schema }) |
| 211 | assert.isTrue(DataType.isDictionary(tableWithDict2.getChild('str')?.type)) |
| 212 | }) |
| 213 | |
| 214 | it('will infer data types correctly', async function () { |
| 215 | await checkTableCreation(async (records) => makeArrowTable(records)) |
| 216 | }) |
| 217 | |
| 218 | it('will allow a schema to be provided', async function () { |
| 219 | await checkTableCreation(async (records, _, schema) => makeArrowTable(records, { schema })) |
| 220 | }) |
| 221 | |
| 222 | it('will use the field order of any provided schema', async function () { |
| 223 | await checkTableCreation(async (_, recordsReversed, schema) => makeArrowTable(recordsReversed, { schema })) |
| 224 | }) |
| 225 | |
| 226 | it('will make an empty table', async function () { |
| 227 | await checkTableCreation(async (_, __, schema) => makeArrowTable([], { schema })) |
| 228 | }) |
| 229 | }) |
| 230 | |
| 231 | class DummyEmbedding implements EmbeddingFunction<string> { |
| 232 | public readonly sourceColumn = 'string' |
| 233 | public readonly embeddingDimension = 2 |
| 234 | public readonly embeddingDataType = new Float16() |
| 235 | |
| 236 | async embed (data: string[]): Promise<number[][]> { |
| 237 | return data.map( |
| 238 | () => [0.0, 0.0] |
| 239 | ) |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | class DummyEmbeddingWithNoDimension implements EmbeddingFunction<string> { |
| 244 | public readonly sourceColumn = 'string' |
| 245 | |
| 246 | async embed (data: string[]): Promise<number[][]> { |
| 247 | return data.map( |
| 248 | () => [0.0, 0.0] |
| 249 | ) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | describe('convertToTable', function () { |
| 254 | it('will infer data types correctly', async function () { |
| 255 | await checkTableCreation(async (records) => await convertToTable(records)) |
| 256 | }) |
| 257 | |
| 258 | it('will allow a schema to be provided', async function () { |
| 259 | await checkTableCreation(async (records, _, schema) => await convertToTable(records, undefined, { schema })) |
| 260 | }) |
| 261 | |
| 262 | it('will use the field order of any provided schema', async function () { |
| 263 | await checkTableCreation(async (_, recordsReversed, schema) => await convertToTable(recordsReversed, undefined, { schema })) |
| 264 | }) |
| 265 | |
| 266 | it('will make an empty table', async function () { |
| 267 | await checkTableCreation(async (_, __, schema) => await convertToTable([], undefined, { schema })) |
| 268 | }) |
| 269 | |
| 270 | it('will apply embeddings', async function () { |
| 271 | const records = sampleRecords() |
| 272 | const table = await convertToTable(records, new DummyEmbedding()) |
| 273 | assert.isTrue(DataType.isFixedSizeList(table.getChild('vector')?.type)) |
| 274 | assert.equal(table.getChild('vector')?.type.children[0].type.toString(), new Float16().toString()) |
| 275 | }) |
| 276 | |
| 277 | it('will fail if missing the embedding source column', async function () { |
| 278 | return await expect(convertToTable([{ id: 1 }], new DummyEmbedding())).to.be.rejectedWith("'string' was not present") |
| 279 | }) |
| 280 | |
| 281 | it('use embeddingDimension if embedding missing from table', async function () { |
| 282 | const schema = new Schema([ |
| 283 | new Field('string', new Utf8(), false) |
| 284 | ]) |
| 285 | // Simulate getting an empty Arrow table (minus embedding) from some other source |
| 286 | // In other words, we aren't starting with records |
| 287 | const table = makeEmptyTable(schema) |
| 288 | |
| 289 | // If the embedding specifies the dimension we are fine |
| 290 | await fromTableToBuffer(table, new DummyEmbedding()) |
| 291 | |
| 292 | // We can also supply a schema and should be ok |
| 293 | const schemaWithEmbedding = new Schema([ |
| 294 | new Field('string', new Utf8(), false), |
| 295 | new Field('vector', new FixedSizeList(2, new Field('item', new Float16(), false)), false) |
| 296 | ]) |
| 297 | await fromTableToBuffer(table, new DummyEmbeddingWithNoDimension(), schemaWithEmbedding) |
| 298 | |
| 299 | // Otherwise we will get an error |
| 300 | return await expect(fromTableToBuffer(table, new DummyEmbeddingWithNoDimension())).to.be.rejectedWith('does not specify `embeddingDimension`') |
| 301 | }) |
| 302 | |
| 303 | it('will apply embeddings to an empty table', async function () { |
| 304 | const schema = new Schema([ |
| 305 | new Field('string', new Utf8(), false), |
| 306 | new Field('vector', new FixedSizeList(2, new Field('item', new Float16(), false)), false) |
| 307 | ]) |
| 308 | const table = await convertToTable([], new DummyEmbedding(), { schema }) |
| 309 | assert.isTrue(DataType.isFixedSizeList(table.getChild('vector')?.type)) |
| 310 | assert.equal(table.getChild('vector')?.type.children[0].type.toString(), new Float16().toString()) |
| 311 | }) |
| 312 | |
| 313 | it('will complain if embeddings present but schema missing embedding column', async function () { |
| 314 | const schema = new Schema([ |
| 315 | new Field('string', new Utf8(), false) |
| 316 | ]) |
| 317 | return await expect(convertToTable([], new DummyEmbedding(), { schema })).to.be.rejectedWith('column vector was missing') |
| 318 | }) |
| 319 | |
| 320 | it('will provide a nice error if run twice', async function () { |
| 321 | const records = sampleRecords() |
| 322 | const table = await convertToTable(records, new DummyEmbedding()) |
| 323 | // fromTableToBuffer will try and apply the embeddings again |
| 324 | return await expect(fromTableToBuffer(table, new DummyEmbedding())).to.be.rejectedWith('already existed') |
| 325 | }) |
| 326 | }) |
| 327 | |
| 328 | describe('makeEmptyTable', function () { |
| 329 | it('will make an empty table', async function () { |
| 330 | await checkTableCreation(async (_, __, schema) => makeEmptyTable(schema)) |
| 331 | }) |
| 332 | }) |
| 333 | |
| 334 | describe('when using two versions of arrow', function () { |
| 335 | it('can still import data', async function() { |
| 336 | const schema = new OldSchema([ |
| 337 | new OldField('id', new OldInt32()), |
| 338 | new OldField('vector', new OldFixedSizeList(1024, new OldField("item", new OldFloat32(), true))), |
| 339 | new OldField('struct', new OldStruct([ |
| 340 | new OldField('nested', new OldDictionary(new OldUtf8(), new OldInt32(), 1, true)), |
| 341 | new OldField('ts_with_tz', new OldTimestampNanosecond("some_tz")), |
| 342 | new OldField('ts_no_tz', new OldTimestampNanosecond(null)) |
| 343 | ])) |
| 344 | ]) as any |
| 345 | // We use arrow version 13 to emulate a "foreign arrow" and this version doesn't have metadataVersion |
| 346 | // In theory, this wouldn't matter. We don't rely on that property. However, it causes deepEqual to |
| 347 | // fail so we patch it back in |
| 348 | schema.metadataVersion = MetadataVersion.V5 |
| 349 | const table = makeArrowTable( |
| 350 | [], |
| 351 | { schema } |
| 352 | ) |
| 353 | |
| 354 | const buf = await fromTableToBuffer(table) |
| 355 | assert.isAbove(buf.byteLength, 0) |
| 356 | const actual = tableFromIPC(buf) |
| 357 | const actualSchema = actual.schema |
| 358 | assert.deepEqual(actualSchema, schema) |
| 359 | }) |
| 360 | }) |