qql 0.5.0

QQL runtime and executor for Qdrant REST and gRPC
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
//! gRPC converter tests (moved from `grpc_route.rs` unchanged).

use std::collections::HashMap;

use super::ddl::{
    hnsw_config_from_plan, quantization_config_from_plan, sparse_vectors_config_diff,
    strict_mode_config_from_plan, vector_params, vectors_config_diff, wal_config_from_plan,
};
use super::execute_write::{to_points_update_operation, update_result_to_typed};
use super::filter::{to_condition, to_match};
use super::query::{
    plan_vector_to_proto, to_count_points, to_facet_counts, to_query_groups, to_query_points,
    to_scroll_points, to_vector_input, to_vectors,
};
use super::typed::{
    collection_mutation_to_typed, facet_hit_to_typed, mutation_response_to_typed,
    point_group_to_typed, retrieved_point_to_hit, scored_point_to_hit, telemetry_from_proto,
    usage_to_json, usage_to_telemetry,
};
use crate::executor::{ExecData, ServerUsage};
use crate::qdrant_grpc::qdrant;
use qql_core::ast::{VectorDatatype, VectorDistance};
use qql_core::parser::Parser;
use qql_plan::types::{
    FieldCondition, FilterClause, FilterExpression, GeoLineString, GeoPoint, GeoPolygon, MatchValue,
};
use qql_plan::{
    DenseVectorParams, PlanFacetValue, PlanGroupId, PlanPointVectors, PlanQueryInput,
    PlanVectorStruct, PlanVectorValue,
};

fn dense_params(datatype: Option<VectorDatatype>) -> DenseVectorParams {
    DenseVectorParams {
        size: 128,
        distance: VectorDistance::Cosine,
        hnsw_config: None,
        quantization_config: None,
        on_disk: None,
        memory: None,
        datatype,
        multivector_config: None,
    }
}

#[test]
fn dense_vector_params_propagates_datatype() {
    let params = vector_params(&dense_params(Some(VectorDatatype::Uint8)));
    assert_eq!(params.datatype, Some(qdrant::Datatype::Uint8 as i32));

    let f16 = vector_params(&dense_params(Some(VectorDatatype::Float16)));
    assert_eq!(f16.datatype, Some(qdrant::Datatype::Float16 as i32));

    let none = vector_params(&dense_params(None));
    assert_eq!(none.datatype, None);
}

/// `ALTER COLLECTION` per-vector diffs convert directly into the typed
/// `UpdateCollection.vectors_config` oneof without a JSON hop.
#[test]
fn grpc_update_collection_converts_named_vector_diffs() {
    let stmt = Parser::parse(
        "ALTER COLLECTION docs \
         WITH VECTOR dense (HNSW (m = 32, inline_storage = true), QUANTIZATION (type = 'scalar', quantile = 0.99), VECTOR (memory = 'cold')) \
         WITH VECTOR colbert (QUANTIZATION (disabled = true)) \
         WITH SPARSE bm25 (SPARSE (modifier = 'idf', full_scan_threshold = 5000, datatype = 'float16'));",
    )
    .unwrap();
    let qql_plan::PlannedOperation::UpdateCollection { request, .. } =
        qql_plan::plan(&stmt).unwrap()
    else {
        panic!("expected UpdateCollection");
    };

    let proto = vectors_config_diff(request.vectors.as_ref().expect("vector diffs"));
    let Some(qdrant::vectors_config_diff::Config::ParamsMap(map)) = proto.config else {
        panic!("named diffs must use the params_map variant");
    };
    let dense = map.map.get("dense").expect("dense entry");
    assert_eq!(dense.hnsw_config.as_ref().and_then(|h| h.m), Some(32));
    assert_eq!(
        dense.hnsw_config.as_ref().and_then(|h| h.inline_storage),
        Some(true),
        "inline_storage must survive the typed → proto conversion"
    );
    assert_eq!(dense.memory, Some(qdrant::Memory::Cold as i32));
    match dense
        .quantization_config
        .as_ref()
        .and_then(|q| q.quantization.as_ref())
    {
        Some(qdrant::quantization_config_diff::Quantization::Scalar(scalar)) => {
            assert_eq!(scalar.quantile, Some(0.99));
        }
        other => panic!("expected scalar quantization, got {other:?}"),
    }

    let colbert = map.map.get("colbert").expect("colbert entry");
    assert!(matches!(
        colbert
            .quantization_config
            .as_ref()
            .and_then(|q| q.quantization.as_ref()),
        Some(qdrant::quantization_config_diff::Quantization::Disabled(_))
    ));

    let sparse = sparse_vectors_config_diff(request.sparse_vectors.as_ref().expect("sparse diffs"));
    let bm25 = sparse.map.get("bm25").expect("bm25 entry");
    assert_eq!(bm25.modifier, Some(qdrant::Modifier::Idf as i32));
    let index = bm25.index.as_ref().expect("sparse index");
    assert_eq!(index.full_scan_threshold, Some(5000));
    assert_eq!(index.datatype, Some(qdrant::Datatype::Float16 as i32));
}

/// The unnamed/default-vector diff uses the bare `params` oneof variant, the
/// same addressing create uses for a single unnamed vector.
#[test]
fn grpc_update_collection_default_vector_uses_params_variant() {
    let stmt = Parser::parse("ALTER COLLECTION docs WITH VECTOR (on_disk = true);").unwrap();
    let qql_plan::PlannedOperation::UpdateCollection { request, .. } =
        qql_plan::plan(&stmt).unwrap()
    else {
        panic!("expected UpdateCollection");
    };
    let proto = vectors_config_diff(request.vectors.as_ref().expect("vector diffs"));
    let Some(qdrant::vectors_config_diff::Config::Params(params)) = proto.config else {
        panic!("default vector diff must use the bare params variant");
    };
    assert_eq!(params.on_disk, Some(true));
    assert!(params.hnsw_config.is_none());
    assert!(params.quantization_config.is_none());
}

#[test]
fn test_grpc_route_conversion_all_statements() {
    let statements = [
        "QUERY TEXT 'search' MODEL 'test-model' FROM docs USING dense LIMIT 10;",
        "QUERY POINTS (1, 2, '550e8400-e29b-41d4-a716-446655440005') FROM docs WITH PAYLOAD INCLUDE ('title');",
        "SCROLL FROM docs WHERE status = 'active' LIMIT 50;",
        "UPSERT INTO docs VALUES {id: 1, text: 'hello', category: 'tech'} USING DENSE MODEL 'm';",
        "DELETE FROM docs WHERE category = 'old';",
        "UPDATE docs SET VECTOR dense = [0.1, 0.2] WHERE id = 1;",
        "UPDATE docs SET VECTOR VALUES {id: 1, vector: [0.1]}, {id: 2, vector: {dense: [0.2]}};",
        "UPDATE docs SET PAYLOAD = {status: 'ok'} WHERE id = 1;",
        "CREATE COLLECTION docs (dense VECTOR(384, COSINE), sparse SPARSE);",
        "ALTER COLLECTION docs WITH HNSW (m = 16);",
        "DROP COLLECTION docs;",
        "CREATE INDEX ON COLLECTION docs FOR title TYPE text;",
        "SHOW COLLECTIONS;",
        "SHOW COLLECTION docs;",
        "FACET category FROM docs WHERE status = 'active' LIMIT 10 EXACT true SHARD 'tenant_1';",
    ];

    for stmt_str in statements {
        let stmt =
            Parser::parse(stmt_str).unwrap_or_else(|e| panic!("parse failed for {stmt_str}: {e}"));
        let op = qql_plan::plan(&stmt).unwrap();
        match &op {
            qql_plan::PlannedOperation::Query {
                collection,
                request,
            } => {
                let grpc_req = to_query_points(request, collection);
                assert!(
                    grpc_req.is_ok(),
                    "to_query_points failed for {stmt_str}: {:?}",
                    grpc_req.err()
                );
            }
            qql_plan::PlannedOperation::QueryGroups {
                collection,
                request,
            } => {
                let grpc_req = to_query_groups(request, collection);
                assert!(
                    grpc_req.is_ok(),
                    "to_query_groups failed for {stmt_str}: {:?}",
                    grpc_req.err()
                );
            }
            qql_plan::PlannedOperation::GetPoints { request, .. } => {
                assert_eq!(request.ids.len(), 3);
            }
            qql_plan::PlannedOperation::Scroll { request, .. } => {
                assert!(request.filter.is_some());
            }
            qql_plan::PlannedOperation::Upsert { request, .. } => {
                assert_eq!(request.points.len(), 1);
            }
            qql_plan::PlannedOperation::Delete { request, .. } => {
                assert!(request.filter.is_some());
            }
            qql_plan::PlannedOperation::UpdateVectors { .. } => {}
            qql_plan::PlannedOperation::UpdatePayload { .. } => {}
            qql_plan::PlannedOperation::CreateCollection { request, .. } => {
                assert!(request.vectors.is_some() || request.hnsw_config.is_some());
            }
            qql_plan::PlannedOperation::UpdateCollection { .. } => {}
            qql_plan::PlannedOperation::CreateIndex { request, .. } => {
                assert_eq!(request.field_name, "title");
            }
            qql_plan::PlannedOperation::ClearPayload { .. } => {}
            qql_plan::PlannedOperation::DeleteVectors { .. } => {}
            qql_plan::PlannedOperation::Count { .. } => {}
            qql_plan::PlannedOperation::CreateShardKey { .. } => {}
            qql_plan::PlannedOperation::DropShardKey { .. } => {}
            qql_plan::PlannedOperation::Facet {
                collection,
                request,
            } => {
                let grpc_req = to_facet_counts(request, collection);
                assert!(
                    grpc_req.is_ok(),
                    "to_facet_counts failed for {stmt_str}: {:?}",
                    grpc_req.err()
                );
            }
            _ => {}
        }
    }
}

#[test]
fn converts_collection_quantization_and_vector_update() {
    let scalar = qql_plan::QuantizationConfig::Scalar {
        scalar: qql_plan::ScalarQuantization {
            qtype: "int8".into(),
            quantile: Some(0.95),
            always_ram: Some(true),
            memory: None,
        },
    };
    let q_proto = quantization_config_from_plan(&scalar);
    assert!(q_proto.is_some());

    let stmt = Parser::parse("UPDATE docs SET VECTOR dense = [0.1, 0.2] WHERE id = 1;").unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    if let qql_plan::PlannedOperation::UpdateVectors { request, .. } = op {
        assert_eq!(request.points.len(), 1);
    } else {
        panic!("expected UpdateVectors");
    }

    let batch = Parser::parse(
        "UPDATE docs SET VECTOR VALUES {id: 1, vector: [0.1]}, {id: 2, vector: {dense: [0.2]}};",
    )
    .unwrap();
    let op = qql_plan::plan(&batch).unwrap();
    let qql_plan::PlannedOperation::UpdateVectors { request, .. } = op else {
        panic!("expected UpdateVectors");
    };
    assert_eq!(request.points.len(), 2);
}

/// Query → gRPC with limit, offset, using, score_threshold
#[test]
fn query_points_field_level_basics() {
    let stmt = Parser::parse(
        "QUERY TEXT 'search' MODEL 'test-model' FROM my_coll USING dense SCORE THRESHOLD 0.7 LIMIT 10 OFFSET 5;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {:?}", other),
    };
    let qp = to_query_points(req, collection).unwrap();

    assert_eq!(qp.collection_name, "my_coll");
    assert_eq!(qp.limit, Some(10));
    assert_eq!(qp.offset, Some(5));
    assert_eq!(qp.using, Some("dense".into()));
    assert_eq!(qp.score_threshold, Some(0.7f32));
    // query variant should be Nearest with vector input
    let query = qp.query.expect("query should be set");
    assert!(matches!(
        query.variant,
        Some(qdrant::query::Variant::Nearest(_))
    ));
}

/// Query with WITH PAYLOAD INCLUDE + WITH VECTOR → gRPC selectors
#[test]
fn query_points_with_payload_and_vectors() {
    let stmt = Parser::parse(
        "QUERY TEXT 'x' MODEL 'test-model' FROM docs WITH PAYLOAD INCLUDE ('title', 'url') WITH VECTOR (dense) LIMIT 5;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {:?}", other),
    };
    let qp = to_query_points(req, collection).unwrap();

    // with_payload → selector_options.Include
    let wp = qp.with_payload.expect("with_payload should be set");
    match wp.selector_options.expect("selector_options should be set") {
        qdrant::with_payload_selector::SelectorOptions::Include(inc) => {
            assert!(inc.fields.contains(&"title".to_string()));
            assert!(inc.fields.contains(&"url".to_string()));
        }
        other => panic!("expected Include, got {:?}", other),
    }
    // with_vectors → selector_options.Include
    let wv = qp.with_vectors.expect("with_vectors should be set");
    match wv.selector_options.expect("selector_options should be set") {
        qdrant::with_vectors_selector::SelectorOptions::Include(inc) => {
            assert_eq!(inc.names, vec!["dense"]);
        }
        other => panic!("expected Include, got {:?}", other),
    }
}

/// Query with SHARD KEY → gRPC shard_key_selector
#[test]
fn query_points_shard_key() {
    let stmt = Parser::parse(
        "QUERY TEXT 'x' MODEL 'test-model' FROM docs USING dense SHARD 'tenant-42' LIMIT 5;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {:?}", other),
    };
    let qp = to_query_points(req, collection).unwrap();

    let sks = qp
        .shard_key_selector
        .expect("shard_key_selector should be set");
    assert_eq!(sks.shard_keys.len(), 1);
    match sks.shard_keys[0].key.as_ref().unwrap() {
        qdrant::shard_key::Key::Keyword(k) => assert_eq!(k, "tenant-42"),
        other => panic!("expected Keyword, got {:?}", other),
    }
}

/// Query with WHERE → gRPC filter present with must conditions
#[test]
fn query_points_filter_equality() {
    let stmt = Parser::parse(
        "QUERY TEXT 'x' MODEL 'test-model' FROM docs WHERE status = 'active' LIMIT 5;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {:?}", other),
    };
    let qp = to_query_points(req, collection).unwrap();

    let filter = qp.filter.expect("filter should be set");
    // Single condition wraps into must
    let must = &filter.must;
    assert_eq!(must.len(), 1, "expected 1 condition in must");
    let cond = &must[0];
    // condition_one_of should be Field with key="status"
    match cond.condition_one_of.as_ref().unwrap() {
        qdrant::condition::ConditionOneOf::Field(fc) => {
            assert_eq!(fc.key, "status");
            // match → Keyword("active")
            let mv = fc.r#match.as_ref().expect("match should be set");
            match mv.match_value.as_ref().unwrap() {
                qdrant::r#match::MatchValue::Keyword(kw) => assert_eq!(kw, "active"),
                _ => panic!("expected Keyword match"),
            }
        }
        other => panic!("expected Field condition, got {:?}", other),
    }
}

/// Query with AND → gRPC filter with 2 must conditions
#[test]
fn query_points_filter_range_compound() {
    let stmt = Parser::parse(
        "QUERY TEXT 'x' MODEL 'test-model' FROM docs WHERE age >= 18 AND age < 65 LIMIT 5;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {:?}", other),
    };
    let qp = to_query_points(req, collection).unwrap();
    let filter = qp.filter.expect("filter should be set");
    let must = &filter.must;
    assert_eq!(must.len(), 2, "expected 2 conditions for AND (>= and <)");
    // Both should be Field conditions on key "age" with Range
    for c in must {
        match c.condition_one_of.as_ref().unwrap() {
            qdrant::condition::ConditionOneOf::Field(fc) => {
                assert_eq!(fc.key, "age");
                assert!(fc.range.is_some(), "expected Range for age comparison");
            }
            _ => panic!("expected Field condition"),
        }
    }
}

/// Group-by query → gRPC QueryPointGroups with lookup
#[test]
fn query_points_group_by_with_lookup() {
    let stmt = Parser::parse(
        "QUERY TEXT 'x' MODEL 'test-model' FROM docs GROUP BY category SIZE 3 LOOKUP FROM categories LIMIT 10;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::QueryGroups {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected QueryGroups, got {:?}", other),
    };
    let qg = to_query_groups(req, collection).unwrap();

    assert_eq!(qg.group_by, "category");
    assert_eq!(qg.group_size, Some(3));
    assert_eq!(qg.limit, Some(10));
    let lookup = qg.with_lookup.expect("with_lookup should be set");
    assert_eq!(lookup.collection, "categories");
}

/// CreateCollection → gRPC vectors config + HNSW validation
#[test]
fn create_collection_vectors_and_hnsw() {
    let stmt = Parser::parse(
        "CREATE COLLECTION docs (dense VECTOR(384, COSINE)) WITH HNSW (m = 32, ef_construct = 100);",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let req = match &op {
        qql_plan::PlannedOperation::CreateCollection { request, .. } => request,
        other => panic!("expected CreateCollection, got {:?}", other),
    };

    // vectors should contain dense → size 384, distance Cosine
    let vectors = req.vectors.as_ref().expect("vectors should be set");
    let qql_plan::DenseVectorsConfig::Named(map) = vectors else {
        panic!("expected named vectors, got {vectors:?}");
    };
    let dense = map.get("dense").expect("dense vector config missing");
    assert_eq!(dense.size, 384);
    assert_eq!(dense.distance, VectorDistance::Cosine);

    // HNSW → gRPC conversion with m + ef_construct
    let hnsw_json = req.hnsw_config.as_ref().expect("hnsw_config should be set");
    let hnsw = hnsw_config_from_plan(hnsw_json);
    assert_eq!(hnsw.m, Some(32));
    assert_eq!(hnsw.ef_construct, Some(100));
}

/// CreateCollection → gRPC WAL + strict mode + metadata validation
#[test]
fn create_collection_wal_strict_mode_metadata() {
    let stmt = Parser::parse(
        "CREATE COLLECTION docs (dense VECTOR(384, COSINE)) \
         WITH WAL (wal_capacity_mb = 64, wal_segments_ahead = 4) \
         WITH STRICT_MODE (enabled = true, max_query_limit = 50) \
         WITH METADATA (env = 'prod');",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let req = match &op {
        qql_plan::PlannedOperation::CreateCollection { request, .. } => request,
        other => panic!("expected CreateCollection, got {:?}", other),
    };

    let wal_json = req.wal_config.as_ref().expect("wal_config should be set");
    let wal = wal_config_from_plan(wal_json);
    assert_eq!(wal.wal_capacity_mb, Some(64));
    assert_eq!(wal.wal_segments_ahead, Some(4));

    let strict_json = req
        .strict_mode_config
        .as_ref()
        .expect("strict_mode_config should be set");
    let strict = strict_mode_config_from_plan(strict_json).unwrap();
    assert_eq!(strict.enabled, Some(true));
    assert_eq!(strict.max_query_limit, Some(50));

    let metadata = req.metadata.as_ref().expect("metadata should be set");
    assert_eq!(
        metadata
            .iter()
            .find(|(k, _)| k == "env")
            .and_then(|(_, v)| v.as_str()),
        Some("prod")
    );
}

/// Upsert → gRPC point count + shard key
#[test]
fn upsert_points_field_level() {
    let stmt =
        Parser::parse("UPSERT INTO docs VALUES {id: 1, text: 'hello'}, {id: 2, text: 'world'};")
            .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let req = match &op {
        qql_plan::PlannedOperation::Upsert { request, .. } => request,
        other => panic!("expected Upsert, got {:?}", other),
    };

    assert_eq!(req.points.len(), 2);
    assert!(req.shard_key.is_none());
}

/// DELETE with compound filter → gRPC must conditions present
#[test]
fn delete_with_compound_filter() {
    let stmt =
        Parser::parse("DELETE FROM docs WHERE category = 'archived' AND priority < 3;").unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let req = match &op {
        qql_plan::PlannedOperation::Delete { request, .. } => request,
        other => panic!("expected Delete, got {:?}", other),
    };

    let filter = req.filter.as_ref().expect("delete filter should be set");
    match filter {
        FilterExpression::Compound(fc) => {
            assert_eq!(
                fc.must.len(),
                2,
                "expected 2 conditions in compound AND filter"
            );
        }
        other => panic!(
            "expected Compound filter, got {:?}",
            std::mem::discriminant(other)
        ),
    }
}

/// Order-by query → gRPC OrderBy variant + filter
#[test]
fn query_order_by_direction() {
    let stmt =
        Parser::parse("QUERY ORDER BY created_at DESC FROM docs WHERE status = 'active' LIMIT 20;")
            .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {:?}", other),
    };
    let qp = to_query_points(req, collection).unwrap();

    let query = qp.query.expect("query should be set");
    match query.variant.expect("variant should be set") {
        qdrant::query::Variant::OrderBy(ob) => {
            assert_eq!(ob.key, "created_at");
            assert_eq!(ob.direction, Some(qdrant::Direction::Desc as i32));
        }
        other => panic!("expected OrderBy variant, got {:?}", other),
    }
    // Filter should be present
    assert!(qp.filter.is_some(), "filter should be set for WHERE clause");
}

/// RRF `k` + `weights` survive the gRPC conversion (regression: they were
/// silently dropped into a bare `Fusion(1)`).
#[test]
fn grpc_rrf_params_are_transmitted() {
    let stmt = Parser::parse(
        "QUERY HYBRID TEXT 'search' MODEL 'bge' DENSE dense SPARSE sparse FUSION RRF \
         FROM docs PARAMS (rrf_k = 5, rrf_weights = [1.0, 0.5]) LIMIT 10;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {:?}", other),
    };
    let qp = to_query_points(req, collection).unwrap();
    use qdrant::query::Variant as Qv;
    match qp.query.as_ref().and_then(|q| q.variant.as_ref()) {
        Some(Qv::Rrf(rrf)) => {
            assert_eq!(rrf.k, Some(5), "rrf k must be transmitted");
            assert_eq!(rrf.weights, vec![1.0, 0.5]);
        }
        other => panic!("expected Rrf variant, got {other:?}"),
    }
}

/// RRF values that the pinned proto cannot represent exactly must produce
/// structured errors, never silent loss.
#[test]
fn grpc_rrf_unrepresentable_values_error() {
    // k beyond uint32 range.
    let stmt = Parser::parse(
        "QUERY HYBRID TEXT 'search' MODEL 'bge' DENSE dense SPARSE sparse FUSION RRF \
         FROM docs PARAMS (rrf_k = 4294967296) LIMIT 10;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {:?}", other),
    };
    let err = to_query_points(req, collection).unwrap_err();
    assert_eq!(err.kind, qql_core::error::ErrorKind::Validation);
    assert_eq!(err.code, "QQL-GRPC-RRF-K");
    assert!(err.message.contains("rrf_k"));

    // Weight that does not round-trip f64 → f32 exactly (0.1 in f32 is
    // 0.10000000149011612…).
    let stmt = Parser::parse(
        "QUERY HYBRID TEXT 'search' MODEL 'bge' DENSE dense SPARSE sparse FUSION RRF \
         FROM docs PARAMS (rrf_weights = [1.0, 0.1]) LIMIT 10;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {:?}", other),
    };
    let err = to_query_points(req, collection).unwrap_err();
    assert_eq!(err.code, "QQL-GRPC-RRF-WEIGHT");
    assert!(err.message.contains("0.1"));
}

/// Fusion methods must map to the correct proto enum values (RRF=0,
/// DBSF=1); previously "rrf" was mapped to 1 (DBSF) and "dbsf" to an
/// undefined 2.
#[test]
fn grpc_fusion_method_maps_to_correct_enum() {
    use qdrant::query::Variant as Qv;

    let stmt = Parser::parse(
        "QUERY HYBRID TEXT 'search' MODEL 'bge' DENSE dense SPARSE sparse FUSION RRF FROM docs LIMIT 10;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {:?}", other),
    };
    let qp = to_query_points(req, collection).unwrap();
    match qp.query.as_ref().and_then(|q| q.variant.as_ref()) {
        Some(Qv::Fusion(f)) => assert_eq!(*f, qdrant::Fusion::Rrf as i32),
        other => panic!("expected Fusion(Rrf), got {other:?}"),
    }

    let stmt = Parser::parse(
        "QUERY HYBRID TEXT 'search' MODEL 'bge' DENSE dense SPARSE sparse FUSION DBSF FROM docs LIMIT 10;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {:?}", other),
    };
    let qp = to_query_points(req, collection).unwrap();
    match qp.query.as_ref().and_then(|q| q.variant.as_ref()) {
        Some(Qv::Fusion(f)) => assert_eq!(*f, qdrant::Fusion::Dbsf as i32),
        other => panic!("expected Fusion(Dbsf), got {other:?}"),
    }
}

/// Float equality filters lower to `range` (gte == lte) in the plan, so the
/// gRPC path converts them exactly like REST: no `QQL-GRPC-FLOAT-MATCH`, no
/// integer coercion (`2.0` stays a float bound).
#[test]
fn grpc_float_equality_filter_is_range() {
    for (sql, expected) in [
        (
            "QUERY TEXT 'x' MODEL 'test-model' FROM docs WHERE rating = 1.5 LIMIT 5;",
            1.5,
        ),
        (
            "QUERY TEXT 'x' MODEL 'test-model' FROM docs WHERE rating = 2.0 LIMIT 5;",
            2.0,
        ),
    ] {
        let stmt = Parser::parse(sql).unwrap();
        let op = qql_plan::plan(&stmt).unwrap();
        let (collection, req) = match &op {
            qql_plan::PlannedOperation::Query {
                collection,
                request,
            } => (collection, request),
            other => panic!("expected Query, got {:?}", other),
        };
        let qp = to_query_points(req, collection).unwrap();
        let filter = qp.filter.expect("filter should be set");
        let range = filter.must[0]
            .condition_one_of
            .as_ref()
            .and_then(|c| match c {
                qdrant::condition::ConditionOneOf::Field(f) => f.range.as_ref(),
                _ => None,
            })
            .expect("field range");
        assert_eq!(range.gte, Some(expected));
        assert_eq!(range.lte, Some(expected));
        assert_eq!(range.gt, None);
        assert_eq!(range.lt, None);
    }
}

/// GetPoints must keep every hit (B-3 regression): the retired JSON path
/// silently dropped them when the envelope shape was wrong, and the typed path
/// maps every `RetrievedPoint` straight into a hit.
#[test]
fn typed_get_points_keeps_every_hit() {
    let point = |id: u64, title: &str| qdrant::RetrievedPoint {
        id: Some(qdrant::PointId {
            point_id_options: Some(qdrant::point_id::PointIdOptions::Num(id)),
        }),
        payload: [(
            "title".to_string(),
            proto_value(qdrant::value::Kind::StringValue(title.to_string())),
        )]
        .into_iter()
        .collect(),
        vectors: None,
        shard_key: None,
        order_value: None,
    };

    let hits: Vec<_> = vec![point(1, "a"), point(2, "b")]
        .into_iter()
        .map(|point| retrieved_point_to_hit(point).expect("retrieved point converts"))
        .collect();
    assert_eq!(hits.len(), 2, "GetPoints hits must survive conversion");
    assert_eq!(hits[0].id, qql_plan::PlanPointId::Number(1));
    assert_eq!(hits[1].id, qql_plan::PlanPointId::Number(2));
    assert_eq!(
        hits[1].payload.as_ref().expect("payload")["title"],
        serde_json::json!("b")
    );
}

/// IN/NOT IN lists must be homogeneous and int64-representable: valid
/// string/integer lists survive, while mixed lists, non-integral floats,
/// and `u64` values above `i64::MAX` produce structured errors instead of
/// being silently dropped or wrapped into negative integers.
#[test]
fn grpc_exact_list_match_is_homogeneous_and_fallible() {
    // Homogeneous string list → keywords.
    let mv = to_match(&MatchValue::Any {
        any: vec![
            qql_core::ast::Value::Str("a".into()),
            qql_core::ast::Value::Str("b".into()),
        ],
    })
    .unwrap();
    match mv.match_value.unwrap() {
        qdrant::r#match::MatchValue::Keywords(k) => {
            assert_eq!(k.strings, vec!["a", "b"]);
        }
        other => panic!("expected Keywords, got {other:?}"),
    }

    // Homogeneous string list via Except → except_keywords.
    let mv = to_match(&MatchValue::Except {
        except: vec![
            qql_core::ast::Value::Str("a".into()),
            qql_core::ast::Value::Str("b".into()),
        ],
    })
    .unwrap();
    match mv.match_value.unwrap() {
        qdrant::r#match::MatchValue::ExceptKeywords(k) => {
            assert_eq!(k.strings, vec!["a", "b"]);
        }
        other => panic!("expected ExceptKeywords, got {other:?}"),
    }

    // Homogeneous integer list (positive and negative) → integers.
    let mv = to_match(&MatchValue::Any {
        any: vec![
            qql_core::ast::Value::Int(1),
            qql_core::ast::Value::Int(-2),
            qql_core::ast::Value::Int(3),
        ],
    })
    .unwrap();
    match mv.match_value.unwrap() {
        qdrant::r#match::MatchValue::Integers(k) => {
            assert_eq!(k.integers, vec![1, -2, 3]);
        }
        other => panic!("expected Integers, got {other:?}"),
    }

    // Homogeneous integer list via Except → except_integers.
    let mv = to_match(&MatchValue::Except {
        except: vec![qql_core::ast::Value::Int(10), qql_core::ast::Value::Int(20)],
    })
    .unwrap();
    match mv.match_value.unwrap() {
        qdrant::r#match::MatchValue::ExceptIntegers(k) => {
            assert_eq!(k.integers, vec![10, 20]);
        }
        other => panic!("expected ExceptIntegers, got {other:?}"),
    }

    // Integral floats map to integer matches, mirroring single-value
    // `WHERE x = 2.0` → Integer(2).
    let mv = to_match(&MatchValue::Any {
        any: vec![
            qql_core::ast::Value::Float(2.0),
            qql_core::ast::Value::Float(3.0),
        ],
    })
    .unwrap();
    match mv.match_value.unwrap() {
        qdrant::r#match::MatchValue::Integers(k) => {
            assert_eq!(k.integers, vec![2, 3]);
        }
        other => panic!("expected Integers, got {other:?}"),
    }
}

#[test]
fn grpc_exact_list_match_rejects_unrepresentable() {
    // Mixed string + integer list → structured error, not a silent drop
    // of the integer entry.
    let err = to_match(&MatchValue::Any {
        any: vec![
            qql_core::ast::Value::Str("a".into()),
            qql_core::ast::Value::Int(1),
        ],
    })
    .unwrap_err();
    assert_eq!(err.kind, qql_core::error::ErrorKind::Validation);
    assert_eq!(err.code, "QQL-GRPC-LIST-TYPE");
    assert!(err.message.contains("mixes strings"), "{err}");

    // Non-integral floats have no list encoding → structured error.
    let err = to_match(&MatchValue::Any {
        any: vec![
            qql_core::ast::Value::Float(1.5),
            qql_core::ast::Value::Float(2.5),
        ],
    })
    .unwrap_err();
    assert_eq!(err.kind, qql_core::error::ErrorKind::Validation);
    assert_eq!(err.code, "QQL-GRPC-LIST-TYPE");
    assert!(err.message.contains("1.5"), "{err}");

    // A float mixed into a string list is caught as heterogeneous.
    let err = to_match(&MatchValue::Except {
        except: vec![
            qql_core::ast::Value::Str("a".into()),
            qql_core::ast::Value::Float(1.5),
        ],
    })
    .unwrap_err();
    assert_eq!(err.code, "QQL-GRPC-LIST-TYPE");
    assert!(err.message.contains("mixes strings"), "{err}");

    // Booleans are unrepresentable in either list form.
    let err = to_match(&MatchValue::Any {
        any: vec![
            qql_core::ast::Value::Bool(true),
            qql_core::ast::Value::Bool(false),
        ],
    })
    .unwrap_err();
    assert_eq!(err.code, "QQL-GRPC-LIST-TYPE");
    assert!(err.message.contains("true"), "{err}");

    // u64 above i64::MAX must error, never wrap into a negative integer.
    let oversized = i64::MAX as u64 + 1;
    let err = to_match(&MatchValue::Any {
        any: vec![qql_core::ast::Value::UInt(oversized)],
    })
    .unwrap_err();
    assert_eq!(err.kind, qql_core::error::ErrorKind::Validation);
    assert_eq!(err.code, "QQL-GRPC-LIST-INT");
    assert!(err.message.contains("9223372036854775808"), "{err}");

    // The scalar form fails closed too (no proto `Match` field can carry it).
    let err = to_match(&MatchValue::Value {
        value: qql_core::ast::Value::UInt(oversized),
    })
    .unwrap_err();
    assert_eq!(err.kind, qql_core::error::ErrorKind::Validation);
    assert_eq!(err.code, "QQL-GRPC-FLOAT-MATCH");
}

/// Unrepresentable match lists are rejected at plan time, before any
/// transport conversion; the transport guards below stay for hand-built plans.
#[test]
fn plan_rejects_unrepresentable_match_lists_before_transport() {
    for (source, offending) in [
        (
            "QUERY TEXT 'x' MODEL 'test-model' FROM docs WHERE status IN ('a', 1) LIMIT 5;",
            "mixes",
        ),
        (
            "QUERY TEXT 'x' MODEL 'test-model' FROM docs WHERE rating IN (1.5, 2.5) LIMIT 5;",
            "1.5",
        ),
    ] {
        let stmt = Parser::parse(source).unwrap();
        let err = qql_plan::plan(&stmt).unwrap_err();
        assert_eq!(err.kind, qql_core::error::ErrorKind::Validation);
        assert_eq!(err.code, "QQL-PLAN-MATCH-TYPE", "{source}: {err:?}");
        assert!(err.message.contains(offending), "{source}: {err:?}");
    }
}

/// Valid homogeneous lists survive the full parser → plan → gRPC path.
#[test]
fn grpc_in_list_homogeneous_lists_survive_full_path() {
    // String list → keywords.
    let stmt = Parser::parse(
        "QUERY TEXT 'x' MODEL 'test-model' FROM docs WHERE status IN ('a', 'b') LIMIT 5;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {other:?}"),
    };
    let qp = to_query_points(req, collection).unwrap();
    let filter = qp.filter.expect("filter should be set");
    let mv = filter.must[0]
        .condition_one_of
        .as_ref()
        .and_then(|c| match c {
            qdrant::condition::ConditionOneOf::Field(f) => f.r#match.as_ref(),
            _ => None,
        })
        .expect("field match");
    match mv.match_value.as_ref().unwrap() {
        qdrant::r#match::MatchValue::Keywords(k) => {
            assert_eq!(k.strings, vec!["a", "b"]);
        }
        other => panic!("expected Keywords, got {other:?}"),
    }

    // Integer list → integers.
    let stmt = Parser::parse(
        "QUERY TEXT 'x' MODEL 'test-model' FROM docs WHERE year IN (2024, 2025) LIMIT 5;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {other:?}"),
    };
    let qp = to_query_points(req, collection).unwrap();
    let filter = qp.filter.expect("filter should be set");
    let mv = filter.must[0]
        .condition_one_of
        .as_ref()
        .and_then(|c| match c {
            qdrant::condition::ConditionOneOf::Field(f) => f.r#match.as_ref(),
            _ => None,
        })
        .expect("field match");
    match mv.match_value.as_ref().unwrap() {
        qdrant::r#match::MatchValue::Integers(k) => {
            assert_eq!(k.integers, vec![2024, 2025]);
        }
        other => panic!("expected Integers, got {other:?}"),
    }

    // NOT IN lowers to a `must_not` condition that still carries the
    // keyword list.
    let stmt = Parser::parse(
        "QUERY TEXT 'x' MODEL 'test-model' FROM docs WHERE status NOT IN ('deleted', 'archived') LIMIT 5;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {other:?}"),
    };
    let qp = to_query_points(req, collection).unwrap();
    let filter = qp.filter.expect("filter should be set");
    assert_eq!(filter.must_not.len(), 1, "NOT IN should lower to must_not");
    let mv = filter.must_not[0]
        .condition_one_of
        .as_ref()
        .and_then(|c| match c {
            qdrant::condition::ConditionOneOf::Field(f) => f.r#match.as_ref(),
            _ => None,
        })
        .expect("field match");
    match mv.match_value.as_ref().unwrap() {
        qdrant::r#match::MatchValue::Keywords(k) => {
            assert_eq!(k.strings, vec!["deleted", "archived"]);
        }
        other => panic!("expected Keywords, got {other:?}"),
    }
}

#[test]
fn scroll_limit_overflow_is_rejected_in_grpc() {
    let stmt = Parser::parse("SCROLL FROM docs LIMIT 18446744073709551615;").unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Scroll {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Scroll, got {other:?}"),
    };
    let err = to_scroll_points(req, collection).unwrap_err();
    assert_eq!(err.code, "QQL-GRPC-SCROLL-LIMIT");
    assert!(err.message.contains("scroll limit"));
}

/// `GEO_POLYGON` must reach the proto `FieldCondition.geo_polygon` or REST and
/// gRPC match different rows for the same query text.
#[test]
fn query_points_filter_geo_polygon_maps_proto() {
    let stmt = Parser::parse(
        "QUERY TEXT 'x' MODEL 'test-model' FROM docs WHERE area GEO_POLYGON \
         {exterior: [{lat: -70.0, lon: -70.0}, {lat: 60.0, lon: -70.0}, {lat: 60.0, lon: 60.0}, {lat: -70.0, lon: 60.0}], \
          interiors: [[{lat: -50.0, lon: -50.0}, {lat: 50.0, lon: -50.0}, {lat: 50.0, lon: 50.0}, {lat: -50.0, lon: 50.0}]]};",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {other:?}"),
    };
    let qp = to_query_points(req, collection).unwrap();
    let condition = qp.filter.expect("filter should be set").must.swap_remove(0);
    let Some(qdrant::condition::ConditionOneOf::Field(field)) = condition.condition_one_of else {
        panic!("expected a field condition, got {condition:?}");
    };
    let polygon = field.geo_polygon.expect("geo_polygon must map to proto");
    let exterior = polygon.exterior.expect("exterior ring must map");
    assert_eq!(exterior.points.len(), 4);
    assert_eq!(exterior.points[0].lat, -70.0);
    assert_eq!(exterior.points[0].lon, -70.0);
    assert_eq!(exterior.points[3].lon, 60.0);
    assert_eq!(polygon.interiors.len(), 1, "interior holes must map");
    assert_eq!(polygon.interiors[0].points.len(), 4);
    assert_eq!(polygon.interiors[0].points[2].lat, 50.0);
}

/// A hand-built degenerate ring fails closed instead of reaching the wire as a
/// polygon the server cannot interpret.
#[test]
fn geo_polygon_degenerate_ring_fails_closed() {
    let ring = |n: usize| GeoLineString {
        points: (0..n)
            .map(|i| GeoPoint {
                lat: i as f64,
                lon: i as f64,
            })
            .collect(),
    };
    let clause = FilterClause::Field(Box::new(FieldCondition {
        key: "area".into(),
        geo_polygon: Some(GeoPolygon {
            exterior: ring(2),
            interiors: Vec::new(),
        }),
        ..Default::default()
    }));
    let err = to_condition(&clause).unwrap_err();
    assert_eq!(err.code, "QQL-GRPC-GEO-POLYGON");
    assert!(err.message.contains("at least 3"));

    let clause = FilterClause::Field(Box::new(FieldCondition {
        key: "area".into(),
        geo_polygon: Some(GeoPolygon {
            exterior: ring(3),
            interiors: vec![ring(1)],
        }),
        ..Default::default()
    }));
    let err = to_condition(&clause).unwrap_err();
    assert_eq!(err.code, "QQL-GRPC-GEO-POLYGON");
    assert!(err.message.contains("interior"));
}

/// `SCROLL … ORDER BY` must reach `ScrollPoints.order_by`; dropping it makes
/// gRPC scroll in ID order while REST scrolls in payload order.
#[test]
fn scroll_points_order_by_maps_proto() {
    let stmt = Parser::parse("SCROLL FROM docs ORDER BY ts DESC START FROM 42 LIMIT 10;").unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Scroll {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Scroll, got {other:?}"),
    };
    let sp = to_scroll_points(req, collection).unwrap();
    let order_by = sp.order_by.expect("scroll order_by must map to proto");
    assert_eq!(order_by.key, "ts");
    assert_eq!(order_by.direction, Some(qdrant::Direction::Desc as i32));
    match order_by.start_from.and_then(|sf| sf.value) {
        Some(qdrant::start_from::Value::Integer(42)) => {}
        other => panic!("expected integer START FROM 42, got {other:?}"),
    }
}

/// `ORDER BY … START FROM` must reach the proto `StartFrom` oneof too (the
/// query arm used to drop it).
#[test]
fn query_order_by_start_from_maps_proto() {
    let stmt = Parser::parse(
        "QUERY ORDER BY created_at ASC START FROM '2024-01-01T00:00:00Z' FROM docs LIMIT 10;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {other:?}"),
    };
    let qp = to_query_points(req, collection).unwrap();
    match qp.query.and_then(|q| q.variant) {
        Some(qdrant::query::Variant::OrderBy(order_by)) => {
            assert_eq!(order_by.key, "created_at");
            assert_eq!(order_by.direction, Some(qdrant::Direction::Asc as i32));
            match order_by.start_from.and_then(|sf| sf.value) {
                Some(qdrant::start_from::Value::Datetime(text)) => {
                    assert_eq!(text, "2024-01-01T00:00:00Z");
                }
                other => panic!("expected datetime START FROM, got {other:?}"),
            }
        }
        other => panic!("expected OrderBy variant, got {other:?}"),
    }
}

/// Per-item `UpdateBatch` statuses follow the same policy as REST:
/// acknowledged/completed succeed, wait_timeout and clock-rejected are
/// per-item failures, unknown values fail closed.
#[test]
fn update_batch_statuses_map_strictly() {
    use qdrant::UpdateStatus;
    let convert = |status: UpdateStatus| {
        update_result_to_typed(qdrant::UpdateResult {
            operation_id: Some(1),
            status: status as i32,
        })
    };
    assert!(convert(UpdateStatus::Acknowledged).is_ok());
    assert!(convert(UpdateStatus::Completed).is_ok());

    let err = convert(UpdateStatus::WaitTimeout).unwrap_err();
    assert_eq!(err.code, "QQL-BACKEND-BATCH");
    assert!(err.message.contains("wait_timeout"));
    let err = convert(UpdateStatus::ClockRejected).unwrap_err();
    assert_eq!(err.code, "QQL-BACKEND-BATCH");

    let err = update_result_to_typed(qdrant::UpdateResult {
        operation_id: None,
        status: 99,
    })
    .unwrap_err();
    assert_eq!(err.code, "QQL-BACKEND-ENVELOPE");
}

/// `COUNT … EXACT false` must stay approximate on gRPC; it used to be forced
/// exact.
#[test]
fn count_points_forwards_exact() {
    let stmt = Parser::parse("COUNT FROM docs WITH (exact = false);").unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Count {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Count, got {other:?}"),
    };
    assert_eq!(to_count_points(req, collection).unwrap().exact, Some(false));

    let stmt = Parser::parse("COUNT FROM docs;").unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Count {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Count, got {other:?}"),
    };
    assert_eq!(to_count_points(req, collection).unwrap().exact, Some(true));
}

#[test]
fn grpc_rerank_with_cte_prefetch_preserves_structure() {
    use qdrant::query::Variant as Qv;
    use qdrant::vector_input::Variant as Vi;

    let stmt = Parser::parse(
        "WITH a AS (QUERY TEXT 'candidate text' MODEL 'e5' FROM docs USING dense LIMIT 20) \
         QUERY RERANK TEXT 'query text' MODEL 'colbert' FROM docs USING colbert PREFETCH (a) LIMIT 10;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {other:?}"),
    };
    let qp = to_query_points(req, collection).unwrap();

    // Verify top-level query is Nearest with colbert model and document input
    assert_eq!(qp.collection_name, "docs");
    assert_eq!(qp.using, Some("colbert".to_string()));
    assert_eq!(qp.limit, Some(10));
    match qp.query.and_then(|q| q.variant) {
        Some(Qv::Nearest(near)) => match near.variant {
            Some(Vi::Document(doc)) => {
                assert_eq!(doc.text, "query text");
                assert_eq!(doc.model, "colbert");
            }
            other => panic!("expected Document variant, got {other:?}"),
        },
        other => panic!("expected Nearest query, got {other:?}"),
    }

    // Verify prefetch preserved CTE candidate query structure
    assert_eq!(qp.prefetch.len(), 1);
    let pf = &qp.prefetch[0];
    assert_eq!(pf.limit, Some(20));
    assert_eq!(pf.using, Some("dense".to_string()));
    match pf.query.as_ref().and_then(|q| q.variant.as_ref()) {
        Some(Qv::Nearest(near)) => match near.variant.as_ref() {
            Some(Vi::Document(doc)) => {
                assert_eq!(doc.text, "candidate text");
                assert_eq!(doc.model, "e5");
            }
            other => panic!("expected Document variant in prefetch, got {other:?}"),
        },
        other => panic!("expected Nearest query in prefetch, got {other:?}"),
    }
}

#[test]
fn grpc_fusion_rrf_standalone_with_params() {
    use qdrant::query::Variant as Qv;

    // Direct fusion with rrf_k and rrf_weights
    let stmt = Parser::parse(
        "QUERY FUSION RRF FROM docs \
         PREFETCH (QUERY TEXT 'a' MODEL 'm' FROM docs USING dense LIMIT 10, \
                   QUERY TEXT 'b' MODEL 'm' FROM docs USING dense LIMIT 10) \
         PARAMS (rrf_k = 10, rrf_weights = [0.75, 0.25]) LIMIT 5;",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {other:?}"),
    };
    let qp = to_query_points(req, collection).unwrap();
    match qp.query.and_then(|q| q.variant) {
        Some(Qv::Rrf(rrf)) => {
            assert_eq!(rrf.k, Some(10));
            assert_eq!(rrf.weights, vec![0.75, 0.25]);
        }
        other => panic!("expected Rrf variant, got {other:?}"),
    }

    // Direct fusion with default params maps to Fusion::Rrf enum
    let stmt_default = Parser::parse(
        "QUERY FUSION RRF FROM docs \
         PREFETCH (QUERY TEXT 'a' MODEL 'm' FROM docs USING dense LIMIT 10, \
                   QUERY TEXT 'b' MODEL 'm' FROM docs USING dense LIMIT 10) LIMIT 5;",
    )
    .unwrap();
    let op_default = qql_plan::plan(&stmt_default).unwrap();
    let (collection, req_default) = match &op_default {
        qql_plan::PlannedOperation::Query {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Query, got {other:?}"),
    };
    let qp_default = to_query_points(req_default, collection).unwrap();
    match qp_default.query.and_then(|q| q.variant) {
        Some(Qv::Fusion(f)) => {
            assert_eq!(f, qdrant::Fusion::Rrf as i32);
        }
        other => panic!("expected Fusion(Rrf), got {other:?}"),
    }
}

#[test]
fn facet_counts_conversion_matches_plan() {
    let stmt = Parser::parse(
        "FACET room_type FROM stays WHERE price < 150 LIMIT 5 EXACT true SHARD 'tenant_1';",
    )
    .unwrap();
    let op = qql_plan::plan(&stmt).unwrap();
    let (collection, req) = match &op {
        qql_plan::PlannedOperation::Facet {
            collection,
            request,
        } => (collection, request),
        other => panic!("expected Facet, got {other:?}"),
    };

    let fc = to_facet_counts(req, collection).unwrap();
    assert_eq!(fc.collection_name, "stays");
    assert_eq!(fc.key, "room_type");
    assert_eq!(fc.limit, Some(5));
    assert_eq!(fc.exact, Some(true));
    assert!(fc.filter.is_some());
    match &fc.shard_key_selector {
        Some(sks) => {
            assert_eq!(sks.shard_keys.len(), 1);
            assert_eq!(
                sks.shard_keys[0].key.as_ref(),
                Some(&qdrant::shard_key::Key::Keyword("tenant_1".to_string()))
            );
        }
        None => panic!("expected shard_key_selector to be set"),
    }
}

#[test]
fn facet_hit_to_typed_handles_all_variants() {
    use qdrant::facet_value::Variant;
    use qdrant::{FacetHit, FacetValue};

    let cases = [
        (
            FacetHit {
                value: Some(FacetValue {
                    variant: Some(Variant::StringValue("hotel".to_string())),
                }),
                count: 42,
            },
            PlanFacetValue::Keyword("hotel".to_string()),
            42,
        ),
        (
            FacetHit {
                value: Some(FacetValue {
                    variant: Some(Variant::IntegerValue(101)),
                }),
                count: 7,
            },
            PlanFacetValue::Integer(101),
            7,
        ),
        (
            FacetHit {
                value: Some(FacetValue {
                    variant: Some(Variant::BoolValue(true)),
                }),
                count: 99,
            },
            PlanFacetValue::Bool(true),
            99,
        ),
    ];
    for (proto, value, count) in cases {
        let typed = facet_hit_to_typed(proto).expect("facet converts");
        assert_eq!(typed.value, value);
        assert_eq!(typed.count, count);
    }

    // A facet hit without a value is a backend contract violation.
    let error = facet_hit_to_typed(FacetHit {
        value: None,
        count: 0,
    })
    .unwrap_err();
    assert_eq!(error.code, "QQL-BACKEND-ENVELOPE");
}

/// RT-01: unbound vector params fail closed on the gRPC path (an error, never
/// a panic). `ensure_no_unbound_params` / `validate_no_unbound_scalar_params`
/// gate the normal paths; these pins cover a hand-built plan bypassing them.
#[test]
fn grpc_to_vector_input_rejects_unbound_params() {
    let named = PlanQueryInput::Vector(PlanVectorValue::Param("q".to_string()));
    let err = to_vector_input(&named).unwrap_err();
    assert_eq!(err.code, "QQL-BIND-UNBOUND-PARAM");

    let positional = PlanQueryInput::Vector(PlanVectorValue::PositionalParam(0));
    let err = to_vector_input(&positional).unwrap_err();
    assert_eq!(err.code, "QQL-BIND-MISSING-POSITIONAL");
}

/// RT-01: `plan_vector_to_proto` returns `QQL-BIND-*`, never panics.
#[test]
fn grpc_plan_vector_to_proto_rejects_unbound_params() {
    let err = plan_vector_to_proto(&PlanVectorValue::Param("v".to_string())).unwrap_err();
    assert_eq!(err.code, "QQL-BIND-UNBOUND-PARAM");

    let err = plan_vector_to_proto(&PlanVectorValue::PositionalParam(2)).unwrap_err();
    assert_eq!(err.code, "QQL-BIND-MISSING-POSITIONAL");
}

/// RT-01: `to_vectors` returns `QQL-BIND-*`, never panics.
#[test]
fn grpc_to_vectors_rejects_unbound_params() {
    let err = to_vectors(&PlanPointVectors::Param("vecs".to_string())).unwrap_err();
    assert_eq!(err.code, "QQL-BIND-UNBOUND-PARAM");

    let err = to_vectors(&PlanPointVectors::PositionalParam(1)).unwrap_err();
    assert_eq!(err.code, "QQL-BIND-MISSING-POSITIONAL");
}

// ── Typed read path: proto → BackendResponse, no JSON in between ──

fn proto_value(kind: qdrant::value::Kind) -> qdrant::Value {
    qdrant::Value { kind: Some(kind) }
}

fn sample_hardware_usage() -> qdrant::HardwareUsage {
    qdrant::HardwareUsage {
        cpu: 11,
        payload_io_read: 22,
        payload_io_write: 33,
        payload_index_io_read: 44,
        payload_index_io_write: 55,
        vector_io_read: 66,
        vector_io_write: 77,
    }
}

fn sample_usage() -> qdrant::Usage {
    qdrant::Usage {
        hardware: Some(sample_hardware_usage()),
        inference: Some(qdrant::InferenceUsage {
            models: [("bm25".to_string(), qdrant::ModelUsage { tokens: 512 })]
                .into_iter()
                .collect(),
        }),
    }
}

/// `scored_point_to_hit` maps point id, score, payload, and typed vectors
/// straight from the proto; `telemetry_from_proto` mirrors the same fields.
#[test]
fn typed_query_hit_maps_proto_directly() {
    let usage = sample_usage();
    let point = qdrant::ScoredPoint {
        id: Some(qdrant::PointId {
            point_id_options: Some(qdrant::point_id::PointIdOptions::Num(7)),
        }),
        payload: [
            (
                "title".to_string(),
                proto_value(qdrant::value::Kind::StringValue("a".to_string())),
            ),
            (
                "stars".to_string(),
                proto_value(qdrant::value::Kind::IntegerValue(5)),
            ),
        ]
        .into_iter()
        .collect(),
        score: 0.75,
        version: 3,
        vectors: Some(qdrant::VectorsOutput {
            vectors_options: Some(qdrant::vectors_output::VectorsOptions::Vector(
                qdrant::VectorOutput {
                    vector: Some(qdrant::vector_output::Vector::Dense(qdrant::DenseVector {
                        data: vec![0.5, 0.25],
                    })),
                    ..Default::default()
                },
            )),
        }),
        shard_key: None,
        order_value: None,
    };

    let hit = scored_point_to_hit(point).expect("scored point converts");
    assert_eq!(hit.id, qql_plan::PlanPointId::Number(7));
    assert_eq!(hit.score, 0.75);
    assert_eq!(
        hit.payload.as_ref().expect("payload")["title"],
        serde_json::json!("a")
    );
    assert_eq!(
        hit.vector,
        Some(PlanVectorStruct::Single(PlanVectorValue::Dense(vec![
            0.5, 0.25
        ]))),
        "dense vectors convert without a JSON hop"
    );

    let telemetry = telemetry_from_proto(0.125, Some(&usage));
    assert_eq!(
        telemetry,
        Some(crate::executor::ServerTelemetry {
            time_s: Some(0.125),
            usage: usage_to_telemetry(Some(&usage)),
        })
    );
}

/// Named proto vectors convert to [`PlanVectorStruct::Named`] with every
/// value typed (dense and sparse entries).
#[test]
fn typed_named_vectors_convert_to_plan_struct() {
    let vectors = qdrant::VectorsOutput {
        vectors_options: Some(qdrant::vectors_output::VectorsOptions::Vectors(
            qdrant::NamedVectorsOutput {
                vectors: [
                    (
                        "dense".to_string(),
                        qdrant::VectorOutput {
                            vector: Some(qdrant::vector_output::Vector::Dense(
                                qdrant::DenseVector {
                                    data: vec![0.5, 0.25],
                                },
                            )),
                            ..Default::default()
                        },
                    ),
                    (
                        "sparse".to_string(),
                        qdrant::VectorOutput {
                            vector: Some(qdrant::vector_output::Vector::Sparse(
                                qdrant::SparseVector {
                                    indices: vec![2, 9],
                                    values: vec![1.5, 0.5],
                                },
                            )),
                            ..Default::default()
                        },
                    ),
                ]
                .into_iter()
                .collect(),
            },
        )),
    };
    let converted = super::typed::vectors_output_to_typed(&vectors).expect("named vectors convert");
    let PlanVectorStruct::Named(entries) = converted else {
        panic!("expected named vector struct");
    };
    assert_eq!(entries["dense"], PlanVectorValue::Dense(vec![0.5, 0.25]));
    assert_eq!(
        entries["sparse"],
        PlanVectorValue::Sparse {
            indices: vec![2, 9],
            values: vec![1.5, 0.5],
        }
    );
}

/// `retrieved_point_to_hit` (get / scroll) keeps UUID ids and the unscored
/// `0.0` default.
#[test]
fn typed_retrieved_hit_maps_proto_directly() {
    let point = qdrant::RetrievedPoint {
        id: Some(qdrant::PointId {
            point_id_options: Some(qdrant::point_id::PointIdOptions::Uuid(
                "11111111-2222-3333-4444-555555555555".to_string(),
            )),
        }),
        payload: Default::default(),
        vectors: None,
        shard_key: None,
        order_value: None,
    };
    let hit = retrieved_point_to_hit(point).expect("retrieved point converts");
    assert_eq!(
        hit.id,
        qql_plan::PlanPointId::String("11111111-2222-3333-4444-555555555555".to_string())
    );
    assert_eq!(hit.score, 0.0);
    // An empty proto payload map is `Some({})`, exactly like a REST
    // `"payload": {}` record.
    assert_eq!(hit.payload, Some(HashMap::new()));
    assert_eq!(hit.vector, None);
}

/// `point_group_to_typed` maps every `GroupId` variant, keeps ordered hits,
/// and drops `lookup` points.
#[test]
fn typed_groups_map_proto_directly() {
    use qdrant::group_id::Kind;

    let point = |id: u64, score: f32| qdrant::ScoredPoint {
        id: Some(qdrant::PointId {
            point_id_options: Some(qdrant::point_id::PointIdOptions::Num(id)),
        }),
        payload: Default::default(),
        score,
        version: 0,
        vectors: None,
        shard_key: None,
        order_value: None,
    };

    let groups: Vec<_> = [
        qdrant::PointGroup {
            id: Some(qdrant::GroupId {
                kind: Some(Kind::UnsignedValue(7)),
            }),
            hits: vec![point(1, 0.75)],
            lookup: Some(qdrant::RetrievedPoint {
                id: Some(qdrant::PointId {
                    point_id_options: Some(qdrant::point_id::PointIdOptions::Num(99)),
                }),
                ..Default::default()
            }),
        },
        qdrant::PointGroup {
            id: Some(qdrant::GroupId {
                kind: Some(Kind::IntegerValue(-3)),
            }),
            hits: vec![point(2, 0.5)],
            lookup: None,
        },
        qdrant::PointGroup {
            id: Some(qdrant::GroupId {
                kind: Some(Kind::StringValue("a".to_string())),
            }),
            hits: Vec::new(),
            lookup: None,
        },
    ]
    .into_iter()
    .map(|group| point_group_to_typed(group).expect("group converts"))
    .collect();

    assert_eq!(groups[0].group_id, PlanGroupId::Unsigned(7));
    assert_eq!(groups[1].group_id, PlanGroupId::Signed(-3));
    assert_eq!(groups[2].group_id, PlanGroupId::Keyword("a".to_string()));
    assert_eq!(groups[0].hits.len(), 1, "lookup points expand into no hits");
}

/// Missing proto ids / group ids / vector values fail closed instead of
/// fabricating placeholder values.
#[test]
fn typed_converters_reject_missing_proto_values() {
    let err = scored_point_to_hit(qdrant::ScoredPoint::default()).unwrap_err();
    assert_eq!(err.code, "QQL-BACKEND-ENVELOPE");

    let err = point_group_to_typed(qdrant::PointGroup::default()).unwrap_err();
    assert_eq!(err.code, "QQL-BACKEND-ENVELOPE");

    let err = super::typed::vectors_output_to_typed(&qdrant::VectorsOutput {
        vectors_options: None,
    })
    .unwrap_err();
    assert_eq!(err.code, "QQL-BACKEND-ENVELOPE");
}

/// Write responses (upsert/delete/payload/vector ops) are status-only typed
/// mutations with telemetry straight from the proto: the proto `UpdateResult`
/// has no affected count (the executor derives upserts from the request).
#[test]
fn typed_mutation_response_is_status_only_with_telemetry() {
    let usage = sample_usage();
    let resp = qdrant::PointsOperationResponse {
        result: Some(qdrant::UpdateResult {
            operation_id: Some(42),
            status: qdrant::UpdateStatus::Completed as i32,
        }),
        time: 0.25,
        usage: Some(usage.clone()),
    };

    let typed = mutation_response_to_typed(resp);
    assert_eq!(typed.data, ExecData::Mutation { affected: None });
    assert_eq!(typed.telemetry, telemetry_from_proto(0.25, Some(&usage)));
    assert_eq!(
        serde_json::to_value(&typed.data).expect("serializes"),
        serde_json::Value::Null,
        "status-only mutations serialize as the report's null data"
    );
}

/// Collection / shard-key mutations (proto bool status + time) are status-only
/// typed mutations — no Raw envelope remains for status responses.
#[test]
fn typed_collection_mutation_is_status_only() {
    let typed = collection_mutation_to_typed(0.125);
    assert_eq!(typed.data, ExecData::Mutation { affected: None });
    assert_eq!(typed.telemetry, telemetry_from_proto(0.125, None));
}

/// `usage_to_telemetry` must mirror `usage_to_json` + `ServerUsage::from_json`
/// for every section combination (absent, empty, hardware-only,
/// inference-only, both).
#[test]
fn usage_to_telemetry_matches_json_pipeline() {
    let usage = sample_usage();
    assert_eq!(
        usage_to_telemetry(Some(&usage)),
        ServerUsage::from_json(&usage_to_json(Some(&usage))),
        "hardware + inference"
    );

    let hardware_only = qdrant::Usage {
        hardware: usage.hardware,
        inference: None,
    };
    assert_eq!(
        usage_to_telemetry(Some(&hardware_only)),
        ServerUsage::from_json(&usage_to_json(Some(&hardware_only))),
        "hardware only"
    );

    let inference_only = qdrant::Usage {
        hardware: None,
        inference: usage.inference.clone(),
    };
    assert_eq!(
        usage_to_telemetry(Some(&inference_only)),
        ServerUsage::from_json(&usage_to_json(Some(&inference_only))),
        "inference only"
    );

    let empty = qdrant::Usage {
        hardware: None,
        inference: None,
    };
    assert_eq!(usage_to_telemetry(Some(&empty)), None);
    assert_eq!(ServerUsage::from_json(&usage_to_json(Some(&empty))), None);
    assert_eq!(usage_to_telemetry(None), None);

    let parsed = usage_to_telemetry(Some(&usage)).expect("usage present");
    assert_eq!(
        parsed.hardware,
        Some(crate::executor::HardwareUsage {
            cpu: 11,
            payload_io_read: 22,
            payload_io_write: 33,
            payload_index_io_read: 44,
            payload_index_io_write: 55,
            vector_io_read: 66,
            vector_io_write: 77,
        })
    );
    assert_eq!(
        parsed.inference.expect("inference present").models["bm25"].tokens,
        512
    );
}

/// Bulk-path timing report: 10k×128-dim upsert through plan → gRPC proto →
/// REST JSON (min-of-5, release). Asserts output shape only; prints timings.
///
/// Copy accounting after the `value_to_json` removal (gRPC path):
/// AST→plan (1 clone, borrowed lowering) → proto (1 clone into messages) →
/// prost encode (1 copy to bytes). Before, payloads additionally paid a
/// plan-time JSON tree plus a whole-subtree pre-clone (`v.clone()`) before
/// proto conversion, and REST paid two JSON trees instead of one.
///
/// Measured on this machine (release, min-of-5, 10k×128-dim upsert):
/// before plan 5.72ms / proto 7.58ms / REST 25.63ms;
/// after  plan 4.27ms / proto 6.47ms / REST 24.70ms.
#[test]
fn bulk_upsert_copy_bench_report() {
    use qql_core::ast::{
        PointEntry, PointId, PointVectors, Stmt, UpsertPoint, UpsertStmt, VectorValue,
    };

    const N: usize = 10_000;
    const DIM: usize = 128;
    let build_stmt = || {
        let mut points = Vec::with_capacity(N);
        for i in 0..N {
            let vec = (0..DIM).map(|d| (i * DIM + d) as f32 * 0.001).collect();
            points.push(PointEntry::Inline(UpsertPoint {
                id: PointId::Number(i as u64),
                vectors: Some(PointVectors::Unnamed(VectorValue::Dense(vec))),
                payload: vec![("t".to_string(), qql_core::ast::Value::Int(i as i64))],
            }));
        }
        Stmt::Upsert(Box::new(UpsertStmt {
            collection: "docs".to_string(),
            points,
            embedding: None,
            embed: Vec::new(),
            update_filter: None,
            update_mode: None,
            shard_key: None,
            wait: None,
        }))
    };

    // Warmup (allocator).
    let op = qql_plan::plan(&build_stmt()).unwrap();
    let qql_plan::PlannedOperation::Upsert { request, .. } = &op else {
        panic!("expected upsert");
    };
    assert_eq!(request.points.len(), N);

    let mut plan_best = f64::INFINITY;
    let mut proto_best = f64::INFINITY;
    let mut rest_best = f64::INFINITY;
    for _ in 0..5 {
        let stmt = build_stmt();
        let t0 = std::time::Instant::now();
        let op = qql_plan::plan(&stmt).unwrap();
        plan_best = plan_best.min(t0.elapsed().as_secs_f64() * 1000.0);

        let t0 = std::time::Instant::now();
        let route = qql_plan::to_rest_route(&op).unwrap();
        assert!(route.body.is_some());
        rest_best = rest_best.min(t0.elapsed().as_secs_f64() * 1000.0);

        // Owned handoff is free (pre-existing `into_update_batch` path);
        // the timed conversion below is exactly what production pays.
        let (_, update_op) =
            qql_plan::mutation::planned_to_update_operation_owned(op).expect("upsert converts");
        let t0 = std::time::Instant::now();
        let proto_op = to_points_update_operation(&update_op).unwrap();
        proto_best = proto_best.min(t0.elapsed().as_secs_f64() * 1000.0);
        assert!(proto_op.operation.is_some());
    }
    eprintln!(
        "bulk upsert {N}x{DIM}: plan min {plan_best:.2}ms, plan→proto min {proto_best:.2}ms, plan→REST min {rest_best:.2}ms"
    );
}