lattice-embed 0.9.0

SIMD-accelerated vector operations and embedding generation
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
//! Quantization tiers, prepared queries, and unified distance dispatch.
//!
//! Tiers trade storage for fidelity; prepared queries avoid repeated
//! quantization in homogeneous candidate searches.
//!
//! See docs/simd.md for tier selection and dispatch semantics.

use super::binary::BinaryVector;
use super::int4::Int4Vector;
use super::quantized::{QuantizedVector, cosine_similarity_i8_trusted, dot_product_i8_trusted};
use super::{cosine_similarity, dot_product};
use crate::error::{EmbedError, Result};

/// Caller assertion that a vector is L2-unit-normalized (norm ≈ 1).
///
/// When both query and stored vectors carry `UnitNorm`, cosine similarity equals
/// the dot product — the norm division can be skipped entirely.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum NormalizationHint {
    /// No guarantee — full cosine (with norm division) is required.
    Unknown,
    /// Caller asserts this vector is L2-unit-normalized (norm ≈ 1 within 1e-4).
    Unit,
}

/// **Unstable**: tier design is under active iteration; tier boundaries may change.
///
/// Quantization precision tier, ordered from highest to lowest fidelity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum QuantizationTier {
    /// Full f32 precision (4 bytes/dim, 1x baseline).
    Full,
    /// INT8 symmetric quantization (1 byte/dim, 4x compression).
    Int8,
    /// INT4 packed nibble quantization (0.5 bytes/dim, 8x compression).
    Int4,
    /// Binary sign-bit quantization (0.125 bytes/dim, 32x compression).
    Binary,
}

impl QuantizationTier {
    /// **Unstable**: bytes-per-dimension constant; may change with new tiers.
    pub fn bytes_per_dim(&self) -> f32 {
        match self {
            Self::Full => 4.0,
            Self::Int8 => 1.0,
            Self::Int4 => 0.5,
            Self::Binary => 0.125,
        }
    }

    /// **Unstable**: compression ratio; derived from `bytes_per_dim`, may be removed.
    pub fn compression_ratio(&self) -> f32 {
        4.0 / self.bytes_per_dim()
    }

    /// **Unstable**: storage byte computation; may change with new tiers.
    pub fn storage_bytes(&self, dims: usize) -> usize {
        match self {
            Self::Full => dims * 4,
            Self::Int8 => dims,
            Self::Int4 => dims.div_ceil(2),
            Self::Binary => dims.div_ceil(8),
        }
    }

    /// **Warning**: this is a placeholder storage policy, not evidence that older vectors
    /// tolerate lower precision. Callers should measure retrieval quality for their workload.
    ///
    /// **Unstable**: tier boundaries may be tuned.
    pub fn from_age_seconds(age_secs: u64) -> Self {
        const HOUR: u64 = 3600;
        const DAY: u64 = 86400;
        const WEEK: u64 = 604800;

        if age_secs < HOUR {
            Self::Full
        } else if age_secs < DAY {
            Self::Int8
        } else if age_secs < WEEK {
            Self::Int4
        } else {
            Self::Binary
        }
    }
}

/// **Unstable**: unified quantized data container; variants may change with tier redesign.
///
/// Wraps the tier-specific vector types into a single enum for
/// uniform storage and distance dispatch.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum QuantizedData {
    /// Full-precision f32 vector.
    Full(Vec<f32>),
    /// INT8 quantized vector.
    Int8(QuantizedVector),
    /// INT4 packed quantized vector.
    Int4(Int4Vector),
    /// Binary sign-bit vector.
    Binary(BinaryVector),
}

impl QuantizedData {
    /// **Unstable**: returns `QuantizationTier` which is itself Unstable.
    pub fn tier(&self) -> QuantizationTier {
        match self {
            Self::Full(_) => QuantizationTier::Full,
            Self::Int8(_) => QuantizationTier::Int8,
            Self::Int4(_) => QuantizationTier::Int4,
            Self::Binary(_) => QuantizationTier::Binary,
        }
    }

    /// **Unstable**: dimension accessor; may be removed if `QuantizedData` gains a dims field.
    pub fn dims(&self) -> usize {
        match self {
            Self::Full(v) => v.len(),
            Self::Int8(q) => q.len(),
            Self::Int4(q) => q.dims,
            Self::Binary(q) => q.dims,
        }
    }

    /// **Unstable**: storage byte count; may change with tier redesign.
    pub fn storage_bytes(&self) -> usize {
        match self {
            Self::Full(v) => v.len() * 4,
            Self::Int8(q) => q.len(),
            Self::Int4(q) => q.data.len(),
            Self::Binary(q) => q.data.len(),
        }
    }

    /// **Unstable**: quantization factory; tier dispatch logic may change.
    pub fn from_f32(vector: &[f32], tier: QuantizationTier) -> Self {
        match tier {
            QuantizationTier::Full => Self::Full(vector.to_vec()),
            QuantizationTier::Int8 => Self::Int8(QuantizedVector::from_f32(vector)),
            QuantizationTier::Int4 => Self::Int4(Int4Vector::from_f32(vector)),
            QuantizationTier::Binary => Self::Binary(BinaryVector::from_f32(vector)),
        }
    }

    /// **Unstable**: dequantization; output precision is tier-dependent.
    pub fn to_f32(&self) -> Vec<f32> {
        match self {
            Self::Full(v) => v.clone(),
            Self::Int8(q) => q.to_f32(),
            Self::Int4(q) => q.to_f32(),
            Self::Binary(q) => q.to_f32(),
        }
    }

    /// **Unstable**: re-quantizes through `f32`; lost information is not recovered.
    pub fn promote(&self, target: QuantizationTier) -> Self {
        let f32_data = self.to_f32();
        Self::from_f32(&f32_data, target)
    }

    /// **Unstable**: tier demotion; delegates to `promote`; may be removed.
    pub fn demote(&self, target: QuantizationTier) -> Self {
        self.promote(target) // Same operation, just going the other direction
    }
}

/// **Unstable**: pre-quantized query for repeated same-tier distance computation.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum PreparedQuery {
    /// Full f32 query.
    Full(Vec<f32>),
    /// INT8 quantized query.
    Int8(QuantizedVector),
    /// INT4 packed quantized query.
    Int4(Int4Vector),
    /// Binary sign-bit query.
    Binary(BinaryVector),
}

impl PreparedQuery {
    /// Quantize a query at the given tier for repeated distance calls.
    #[inline]
    pub fn from_f32(query_f32: &[f32], tier: QuantizationTier) -> Self {
        match tier {
            QuantizationTier::Full => Self::Full(query_f32.to_vec()),
            QuantizationTier::Int8 => Self::Int8(QuantizedVector::from_f32(query_f32)),
            QuantizationTier::Int4 => Self::Int4(Int4Vector::from_f32(query_f32)),
            QuantizationTier::Binary => Self::Binary(BinaryVector::from_f32(query_f32)),
        }
    }

    /// Returns the quantization tier of this prepared query.
    #[inline]
    pub fn tier(&self) -> QuantizationTier {
        match self {
            Self::Full(_) => QuantizationTier::Full,
            Self::Int8(_) => QuantizationTier::Int8,
            Self::Int4(_) => QuantizationTier::Int4,
            Self::Binary(_) => QuantizationTier::Binary,
        }
    }

    /// Returns the number of dimensions.
    #[inline]
    pub fn dims(&self) -> usize {
        match self {
            Self::Full(v) => v.len(),
            Self::Int8(q) => q.len(),
            Self::Int4(q) => q.dims,
            Self::Binary(q) => q.dims,
        }
    }
}

/// Prepare a query vector for repeated distance computation against a homogeneous tier.
#[inline]
pub fn prepare_query(query_f32: &[f32], tier: QuantizationTier) -> PreparedQuery {
    PreparedQuery::from_f32(query_f32, tier)
}

/// A prepared query with caller-provided normalization metadata.
#[derive(Debug, Clone)]
pub struct PreparedQueryWithMeta {
    /// The quantized query (owns the data).
    pub query: PreparedQuery,
    /// Caller assertion about the query vector's normalization state.
    pub norm: NormalizationHint,
}

impl PreparedQueryWithMeta {
    /// Create a prepared query from an f32 vector, asserting its normalization state.
    #[inline]
    pub fn from_f32(query_f32: &[f32], tier: QuantizationTier, norm: NormalizationHint) -> Self {
        Self {
            query: PreparedQuery::from_f32(query_f32, tier),
            norm,
        }
    }

    /// Returns the quantization tier.
    #[inline]
    pub fn tier(&self) -> QuantizationTier {
        self.query.tier()
    }

    /// Returns the number of dimensions.
    #[inline]
    pub fn dims(&self) -> usize {
        self.query.dims()
    }
}

/// Returns `true` when the squared norm of `v` is within 1e-4 of 1.0.
///
/// Uses the SIMD-dispatched [`dot_product`] for the self-dot rather than a plain
/// scalar reduction. This helper is no longer called on the cosine hot path
/// (`approximate_cosine_distance_prepared_with_meta` delegates to the fused
/// path instead of guarding a hint-selected shortcut), but any caller checking
/// norms per candidate gets the SIMD cost model, not a scalar one.
#[inline]
pub fn is_unit_norm(v: &[f32]) -> bool {
    let sq = dot_product(v, v);
    (sq - 1.0).abs() < 1e-4
}

/// Prepare a query annotated with the given normalization hint.
#[inline]
pub fn prepare_query_with_norm(
    query_f32: &[f32],
    tier: QuantizationTier,
    norm: NormalizationHint,
) -> PreparedQueryWithMeta {
    PreparedQueryWithMeta::from_f32(query_f32, tier, norm)
}

/// **Unstable**: computes prepared cosine distance in `[0, 2]` for matching tiers.
///
/// Returns [`EmbedError::TierMismatch`] for a different stored tier.
/// See [`docs/simd.md`](../../docs/simd.md#prepared-queries-and-tier-matching) for the per-tier paths.
#[inline]
pub fn approximate_cosine_distance_prepared(
    query: &PreparedQuery,
    stored: &QuantizedData,
) -> Result<f32> {
    match (query, stored) {
        (PreparedQuery::Full(q), QuantizedData::Full(s)) => Ok(1.0 - cosine_similarity(q, s)),
        (PreparedQuery::Int8(q), QuantizedData::Int8(s)) => {
            Ok(1.0 - cosine_similarity_i8_trusted(s, q))
        }
        (PreparedQuery::Int4(q), QuantizedData::Int4(s)) => Ok(s.cosine_distance(q)),
        (PreparedQuery::Binary(q), QuantizedData::Binary(s)) => Ok(s.cosine_distance_approx(q)),
        _ => Err(EmbedError::TierMismatch {
            op: "approximate_cosine_distance_prepared",
            expected: stored.tier(),
            actual: query.tier(),
        }),
    }
}

/// Alias for [`approximate_cosine_distance_prepared`] retained for compatibility.
#[inline]
pub fn try_approximate_cosine_distance_prepared(
    query: &PreparedQuery,
    stored: &QuantizedData,
) -> Result<f32> {
    approximate_cosine_distance_prepared(query, stored)
}

/// Alias for [`approximate_dot_product_prepared`] retained for compatibility.
#[inline]
pub fn try_approximate_dot_product_prepared(
    query: &PreparedQuery,
    stored: &QuantizedData,
) -> Result<f32> {
    approximate_dot_product_prepared(query, stored)
}

/// Computes prepared cosine distance; hints are accepted but do not select a
/// separate code path.
///
/// The former `Full` unit-norm "fast path" (skip norm division when both sides
/// assert unit norm) was measurably slower than the general path it guarded:
/// verifying the stored side's norm plus the query dot takes two O(d) passes,
/// while [`cosine_similarity`] computes the dot and both norms in one fused
/// pass. With the guard it was also a correctness risk, trusting release-time
/// hints. Delegating unconditionally is both the fastest and the safest shape.
///
/// Returns [`EmbedError::TierMismatch`] for a tier mismatch.
/// See [`docs/simd.md`](../../docs/simd.md#prepared-queries-and-tier-matching) for hint semantics.
#[inline]
pub fn approximate_cosine_distance_prepared_with_meta(
    meta: &PreparedQueryWithMeta,
    stored: &QuantizedData,
    _stored_norm: NormalizationHint,
) -> Result<f32> {
    approximate_cosine_distance_prepared(&meta.query, stored)
}

/// **Unstable**: computes a prepared dot product for matching non-binary tiers.
///
/// Returns [`EmbedError::TierMismatch`] for different tiers or [`EmbedError::Internal`] for binary.
/// See [`docs/simd.md`](../../docs/simd.md#prepared-queries-and-tier-matching) for supported paths.
#[inline]
pub fn approximate_dot_product_prepared(
    query: &PreparedQuery,
    stored: &QuantizedData,
) -> Result<f32> {
    match (query, stored) {
        (PreparedQuery::Full(q), QuantizedData::Full(s)) => Ok(dot_product(q, s)),
        (PreparedQuery::Int8(q), QuantizedData::Int8(s)) => Ok(dot_product_i8_trusted(q, s)),
        (PreparedQuery::Int4(q), QuantizedData::Int4(s)) => Ok(s.dot_product(q)),
        (PreparedQuery::Binary(_), QuantizedData::Binary(_)) => Err(EmbedError::Internal(
            "Binary has no prepared dot product; use approximate_cosine_distance_prepared".into(),
        )),
        _ => Err(EmbedError::TierMismatch {
            op: "approximate_dot_product_prepared",
            expected: stored.tier(),
            actual: query.tier(),
        }),
    }
}

/// Computes distances from one prepared query to all stored vectors.
///
/// Returns [`EmbedError::TierMismatch`] if any stored tier differs.
#[inline]
pub fn batch_approximate_cosine_distance_prepared(
    query: &PreparedQuery,
    stored: &[QuantizedData],
) -> Result<Vec<f32>> {
    stored
        .iter()
        .map(|item| approximate_cosine_distance_prepared(query, item))
        .collect()
}

/// Writes prepared-query distances into a reusable buffer, clearing it on error.
///
/// Returns [`EmbedError::TierMismatch`] if any stored tier differs.
/// See [`docs/simd.md`](../../docs/simd.md#prepared-queries-and-tier-matching) for buffer semantics.
#[inline]
pub fn batch_approximate_cosine_distance_prepared_into(
    query: &PreparedQuery,
    stored: &[QuantizedData],
    out: &mut Vec<f32>,
) -> Result<()> {
    out.clear();
    out.reserve(stored.len());
    for item in stored {
        match approximate_cosine_distance_prepared(query, item) {
            Ok(distance) => out.push(distance),
            Err(e) => {
                out.clear();
                return Err(e);
            }
        }
    }
    Ok(())
}

/// Computes distances from one prepared INT8 query without re-quantizing it.
///
/// Returns [`EmbedError::TierMismatch`] unless the query is INT8.
#[inline]
pub fn approximate_int8_batch_prepared(
    query: &PreparedQuery,
    candidates: &[QuantizedVector],
) -> Result<Vec<f32>> {
    let PreparedQuery::Int8(q) = query else {
        return Err(EmbedError::TierMismatch {
            op: "approximate_int8_batch_prepared",
            expected: QuantizationTier::Int8,
            actual: query.tier(),
        });
    };
    Ok(candidates
        .iter()
        .map(|candidate| 1.0 - cosine_similarity_i8_trusted(candidate, q))
        .collect())
}

/// Writes prepared INT8 distances into a reusable buffer, clearing it on error.
///
/// Returns [`EmbedError::TierMismatch`] unless the query is INT8.
#[inline]
pub fn approximate_int8_batch_prepared_into(
    query: &PreparedQuery,
    candidates: &[QuantizedVector],
    out: &mut Vec<f32>,
) -> Result<()> {
    out.clear();
    let PreparedQuery::Int8(q) = query else {
        return Err(EmbedError::TierMismatch {
            op: "approximate_int8_batch_prepared_into",
            expected: QuantizationTier::Int8,
            actual: query.tier(),
        });
    };
    out.reserve(candidates.len());
    out.extend(
        candidates
            .iter()
            .map(|candidate| 1.0 - cosine_similarity_i8_trusted(candidate, q)),
    );
    Ok(())
}

/// Computes distances from one prepared INT4 query without re-quantizing it.
///
/// Returns [`EmbedError::TierMismatch`] unless the query is INT4.
#[inline]
pub fn approximate_int4_batch_prepared(
    query: &PreparedQuery,
    candidates: &[Int4Vector],
) -> Result<Vec<f32>> {
    let PreparedQuery::Int4(q) = query else {
        return Err(EmbedError::TierMismatch {
            op: "approximate_int4_batch_prepared",
            expected: QuantizationTier::Int4,
            actual: query.tier(),
        });
    };
    Ok(candidates
        .iter()
        .map(|candidate| candidate.cosine_distance(q))
        .collect())
}

/// Writes prepared INT4 distances into a reusable buffer, clearing it on error.
///
/// Returns [`EmbedError::TierMismatch`] unless the query is INT4.
#[inline]
pub fn approximate_int4_batch_prepared_into(
    query: &PreparedQuery,
    candidates: &[Int4Vector],
    out: &mut Vec<f32>,
) -> Result<()> {
    out.clear();
    let PreparedQuery::Int4(q) = query else {
        return Err(EmbedError::TierMismatch {
            op: "approximate_int4_batch_prepared_into",
            expected: QuantizationTier::Int4,
            actual: query.tier(),
        });
    };
    out.reserve(candidates.len());
    out.extend(
        candidates
            .iter()
            .map(|candidate| candidate.cosine_distance(q)),
    );
    Ok(())
}

/// **Unstable**: quantizes an `f32` query and computes tiered cosine distance.
///
/// `query_f32.len()` must match stored dimensionality.
/// See [`docs/simd.md`](../../docs/simd.md#prepared-queries-and-tier-matching) for hot-loop guidance.
pub fn approximate_cosine_distance(query_f32: &[f32], stored: &QuantizedData) -> f32 {
    debug_assert_eq!(
        query_f32.len(),
        stored.dims(),
        "approximate_cosine_distance: query length {} != stored dims {}",
        query_f32.len(),
        stored.dims(),
    );
    match stored {
        QuantizedData::Full(v) => {
            // Exact cosine distance
            1.0 - cosine_similarity(query_f32, v)
        }
        QuantizedData::Int8(q) => {
            let query_q = QuantizedVector::from_f32(query_f32);
            1.0 - q.cosine_similarity(&query_q)
        }
        QuantizedData::Int4(q) => {
            let query_q = Int4Vector::from_f32(query_f32);
            q.cosine_distance(&query_q)
        }
        QuantizedData::Binary(q) => {
            let query_q = BinaryVector::from_f32(query_f32);
            q.cosine_distance_approx(&query_q)
        }
    }
}

/// **Unstable**: approximate tiered dot-product dispatch.
pub fn approximate_dot_product(query_f32: &[f32], stored: &QuantizedData) -> f32 {
    match stored {
        QuantizedData::Full(v) => dot_product(query_f32, v),
        QuantizedData::Int8(q) => {
            let query_q = QuantizedVector::from_f32(query_f32);
            q.dot_product(&query_q)
        }
        QuantizedData::Int4(q) => {
            let query_q = Int4Vector::from_f32(query_f32);
            q.dot_product(&query_q)
        }
        QuantizedData::Binary(_q) => {
            // Binary doesn't have a meaningful dot product; fall back to dequantize
            let stored_f32 = _q.to_f32();
            dot_product(query_f32, &stored_f32)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn generate_vector(dim: usize, seed: u64) -> Vec<f32> {
        let mut state = seed ^ ((dim as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15));
        (0..dim)
            .map(|i| {
                state = state
                    .wrapping_mul(6364136223846793005)
                    .wrapping_add(1442695040888963407)
                    .wrapping_add(i as u64);
                let unit = ((state >> 32) as u32) as f32 / u32::MAX as f32;
                unit * 2.0 - 1.0
            })
            .collect()
    }

    fn scalar_cosine_f64(a: &[f32], b: &[f32]) -> f64 {
        assert_eq!(a.len(), b.len());
        let mut dot = 0.0f64;
        let mut norm_a = 0.0f64;
        let mut norm_b = 0.0f64;
        for (&a, &b) in a.iter().zip(b) {
            let a = f64::from(a);
            let b = f64::from(b);
            dot += a * b;
            norm_a += a * a;
            norm_b += b * b;
        }
        let denom = norm_a.sqrt() * norm_b.sqrt();
        if denom == 0.0 { 0.0 } else { dot / denom }
    }

    fn reference_ranking(query: &[f32], corpus: &[Vec<f32>]) -> Vec<usize> {
        let mut ranked: Vec<_> = corpus
            .iter()
            .enumerate()
            .map(|(index, candidate)| (index, scalar_cosine_f64(query, candidate)))
            .collect();
        ranked.sort_unstable_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
        ranked.into_iter().map(|(index, _)| index).collect()
    }

    fn tier_ranking(query: &[f32], stored: &[QuantizedData], tier: QuantizationTier) -> Vec<usize> {
        let prepared = PreparedQuery::from_f32(query, tier);
        assert_eq!(prepared.tier(), tier);
        let mut ranked: Vec<_> = stored
            .iter()
            .enumerate()
            .map(|(index, candidate)| {
                (
                    index,
                    approximate_cosine_distance_prepared(&prepared, candidate).unwrap(),
                )
            })
            .collect();
        ranked.sort_unstable_by(|a, b| a.1.total_cmp(&b.1).then_with(|| a.0.cmp(&b.0)));
        ranked.into_iter().map(|(index, _)| index).collect()
    }

    fn recall_hits_at(reference: &[usize], actual: &[usize], k: usize) -> usize {
        actual[..k]
            .iter()
            .filter(|candidate| reference[..k].contains(candidate))
            .count()
    }

    fn recall_at(reference: &[usize], actual: &[usize], k: usize) -> f64 {
        recall_hits_at(reference, actual, k) as f64 / k as f64
    }

    fn pairwise_ranking_agreements(reference: &[usize], actual: &[usize]) -> usize {
        assert_eq!(reference.len(), actual.len());
        let mut actual_position = vec![0usize; actual.len()];
        for (position, &candidate) in actual.iter().enumerate() {
            actual_position[candidate] = position;
        }
        let mut agreements = 0usize;
        for (position, &left) in reference.iter().enumerate() {
            for &right in &reference[position + 1..] {
                agreements += usize::from(actual_position[left] < actual_position[right]);
            }
        }
        agreements
    }

    fn pairwise_ranking_agreement(reference: &[usize], actual: &[usize]) -> f64 {
        let pairs = reference.len() * (reference.len() - 1) / 2;
        pairwise_ranking_agreements(reference, actual) as f64 / pairs as f64
    }

    fn retrieval_quality_counts(
        reference: &[usize],
        actual: &[usize],
        top_k: usize,
    ) -> (usize, usize) {
        (
            recall_hits_at(reference, actual, top_k),
            pairwise_ranking_agreements(reference, actual),
        )
    }

    fn index_order_surrogate_quality(
        corpus: &[Vec<f32>],
        queries: &[Vec<f32>],
        top_k: usize,
    ) -> (f64, f64) {
        let index_order: Vec<_> = (0..corpus.len()).collect();
        let mut recall = 0.0;
        let mut agreement = 0.0;
        for query in queries {
            let reference = reference_ranking(query, corpus);
            recall += recall_at(&reference, &index_order, top_k);
            agreement += pairwise_ranking_agreement(&reference, &index_order);
        }
        (
            recall / queries.len() as f64,
            agreement / queries.len() as f64,
        )
    }

    fn retrieval_quality_floor(tier: QuantizationTier) -> (f64, f64) {
        match tier {
            QuantizationTier::Full => (1.0, 0.999),
            QuantizationTier::Int8 => (0.98, 0.995),
            QuantizationTier::Int4 => (0.85, 0.95),
            QuantizationTier::Binary => (0.30, 0.70),
        }
    }

    /// A floor includes equality; one epsilon recovers equality lost while averaging.
    fn meets_retrieval_quality_floor(value: f64, minimum: f64) -> bool {
        value.is_finite() && value + f64::EPSILON >= minimum
    }

    /// Bounds each query so a collapsed subset cannot hide behind healthy queries.
    ///
    /// The fixed 16-query fixture produces these per-query ranges at Recall@10:
    ///
    /// | Tier | Recall@10 hits | Agreeing pairs |
    /// | --- | --- | --- |
    /// | Full | 10..=10 | 32,640..=32,640 |
    /// | Int8 | 10..=10 | 32,567..=32,604 |
    /// | Int4 | 8..=10 | 31,531..=31,773 |
    /// | Binary | 3..=7 | 24,423..=25,705 |
    ///
    /// Recall gets one additional miss beyond the observed minimum, exactly one
    /// Recall@10 step. Agreement gets one full observed min-to-max range below
    /// the observed minimum. This fixture-derived slack rejects whole-query
    /// collapse without making ordinary variation in the healthy fixture fatal.
    /// Full agreement has no observed spread and remains exact.
    fn retrieval_quality_per_query_floor(tier: QuantizationTier) -> (usize, usize) {
        match tier {
            QuantizationTier::Full => (9, 32_640),
            QuantizationTier::Int8 => (9, 32_530),
            QuantizationTier::Int4 => (7, 31_289),
            QuantizationTier::Binary => (2, 23_141),
        }
    }

    /// Pins known-good metrics as Recall@10 hits and agreeing pairs out of 32,640.
    ///
    /// Each metric may move by one observed min-to-max span in total across all
    /// 16 queries, or one sixteenth of that span under a uniform shift. Absolute
    /// movement prevents cross-query cancellation and makes a broader path change
    /// require deliberate recalibration. A zero-spread metric remains exact.
    /// Recall-hit and agreeing-pair counts can collide across different rankings. The
    /// exercised path breaks equal distances by candidate index, so this remains a
    /// metric limitation. A future top-k identity check would detect membership changes;
    /// a rank fingerprint would also detect position changes that preserve both counts.
    const HEALTHY_FULL_QUERY_QUALITY: [(usize, usize); 16] = [(10, 32_640); 16];
    const HEALTHY_INT8_QUERY_QUALITY: [(usize, usize); 16] = [
        (10, 32_588),
        (10, 32_575),
        (10, 32_597),
        (10, 32_590),
        (10, 32_595),
        (10, 32_592),
        (10, 32_580),
        (10, 32_604),
        (10, 32_587),
        (10, 32_573),
        (10, 32_580),
        (10, 32_579),
        (10, 32_567),
        (10, 32_578),
        (10, 32_576),
        (10, 32_588),
    ];
    const HEALTHY_INT4_QUERY_QUALITY: [(usize, usize); 16] = [
        (8, 31_582),
        (9, 31_531),
        (9, 31_642),
        (8, 31_656),
        (10, 31_773),
        (8, 31_638),
        (10, 31_744),
        (9, 31_758),
        (10, 31_661),
        (10, 31_651),
        (10, 31_662),
        (8, 31_727),
        (10, 31_531),
        (10, 31_625),
        (9, 31_655),
        (9, 31_653),
    ];
    const HEALTHY_BINARY_QUERY_QUALITY: [(usize, usize); 16] = [
        (7, 25_430),
        (3, 25_031),
        (6, 25_033),
        (5, 25_339),
        (4, 25_534),
        (3, 25_166),
        (3, 25_156),
        (6, 25_705),
        (5, 25_677),
        (4, 25_419),
        (4, 25_040),
        (3, 25_150),
        (4, 24_965),
        (5, 25_190),
        (5, 24_423),
        (4, 25_355),
    ];

    fn healthy_query_quality(tier: QuantizationTier) -> &'static [(usize, usize); 16] {
        match tier {
            QuantizationTier::Full => &HEALTHY_FULL_QUERY_QUALITY,
            QuantizationTier::Int8 => &HEALTHY_INT8_QUERY_QUALITY,
            QuantizationTier::Int4 => &HEALTHY_INT4_QUERY_QUALITY,
            QuantizationTier::Binary => &HEALTHY_BINARY_QUERY_QUALITY,
        }
    }

    fn retrieval_quality_movement_budget(healthy: &[(usize, usize)]) -> (usize, usize) {
        let minimum_recall_hits = healthy.iter().map(|quality| quality.0).min().unwrap();
        let maximum_recall_hits = healthy.iter().map(|quality| quality.0).max().unwrap();
        let minimum_agreements = healthy.iter().map(|quality| quality.1).min().unwrap();
        let maximum_agreements = healthy.iter().map(|quality| quality.1).max().unwrap();
        (
            maximum_recall_hits - minimum_recall_hits,
            maximum_agreements - minimum_agreements,
        )
    }

    /// Bounds concentration relative to each query's own healthy counts.
    ///
    /// Each cap is the ceiling of one sixteenth of the full healthy span, the smallest
    /// integer allowance that admits the total budget's uniform per-query share. Binary
    /// therefore permits one Recall@10 hit or 81 agreeing pairs to move on one query.
    /// This catches concentrated cliffs; the retained L1 budget catches broad movement.
    fn retrieval_quality_concentration_budget(healthy: &[(usize, usize)]) -> (usize, usize) {
        let movement_budget = retrieval_quality_movement_budget(healthy);
        (
            movement_budget.0.div_ceil(healthy.len()),
            movement_budget.1.div_ceil(healthy.len()),
        )
    }

    fn validate_tier_retrieval_quality(
        tier: QuantizationTier,
        query_quality: &[(usize, usize)],
        top_k: usize,
    ) -> std::result::Result<(f64, f64), String> {
        if query_quality.is_empty() {
            return Err(format!("{tier:?} retrieval quality has zero queries"));
        }

        let healthy = healthy_query_quality(tier);
        if query_quality.len() != healthy.len() {
            return Err(format!(
                "{tier:?} retrieval quality has {} queries, expected {}",
                query_quality.len(),
                healthy.len()
            ));
        }

        let (minimum_query_recall, minimum_query_agreement) =
            retrieval_quality_per_query_floor(tier);
        for (query_index, &(recall_hits, agreements)) in query_quality.iter().enumerate() {
            if recall_hits < minimum_query_recall || agreements < minimum_query_agreement {
                return Err(format!(
                    "{tier:?} query {query_index} fails the per-query floor: Recall@{top_k}=\
                     {:.6} (minimum {:.6}), pairwise ranking agreement=\
                     {:.6} (minimum {:.6})",
                    recall_hits as f64 / top_k as f64,
                    minimum_query_recall as f64 / top_k as f64,
                    agreements as f64 / 32_640.0,
                    minimum_query_agreement as f64 / 32_640.0,
                ));
            }
        }

        let recall_hits = query_quality.iter().map(|quality| quality.0).sum::<usize>();
        let agreements = query_quality.iter().map(|quality| quality.1).sum::<usize>();
        let recall = recall_hits as f64 / (query_quality.len() * top_k) as f64;
        let agreement = agreements as f64 / (query_quality.len() * 32_640) as f64;
        let (minimum_recall, minimum_agreement) = retrieval_quality_floor(tier);
        if !meets_retrieval_quality_floor(recall, minimum_recall) {
            return Err(format!(
                "{tier:?} Recall@{top_k} {recall:.6} is below the measured-data floor \
                 {minimum_recall:.3}"
            ));
        }
        if !meets_retrieval_quality_floor(agreement, minimum_agreement) {
            return Err(format!(
                "{tier:?} pairwise ranking agreement {agreement:.6} is below the measured-data \
                 floor {minimum_agreement:.3}"
            ));
        }

        let (recall_movement, agreement_movement) = query_quality.iter().zip(healthy).fold(
            (0usize, 0usize),
            |(recall_movement, agreement_movement), (actual, expected)| {
                (
                    recall_movement + actual.0.abs_diff(expected.0),
                    agreement_movement + actual.1.abs_diff(expected.1),
                )
            },
        );
        let (recall_budget, agreement_budget) = retrieval_quality_movement_budget(healthy);
        if recall_movement > recall_budget || agreement_movement > agreement_budget {
            return Err(format!(
                "{tier:?} retrieval quality exceeds the fixture-relative movement budget: \
                 total absolute Recall@{top_k} movement={recall_movement} hit(s) \
                 (maximum {recall_budget}), total absolute pairwise-agreement movement=\
                 {agreement_movement} pair(s) (maximum {agreement_budget})"
            ));
        }

        let (maximum_query_recall_movement, maximum_query_agreement_movement) =
            retrieval_quality_concentration_budget(healthy);
        for (query_index, (&(recall_hits, agreements), &(healthy_hits, healthy_agreements))) in
            query_quality.iter().zip(healthy).enumerate()
        {
            let recall_movement = recall_hits.abs_diff(healthy_hits);
            let agreement_movement = agreements.abs_diff(healthy_agreements);
            if recall_movement > maximum_query_recall_movement
                || agreement_movement > maximum_query_agreement_movement
            {
                return Err(format!(
                    "{tier:?} query {query_index} exceeds the fixture-relative concentration \
                     bound: Recall@{top_k} movement={recall_movement} hit(s) \
                     (maximum {maximum_query_recall_movement}), pairwise-agreement \
                     movement={agreement_movement} pair(s) \
                     (maximum {maximum_query_agreement_movement})"
                ));
            }
        }
        Ok((recall, agreement))
    }

    /// Refuses to let a retrieval-fidelity fixture be scored when it cannot
    /// distinguish quality tiers from each other.
    ///
    /// Only the independent f64 reference ranking is checked here — ties
    /// among *quantized* tier scores are the exact behaviour under test
    /// (e.g. Binary legitimately collapses many candidates to the same
    /// Hamming distance) and must never be rejected.
    fn validate_retrieval_fixture(
        corpus: &[Vec<f32>],
        queries: &[Vec<f32>],
        top_k: usize,
    ) -> std::result::Result<(), String> {
        if top_k == 0 {
            return Err("retrieval fixture has top_k=0".to_string());
        }
        if queries.is_empty() {
            return Err("retrieval fixture has zero queries".to_string());
        }
        if corpus.len() < top_k {
            return Err(format!(
                "retrieval fixture corpus size {} is smaller than top_k={top_k}",
                corpus.len()
            ));
        }
        for (query_index, query) in queries.iter().enumerate() {
            let mut ranked_scores = Vec::with_capacity(corpus.len());
            for (candidate_index, candidate) in corpus.iter().enumerate() {
                let score = scalar_cosine_f64(query, candidate);
                if !score.is_finite() {
                    return Err(format!(
                        "retrieval fixture query {query_index} candidate {candidate_index} has \
                         non-finite reference score {score}"
                    ));
                }
                ranked_scores.push((candidate_index, score));
            }
            ranked_scores.sort_unstable_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));

            let mut distinct_scores: Vec<_> =
                ranked_scores.iter().map(|(_, score)| *score).collect();
            distinct_scores.sort_unstable_by(f64::total_cmp);
            distinct_scores.dedup();
            if distinct_scores.len() <= top_k {
                return Err(format!(
                    "retrieval fixture query {query_index} is non-discriminating: only \
                     {} distinct finite reference score(s) across {} candidates, need \
                     more than top_k={top_k}",
                    distinct_scores.len(),
                    corpus.len()
                ));
            }

            for (rank, boundary) in ranked_scores.windows(2).enumerate() {
                let higher_score = boundary[0].1;
                let lower_score = boundary[1].1;
                if higher_score as f32 <= lower_score as f32 {
                    return Err(format!(
                        "retrieval fixture query {query_index} has a near-tied ranking boundary \
                         at ranks {rank} and {}: reference scores {higher_score} and \
                         {lower_score} do not remain ordered at f32 precision",
                        rank + 1
                    ));
                }
            }
        }

        let (surrogate_recall, surrogate_agreement) =
            index_order_surrogate_quality(corpus, queries, top_k);
        for tier in [
            QuantizationTier::Full,
            QuantizationTier::Int8,
            QuantizationTier::Int4,
            QuantizationTier::Binary,
        ] {
            let (minimum_recall, minimum_agreement) = retrieval_quality_floor(tier);
            if meets_retrieval_quality_floor(surrogate_recall, minimum_recall)
                && meets_retrieval_quality_floor(surrogate_agreement, minimum_agreement)
            {
                return Err(format!(
                    "retrieval fixture is non-discriminating: an all-tied index-order surrogate \
                     passes the {tier:?} floor with Recall@{top_k}={surrogate_recall:.6} and \
                     pairwise ranking agreement={surrogate_agreement:.6}"
                ));
            }
        }
        Ok(())
    }

    fn fixed_retrieval_fixture() -> (Vec<Vec<f32>>, Vec<Vec<f32>>) {
        const DIMS: usize = 384;
        const CORPUS_SIZE: usize = 256;
        const QUERY_COUNT: usize = 16;
        let corpus = (0..CORPUS_SIZE)
            .map(|index| generate_vector(DIMS, 0xC0A5_0000 + index as u64))
            .collect();
        let queries = (0..QUERY_COUNT)
            .map(|index| generate_vector(DIMS, 0x0A11_0000 + index as u64))
            .collect();
        (corpus, queries)
    }

    #[test]
    fn test_tier_retrieval_quality_against_independent_f64_ranking() {
        const TOP_K: usize = 10;
        let (corpus, queries) = fixed_retrieval_fixture();
        validate_retrieval_fixture(&corpus, &queries, TOP_K)
            .expect("retrieval fixture must be discriminating before scoring tiers against it");

        for tier in [
            QuantizationTier::Full,
            QuantizationTier::Int8,
            QuantizationTier::Int4,
            QuantizationTier::Binary,
        ] {
            let stored: Vec<_> = corpus
                .iter()
                .map(|candidate| QuantizedData::from_f32(candidate, tier))
                .collect();
            assert!(
                stored.iter().all(|candidate| candidate.tier() == tier),
                "{tier:?} conversion was bypassed or routed to another tier"
            );
            assert!(
                stored
                    .iter()
                    .all(|candidate| candidate.storage_bytes()
                        == tier.storage_bytes(candidate.dims())),
                "{tier:?} conversion produced the wrong representation size"
            );

            if tier != QuantizationTier::Full {
                assert!(
                    stored.iter().zip(&corpus).any(|(quantized, original)| {
                        quantized
                            .to_f32()
                            .iter()
                            .zip(original)
                            .any(|(actual, expected)| (actual - expected).abs() > 1e-4)
                    }),
                    "{tier:?} conversion did not exercise a lossy representation"
                );
            }

            let mut query_quality = Vec::with_capacity(queries.len());
            let mut quantized_distance_witness = false;
            for query in &queries {
                let reference = reference_ranking(query, &corpus);
                let actual = tier_ranking(query, &stored, tier);
                query_quality.push(retrieval_quality_counts(&reference, &actual, TOP_K));

                if tier != QuantizationTier::Full {
                    let prepared = PreparedQuery::from_f32(query, tier);
                    quantized_distance_witness |=
                        stored.iter().zip(&corpus).any(|(quantized, original)| {
                            let actual =
                                approximate_cosine_distance_prepared(&prepared, quantized).unwrap();
                            let reference = 1.0 - scalar_cosine_f64(query, original) as f32;
                            (actual - reference).abs() > 1e-4
                        });
                }
            }
            let (recall, agreement) = validate_tier_retrieval_quality(tier, &query_quality, TOP_K)
                .unwrap_or_else(|error| panic!("{error}"));
            eprintln!(
                "{tier:?}: Recall@{TOP_K}={recall:.6}, pairwise ranking agreement={agreement:.6}"
            );

            if tier != QuantizationTier::Full {
                assert!(
                    quantized_distance_witness,
                    "{tier:?} distance path did not differ from the independent f32 reference"
                );
            }
        }
    }

    #[test]
    fn test_tier_retrieval_quality_rejects_concentrated_binary_query_collapse() {
        const TOP_K: usize = 10;
        const COLLAPSED_QUERY_COUNT: usize = 10;
        let (corpus, queries) = fixed_retrieval_fixture();
        let index_order: Vec<_> = (0..corpus.len()).collect();
        let query_quality: Vec<_> = queries
            .iter()
            .enumerate()
            .map(|(query_index, query)| {
                let reference = reference_ranking(query, &corpus);
                let actual = if query_index < COLLAPSED_QUERY_COUNT {
                    index_order.clone()
                } else {
                    reference.clone()
                };
                retrieval_quality_counts(&reference, &actual, TOP_K)
            })
            .collect();

        let mean_recall = query_quality.iter().map(|quality| quality.0).sum::<usize>() as f64
            / (query_quality.len() * TOP_K) as f64;
        let mean_agreement = query_quality.iter().map(|quality| quality.1).sum::<usize>() as f64
            / (query_quality.len() * 32_640) as f64;
        assert_eq!(format!("{mean_recall:.6}"), "0.381250");
        assert_eq!(format!("{mean_agreement:.6}"), "0.705356");

        let error = validate_tier_retrieval_quality(
            QuantizationTier::Binary,
            &query_quality,
            TOP_K,
        )
        .expect_err(
            "collapsing fixed fixture queries 0 through 9 must fail despite passing both means",
        );
        assert!(error.contains("query 0"), "unexpected error: {error}");
    }

    #[test]
    fn test_tier_retrieval_quality_rejects_single_binary_query_concentration() {
        const TOP_K: usize = 10;
        const SUFFIX_INVERSIONS: usize = 7_161;
        let (corpus, queries) = fixed_retrieval_fixture();
        let reference = reference_ranking(&queries[0], &corpus);
        let mut remaining = reference[3..10]
            .iter()
            .chain(&reference[17..])
            .copied()
            .collect::<Vec<_>>();
        let mut suffix = Vec::with_capacity(remaining.len());
        let mut inversions = SUFFIX_INVERSIONS;
        while !remaining.is_empty() {
            let index = inversions.min(remaining.len() - 1);
            inversions -= index;
            suffix.push(remaining.remove(index));
        }
        assert_eq!(inversions, 0);

        let mut actual = Vec::with_capacity(reference.len());
        actual.extend_from_slice(&reference[..3]);
        actual.extend_from_slice(&reference[10..17]);
        actual.extend(suffix);
        assert_eq!(actual.len(), reference.len());

        let collapsed_quality = retrieval_quality_counts(&reference, &actual, TOP_K);
        assert_eq!(collapsed_quality, (3, 25_430));

        let mut query_quality = healthy_query_quality(QuantizationTier::Binary).to_vec();
        query_quality[0] = collapsed_quality;

        let error =
            validate_tier_retrieval_quality(QuantizationTier::Binary, &query_quality, TOP_K)
                .expect_err("one Binary query must not spend the complete fixture movement budget");
        assert!(
            error.contains("query 0") && error.contains("concentration"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn test_tier_retrieval_quality_rejects_single_binary_query_agreement_concentration() {
        const TOP_K: usize = 10;
        let mut query_quality = healthy_query_quality(QuantizationTier::Binary).to_vec();
        query_quality[0].1 -= 1_281;

        let error =
            validate_tier_retrieval_quality(QuantizationTier::Binary, &query_quality, TOP_K)
                .expect_err("one Binary query must not spend nearly the complete pair budget");
        assert!(
            error.contains("query 0") && error.contains("concentration"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn test_tier_retrieval_quality_rejects_distributed_binary_query_collapse() {
        const TOP_K: usize = 10;
        let (corpus, queries) = fixed_retrieval_fixture();
        let query_quality: Vec<_> = queries
            .iter()
            .map(|query| {
                let reference = reference_ranking(query, &corpus);
                let mut actual = Vec::with_capacity(reference.len());
                actual.extend_from_slice(&reference[..3]);
                actual.extend_from_slice(&reference[10..17]);
                actual.extend_from_slice(&reference[3..10]);
                actual.extend(reference[17..154].iter().rev().copied());
                actual.extend_from_slice(&reference[154..]);
                assert_eq!(actual.len(), reference.len());
                retrieval_quality_counts(&reference, &actual, TOP_K)
            })
            .collect();

        assert!(
            query_quality
                .iter()
                .all(|&(recall, agreement)| { recall == 3 && agreement == 32_640 - 9_365 })
        );

        let error =
            validate_tier_retrieval_quality(QuantizationTier::Binary, &query_quality, TOP_K)
                .expect_err("a distributed 70% Recall@10 loss across every query must fail");
        assert!(
            error.contains("movement budget"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn test_tier_retrieval_quality_rejects_shallow_all_query_movement() {
        const TOP_K: usize = 10;
        let (corpus, queries) = fixed_retrieval_fixture();
        let query_quality: Vec<_> = queries
            .iter()
            .map(|query| {
                let reference = reference_ranking(query, &corpus);
                let mut actual = reference.clone();
                let last = actual.len() - 1;
                actual.swap(TOP_K - 1, last);
                retrieval_quality_counts(&reference, &actual, TOP_K)
            })
            .collect();

        assert!(
            query_quality
                .iter()
                .all(|&(recall, agreement)| { recall == 9 && agreement == 32_640 - 491 })
        );

        for (tier, result) in [
            (
                QuantizationTier::Int4,
                validate_tier_retrieval_quality(QuantizationTier::Int4, &query_quality, TOP_K),
            ),
            (
                QuantizationTier::Binary,
                validate_tier_retrieval_quality(QuantizationTier::Binary, &query_quality, TOP_K),
            ),
        ] {
            let error = result.unwrap_err();
            assert!(
                error.contains("movement budget"),
                "unexpected {tier:?} error: {error}"
            );
        }
    }

    #[test]
    fn test_tier_retrieval_quality_bounds_stated_binary_uniform_movement() {
        const TOP_K: usize = 10;
        let query_quality_with_pair_loss = |pair_loss: u16| {
            healthy_query_quality(QuantizationTier::Binary)
                .iter()
                .map(|&(recall_hits, agreements)| {
                    (recall_hits, agreements - usize::from(pair_loss))
                })
                .collect::<Vec<_>>()
        };

        validate_tier_retrieval_quality(
            QuantizationTier::Binary,
            &query_quality_with_pair_loss(80),
            TOP_K,
        )
        .expect("1,280 total agreement-pair changes are within the 1,282-pair budget");

        let error = validate_tier_retrieval_quality(
            QuantizationTier::Binary,
            &query_quality_with_pair_loss(81),
            TOP_K,
        )
        .expect_err("1,296 total agreement-pair changes must exceed the 1,282-pair budget");
        assert!(
            error.contains("movement budget"),
            "unexpected error: {error}"
        );
    }

    #[test]
    fn test_tier_retrieval_quality_accepts_non_uniform_exact_binary_movement_boundary() {
        const TOP_K: usize = 10;
        let query_quality = healthy_query_quality(QuantizationTier::Binary)
            .iter()
            .enumerate()
            .map(|(query_index, &(recall_hits, agreements))| {
                let pair_loss = if query_index < 14 { 81 } else { 74 };
                (recall_hits, agreements - pair_loss)
            })
            .collect::<Vec<_>>();

        validate_tier_retrieval_quality(QuantizationTier::Binary, &query_quality, TOP_K)
            .expect("the exact 1,282-pair non-uniform movement boundary must be accepted");
    }

    #[test]
    fn test_validate_retrieval_fixture_rejects_non_discriminating_corpus() {
        const TOP_K: usize = 10;
        const DIMS: usize = 384;
        const CORPUS_SIZE: usize = 256;
        const QUERY_COUNT: usize = 16;

        // Every candidate is the *same* lossy, non-constant vector: the
        // independent f64 reference score ties across the whole corpus, so
        // recall@10 and pairwise agreement would collapse to a meaningless
        // 1.0 for every tier if this fixture were ever scored.
        let repeated_vector = generate_vector(DIMS, 0xC0A5_0000);
        let corpus: Vec<Vec<f32>> = std::iter::repeat_n(repeated_vector, CORPUS_SIZE).collect();
        let queries: Vec<Vec<f32>> = (0..QUERY_COUNT)
            .map(|index| generate_vector(DIMS, 0x0A11_0000 + index as u64))
            .collect();

        let err = validate_retrieval_fixture(&corpus, &queries, TOP_K)
            .expect_err("a corpus of identical vectors ties every reference score; the guard must refuse rather than let it be scored");
        eprintln!("guard refused as expected: {err}");
    }

    #[test]
    fn test_validate_retrieval_fixture_rejects_zero_queries() {
        let (corpus, _queries) = fixed_retrieval_fixture();
        let err = validate_retrieval_fixture(&corpus, &[], 10)
            .expect_err("zero queries must be refused rather than panic or silently pass");
        eprintln!("guard refused as expected: {err}");
    }

    #[test]
    fn test_validate_retrieval_fixture_rejects_corpus_smaller_than_top_k() {
        let (corpus, queries) = fixed_retrieval_fixture();
        let small_corpus = corpus[..5].to_vec();
        let err = validate_retrieval_fixture(&small_corpus, &queries, 10).expect_err(
            "a corpus smaller than top_k must be refused rather than panic or return NaN",
        );
        eprintln!("guard refused as expected: {err}");
    }

    #[test]
    fn test_validate_retrieval_fixture_accepts_the_real_fixture() {
        let (corpus, queries) = fixed_retrieval_fixture();
        validate_retrieval_fixture(&corpus, &queries, 10)
            .expect("the real fixture is discriminating and must not be rejected");

        let (recall, agreement) = index_order_surrogate_quality(&corpus, &queries, 10);
        assert!((recall - 0.025).abs() < f64::EPSILON);
        assert!((agreement - 0.526_646_752_450_980_4).abs() < 1e-15);
        for (tier, minimum_recall, minimum_agreement) in [
            ("Full", 1.0, 0.999),
            ("Int8", 0.98, 0.995),
            ("Int4", 0.85, 0.95),
            ("Binary", 0.30, 0.70),
        ] {
            assert!(
                !meets_retrieval_quality_floor(recall, minimum_recall)
                    || !meets_retrieval_quality_floor(agreement, minimum_agreement),
                "index-order surrogate must fail the pinned {tier} floor"
            );
        }
    }

    #[test]
    fn test_validate_retrieval_fixture_rejects_binary_index_aligned_collapse() {
        const TOP_K: usize = 10;
        let query = vec![1.0, 0.0];
        let corpus: Vec<_> = (0..21)
            .map(|index| vec![21.0 - index as f32, 1.0])
            .collect();
        let queries = vec![query.clone()];

        let mut scores: Vec<_> = corpus
            .iter()
            .map(|candidate| scalar_cosine_f64(&query, candidate))
            .collect();
        scores.sort_unstable_by(f64::total_cmp);
        scores.dedup();
        assert_eq!(scores.len(), 21);

        let reference = reference_ranking(&query, &corpus);
        let binary: Vec<_> = corpus
            .iter()
            .map(|candidate| QuantizedData::from_f32(candidate, QuantizationTier::Binary))
            .collect();
        let prepared = PreparedQuery::from_f32(&query, QuantizationTier::Binary);
        let first_code = match &binary[0] {
            QuantizedData::Binary(value) => &value.data,
            _ => unreachable!("binary conversion must produce the Binary variant"),
        };
        assert!(binary.iter().all(|candidate| {
            let QuantizedData::Binary(value) = candidate else {
                return false;
            };
            value.data == *first_code
                && approximate_cosine_distance_prepared(&prepared, candidate).unwrap() == 0.0
        }));
        let actual = tier_ranking(&query, &binary, QuantizationTier::Binary);
        assert_eq!(reference, (0..21).collect::<Vec<_>>());
        assert_eq!(actual, reference);
        assert_eq!(recall_at(&reference, &actual, TOP_K), 1.0);
        assert_eq!(pairwise_ranking_agreement(&reference, &actual), 1.0);

        let err = validate_retrieval_fixture(&corpus, &queries, TOP_K).expect_err(
            "an index-aligned reference must not let a totally collapsed tier pass its floors",
        );
        assert!(
            err.contains("index-order surrogate"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_validate_retrieval_fixture_rejects_mixed_non_finite_scores() {
        for non_finite in [f32::NAN, f32::INFINITY] {
            let (mut corpus, queries) = fixed_retrieval_fixture();
            corpus[0][0] = non_finite;
            let err = validate_retrieval_fixture(&corpus, &queries, 10)
                .expect_err("the first non-finite reference score must invalidate the oracle");
            assert!(
                err.contains("query 0 candidate 0"),
                "unexpected error: {err}"
            );
            assert!(err.contains("non-finite"), "unexpected error: {err}");
        }
    }

    #[test]
    fn test_validate_retrieval_fixture_rejects_zero_top_k() {
        let (corpus, queries) = fixed_retrieval_fixture();
        let err = validate_retrieval_fixture(&corpus, &queries, 0)
            .expect_err("top_k=0 must be refused before recall divides by zero");
        assert!(err.contains("top_k=0"), "unexpected error: {err}");
    }

    #[test]
    fn test_validate_retrieval_fixture_rejects_near_tied_top_k_boundary() {
        let query = vec![1.0, 0.0];
        let corpus = vec![
            vec![0.0, 1.0],
            vec![1.0, 0.0],
            vec![1.0, 0.0001],
            vec![-1.0, 0.0],
        ];
        let best = scalar_cosine_f64(&query, &corpus[1]);
        let runner_up = scalar_cosine_f64(&query, &corpus[2]);
        let boundary_gap = best - runner_up;
        assert!(boundary_gap > 0.0 && boundary_gap < 1e-6);

        let err = validate_retrieval_fixture(&corpus, &[query], 1)
            .expect_err("an f64-only near-tie at the evaluated cutoff must be refused");
        assert!(err.contains("near-tied"), "unexpected error: {err}");
    }

    #[test]
    fn test_validate_retrieval_fixture_rejects_near_tied_pairwise_boundary() {
        let query = vec![1.0, 0.0];
        let corpus = vec![
            vec![-1.0, 0.0],
            vec![1.0, 0.0],
            vec![100.0, 1.0],
            vec![100.0, 1.0001],
        ];
        let second = scalar_cosine_f64(&query, &corpus[2]);
        let third = scalar_cosine_f64(&query, &corpus[3]);
        assert!(second > third);
        assert_eq!(second as f32, third as f32);

        let err = validate_retrieval_fixture(&corpus, &[query], 1)
            .expect_err("an f64-only near-tie evaluated by pairwise agreement must be refused");
        assert!(err.contains("near-tied"), "unexpected error: {err}");
    }

    #[test]
    fn test_tier_bytes_per_dim() {
        assert_eq!(QuantizationTier::Full.bytes_per_dim(), 4.0);
        assert_eq!(QuantizationTier::Int8.bytes_per_dim(), 1.0);
        assert_eq!(QuantizationTier::Int4.bytes_per_dim(), 0.5);
        assert_eq!(QuantizationTier::Binary.bytes_per_dim(), 0.125);
    }

    #[test]
    fn test_tier_compression_ratios() {
        assert_eq!(QuantizationTier::Full.compression_ratio(), 1.0);
        assert_eq!(QuantizationTier::Int8.compression_ratio(), 4.0);
        assert_eq!(QuantizationTier::Int4.compression_ratio(), 8.0);
        assert_eq!(QuantizationTier::Binary.compression_ratio(), 32.0);
    }

    #[test]
    fn test_tier_storage_bytes() {
        assert_eq!(QuantizationTier::Full.storage_bytes(384), 1536);
        assert_eq!(QuantizationTier::Int8.storage_bytes(384), 384);
        assert_eq!(QuantizationTier::Int4.storage_bytes(384), 192);
        assert_eq!(QuantizationTier::Binary.storage_bytes(384), 48);
    }

    #[test]
    fn test_tier_from_age() {
        assert_eq!(
            QuantizationTier::from_age_seconds(0),
            QuantizationTier::Full
        );
        assert_eq!(
            QuantizationTier::from_age_seconds(1800),
            QuantizationTier::Full
        ); // 30 min
        assert_eq!(
            QuantizationTier::from_age_seconds(7200),
            QuantizationTier::Int8
        ); // 2 hours
        assert_eq!(
            QuantizationTier::from_age_seconds(172800),
            QuantizationTier::Int4
        ); // 2 days
        assert_eq!(
            QuantizationTier::from_age_seconds(1_000_000),
            QuantizationTier::Binary
        ); // ~11 days
    }

    #[test]
    fn test_quantized_data_from_f32_all_tiers() {
        let v = generate_vector(384, 42);

        for tier in [
            QuantizationTier::Full,
            QuantizationTier::Int8,
            QuantizationTier::Int4,
            QuantizationTier::Binary,
        ] {
            let data = QuantizedData::from_f32(&v, tier);
            assert_eq!(data.tier(), tier, "tier mismatch for {tier:?}");
            assert_eq!(data.dims(), 384, "dims mismatch for {tier:?}");

            // Verify storage bytes match expected
            let expected_bytes = tier.storage_bytes(384);
            assert_eq!(
                data.storage_bytes(),
                expected_bytes,
                "storage bytes mismatch for {tier:?}"
            );
        }
    }

    #[test]
    fn test_approximate_cosine_distance_ordering() {
        // Vectors a and b should be "closer" than a and c.
        let a = generate_vector(384, 1);
        // b = a + small noise
        let b: Vec<f32> = a
            .iter()
            .enumerate()
            .map(|(i, &x)| x + 0.05 * (i as f32 * 0.3).sin())
            .collect();
        // c = random, uncorrelated
        let c = generate_vector(384, 999);

        for tier in [
            QuantizationTier::Full,
            QuantizationTier::Int8,
            QuantizationTier::Int4,
            QuantizationTier::Binary,
        ] {
            let stored_b = QuantizedData::from_f32(&b, tier);
            let stored_c = QuantizedData::from_f32(&c, tier);

            let dist_ab = approximate_cosine_distance(&a, &stored_b);
            let dist_ac = approximate_cosine_distance(&a, &stored_c);

            // a should be closer to b than to c at all tiers
            assert!(
                dist_ab < dist_ac,
                "{tier:?}: dist(a,b)={dist_ab} should be < dist(a,c)={dist_ac}"
            );
        }
    }

    #[test]
    fn test_promote_demote_roundtrip() {
        let v = generate_vector(384, 42);
        let binary = QuantizedData::from_f32(&v, QuantizationTier::Binary);

        // Promote Binary -> Int4 -> Int8 -> Full
        let int4 = binary.promote(QuantizationTier::Int4);
        assert_eq!(int4.tier(), QuantizationTier::Int4);

        let int8 = int4.promote(QuantizationTier::Int8);
        assert_eq!(int8.tier(), QuantizationTier::Int8);

        let full = int8.promote(QuantizationTier::Full);
        assert_eq!(full.tier(), QuantizationTier::Full);
        assert_eq!(full.dims(), 384);
    }

    #[test]
    fn test_int8_batch_prepared_matches_per_item_prepared() {
        let query = generate_vector(384, 42);
        let prepared = PreparedQuery::from_f32(&query, QuantizationTier::Int8);
        let candidates: Vec<QuantizedVector> = (0..32)
            .map(|i| QuantizedVector::from_f32(&generate_vector(384, i + 1)))
            .collect();
        let wrapped: Vec<QuantizedData> = candidates
            .iter()
            .cloned()
            .map(QuantizedData::Int8)
            .collect();

        let got = approximate_int8_batch_prepared(&prepared, &candidates).unwrap();
        for (i, item) in wrapped.iter().enumerate() {
            let expected = approximate_cosine_distance_prepared(&prepared, item).unwrap();
            assert!(
                (got[i] - expected).abs() < 1e-6,
                "int8 batch prepared mismatch at candidate {i}: got={}, expected={}",
                got[i],
                expected
            );
        }
    }

    #[test]
    fn test_int4_batch_prepared_matches_per_item_prepared() {
        let query = generate_vector(384, 42);
        let prepared = PreparedQuery::from_f32(&query, QuantizationTier::Int4);
        let candidates: Vec<Int4Vector> = (0..32)
            .map(|i| Int4Vector::from_f32(&generate_vector(384, i + 1)))
            .collect();
        let wrapped: Vec<QuantizedData> = candidates
            .iter()
            .cloned()
            .map(QuantizedData::Int4)
            .collect();

        let got = approximate_int4_batch_prepared(&prepared, &candidates).unwrap();
        for (i, item) in wrapped.iter().enumerate() {
            let expected = approximate_cosine_distance_prepared(&prepared, item).unwrap();
            assert!(
                (got[i] - expected).abs() < 1e-5,
                "int4 batch prepared mismatch at candidate {i}: got={}, expected={}",
                got[i],
                expected
            );
        }
    }

    #[test]
    fn test_int4_batch_prepared_api_dispatch_parity() {
        // Verify that approximate_int4_batch_prepared produces the same cosine distance
        // as approximate_cosine_distance_prepared for each candidate. On aarch64 both
        // sides dispatch to NEON; on other targets both use the packed scalar fallback.
        // For direct scalar-vs-NEON integer parity, see int4::tests::test_packed_scalar_matches_neon_exact.
        for dim in [1usize, 3, 31, 127, 383, 384] {
            let query = generate_vector(dim, 700 + dim as u64);
            let candidate = generate_vector(dim, 800 + dim as u64);
            let prepared = PreparedQuery::from_f32(&query, QuantizationTier::Int4);
            let q_cand = Int4Vector::from_f32(&candidate);
            let wrapped = QuantizedData::Int4(q_cand.clone());

            let batch_result = approximate_int4_batch_prepared(&prepared, &[q_cand]).unwrap();
            let per_item_result =
                approximate_cosine_distance_prepared(&prepared, &wrapped).unwrap();

            assert!(
                (batch_result[0] - per_item_result).abs() < 1e-5,
                "int4 batch prepared dispatch mismatch at dim={dim}: batch={}, per_item={}",
                batch_result[0],
                per_item_result
            );
        }
    }

    #[test]
    fn test_quantized_data_to_f32_roundtrip() {
        let v = generate_vector(384, 55);

        // Full tier should be lossless
        let full_data = QuantizedData::from_f32(&v, QuantizationTier::Full);
        let full_rt = full_data.to_f32();
        for (a, b) in v.iter().zip(full_rt.iter()) {
            assert!((a - b).abs() < 1e-10, "Full tier should be lossless");
        }
    }

    // ------------------------------------------------------------------
    // Regression tests for issue #210: tier-mismatch in prepared SIMD
    // dispatch must return a typed error, not panic.
    // ------------------------------------------------------------------

    #[test]
    fn test_cosine_distance_prepared_tier_mismatch_returns_typed_error() {
        let v = generate_vector(64, 1);
        let query = PreparedQuery::from_f32(&v, QuantizationTier::Int8);
        let stored = QuantizedData::from_f32(&v, QuantizationTier::Int4);

        let err = approximate_cosine_distance_prepared(&query, &stored).unwrap_err();
        match err {
            EmbedError::TierMismatch {
                op,
                expected,
                actual,
            } => {
                assert_eq!(op, "approximate_cosine_distance_prepared");
                assert_eq!(expected, QuantizationTier::Int4);
                assert_eq!(actual, QuantizationTier::Int8);
            }
            other => panic!("expected TierMismatch, got {other:?}"),
        }

        // try_ alias must agree.
        assert!(try_approximate_cosine_distance_prepared(&query, &stored).is_err());
    }

    #[test]
    fn test_dot_product_prepared_tier_mismatch_returns_typed_error() {
        let v = generate_vector(64, 2);
        let query = PreparedQuery::from_f32(&v, QuantizationTier::Full);
        let stored = QuantizedData::from_f32(&v, QuantizationTier::Int8);

        let err = approximate_dot_product_prepared(&query, &stored).unwrap_err();
        assert!(
            matches!(
                err,
                EmbedError::TierMismatch {
                    op: "approximate_dot_product_prepared",
                    ..
                }
            ),
            "unexpected error variant: {err:?}"
        );

        assert!(try_approximate_dot_product_prepared(&query, &stored).is_err());
    }

    #[test]
    fn test_dot_product_prepared_binary_returns_typed_error_not_panic() {
        let v = generate_vector(64, 3);
        let query = PreparedQuery::from_f32(&v, QuantizationTier::Binary);
        let stored = QuantizedData::from_f32(&v, QuantizationTier::Binary);

        let err = approximate_dot_product_prepared(&query, &stored).unwrap_err();
        assert!(
            matches!(err, EmbedError::Internal(_)),
            "unexpected error variant: {err:?}"
        );
    }

    #[test]
    fn test_cosine_distance_prepared_with_meta_tier_mismatch_returns_typed_error() {
        let v = generate_vector(64, 4);
        let meta =
            PreparedQueryWithMeta::from_f32(&v, QuantizationTier::Full, NormalizationHint::Unknown);
        let stored = QuantizedData::from_f32(&v, QuantizationTier::Int8);

        let err = approximate_cosine_distance_prepared_with_meta(
            &meta,
            &stored,
            NormalizationHint::Unknown,
        )
        .unwrap_err();
        assert!(matches!(err, EmbedError::TierMismatch { .. }));
    }

    #[test]
    fn test_cosine_distance_prepared_with_meta_validates_stored_unit_norm() {
        let query = vec![std::f32::consts::FRAC_1_SQRT_2; 2];
        let meta = PreparedQueryWithMeta::from_f32(
            &query,
            QuantizationTier::Full,
            NormalizationHint::Unit,
        );
        let stored = QuantizedData::Full(vec![2.0, 0.0]);

        let got =
            approximate_cosine_distance_prepared_with_meta(&meta, &stored, NormalizationHint::Unit)
                .unwrap();
        let expected = approximate_cosine_distance_prepared(&meta.query, &stored).unwrap();

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    #[test]
    fn test_batch_cosine_distance_prepared_tier_mismatch_returns_typed_error() {
        let v = generate_vector(64, 5);
        let query = PreparedQuery::from_f32(&v, QuantizationTier::Int8);
        let stored = vec![
            QuantizedData::from_f32(&v, QuantizationTier::Int8),
            QuantizedData::from_f32(&v, QuantizationTier::Int4), // mismatched
        ];

        let err = batch_approximate_cosine_distance_prepared(&query, &stored).unwrap_err();
        assert!(matches!(err, EmbedError::TierMismatch { .. }));

        let mut out = vec![9.0, 9.0, 9.0]; // pre-populated, must be cleared even on error
        let err =
            batch_approximate_cosine_distance_prepared_into(&query, &stored, &mut out).unwrap_err();
        assert!(matches!(err, EmbedError::TierMismatch { .. }));
        assert!(
            out.is_empty(),
            "buffer must be cleared, not left with stale data"
        );
    }

    #[test]
    fn test_int8_batch_prepared_wrong_tier_returns_typed_error() {
        let v = generate_vector(64, 6);
        let query = PreparedQuery::from_f32(&v, QuantizationTier::Int4); // not Int8
        let candidates = vec![QuantizedVector::from_f32(&v)];

        let err = approximate_int8_batch_prepared(&query, &candidates).unwrap_err();
        match err {
            EmbedError::TierMismatch {
                op,
                expected,
                actual,
            } => {
                assert_eq!(op, "approximate_int8_batch_prepared");
                assert_eq!(expected, QuantizationTier::Int8);
                assert_eq!(actual, QuantizationTier::Int4);
            }
            other => panic!("expected TierMismatch, got {other:?}"),
        }

        let mut out = vec![9.0];
        let err = approximate_int8_batch_prepared_into(&query, &candidates, &mut out).unwrap_err();
        assert!(matches!(err, EmbedError::TierMismatch { .. }));
        assert!(
            out.is_empty(),
            "buffer must be cleared, not left with stale data"
        );
    }

    #[test]
    fn test_int4_batch_prepared_wrong_tier_returns_typed_error() {
        let v = generate_vector(64, 7);
        let query = PreparedQuery::from_f32(&v, QuantizationTier::Int8); // not Int4
        let candidates = vec![Int4Vector::from_f32(&v)];

        let err = approximate_int4_batch_prepared(&query, &candidates).unwrap_err();
        match err {
            EmbedError::TierMismatch {
                op,
                expected,
                actual,
            } => {
                assert_eq!(op, "approximate_int4_batch_prepared");
                assert_eq!(expected, QuantizationTier::Int4);
                assert_eq!(actual, QuantizationTier::Int8);
            }
            other => panic!("expected TierMismatch, got {other:?}"),
        }

        let mut out = vec![9.0];
        let err = approximate_int4_batch_prepared_into(&query, &candidates, &mut out).unwrap_err();
        assert!(matches!(err, EmbedError::TierMismatch { .. }));
        assert!(
            out.is_empty(),
            "buffer must be cleared, not left with stale data"
        );
    }
}