-
Notifications
You must be signed in to change notification settings - Fork 20
/
collection_test.go
690 lines (624 loc) · 18 KB
/
collection_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
package chromem
import (
"context"
"errors"
"math/rand"
"os"
"slices"
"strconv"
"testing"
)
func TestCollection_Add(t *testing.T) {
ctx := context.Background()
name := "test"
metadata := map[string]string{"foo": "bar"}
vectors := []float32{-0.40824828, 0.40824828, 0.81649655} // normalized version of `{-0.1, 0.1, 0.2}`
embeddingFunc := func(_ context.Context, _ string) ([]float32, error) {
return vectors, nil
}
// Create collection
db := NewDB()
c, err := db.CreateCollection(name, metadata, embeddingFunc)
if err != nil {
t.Fatal("expected no error, got", err)
}
if c == nil {
t.Fatal("expected collection, got nil")
}
// Add documents
ids := []string{"1", "2"}
embeddings := [][]float32{vectors, vectors}
metadatas := []map[string]string{{"foo": "bar"}, {"a": "b"}}
contents := []string{"hello world", "hallo welt"}
tt := []struct {
name string
ids []string
embeddings [][]float32
metadatas []map[string]string
contents []string
}{
{
name: "No embeddings",
ids: ids,
embeddings: nil,
metadatas: metadatas,
contents: contents,
},
{
name: "With embeddings",
ids: ids,
embeddings: embeddings,
metadatas: metadatas,
contents: contents,
},
{
name: "With embeddings but no contents",
ids: ids,
embeddings: embeddings,
metadatas: metadatas,
contents: nil,
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
err = c.Add(ctx, ids, nil, metadatas, contents)
if err != nil {
t.Fatal("expected nil, got", err)
}
// Check documents
if len(c.documents) != 2 {
t.Fatal("expected 2, got", len(c.documents))
}
for i, id := range ids {
doc, ok := c.documents[id]
if !ok {
t.Fatal("expected document, got nil")
}
if doc.ID != id {
t.Fatal("expected", id, "got", doc.ID)
}
if len(doc.Metadata) != 1 {
t.Fatal("expected 1, got", len(doc.Metadata))
}
if !slices.Equal(doc.Embedding, vectors) {
t.Fatal("expected", vectors, "got", doc.Embedding)
}
if doc.Content != contents[i] {
t.Fatal("expected", contents[i], "got", doc.Content)
}
}
// Metadata can't be accessed with the loop's i
if c.documents[ids[0]].Metadata["foo"] != "bar" {
t.Fatal("expected bar, got", c.documents[ids[0]].Metadata["foo"])
}
if c.documents[ids[1]].Metadata["a"] != "b" {
t.Fatal("expected b, got", c.documents[ids[1]].Metadata["a"])
}
})
}
}
func TestCollection_Add_Error(t *testing.T) {
ctx := context.Background()
name := "test"
metadata := map[string]string{"foo": "bar"}
vectors := []float32{-0.40824828, 0.40824828, 0.81649655} // normalized version of `{-0.1, 0.1, 0.2}`
embeddingFunc := func(_ context.Context, _ string) ([]float32, error) {
return vectors, nil
}
// Create collection
db := NewDB()
c, err := db.CreateCollection(name, metadata, embeddingFunc)
if err != nil {
t.Fatal("expected no error, got", err)
}
if c == nil {
t.Fatal("expected collection, got nil")
}
// Add documents, provoking errors
ids := []string{"1", "2"}
embeddings := [][]float32{vectors, vectors}
metadatas := []map[string]string{{"foo": "bar"}, {"a": "b"}}
contents := []string{"hello world", "hallo welt"}
// Empty IDs
err = c.Add(ctx, []string{}, embeddings, metadatas, contents)
if err == nil {
t.Fatal("expected error, got nil")
}
// Empty embeddings and contents (both at the same time!)
err = c.Add(ctx, ids, [][]float32{}, metadatas, []string{})
if err == nil {
t.Fatal("expected error, got nil")
}
// Bad embeddings length
err = c.Add(ctx, ids, [][]float32{vectors}, metadatas, contents)
if err == nil {
t.Fatal("expected error, got nil")
}
// Bad metadatas length
err = c.Add(ctx, ids, embeddings, []map[string]string{{"foo": "bar"}}, contents)
if err == nil {
t.Fatal("expected error, got nil")
}
// Bad contents length
err = c.Add(ctx, ids, embeddings, metadatas, []string{"hello world"})
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestCollection_AddConcurrently(t *testing.T) {
ctx := context.Background()
name := "test"
metadata := map[string]string{"foo": "bar"}
vectors := []float32{-0.40824828, 0.40824828, 0.81649655} // normalized version of `{-0.1, 0.1, 0.2}`
embeddingFunc := func(_ context.Context, _ string) ([]float32, error) {
return vectors, nil
}
// Create collection
db := NewDB()
c, err := db.CreateCollection(name, metadata, embeddingFunc)
if err != nil {
t.Fatal("expected no error, got", err)
}
if c == nil {
t.Fatal("expected collection, got nil")
}
// Add documents
ids := []string{"1", "2"}
embeddings := [][]float32{vectors, vectors}
metadatas := []map[string]string{{"foo": "bar"}, {"a": "b"}}
contents := []string{"hello world", "hallo welt"}
tt := []struct {
name string
ids []string
embeddings [][]float32
metadatas []map[string]string
contents []string
}{
{
name: "No embeddings",
ids: ids,
embeddings: nil,
metadatas: metadatas,
contents: contents,
},
{
name: "With embeddings",
ids: ids,
embeddings: embeddings,
metadatas: metadatas,
contents: contents,
},
{
name: "With embeddings but no contents",
ids: ids,
embeddings: embeddings,
metadatas: metadatas,
contents: nil,
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
err = c.AddConcurrently(ctx, ids, nil, metadatas, contents, 2)
if err != nil {
t.Fatal("expected nil, got", err)
}
// Check documents
if len(c.documents) != 2 {
t.Fatal("expected 2, got", len(c.documents))
}
for i, id := range ids {
doc, ok := c.documents[id]
if !ok {
t.Fatal("expected document, got nil")
}
if doc.ID != id {
t.Fatal("expected", id, "got", doc.ID)
}
if len(doc.Metadata) != 1 {
t.Fatal("expected 1, got", len(doc.Metadata))
}
if !slices.Equal(doc.Embedding, vectors) {
t.Fatal("expected", vectors, "got", doc.Embedding)
}
if doc.Content != contents[i] {
t.Fatal("expected", contents[i], "got", doc.Content)
}
}
// Metadata can't be accessed with the loop's i
if c.documents[ids[0]].Metadata["foo"] != "bar" {
t.Fatal("expected bar, got", c.documents[ids[0]].Metadata["foo"])
}
if c.documents[ids[1]].Metadata["a"] != "b" {
t.Fatal("expected b, got", c.documents[ids[1]].Metadata["a"])
}
})
}
}
func TestCollection_AddConcurrently_Error(t *testing.T) {
ctx := context.Background()
name := "test"
metadata := map[string]string{"foo": "bar"}
vectors := []float32{-0.40824828, 0.40824828, 0.81649655} // normalized version of `{-0.1, 0.1, 0.2}`
embeddingFunc := func(_ context.Context, _ string) ([]float32, error) {
return vectors, nil
}
// Create collection
db := NewDB()
c, err := db.CreateCollection(name, metadata, embeddingFunc)
if err != nil {
t.Fatal("expected no error, got", err)
}
if c == nil {
t.Fatal("expected collection, got nil")
}
// Add documents, provoking errors
ids := []string{"1", "2"}
embeddings := [][]float32{vectors, vectors}
metadatas := []map[string]string{{"foo": "bar"}, {"a": "b"}}
contents := []string{"hello world", "hallo welt"}
// Empty IDs
err = c.AddConcurrently(ctx, []string{}, embeddings, metadatas, contents, 2)
if err == nil {
t.Fatal("expected error, got nil")
}
// Empty embeddings and contents (both at the same time!)
err = c.AddConcurrently(ctx, ids, [][]float32{}, metadatas, []string{}, 2)
if err == nil {
t.Fatal("expected error, got nil")
}
// Bad embeddings length
err = c.AddConcurrently(ctx, ids, [][]float32{vectors}, metadatas, contents, 2)
if err == nil {
t.Fatal("expected error, got nil")
}
// Bad metadatas length
err = c.AddConcurrently(ctx, ids, embeddings, []map[string]string{{"foo": "bar"}}, contents, 2)
if err == nil {
t.Fatal("expected error, got nil")
}
// Bad contents length
err = c.AddConcurrently(ctx, ids, embeddings, metadatas, []string{"hello world"}, 2)
if err == nil {
t.Fatal("expected error, got nil")
}
// Bad concurrency
err = c.AddConcurrently(ctx, ids, embeddings, metadatas, contents, 0)
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestCollection_QueryError(t *testing.T) {
// Create collection
db := NewDB()
name := "test"
metadata := map[string]string{"foo": "bar"}
vectors := []float32{-0.40824828, 0.40824828, 0.81649655} // normalized version of `{-0.1, 0.1, 0.2}`
embeddingFunc := func(_ context.Context, _ string) ([]float32, error) {
return vectors, nil
}
c, err := db.CreateCollection(name, metadata, embeddingFunc)
if err != nil {
t.Fatal("expected no error, got", err)
}
if c == nil {
t.Fatal("expected collection, got nil")
}
// Add a document
err = c.AddDocument(context.Background(), Document{ID: "1", Content: "hello world"})
if err != nil {
t.Fatal("expected nil, got", err)
}
tt := []struct {
name string
query func() error
expErr string
}{
{
name: "Empty query",
query: func() error {
_, err := c.Query(context.Background(), "", 1, nil, nil)
return err
},
expErr: "queryText is empty",
},
{
name: "Negative limit",
query: func() error {
_, err := c.Query(context.Background(), "foo", -1, nil, nil)
return err
},
expErr: "nResults must be > 0",
},
{
name: "Zero limit",
query: func() error {
_, err := c.Query(context.Background(), "foo", 0, nil, nil)
return err
},
expErr: "nResults must be > 0",
},
{
name: "Limit greater than number of documents",
query: func() error {
_, err := c.Query(context.Background(), "foo", 2, nil, nil)
return err
},
expErr: "nResults must be <= the number of documents in the collection",
},
{
name: "Bad content filter",
query: func() error {
_, err := c.Query(context.Background(), "foo", 1, nil, map[string]string{"invalid": "foo"})
return err
},
expErr: "unsupported operator",
},
}
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
err := tc.query()
if err == nil {
t.Fatal("expected error, got nil")
} else if err.Error() != tc.expErr {
t.Fatal("expected", tc.expErr, "got", err)
}
})
}
}
func TestCollection_Get(t *testing.T) {
ctx := context.Background()
// Create collection
db := NewDB()
name := "test"
metadata := map[string]string{"foo": "bar"}
vectors := []float32{-0.40824828, 0.40824828, 0.81649655} // normalized version of `{-0.1, 0.1, 0.2}`
embeddingFunc := func(_ context.Context, _ string) ([]float32, error) {
return vectors, nil
}
c, err := db.CreateCollection(name, metadata, embeddingFunc)
if err != nil {
t.Fatal("expected no error, got", err)
}
if c == nil {
t.Fatal("expected collection, got nil")
}
// Add documents
ids := []string{"1", "2"}
metadatas := []map[string]string{{"foo": "bar"}, {"a": "b"}}
contents := []string{"hello world", "hallo welt"}
err = c.Add(context.Background(), ids, nil, metadatas, contents)
if err != nil {
t.Fatal("expected nil, got", err)
}
// Get by ID
doc, err := c.GetByID(ctx, ids[0])
if err != nil {
t.Fatal("expected nil, got", err)
}
// Check fields
if doc.ID != ids[0] {
t.Fatal("expected", ids[0], "got", doc.ID)
}
if len(doc.Metadata) != 1 {
t.Fatal("expected 1, got", len(doc.Metadata))
}
if !slices.Equal(doc.Embedding, vectors) {
t.Fatal("expected", vectors, "got", doc.Embedding)
}
if doc.Content != contents[0] {
t.Fatal("expected", contents[0], "got", doc.Content)
}
// Check error
_, err = c.GetByID(ctx, "3")
if err == nil {
t.Fatal("expected error, got nil")
}
}
func TestCollection_Count(t *testing.T) {
// Create collection
db := NewDB()
name := "test"
metadata := map[string]string{"foo": "bar"}
vectors := []float32{-0.40824828, 0.40824828, 0.81649655} // normalized version of `{-0.1, 0.1, 0.2}`
embeddingFunc := func(_ context.Context, _ string) ([]float32, error) {
return vectors, nil
}
c, err := db.CreateCollection(name, metadata, embeddingFunc)
if err != nil {
t.Fatal("expected no error, got", err)
}
if c == nil {
t.Fatal("expected collection, got nil")
}
// Add documents
ids := []string{"1", "2"}
metadatas := []map[string]string{{"foo": "bar"}, {"a": "b"}}
contents := []string{"hello world", "hallo welt"}
err = c.Add(context.Background(), ids, nil, metadatas, contents)
if err != nil {
t.Fatal("expected nil, got", err)
}
// Check count
if c.Count() != 2 {
t.Fatal("expected 2, got", c.Count())
}
}
func TestCollection_Delete(t *testing.T) {
// Create persistent collection
tmpdir, err := os.MkdirTemp(os.TempDir(), "chromem-test-*")
if err != nil {
t.Fatal("expected no error, got", err)
}
db, err := NewPersistentDB(tmpdir, false)
if err != nil {
t.Fatal("expected no error, got", err)
}
name := "test"
metadata := map[string]string{"foo": "bar"}
vectors := []float32{-0.40824828, 0.40824828, 0.81649655} // normalized version of `{-0.1, 0.1, 0.2}`
embeddingFunc := func(_ context.Context, _ string) ([]float32, error) {
return vectors, nil
}
c, err := db.CreateCollection(name, metadata, embeddingFunc)
if err != nil {
t.Fatal("expected no error, got", err)
}
if c == nil {
t.Fatal("expected collection, got nil")
}
// Add documents
ids := []string{"1", "2", "3", "4"}
metadatas := []map[string]string{{"foo": "bar"}, {"a": "b"}, {"foo": "bar"}, {"e": "f"}}
contents := []string{"hello world", "hallo welt", "bonjour le monde", "hola mundo"}
err = c.Add(context.Background(), ids, nil, metadatas, contents)
if err != nil {
t.Fatal("expected nil, got", err)
}
// Check count
if c.Count() != 4 {
t.Fatal("expected 4 documents, got", c.Count())
}
// Check number of files in the persist directory
d, err := os.ReadDir(c.persistDirectory)
if err != nil {
t.Fatal("expected nil, got", err)
}
if len(d) != 5 { // 4 documents + 1 metadata file
t.Fatal("expected 4 document files + 1 metadata file in persist_dir, got", len(d))
}
checkCount := func(expected int) {
// Check count
if c.Count() != expected {
t.Fatalf("expected %d documents, got %d", expected, c.Count())
}
// Check number of files in the persist directory
d, err = os.ReadDir(c.persistDirectory)
if err != nil {
t.Fatal("expected nil, got", err)
}
if len(d) != expected+1 { // 3 document + 1 metadata file
t.Fatalf("expected %d document files + 1 metadata file in persist_dir, got %d", expected, len(d))
}
}
// Test 1 - Remove document by ID: should delete one document
err = c.Delete(context.Background(), nil, nil, "4")
if err != nil {
t.Fatal("expected nil, got", err)
}
checkCount(3)
// Test 2 - Remove document by metadata
err = c.Delete(context.Background(), map[string]string{"foo": "bar"}, nil)
if err != nil {
t.Fatal("expected nil, got", err)
}
checkCount(1)
// Test 3 - Remove document by content
err = c.Delete(context.Background(), nil, map[string]string{"$contains": "hallo welt"})
if err != nil {
t.Fatal("expected nil, got", err)
}
checkCount(0)
}
// Global var for assignment in the benchmark to avoid compiler optimizations.
var globalRes []Result
func BenchmarkCollection_Query_NoContent_100(b *testing.B) {
benchmarkCollection_Query(b, 100, false)
}
func BenchmarkCollection_Query_NoContent_1000(b *testing.B) {
benchmarkCollection_Query(b, 1000, false)
}
func BenchmarkCollection_Query_NoContent_5000(b *testing.B) {
benchmarkCollection_Query(b, 5000, false)
}
func BenchmarkCollection_Query_NoContent_25000(b *testing.B) {
benchmarkCollection_Query(b, 25000, false)
}
func BenchmarkCollection_Query_NoContent_100000(b *testing.B) {
benchmarkCollection_Query(b, 100_000, false)
}
func BenchmarkCollection_Query_100(b *testing.B) {
benchmarkCollection_Query(b, 100, true)
}
func BenchmarkCollection_Query_1000(b *testing.B) {
benchmarkCollection_Query(b, 1000, true)
}
func BenchmarkCollection_Query_5000(b *testing.B) {
benchmarkCollection_Query(b, 5000, true)
}
func BenchmarkCollection_Query_25000(b *testing.B) {
benchmarkCollection_Query(b, 25000, true)
}
func BenchmarkCollection_Query_100000(b *testing.B) {
benchmarkCollection_Query(b, 100_000, true)
}
// n is number of documents in the collection
func benchmarkCollection_Query(b *testing.B, n int, withContent bool) {
ctx := context.Background()
// Seed to make deterministic
r := rand.New(rand.NewSource(42))
d := 1536 // dimensions, same as text-embedding-3-small
// Random query vector
qv := make([]float32, d)
for j := 0; j < d; j++ {
qv[j] = r.Float32()
}
// The document embeddings are normalized, so the query must be normalized too.
qv = normalizeVector(qv)
// Create collection
db := NewDB()
name := "test"
embeddingFunc := func(_ context.Context, text string) ([]float32, error) {
return nil, errors.New("embedding func not expected to be called")
}
c, err := db.CreateCollection(name, nil, embeddingFunc)
if err != nil {
b.Fatal("expected no error, got", err)
}
if c == nil {
b.Fatal("expected collection, got nil")
}
// Add documents
for i := 0; i < n; i++ {
// Random embedding
v := make([]float32, d)
for j := 0; j < d; j++ {
v[j] = r.Float32()
}
v = normalizeVector(v)
// Add document with some metadata and content depending on parameter.
// When providing embeddings, the embedding func is not called.
is := strconv.Itoa(i)
doc := Document{
ID: is,
Metadata: map[string]string{"i": is, "foo": "bar" + is},
Embedding: v,
}
if withContent {
// Let's say we embed 500 tokens, that's ~375 words, ~1875 characters
doc.Content = randomString(r, 1875)
}
if err := c.AddDocument(ctx, doc); err != nil {
b.Fatal("expected nil, got", err)
}
}
b.ResetTimer()
// Query
var res []Result
for i := 0; i < b.N; i++ {
res, err = c.QueryEmbedding(ctx, qv, 10, nil, nil)
}
if err != nil {
b.Fatal("expected nil, got", err)
}
globalRes = res
}
// randomString returns a random string of length n using lowercase letters and space.
func randomString(r *rand.Rand, n int) string {
// We add 5 spaces to get roughly one space every 5 characters
characters := []rune("abcdefghijklmnopqrstuvwxyz ")
b := make([]rune, n)
for i := range b {
b[i] = characters[r.Intn(len(characters))]
}
return string(b)
}