-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtest_executor.py
More file actions
3106 lines (2633 loc) · 126 KB
/
test_executor.py
File metadata and controls
3106 lines (2633 loc) · 126 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 pytest
from qql.ast_nodes import (
AlterCollectionStmt,
CollectionParamsConfig,
CollectionConfig,
CreateCollectionStmt,
CreateIndexStmt,
DeleteStmt,
HnswRuntimeConfig,
DropCollectionStmt,
InsertBulkStmt,
InsertStmt,
OptimizersRuntimeConfig,
QuantizationConfig,
QuantizationUpdate,
QuantizationSearchWith,
QuantizationType,
RecommendStmt,
SelectStmt,
ScrollStmt,
SearchStmt,
SearchWith,
ShowCollectionStmt,
ShowCollectionsStmt,
VectorsConfig,
)
from qql.config import QQLConfig
from qql.exceptions import QQLRuntimeError
from qql.cli import _format_collection_diagnostics
from qql.executor import Executor
FAKE_VECTOR = [0.1] * 384
DEFAULT_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
@pytest.fixture
def cfg():
return QQLConfig(url="http://localhost:6333", secret=None)
@pytest.fixture
def mock_client(mocker):
client = mocker.MagicMock()
client.collection_exists.return_value = False
state = {"exists": False}
def collection_exists(_name):
return state["exists"] or bool(client.collection_exists.return_value)
def create_collection(**_kwargs):
state["exists"] = True
client.collection_exists.side_effect = collection_exists
client.create_collection.side_effect = create_collection
return client
@pytest.fixture
def executor(mock_client, cfg):
return Executor(mock_client, cfg)
@pytest.fixture(autouse=True)
def mock_embedder(mocker):
mock_embed = mocker.MagicMock()
mock_embed.embed.return_value = FAKE_VECTOR
mock_embed.dimensions = 384
mocker.patch("qql.executor.Embedder", return_value=mock_embed)
return mock_embed
class TestInsert:
def test_insert_creates_collection_when_missing(self, executor, mock_client):
node = InsertStmt(collection="notes", values={"text": "hello"}, model=None)
executor.execute(node)
mock_client.create_collection.assert_called_once()
def test_insert_skips_create_when_collection_exists(self, executor, mock_client):
mock_client.collection_exists.return_value = True
# Simulate same vector size
mock_client.get_collection.return_value.config.params.vectors.size = 384
node = InsertStmt(collection="notes", values={"text": "hello"}, model=None)
executor.execute(node)
mock_client.create_collection.assert_not_called()
def test_insert_calls_upsert(self, executor, mock_client):
node = InsertStmt(collection="notes", values={"text": "hello", "author": "alice"}, model=None)
result = executor.execute(node)
mock_client.upsert.assert_called_once()
assert result.success is True
assert "Inserted 1 point" in result.message
def test_insert_result_contains_point_id(self, executor, mock_client):
node = InsertStmt(collection="notes", values={"text": "hi"}, model=None)
result = executor.execute(node)
assert result.data["id"] is not None
assert len(result.data["id"]) == 36 # UUID format
def test_insert_uses_explicit_uuid_id_when_provided(self, executor, mock_client):
node = InsertStmt(
collection="notes",
values={"id": "550e8400-e29b-41d4-a716-446655440000", "text": "hello"},
model=None,
)
result = executor.execute(node)
point = mock_client.upsert.call_args.kwargs["points"][0]
assert point.id == "550e8400-e29b-41d4-a716-446655440000"
assert "id" not in point.payload
assert result.data["id"] == "550e8400-e29b-41d4-a716-446655440000"
def test_insert_uses_explicit_integer_id_when_provided(self, executor, mock_client):
node = InsertStmt(
collection="notes",
values={"id": 42, "text": "hello"},
model=None,
)
executor.execute(node)
point = mock_client.upsert.call_args.kwargs["points"][0]
assert point.id == 42
def test_insert_rejects_non_scalar_id(self, executor):
node = InsertStmt(
collection="notes",
values={"id": {"bad": "id"}, "text": "hello"},
model=None,
)
with pytest.raises(QQLRuntimeError, match="unsigned integer or UUID string"):
executor.execute(node)
def test_insert_rejects_non_uuid_string_id(self, executor):
node = InsertStmt(
collection="notes",
values={"id": "note-1", "text": "hello"},
model=None,
)
with pytest.raises(QQLRuntimeError, match="unsigned integer or UUID string"):
executor.execute(node)
def test_insert_stores_text_in_payload(self, executor, mock_client):
node = InsertStmt(collection="notes", values={"text": "hello"}, model=None)
executor.execute(node)
call_args = mock_client.upsert.call_args
points = call_args.kwargs["points"]
assert points[0].payload["text"] == "hello"
def test_insert_raises_when_text_missing(self, executor):
node = InsertStmt(collection="notes", values={"author": "alice"}, model=None)
with pytest.raises(QQLRuntimeError, match="'text' field"):
executor.execute(node)
def test_insert_raises_on_dimension_mismatch(self, executor, mock_client):
mock_client.collection_exists.return_value = True
mock_client.get_collection.return_value.config.params.vectors.size = 768
node = InsertStmt(collection="notes", values={"text": "hi"}, model=None)
with pytest.raises(QQLRuntimeError, match="dimension mismatch"):
executor.execute(node)
class TestInsertBulk:
def test_bulk_insert_calls_upsert_once(self, executor, mock_client):
node = InsertBulkStmt(
collection="col",
values_list=({"text": "hello"}, {"text": "world"}),
model=None,
)
executor.execute(node)
mock_client.upsert.assert_called_once()
def test_bulk_insert_upserts_correct_count(self, executor, mock_client):
node = InsertBulkStmt(
collection="col",
values_list=({"text": "a"}, {"text": "b"}, {"text": "c"}),
model=None,
)
executor.execute(node)
call_args = mock_client.upsert.call_args.kwargs
assert len(call_args["points"]) == 3
def test_bulk_insert_creates_collection_when_missing(self, executor, mock_client):
node = InsertBulkStmt(
collection="col",
values_list=({"text": "hello"},),
model=None,
)
executor.execute(node)
mock_client.create_collection.assert_called_once()
def test_bulk_insert_skips_create_when_exists(self, executor, mock_client):
mock_client.collection_exists.return_value = True
mock_client.get_collection.return_value.config.params.vectors.size = 384
node = InsertBulkStmt(
collection="col",
values_list=({"text": "hello"},),
model=None,
)
executor.execute(node)
mock_client.create_collection.assert_not_called()
def test_bulk_insert_raises_on_missing_text(self, executor):
node = InsertBulkStmt(
collection="col",
values_list=({"text": "ok"}, {"author": "bob"}),
model=None,
)
with pytest.raises(QQLRuntimeError, match="index 1"):
executor.execute(node)
def test_bulk_insert_empty_list_raises(self, executor):
node = InsertBulkStmt(collection="col", values_list=(), model=None)
with pytest.raises(QQLRuntimeError, match="empty"):
executor.execute(node)
def test_bulk_insert_result_message_contains_count(self, executor, mock_client):
node = InsertBulkStmt(
collection="col",
values_list=({"text": "a"}, {"text": "b"}),
model=None,
)
result = executor.execute(node)
assert result.success is True
assert "2" in result.message
assert "points" in result.message
def test_bulk_insert_preserves_explicit_ids(self, executor, mock_client):
node = InsertBulkStmt(
collection="col",
values_list=(
{"id": "550e8400-e29b-41d4-a716-446655440001", "text": "a"},
{"id": 2, "text": "b"},
),
model=None,
)
executor.execute(node)
points = mock_client.upsert.call_args.kwargs["points"]
assert [point.id for point in points] == ["550e8400-e29b-41d4-a716-446655440001", 2]
assert all("id" not in point.payload for point in points)
def test_single_insert_unaffected_by_bulk_dispatch(self, executor, mock_client):
"""Ensure single INSERT still routes correctly after bulk dispatch added."""
node = InsertStmt(collection="notes", values={"text": "hello"}, model=None)
result = executor.execute(node)
assert result.success is True
assert "Inserted 1 point" in result.message
class TestCreate:
def test_create_new_collection(self, executor, mock_client):
node = CreateCollectionStmt(collection="new_col")
result = executor.execute(node)
mock_client.create_collection.assert_called_once()
assert result.success is True
def test_create_collection_passes_payload_m(self, executor, mock_client):
from qdrant_client.models import HnswConfigDiff
node = CreateCollectionStmt(
collection="new_col",
config=CollectionConfig(hnsw=HnswRuntimeConfig(payload_m=24)),
)
executor.execute(node)
kw = mock_client.create_collection.call_args.kwargs
assert isinstance(kw["hnsw_config"], HnswConfigDiff)
assert kw["hnsw_config"].payload_m == 24
def test_create_collection_passes_all_new_config_blocks(self, executor, mock_client):
node = CreateCollectionStmt(
collection="new_col",
config=CollectionConfig(
vectors=VectorsConfig(on_disk=True),
hnsw=HnswRuntimeConfig(
m=32,
ef_construct=200,
full_scan_threshold=5000,
max_indexing_threads=2,
on_disk=True,
payload_m=24,
inline_storage=False,
),
optimizers=OptimizersRuntimeConfig(
indexing_threshold=10000,
memmap_threshold=20000,
deleted_threshold=0.2,
max_optimization_threads="auto",
),
params=CollectionParamsConfig(
replication_factor=2,
write_consistency_factor=1,
on_disk_payload=True,
),
),
)
executor.execute(node)
kw = mock_client.create_collection.call_args.kwargs
assert kw["vectors_config"].on_disk is True
assert kw["hnsw_config"].m == 32
assert kw["hnsw_config"].ef_construct == 200
assert kw["hnsw_config"].full_scan_threshold == 5000
assert kw["hnsw_config"].max_indexing_threads == 2
assert kw["hnsw_config"].on_disk is True
assert kw["hnsw_config"].payload_m == 24
assert kw["hnsw_config"].inline_storage is False
assert kw["optimizers_config"].deleted_threshold == pytest.approx(0.2)
assert kw["optimizers_config"].indexing_threshold == 10000
assert kw["optimizers_config"].memmap_threshold == 20000
assert kw["optimizers_config"].max_optimization_threads.value == "auto"
assert kw["replication_factor"] == 2
assert kw["write_consistency_factor"] == 1
assert kw["on_disk_payload"] is True
def test_create_existing_collection_is_noop(self, executor, mock_client):
mock_client.collection_exists.return_value = True
node = CreateCollectionStmt(collection="existing")
result = executor.execute(node)
mock_client.create_collection.assert_not_called()
assert result.success is True
assert "already exists" in result.message
def test_alter_collection_passes_all_new_config_blocks(self, executor, mock_client):
mock_client.collection_exists.return_value = True
node = AlterCollectionStmt(
collection="new_col",
config=CollectionConfig(
vectors=VectorsConfig(on_disk=True),
hnsw=HnswRuntimeConfig(full_scan_threshold=5000),
optimizers=OptimizersRuntimeConfig(indexing_threshold=10000),
params=CollectionParamsConfig(
on_disk_payload=False,
read_fan_out_factor=4,
),
),
quantization=QuantizationUpdate(
config=QuantizationConfig(type=QuantizationType.BINARY)
),
)
executor.execute(node)
kw = mock_client.update_collection.call_args.kwargs
assert kw["vectors_config"][""].on_disk is True
assert kw["hnsw_config"].full_scan_threshold == 5000
assert kw["optimizers_config"].indexing_threshold == 10000
assert kw["collection_params"].on_disk_payload is False
assert kw["collection_params"].read_fan_out_factor == 4
assert kw["quantization_config"].binary is not None
def test_alter_collection_named_vectors_use_dense_key(self, executor, mock_client, mocker):
from qdrant_client.models import Distance, VectorParams
mock_client.collection_exists.return_value = True
mock_client.get_collection.return_value.config.params.vectors = {
"dense": VectorParams(size=384, distance=Distance.COSINE)
}
node = AlterCollectionStmt(
collection="named_col",
config=CollectionConfig(vectors=VectorsConfig(on_disk=True)),
)
executor.execute(node)
kw = mock_client.update_collection.call_args.kwargs
assert kw["vectors_config"]["dense"].on_disk is True
def test_alter_collection_can_disable_quantization(self, executor, mock_client):
mock_client.collection_exists.return_value = True
node = AlterCollectionStmt(
collection="new_col",
quantization=QuantizationUpdate(disabled=True),
)
executor.execute(node)
kw = mock_client.update_collection.call_args.kwargs
assert kw["quantization_config"].value == "Disabled"
def test_collection_is_hybrid_depends_on_sparse_vectors(self, executor, mock_client, mocker):
mock_client.collection_exists.return_value = True
mock_client.get_collection.return_value.config.params.vectors = {"dense": object()}
mock_client.get_collection.return_value.config.params.sparse_vectors = None
assert executor._collection_is_hybrid("named_dense") is False
def test_insert_named_dense_collection_uses_named_vector_payload(self, executor, mock_client):
mock_client.collection_exists.return_value = True
mock_client.get_collection.return_value.config.params.vectors = {"dense": object()}
mock_client.get_collection.return_value.config.params.sparse_vectors = None
node = InsertStmt(collection="named_dense", values={"text": "hello"}, model=None)
executor.execute(node)
point = mock_client.upsert.call_args.kwargs["points"][0]
assert point.vector == {"dense": FAKE_VECTOR}
class TestCreateIndex:
def test_create_index_calls_qdrant(self, executor, mock_client):
mock_client.collection_exists.return_value = True
node = CreateIndexStmt(collection="articles", field_name="category", schema="keyword")
result = executor.execute(node)
mock_client.create_payload_index.assert_called_once()
assert result.success is True
def test_create_index_supports_keyword_options(self, executor, mock_client):
from qdrant_client.models import KeywordIndexParams
mock_client.collection_exists.return_value = True
node = CreateIndexStmt(
collection="articles",
field_name="tenant_id",
schema="keyword",
options={"is_tenant": True, "on_disk": True, "enable_hnsw": False},
)
executor.execute(node)
field_schema = mock_client.create_payload_index.call_args.kwargs["field_schema"]
assert isinstance(field_schema, KeywordIndexParams)
assert field_schema.is_tenant is True
assert field_schema.on_disk is True
assert field_schema.enable_hnsw is False
def test_create_index_supports_text_options(self, executor, mock_client):
from qdrant_client.models import TextIndexParams, TokenizerType
mock_client.collection_exists.return_value = True
node = CreateIndexStmt(
collection="articles",
field_name="title",
schema="text",
options={
"tokenizer": "word",
"min_token_len": 2,
"max_token_len": 20,
"lowercase": True,
"phrase_matching": True,
},
)
executor.execute(node)
field_schema = mock_client.create_payload_index.call_args.kwargs["field_schema"]
assert isinstance(field_schema, TextIndexParams)
assert field_schema.tokenizer == TokenizerType.WORD
assert field_schema.min_token_len == 2
assert field_schema.max_token_len == 20
assert field_schema.lowercase is True
assert field_schema.phrase_matching is True
def test_create_index_supports_uuid_options(self, executor, mock_client):
from qdrant_client.models import UuidIndexParams
mock_client.collection_exists.return_value = True
node = CreateIndexStmt(
collection="articles",
field_name="doc_id",
schema="uuid",
options={"on_disk": True},
)
executor.execute(node)
field_schema = mock_client.create_payload_index.call_args.kwargs["field_schema"]
assert isinstance(field_schema, UuidIndexParams)
assert field_schema.on_disk is True
def test_create_index_rejects_unknown_option(self, executor, mock_client):
mock_client.collection_exists.return_value = True
node = CreateIndexStmt(
collection="articles",
field_name="tenant_id",
schema="keyword",
options={"tokenizer": "word"},
)
with pytest.raises(QQLRuntimeError, match="Unknown CREATE INDEX option"):
executor.execute(node)
def test_create_index_nonexistent_collection_raises(self, executor, mock_client):
mock_client.collection_exists.return_value = False
node = CreateIndexStmt(collection="ghost", field_name="category", schema="keyword")
with pytest.raises(QQLRuntimeError, match="does not exist"):
executor.execute(node)
class TestCreateWithModel:
def test_create_with_model_passes_model_to_embedder(self, mock_client, cfg, mocker):
mock_emb = mocker.MagicMock()
mock_emb.dimensions = 768
embedder_cls = mocker.patch("qql.executor.Embedder", return_value=mock_emb)
executor = Executor(mock_client, cfg)
node = CreateCollectionStmt(collection="col", model="BAAI/bge-base-en-v1.5")
executor.execute(node)
embedder_cls.assert_called_once_with("BAAI/bge-base-en-v1.5")
def test_create_without_model_uses_default_model(self, mock_client, cfg, mocker):
mock_emb = mocker.MagicMock()
mock_emb.dimensions = 384
embedder_cls = mocker.patch("qql.executor.Embedder", return_value=mock_emb)
executor = Executor(mock_client, cfg)
node = CreateCollectionStmt(collection="col")
executor.execute(node)
embedder_cls.assert_called_once_with(cfg.default_model)
def test_create_hybrid_with_model_uses_named_vectors(self, mock_client, cfg, mocker):
mock_emb = mocker.MagicMock()
mock_emb.dimensions = 768
embedder_cls = mocker.patch("qql.executor.Embedder", return_value=mock_emb)
executor = Executor(mock_client, cfg)
node = CreateCollectionStmt(collection="col", hybrid=True, model="BAAI/bge-base-en-v1.5")
executor.execute(node)
embedder_cls.assert_called_once_with("BAAI/bge-base-en-v1.5")
kw = mock_client.create_collection.call_args.kwargs
assert isinstance(kw["vectors_config"], dict)
assert "dense" in kw["vectors_config"]
assert "sparse_vectors_config" in kw
def test_create_hybrid_without_model_uses_default(self, mock_client, cfg, mocker):
mock_emb = mocker.MagicMock()
mock_emb.dimensions = 384
embedder_cls = mocker.patch("qql.executor.Embedder", return_value=mock_emb)
executor = Executor(mock_client, cfg)
node = CreateCollectionStmt(collection="col", hybrid=True)
executor.execute(node)
embedder_cls.assert_called_once_with(cfg.default_model)
kw = mock_client.create_collection.call_args.kwargs
assert isinstance(kw["vectors_config"], dict)
def test_create_dense_with_model_uses_scalar_vectors(self, mock_client, cfg, mocker):
from qdrant_client.models import VectorParams
mock_emb = mocker.MagicMock()
mock_emb.dimensions = 768
mocker.patch("qql.executor.Embedder", return_value=mock_emb)
executor = Executor(mock_client, cfg)
node = CreateCollectionStmt(collection="col", model="BAAI/bge-base-en-v1.5")
executor.execute(node)
kw = mock_client.create_collection.call_args.kwargs
assert isinstance(kw["vectors_config"], VectorParams)
assert "sparse_vectors_config" not in kw
def test_create_existing_noop_with_model(self, executor, mock_client):
mock_client.collection_exists.return_value = True
node = CreateCollectionStmt(collection="col", model="some/model")
result = executor.execute(node)
mock_client.create_collection.assert_not_called()
assert result.success is True
assert "already exists" in result.message
class TestDrop:
def test_drop_existing_collection(self, executor, mock_client):
mock_client.collection_exists.return_value = True
node = DropCollectionStmt(collection="old_col")
result = executor.execute(node)
mock_client.delete_collection.assert_called_once_with("old_col")
assert result.success is True
def test_drop_nonexistent_raises(self, executor, mock_client):
mock_client.collection_exists.return_value = False
node = DropCollectionStmt(collection="ghost")
with pytest.raises(QQLRuntimeError, match="does not exist"):
executor.execute(node)
class TestShow:
def test_show_returns_collection_names(self, executor, mock_client, mocker):
col1 = mocker.MagicMock()
col1.name = "notes"
col2 = mocker.MagicMock()
col2.name = "docs"
mock_client.get_collections.return_value.collections = [col1, col2]
node = ShowCollectionsStmt()
result = executor.execute(node)
assert result.success is True
assert "notes" in result.data
assert "docs" in result.data
class TestShowCollection:
def test_show_collection_returns_diagnostics(self, executor, mock_client, mocker):
from qdrant_client.models import (
CollectionStatus,
Distance,
VectorParams,
)
mock_client.collection_exists.return_value = True
mock_info = mocker.MagicMock()
mock_info.status = CollectionStatus.GREEN
mock_info.points_count = 42
mock_info.indexed_vectors_count = 42
mock_info.segments_count = 2
mock_info.config.params.vectors = VectorParams(
size=384,
distance=Distance.COSINE,
on_disk=True,
)
mock_info.config.params.shard_number = 1
mock_info.config.params.replication_factor = 1
mock_info.config.params.write_consistency_factor = 1
mock_info.config.params.read_fan_out_factor = None
mock_info.config.params.read_fan_out_delay_ms = None
mock_info.config.params.on_disk_payload = False
mock_info.config.params.sparse_vectors = None
mock_info.config.hnsw_config.m = 16
mock_info.config.hnsw_config.ef_construct = 100
mock_info.config.hnsw_config.full_scan_threshold = None
mock_info.config.hnsw_config.max_indexing_threads = None
mock_info.config.hnsw_config.on_disk = None
mock_info.config.hnsw_config.payload_m = None
mock_info.config.quantization_config = None
mock_info.payload_schema = {}
mock_client.get_collection.return_value = mock_info
node = ShowCollectionStmt(collection="docs")
result = executor.execute(node)
assert result.success is True
data = result.data
assert data["name"] == "docs"
assert data["points_count"] == 42
assert data["topology"] == "dense"
assert data["vectors"][""]["size"] == 384
assert data["vectors"][""]["distance"] == "Cosine"
assert data["vectors"][""]["on_disk"] is True
assert data["quantization"] is None
assert data["hnsw_config"]["m"] == 16
assert data["hnsw_config"]["ef_construct"] == 100
assert data["payload_schema"] is None
assert data["sparse_vectors"] is None
def test_show_collection_hybrid(self, executor, mock_client, mocker):
from qdrant_client.models import (
CollectionStatus,
Distance,
Modifier,
SparseVectorParams,
VectorParams,
)
mock_client.collection_exists.return_value = True
mock_info = mocker.MagicMock()
mock_info.status = CollectionStatus.GREEN
mock_info.points_count = 10
mock_info.indexed_vectors_count = 10
mock_info.segments_count = 1
mock_info.config.params.vectors = {
"dense": VectorParams(size=768, distance=Distance.COSINE),
}
mock_info.config.params.sparse_vectors = {
"sparse": SparseVectorParams(modifier=Modifier.IDF),
}
mock_info.config.params.shard_number = 1
mock_info.config.params.replication_factor = 1
mock_info.config.params.write_consistency_factor = 1
mock_info.config.params.read_fan_out_factor = None
mock_info.config.params.read_fan_out_delay_ms = None
mock_info.config.params.on_disk_payload = None
mock_info.config.hnsw_config.m = 16
mock_info.config.hnsw_config.ef_construct = 100
mock_info.config.hnsw_config.full_scan_threshold = None
mock_info.config.hnsw_config.max_indexing_threads = None
mock_info.config.hnsw_config.on_disk = None
mock_info.config.hnsw_config.payload_m = None
mock_info.config.quantization_config = None
mock_info.payload_schema = {}
mock_client.get_collection.return_value = mock_info
node = ShowCollectionStmt(collection="hybrid_col")
result = executor.execute(node)
assert result.success is True
data = result.data
assert data["topology"] == "hybrid"
assert data["vectors"]["dense"]["size"] == 768
assert data["sparse_vectors"]["sparse"]["modifier"] == "idf"
def test_show_collection_named_dense_is_not_reported_as_hybrid(self, executor, mock_client, mocker):
from qdrant_client.models import (
CollectionStatus,
Distance,
VectorParams,
)
mock_client.collection_exists.return_value = True
mock_info = mocker.MagicMock()
mock_info.status = CollectionStatus.GREEN
mock_info.points_count = 3
mock_info.indexed_vectors_count = 3
mock_info.segments_count = 1
mock_info.config.params.vectors = {
"body": VectorParams(size=384, distance=Distance.COSINE),
"title": VectorParams(size=128, distance=Distance.DOT),
}
mock_info.config.params.sparse_vectors = None
mock_info.config.params.shard_number = 1
mock_info.config.params.replication_factor = 1
mock_info.config.params.write_consistency_factor = 1
mock_info.config.params.read_fan_out_factor = None
mock_info.config.params.read_fan_out_delay_ms = None
mock_info.config.params.on_disk_payload = None
mock_info.config.hnsw_config.m = 16
mock_info.config.hnsw_config.ef_construct = 100
mock_info.config.hnsw_config.full_scan_threshold = None
mock_info.config.hnsw_config.max_indexing_threads = None
mock_info.config.hnsw_config.on_disk = None
mock_info.config.hnsw_config.payload_m = None
mock_info.config.quantization_config = None
mock_info.payload_schema = {}
mock_client.get_collection.return_value = mock_info
result = executor.execute(ShowCollectionStmt(collection="named_dense"))
assert result.success is True
assert result.data["topology"] == "dense"
assert result.data["sparse_vectors"] is None
def test_show_collection_with_payload_schema(self, executor, mock_client, mocker):
from qdrant_client.models import (
CollectionStatus,
Distance,
KeywordIndexParams,
KeywordIndexType,
PayloadSchemaType,
VectorParams,
)
mock_client.collection_exists.return_value = True
idx_info = mocker.MagicMock()
idx_info.data_type = PayloadSchemaType.KEYWORD
idx_info.params = KeywordIndexParams(
type=KeywordIndexType.KEYWORD,
is_tenant=True,
on_disk=True,
)
mock_info = mocker.MagicMock()
mock_info.status = CollectionStatus.GREEN
mock_info.points_count = 0
mock_info.indexed_vectors_count = 0
mock_info.segments_count = 0
mock_info.config.params.vectors = VectorParams(size=384, distance=Distance.COSINE)
mock_info.config.params.shard_number = 1
mock_info.config.params.replication_factor = 1
mock_info.config.params.write_consistency_factor = 1
mock_info.config.params.read_fan_out_factor = None
mock_info.config.params.read_fan_out_delay_ms = None
mock_info.config.params.on_disk_payload = None
mock_info.config.params.sparse_vectors = None
mock_info.config.hnsw_config.m = 16
mock_info.config.hnsw_config.ef_construct = 100
mock_info.config.hnsw_config.full_scan_threshold = None
mock_info.config.hnsw_config.max_indexing_threads = None
mock_info.config.hnsw_config.on_disk = None
mock_info.config.hnsw_config.payload_m = None
mock_info.config.hnsw_config.inline_storage = True
mock_info.config.quantization_config = None
mock_info.payload_schema = {"category": idx_info}
mock_client.get_collection.return_value = mock_info
node = ShowCollectionStmt(collection="docs")
result = executor.execute(node)
assert result.success is True
assert result.data["payload_schema"] == {
"category": {
"type": "keyword",
"params": {"is_tenant": True, "on_disk": True},
}
}
assert result.data["hnsw_config"]["inline_storage"] is True
def test_format_collection_diagnostics_does_not_duplicate_replication(self):
text = _format_collection_diagnostics(
{
"name": "docs",
"status": "green",
"points_count": 1,
"indexed_vectors_count": 1,
"segments_count": 1,
"topology": "dense",
"vectors": {"": {"size": 384, "distance": "Cosine", "on_disk": True}},
"sparse_vectors": None,
"quantization": None,
"hnsw_config": {"m": 16, "ef_construct": 100, "inline_storage": True},
"payload_schema": None,
"sharding": {
"shard_number": 1,
"replication_factor": 2,
"write_consistency_factor": 1,
"read_fan_out_factor": 4,
"read_fan_out_delay_ms": 10,
"on_disk_payload": False,
},
}
)
assert text.count("Replication factor") == 1
assert text.count("Write consistency") == 1
assert "Replicas :" not in text
assert "Payload indexes : none" in text
assert "HNSW inline_storage : True" in text
def test_show_collection_handles_missing_payload_schema(self, executor, mock_client, mocker):
from qdrant_client.models import (
CollectionStatus,
Distance,
VectorParams,
)
mock_client.collection_exists.return_value = True
mock_info = mocker.MagicMock()
mock_info.status = CollectionStatus.GREEN
mock_info.points_count = 0
mock_info.indexed_vectors_count = 0
mock_info.segments_count = 0
mock_info.config.params.vectors = VectorParams(size=384, distance=Distance.COSINE)
mock_info.config.params.shard_number = 1
mock_info.config.params.replication_factor = 1
mock_info.config.params.write_consistency_factor = 1
mock_info.config.params.sparse_vectors = None
mock_info.config.hnsw_config.m = 16
mock_info.config.hnsw_config.ef_construct = 100
mock_info.config.hnsw_config.full_scan_threshold = None
mock_info.config.hnsw_config.max_indexing_threads = None
mock_info.config.hnsw_config.on_disk = None
mock_info.config.hnsw_config.payload_m = None
mock_info.config.quantization_config = None
mock_info.payload_schema = None
mock_client.get_collection.return_value = mock_info
result = executor.execute(ShowCollectionStmt(collection="docs"))
assert result.success is True
assert result.data["payload_schema"] is None
def test_show_collection_nonexistent_raises(self, executor, mock_client):
mock_client.collection_exists.return_value = False
node = ShowCollectionStmt(collection="ghost")
with pytest.raises(QQLRuntimeError, match="does not exist"):
executor.execute(node)
class TestScroll:
def test_scroll_returns_points_and_next_offset(self, executor, mock_client, mocker):
mock_client.collection_exists.return_value = True
rec1 = mocker.MagicMock()
rec1.id = "a"
rec1.payload = {"text": "first"}
rec2 = mocker.MagicMock()
rec2.id = 2
rec2.payload = {"text": "second"}
mock_client.scroll.return_value = ([rec1, rec2], "next-1")
node = ScrollStmt(collection="notes", limit=2)
result = executor.execute(node)
mock_client.scroll.assert_called_once_with(
collection_name="notes",
scroll_filter=None,
limit=2,
offset=None,
with_payload=True,
with_vectors=False,
)
assert result.success is True
assert result.data == {
"points": [
{"id": "a", "payload": {"text": "first"}},
{"id": "2", "payload": {"text": "second"}},
],
"next_offset": "next-1",
}
def test_scroll_preserves_numeric_next_offset_type(self, executor, mock_client, mocker):
mock_client.collection_exists.return_value = True
rec = mocker.MagicMock()
rec.id = 1
rec.payload = {"text": "first"}
mock_client.scroll.return_value = ([rec], 42)
node = ScrollStmt(collection="notes", limit=1)
result = executor.execute(node)
assert result.success is True
assert result.data["next_offset"] == 42
def test_scroll_with_after_and_filter(self, executor, mock_client, mocker):
from qql.ast_nodes import CompareExpr
from qdrant_client.models import Filter
mock_client.collection_exists.return_value = True
mock_client.scroll.return_value = ([], None)
node = ScrollStmt(
collection="notes",
limit=10,
after="cursor-id",
query_filter=CompareExpr(field="year", op=">=", value=2024),
)
executor.execute(node)
kwargs = mock_client.scroll.call_args.kwargs
assert kwargs["offset"] == "cursor-id"
assert isinstance(kwargs["scroll_filter"], Filter)
def test_scroll_nonexistent_collection_raises(self, executor, mock_client):
mock_client.collection_exists.return_value = False
node = ScrollStmt(collection="ghost", limit=5)
with pytest.raises(QQLRuntimeError, match="does not exist"):
executor.execute(node)
class TestSelect:
def test_select_by_id_returns_payload(self, executor, mock_client, mocker):
mock_client.collection_exists.return_value = True
rec = mocker.MagicMock()
rec.id = "abc-123"
rec.payload = {"text": "hello", "year": 2024}
mock_client.retrieve.return_value = [rec]
node = SelectStmt(collection="notes", point_id="abc-123")
result = executor.execute(node)
mock_client.retrieve.assert_called_once_with(
collection_name="notes",
ids=["abc-123"],
with_payload=True,
with_vectors=False,
)
assert result.success is True
assert result.data == {"id": "abc-123", "payload": {"text": "hello", "year": 2024}}
def test_select_not_found(self, executor, mock_client):
mock_client.collection_exists.return_value = True
mock_client.retrieve.return_value = []
node = SelectStmt(collection="notes", point_id=7)
result = executor.execute(node)
assert result.success is True
assert "not found" in result.message
assert result.data is None
def test_select_nonexistent_collection_raises(self, executor, mock_client):
mock_client.collection_exists.return_value = False
node = SelectStmt(collection="ghost", point_id="x")
with pytest.raises(QQLRuntimeError, match="does not exist"):
executor.execute(node)
class TestSearch:
def test_search_calls_qdrant_query_points(self, executor, mock_client, mocker):
mock_client.collection_exists.return_value = True
mock_response = mocker.MagicMock()
mock_response.points = []
mock_client.query_points.return_value = mock_response
node = SearchStmt(collection="notes", query_text="hello", limit=5, model=None)
result = executor.execute(node)
mock_client.query_points.assert_called_once()
assert result.success is True
def test_search_nonexistent_collection_raises(self, executor, mock_client):
mock_client.collection_exists.return_value = False
node = SearchStmt(collection="ghost", query_text="hi", limit=3, model=None)
with pytest.raises(QQLRuntimeError, match="does not exist"):
executor.execute(node)
def test_search_with_exact_forwards_search_params(
self, executor, mock_client, mocker
):
mock_client.collection_exists.return_value = True
mock_response = mocker.MagicMock()
mock_response.points = []
mock_client.query_points.return_value = mock_response
node = SearchStmt(
collection="notes",
query_text="hello",
limit=5,
model=None,
with_clause=SearchWith(exact=True),
)
executor.execute(node)
search_params = mock_client.query_points.call_args.kwargs["search_params"]
assert search_params.exact is True
def test_search_with_acorn_forwards_search_params(
self, executor, mock_client, mocker
):
mock_client.collection_exists.return_value = True
mock_response = mocker.MagicMock()
mock_response.points = []
mock_client.query_points.return_value = mock_response
node = SearchStmt(
collection="notes",
query_text="hello",
limit=5,
model=None,
with_clause=SearchWith(hnsw_ef=128, acorn=True),
)
executor.execute(node)