This repository was archived by the owner on May 15, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathqdrant-client.spec.ts
More file actions
1861 lines (1660 loc) · 59.7 KB
/
Copy pathqdrant-client.spec.ts
File metadata and controls
1861 lines (1660 loc) · 59.7 KB
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { QdrantClient } from "@qdrant/js-client-rest"
import { createHash } from "crypto"
import { QdrantVectorStore } from "../qdrant-client"
import { getWorkspacePath } from "../../../../utils/path"
import { DEFAULT_MAX_SEARCH_RESULTS, DEFAULT_SEARCH_MIN_SCORE } from "../../constants"
// Mocks
vitest.mock("@qdrant/js-client-rest")
vitest.mock("crypto")
vitest.mock("../../../../utils/path")
vitest.mock("../../../../i18n", () => ({
t: (key: string, params?: any) => {
// Mock translation function that includes parameters for testing
if (key === "embeddings:vectorStore.vectorDimensionMismatch" && params?.errorMessage) {
return `Failed to update vector index for new model. Please try clearing the index and starting again. Details: ${params.errorMessage}`
}
if (key === "embeddings:vectorStore.qdrantConnectionFailed" && params?.qdrantUrl && params?.errorMessage) {
return `Failed to connect to Qdrant vector database. Please ensure Qdrant is running and accessible at ${params.qdrantUrl}. Error: ${params.errorMessage}`
}
return key // Just return the key for other cases
},
}))
vitest.mock("path", async () => {
const actual = await vitest.importActual("path")
return {
...actual,
sep: "/",
posix: actual.posix,
}
})
const mockQdrantClientInstance = {
getCollection: vitest.fn(),
createCollection: vitest.fn(),
deleteCollection: vitest.fn(),
createPayloadIndex: vitest.fn(),
updateCollectionAliases: vitest.fn(),
upsert: vitest.fn(),
query: vitest.fn(),
delete: vitest.fn(),
}
const mockCreateHashInstance = {
update: vitest.fn().mockReturnThis(),
digest: vitest.fn(),
}
describe("QdrantVectorStore", () => {
let vectorStore: QdrantVectorStore
const mockWorkspacePath = "/test/workspace"
const mockQdrantUrl = "http://mock-qdrant:6333"
const mockApiKey = "test-api-key"
const mockVectorSize = 1536
const mockHashedPath = "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6" // Needs to be long enough
const expectedCollectionName = `ws-${mockHashedPath.substring(0, 16)}`
beforeEach(() => {
vitest.clearAllMocks()
// Mock QdrantClient constructor
;(QdrantClient as any).mockImplementation(() => mockQdrantClientInstance)
// Mock crypto.createHash
;(createHash as any).mockReturnValue(mockCreateHashInstance)
mockCreateHashInstance.update.mockReturnValue(mockCreateHashInstance) // Ensure it returns 'this'
mockCreateHashInstance.digest.mockReturnValue(mockHashedPath)
// Mock getWorkspacePath
;(getWorkspacePath as any).mockReturnValue(mockWorkspacePath)
vectorStore = new QdrantVectorStore(mockWorkspacePath, mockQdrantUrl, mockVectorSize, mockApiKey)
})
it("should correctly initialize QdrantClient and collectionName in constructor", () => {
expect(QdrantClient).toHaveBeenCalledTimes(1)
expect(QdrantClient).toHaveBeenCalledWith({
host: "mock-qdrant",
https: false,
port: 6333,
apiKey: mockApiKey,
headers: {
"User-Agent": "Roo-Code",
},
})
expect(createHash).toHaveBeenCalledWith("sha256")
expect(mockCreateHashInstance.update).toHaveBeenCalledWith(mockWorkspacePath)
expect(mockCreateHashInstance.digest).toHaveBeenCalledWith("hex")
// Access private member for testing constructor logic (not ideal, but necessary here)
expect((vectorStore as any).collectionName).toBe(expectedCollectionName)
expect((vectorStore as any).vectorSize).toBe(mockVectorSize)
})
it("should handle constructor with default URL when none provided", () => {
const vectorStoreWithDefaults = new QdrantVectorStore(mockWorkspacePath, undefined as any, mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "localhost",
https: false,
port: 6333,
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
})
it("should handle constructor without API key", () => {
const vectorStoreWithoutKey = new QdrantVectorStore(mockWorkspacePath, mockQdrantUrl, mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "mock-qdrant",
https: false,
port: 6333,
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
})
describe("URL Parsing and Explicit Port Handling", () => {
describe("HTTPS URL handling", () => {
it("should use explicit port 443 for HTTPS URLs without port (fixes the main bug)", () => {
const vectorStore = new QdrantVectorStore(
mockWorkspacePath,
"https://qdrant.ashbyfam.com",
mockVectorSize,
)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "qdrant.ashbyfam.com",
https: true,
port: 443,
prefix: undefined, // No prefix for root path
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("https://qdrant.ashbyfam.com")
})
it("should use explicit port for HTTPS URLs with explicit port", () => {
const vectorStore = new QdrantVectorStore(mockWorkspacePath, "https://example.com:9000", mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "example.com",
https: true,
port: 9000,
prefix: undefined, // No prefix for root path
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("https://example.com:9000")
})
it("should use port 443 for HTTPS URLs with paths and query parameters", () => {
const vectorStore = new QdrantVectorStore(
mockWorkspacePath,
"https://example.com/api/v1?key=value",
mockVectorSize,
)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "example.com",
https: true,
port: 443,
prefix: "/api/v1", // Should have prefix
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("https://example.com/api/v1?key=value")
})
})
describe("HTTP URL handling", () => {
it("should use explicit port 80 for HTTP URLs without port", () => {
const vectorStore = new QdrantVectorStore(mockWorkspacePath, "http://example.com", mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "example.com",
https: false,
port: 80,
prefix: undefined, // No prefix for root path
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("http://example.com")
})
it("should use explicit port for HTTP URLs with explicit port", () => {
const vectorStore = new QdrantVectorStore(mockWorkspacePath, "http://localhost:8080", mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "localhost",
https: false,
port: 8080,
prefix: undefined, // No prefix for root path
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("http://localhost:8080")
})
it("should use port 80 for HTTP URLs while preserving paths and query parameters", () => {
const vectorStore = new QdrantVectorStore(
mockWorkspacePath,
"http://example.com/api/v1?key=value",
mockVectorSize,
)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "example.com",
https: false,
port: 80,
prefix: "/api/v1", // Should have prefix
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("http://example.com/api/v1?key=value")
})
})
describe("Hostname handling", () => {
it("should convert hostname to http with port 80", () => {
const vectorStore = new QdrantVectorStore(mockWorkspacePath, "qdrant.example.com", mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "qdrant.example.com",
https: false,
port: 80,
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("http://qdrant.example.com")
})
it("should handle hostname:port format with explicit port", () => {
const vectorStore = new QdrantVectorStore(mockWorkspacePath, "localhost:6333", mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "localhost",
https: false,
port: 6333,
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("http://localhost:6333")
})
it("should handle explicit HTTP URLs correctly", () => {
const vectorStore = new QdrantVectorStore(mockWorkspacePath, "http://localhost:9000", mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "localhost",
https: false,
port: 9000,
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("http://localhost:9000")
})
})
describe("IP address handling", () => {
it("should convert IP address to http with port 80", () => {
const vectorStore = new QdrantVectorStore(mockWorkspacePath, "192.168.1.100", mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "192.168.1.100",
https: false,
port: 80,
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("http://192.168.1.100")
})
it("should handle IP:port format with explicit port", () => {
const vectorStore = new QdrantVectorStore(mockWorkspacePath, "192.168.1.100:6333", mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "192.168.1.100",
https: false,
port: 6333,
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("http://192.168.1.100:6333")
})
})
describe("Edge cases", () => {
it("should handle undefined URL with host-based config", () => {
const vectorStore = new QdrantVectorStore(mockWorkspacePath, undefined as any, mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "localhost",
https: false,
port: 6333,
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("http://localhost:6333")
})
it("should handle empty string URL with host-based config", () => {
const vectorStore = new QdrantVectorStore(mockWorkspacePath, "", mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "localhost",
https: false,
port: 6333,
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("http://localhost:6333")
})
it("should handle whitespace-only URL with host-based config", () => {
const vectorStore = new QdrantVectorStore(mockWorkspacePath, " ", mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "localhost",
https: false,
port: 6333,
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("http://localhost:6333")
})
})
describe("Invalid URL fallback", () => {
it("should treat invalid URLs as hostnames with port 80", () => {
const vectorStore = new QdrantVectorStore(mockWorkspacePath, "invalid-url-format", mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "invalid-url-format",
https: false,
port: 80,
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStore as any).qdrantUrl).toBe("http://invalid-url-format")
})
})
})
describe("URL Prefix Handling", () => {
it("should pass the URL pathname as prefix to QdrantClient if not root", () => {
const vectorStoreWithPrefix = new QdrantVectorStore(
mockWorkspacePath,
"http://localhost:6333/some/path",
mockVectorSize,
)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "localhost",
https: false,
port: 6333,
prefix: "/some/path",
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStoreWithPrefix as any).qdrantUrl).toBe("http://localhost:6333/some/path")
})
it("should not pass prefix if the URL pathname is root ('/')", () => {
const vectorStoreWithoutPrefix = new QdrantVectorStore(
mockWorkspacePath,
"http://localhost:6333/",
mockVectorSize,
)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "localhost",
https: false,
port: 6333,
prefix: undefined,
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStoreWithoutPrefix as any).qdrantUrl).toBe("http://localhost:6333/")
})
it("should handle HTTPS URL with path as prefix", () => {
const vectorStoreWithHttpsPrefix = new QdrantVectorStore(
mockWorkspacePath,
"https://qdrant.ashbyfam.com/api",
mockVectorSize,
)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "qdrant.ashbyfam.com",
https: true,
port: 443,
prefix: "/api",
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStoreWithHttpsPrefix as any).qdrantUrl).toBe("https://qdrant.ashbyfam.com/api")
})
it("should normalize URL pathname by removing trailing slash for prefix", () => {
const vectorStoreWithTrailingSlash = new QdrantVectorStore(
mockWorkspacePath,
"http://localhost:6333/api/",
mockVectorSize,
)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "localhost",
https: false,
port: 6333,
prefix: "/api", // Trailing slash should be removed
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStoreWithTrailingSlash as any).qdrantUrl).toBe("http://localhost:6333/api/")
})
it("should normalize URL pathname by removing multiple trailing slashes for prefix", () => {
const vectorStoreWithMultipleTrailingSlashes = new QdrantVectorStore(
mockWorkspacePath,
"http://localhost:6333/api///",
mockVectorSize,
)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "localhost",
https: false,
port: 6333,
prefix: "/api", // All trailing slashes should be removed
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStoreWithMultipleTrailingSlashes as any).qdrantUrl).toBe("http://localhost:6333/api///")
})
it("should handle multiple path segments correctly for prefix", () => {
const vectorStoreWithMultiSegment = new QdrantVectorStore(
mockWorkspacePath,
"http://localhost:6333/api/v1/qdrant",
mockVectorSize,
)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "localhost",
https: false,
port: 6333,
prefix: "/api/v1/qdrant",
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStoreWithMultiSegment as any).qdrantUrl).toBe("http://localhost:6333/api/v1/qdrant")
})
it("should handle complex URL with multiple segments, multiple trailing slashes, query params, and fragment", () => {
const complexUrl = "https://example.com/ollama/api/v1///?key=value#pos"
const vectorStoreComplex = new QdrantVectorStore(mockWorkspacePath, complexUrl, mockVectorSize)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "example.com",
https: true,
port: 443,
prefix: "/ollama/api/v1", // Trailing slash removed, query/fragment ignored
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStoreComplex as any).qdrantUrl).toBe(complexUrl)
})
it("should ignore query parameters and fragments when determining prefix", () => {
const vectorStoreWithQueryParams = new QdrantVectorStore(
mockWorkspacePath,
"http://localhost:6333/api/path?key=value#fragment",
mockVectorSize,
)
expect(QdrantClient).toHaveBeenLastCalledWith({
host: "localhost",
https: false,
port: 6333,
prefix: "/api/path", // Query params and fragment should be ignored
apiKey: undefined,
headers: {
"User-Agent": "Roo-Code",
},
})
expect((vectorStoreWithQueryParams as any).qdrantUrl).toBe(
"http://localhost:6333/api/path?key=value#fragment",
)
})
})
describe("initialize", () => {
it("should create a new collection if none exists and return true", async () => {
// Mock getCollection to throw a 404-like error
mockQdrantClientInstance.getCollection.mockRejectedValue({
response: { status: 404 },
message: "Not found",
})
mockQdrantClientInstance.createCollection.mockResolvedValue(true as any) // Cast to any to satisfy QdrantClient types if strict
mockQdrantClientInstance.createPayloadIndex.mockResolvedValue({} as any) // Mock successful index creation
const result = await vectorStore.initialize()
expect(result).toBe(true)
expect(mockQdrantClientInstance.getCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.getCollection).toHaveBeenCalledWith(expectedCollectionName)
expect(mockQdrantClientInstance.createCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.createCollection).toHaveBeenCalledWith(expectedCollectionName, {
vectors: {
size: mockVectorSize,
distance: "Cosine", // Assuming 'Cosine' is the DISTANCE_METRIC
on_disk: true,
},
hnsw_config: {
m: 64,
ef_construct: 512,
on_disk: true,
},
})
expect(mockQdrantClientInstance.deleteCollection).not.toHaveBeenCalled()
// Verify payload index creation - 'type' field first, then pathSegments
expect(mockQdrantClientInstance.createPayloadIndex).toHaveBeenCalledWith(expectedCollectionName, {
field_name: "type",
field_schema: "keyword",
})
for (let i = 0; i <= 4; i++) {
expect(mockQdrantClientInstance.createPayloadIndex).toHaveBeenCalledWith(expectedCollectionName, {
field_name: `pathSegments.${i}`,
field_schema: "keyword",
})
}
expect(mockQdrantClientInstance.createPayloadIndex).toHaveBeenCalledTimes(6)
})
it("should not create a new collection if one exists with matching vectorSize and return false", async () => {
// Mock getCollection to return existing collection info with matching vector size
mockQdrantClientInstance.getCollection.mockResolvedValue({
config: {
params: {
vectors: {
size: mockVectorSize, // Matching vector size
},
},
},
} as any) // Cast to any to satisfy QdrantClient types
mockQdrantClientInstance.createPayloadIndex.mockResolvedValue({} as any)
const result = await vectorStore.initialize()
expect(result).toBe(false)
expect(mockQdrantClientInstance.getCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.getCollection).toHaveBeenCalledWith(expectedCollectionName)
expect(mockQdrantClientInstance.createCollection).not.toHaveBeenCalled()
expect(mockQdrantClientInstance.deleteCollection).not.toHaveBeenCalled()
// Verify payload index creation still happens - 'type' field first, then pathSegments
expect(mockQdrantClientInstance.createPayloadIndex).toHaveBeenCalledWith(expectedCollectionName, {
field_name: "type",
field_schema: "keyword",
})
for (let i = 0; i <= 4; i++) {
expect(mockQdrantClientInstance.createPayloadIndex).toHaveBeenCalledWith(expectedCollectionName, {
field_name: `pathSegments.${i}`,
field_schema: "keyword",
})
}
expect(mockQdrantClientInstance.createPayloadIndex).toHaveBeenCalledTimes(6)
})
it("should recreate collection if it exists but vectorSize mismatches and return true", async () => {
const differentVectorSize = 768
// Mock getCollection to return existing collection info with different vector size first,
// then return 404 to confirm deletion
mockQdrantClientInstance.getCollection
.mockResolvedValueOnce({
config: {
params: {
vectors: {
size: differentVectorSize, // Mismatching vector size
},
},
},
} as any)
.mockRejectedValueOnce({
response: { status: 404 },
message: "Not found",
})
mockQdrantClientInstance.deleteCollection.mockResolvedValue(true as any)
mockQdrantClientInstance.createCollection.mockResolvedValue(true as any)
mockQdrantClientInstance.createPayloadIndex.mockResolvedValue({} as any)
vitest.spyOn(console, "warn").mockImplementation(() => {}) // Suppress console.warn
const result = await vectorStore.initialize()
expect(result).toBe(true)
expect(mockQdrantClientInstance.getCollection).toHaveBeenCalledTimes(2) // Once to check, once to verify deletion
expect(mockQdrantClientInstance.getCollection).toHaveBeenCalledWith(expectedCollectionName)
expect(mockQdrantClientInstance.deleteCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.deleteCollection).toHaveBeenCalledWith(expectedCollectionName)
expect(mockQdrantClientInstance.createCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.createCollection).toHaveBeenCalledWith(expectedCollectionName, {
vectors: {
size: mockVectorSize, // Should use the new, correct vector size
distance: "Cosine",
on_disk: true,
},
hnsw_config: {
m: 64,
ef_construct: 512,
on_disk: true,
},
})
// Verify payload index creation - 'type' field first, then pathSegments
expect(mockQdrantClientInstance.createPayloadIndex).toHaveBeenCalledWith(expectedCollectionName, {
field_name: "type",
field_schema: "keyword",
})
for (let i = 0; i <= 4; i++) {
expect(mockQdrantClientInstance.createPayloadIndex).toHaveBeenCalledWith(expectedCollectionName, {
field_name: `pathSegments.${i}`,
field_schema: "keyword",
})
}
expect(mockQdrantClientInstance.createPayloadIndex).toHaveBeenCalledTimes(6)
;(console.warn as any).mockRestore() // Restore console.warn
})
it("should log warning for non-404 errors but still create collection", async () => {
const genericError = new Error("Generic Qdrant Error")
mockQdrantClientInstance.getCollection.mockRejectedValue(genericError)
vitest.spyOn(console, "warn").mockImplementation(() => {}) // Suppress console.warn
const result = await vectorStore.initialize()
expect(result).toBe(true) // Collection was created
expect(mockQdrantClientInstance.getCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.createCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.deleteCollection).not.toHaveBeenCalled()
expect(mockQdrantClientInstance.createPayloadIndex).toHaveBeenCalledTimes(6)
expect(console.warn).toHaveBeenCalledWith(
expect.stringContaining(`Warning during getCollectionInfo for "${expectedCollectionName}"`),
genericError.message,
)
;(console.warn as any).mockRestore()
})
it("should re-throw error from createCollection when no collection initially exists", async () => {
mockQdrantClientInstance.getCollection.mockRejectedValue({
response: { status: 404 },
message: "Not found",
})
const createError = new Error("Create Collection Failed")
mockQdrantClientInstance.createCollection.mockRejectedValue(createError)
vitest.spyOn(console, "error").mockImplementation(() => {}) // Suppress console.error
// The actual error message includes the URL and error details
await expect(vectorStore.initialize()).rejects.toThrow(
/Failed to connect to Qdrant vector database|vectorStore\.qdrantConnectionFailed/,
)
expect(mockQdrantClientInstance.getCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.createCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.deleteCollection).not.toHaveBeenCalled()
expect(mockQdrantClientInstance.createPayloadIndex).not.toHaveBeenCalled() // Should not be called if createCollection fails
expect(console.error).toHaveBeenCalledTimes(1) // Only the outer try/catch
;(console.error as any).mockRestore()
})
it("should log but not fail if payload index creation errors occur", async () => {
// Mock successful collection creation
mockQdrantClientInstance.getCollection.mockRejectedValue({
response: { status: 404 },
message: "Not found",
})
mockQdrantClientInstance.createCollection.mockResolvedValue(true as any)
// Mock payload index creation to fail
const indexError = new Error("Index creation failed")
mockQdrantClientInstance.createPayloadIndex.mockRejectedValue(indexError)
vitest.spyOn(console, "warn").mockImplementation(() => {}) // Suppress console.warn
const result = await vectorStore.initialize()
// Should still return true since main collection setup succeeded
expect(result).toBe(true)
expect(mockQdrantClientInstance.createCollection).toHaveBeenCalledTimes(1)
// Verify all payload index creations were attempted (6: type + 5 pathSegments)
expect(mockQdrantClientInstance.createPayloadIndex).toHaveBeenCalledTimes(6)
// Verify warnings were logged for each failed index (now 6)
expect(console.warn).toHaveBeenCalledTimes(6)
// Verify warning for 'type' index
expect(console.warn).toHaveBeenCalledWith(
expect.stringContaining(`Could not create payload index for type`),
indexError.message,
)
for (let i = 0; i <= 4; i++) {
expect(console.warn).toHaveBeenCalledWith(
expect.stringContaining(`Could not create payload index for pathSegments.${i}`),
indexError.message,
)
}
;(console.warn as any).mockRestore()
})
it("should throw vectorDimensionMismatch error when deleteCollection fails during recreation", async () => {
const differentVectorSize = 768
mockQdrantClientInstance.getCollection.mockResolvedValue({
config: {
params: {
vectors: {
size: differentVectorSize,
},
},
},
} as any)
const deleteError = new Error("Delete Collection Failed")
mockQdrantClientInstance.deleteCollection.mockRejectedValue(deleteError)
vitest.spyOn(console, "error").mockImplementation(() => {})
vitest.spyOn(console, "warn").mockImplementation(() => {})
// The error should have a cause property set to the original error
let caughtError: any
try {
await vectorStore.initialize()
} catch (error: any) {
caughtError = error
}
expect(caughtError).toBeDefined()
expect(caughtError.message).toContain("Failed to update vector index for new model")
expect(caughtError.cause).toBe(deleteError)
expect(mockQdrantClientInstance.getCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.deleteCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.createCollection).not.toHaveBeenCalled()
expect(mockQdrantClientInstance.createPayloadIndex).not.toHaveBeenCalled()
// Should log both the warning and the critical error
expect(console.warn).toHaveBeenCalledTimes(1)
expect(console.error).toHaveBeenCalledTimes(2) // One for the critical error, one for the outer catch
;(console.error as any).mockRestore()
;(console.warn as any).mockRestore()
})
it("should throw vectorDimensionMismatch error when createCollection fails during recreation", async () => {
const differentVectorSize = 768
mockQdrantClientInstance.getCollection
.mockResolvedValueOnce({
config: {
params: {
vectors: {
size: differentVectorSize,
},
},
},
} as any)
// Second call should return 404 to confirm deletion
.mockRejectedValueOnce({
response: { status: 404 },
message: "Not found",
})
// Delete succeeds but create fails
mockQdrantClientInstance.deleteCollection.mockResolvedValue(true as any)
const createError = new Error("Create Collection Failed")
mockQdrantClientInstance.createCollection.mockRejectedValue(createError)
vitest.spyOn(console, "error").mockImplementation(() => {})
vitest.spyOn(console, "warn").mockImplementation(() => {})
// Should throw an error with cause property set to the original error
let caughtError: any
try {
await vectorStore.initialize()
} catch (error: any) {
caughtError = error
}
expect(caughtError).toBeDefined()
expect(caughtError.message).toContain("Failed to update vector index for new model")
expect(caughtError.cause).toBe(createError)
expect(mockQdrantClientInstance.getCollection).toHaveBeenCalledTimes(2)
expect(mockQdrantClientInstance.deleteCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.createCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.createPayloadIndex).not.toHaveBeenCalled()
// Should log warning, critical error, and outer error
expect(console.warn).toHaveBeenCalledTimes(1)
expect(console.error).toHaveBeenCalledTimes(2)
;(console.error as any).mockRestore()
;(console.warn as any).mockRestore()
})
it("should verify collection deletion before proceeding with recreation", async () => {
const differentVectorSize = 768
mockQdrantClientInstance.getCollection
.mockResolvedValueOnce({
config: {
params: {
vectors: {
size: differentVectorSize,
},
},
},
} as any)
// Second call should return 404 to confirm deletion
.mockRejectedValueOnce({
response: { status: 404 },
message: "Not found",
})
mockQdrantClientInstance.deleteCollection.mockResolvedValue(true as any)
mockQdrantClientInstance.createCollection.mockResolvedValue(true as any)
mockQdrantClientInstance.createPayloadIndex.mockResolvedValue({} as any)
vitest.spyOn(console, "warn").mockImplementation(() => {})
const result = await vectorStore.initialize()
expect(result).toBe(true)
// Should call getCollection twice: once to check existing, once to verify deletion
expect(mockQdrantClientInstance.getCollection).toHaveBeenCalledTimes(2)
expect(mockQdrantClientInstance.deleteCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.createCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.createPayloadIndex).toHaveBeenCalledTimes(6)
;(console.warn as any).mockRestore()
})
it("should throw error if collection still exists after deletion attempt", async () => {
const differentVectorSize = 768
mockQdrantClientInstance.getCollection
.mockResolvedValueOnce({
config: {
params: {
vectors: {
size: differentVectorSize,
},
},
},
} as any)
// Second call should still return the collection (deletion failed)
.mockResolvedValueOnce({
config: {
params: {
vectors: {
size: differentVectorSize,
},
},
},
} as any)
mockQdrantClientInstance.deleteCollection.mockResolvedValue(true as any)
vitest.spyOn(console, "error").mockImplementation(() => {})
vitest.spyOn(console, "warn").mockImplementation(() => {})
let caughtError: any
try {
await vectorStore.initialize()
} catch (error: any) {
caughtError = error
}
expect(caughtError).toBeDefined()
expect(caughtError.message).toContain("Failed to update vector index for new model")
// The error message should contain the contextual error details
expect(caughtError.message).toContain("Deleted existing collection but failed verification step")
expect(mockQdrantClientInstance.getCollection).toHaveBeenCalledTimes(2)
expect(mockQdrantClientInstance.deleteCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.createCollection).not.toHaveBeenCalled()
expect(mockQdrantClientInstance.createPayloadIndex).not.toHaveBeenCalled()
;(console.error as any).mockRestore()
;(console.warn as any).mockRestore()
})
it("should handle dimension mismatch scenario from 2048 to 768 dimensions", async () => {
// Simulate the exact scenario from the issue: switching from 2048 to 768 dimensions
const oldVectorSize = 2048
const newVectorSize = 768
// Create a new vector store with the new dimension
const newVectorStore = new QdrantVectorStore(mockWorkspacePath, mockQdrantUrl, newVectorSize, mockApiKey)
mockQdrantClientInstance.getCollection
.mockResolvedValueOnce({
config: {
params: {
vectors: {
size: oldVectorSize, // Existing collection has 2048 dimensions
},
},
},
} as any)
// Second call should return 404 to confirm deletion
.mockRejectedValueOnce({
response: { status: 404 },
message: "Not found",
})
mockQdrantClientInstance.deleteCollection.mockResolvedValue(true as any)
mockQdrantClientInstance.createCollection.mockResolvedValue(true as any)
mockQdrantClientInstance.createPayloadIndex.mockResolvedValue({} as any)
vitest.spyOn(console, "warn").mockImplementation(() => {})
const result = await newVectorStore.initialize()
expect(result).toBe(true)
expect(mockQdrantClientInstance.getCollection).toHaveBeenCalledTimes(2)
expect(mockQdrantClientInstance.deleteCollection).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.createCollection).toHaveBeenCalledWith(expectedCollectionName, {
vectors: {
size: newVectorSize, // Should create with new 768 dimensions
distance: "Cosine",
on_disk: true,
},
hnsw_config: {
m: 64,
ef_construct: 512,
on_disk: true,
},
})
expect(mockQdrantClientInstance.createPayloadIndex).toHaveBeenCalledTimes(6)
;(console.warn as any).mockRestore()
})
it("should provide detailed error context for different failure scenarios", async () => {
const differentVectorSize = 768
mockQdrantClientInstance.getCollection.mockResolvedValue({
config: {
params: {
vectors: {
size: differentVectorSize,
},
},
},
} as any)
// Test deletion failure with specific error message
const deleteError = new Error("Qdrant server unavailable")
mockQdrantClientInstance.deleteCollection.mockRejectedValue(deleteError)
vitest.spyOn(console, "error").mockImplementation(() => {})
vitest.spyOn(console, "warn").mockImplementation(() => {})
let caughtError: any
try {
await vectorStore.initialize()
} catch (error: any) {
caughtError = error
}
expect(caughtError).toBeDefined()
expect(caughtError.message).toContain("Failed to update vector index for new model")
// The error message should contain the contextual error details
expect(caughtError.message).toContain("Failed to delete existing collection with vector size")
expect(caughtError.message).toContain("Qdrant server unavailable")
expect(caughtError.cause).toBe(deleteError)
;(console.error as any).mockRestore()
;(console.warn as any).mockRestore()
})
})
describe("workspace alias creation", () => {
it("should create a workspace alias during initialization", async () => {
mockQdrantClientInstance.getCollection.mockRejectedValue({
response: { status: 404 },
message: "Not found",
})
mockQdrantClientInstance.createCollection.mockResolvedValue(true as any)
mockQdrantClientInstance.createPayloadIndex.mockResolvedValue({} as any)
mockQdrantClientInstance.updateCollectionAliases.mockResolvedValue(true as any)
vitest.spyOn(console, "log").mockImplementation(() => {})
await vectorStore.initialize()
expect(mockQdrantClientInstance.updateCollectionAliases).toHaveBeenCalledTimes(1)
expect(mockQdrantClientInstance.updateCollectionAliases).toHaveBeenCalledWith({
actions: [
{