aletheiadb 0.1.0

A high-performance bi-temporal graph database for LLM integration
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
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
//! Tests for core vector types and metrics.
//!
//! This module verifies the behavior of the base vector structures, dimensions,
//! metrics, and operations, ensuring fundamental math and logic are correct.

use super::*;
use crate::core::error::{Error, VectorError};
#[allow(unused_imports)]
use crate::core::property::MAX_VECTOR_DIMENSIONS;

#[test]
fn test_vector_dimension_new() {
    let dim = VectorDimension::new(1536);
    assert_eq!(dim.as_usize(), 1536);
}

#[test]
fn test_vector_dimension_from_usize() {
    let dim: VectorDimension = 384.into();
    assert_eq!(dim.as_usize(), 384);
}

#[test]
fn test_vector_dimension_into_usize() {
    let dim = VectorDimension::new(768);
    let size: usize = dim.into();
    assert_eq!(size, 768);
}

#[test]
fn test_max_dimension_constant() {
    assert_eq!(MAX_DIMENSION.as_usize(), 100_000);
    assert_eq!(MAX_DIMENSION.as_usize(), MAX_VECTOR_DIMENSIONS);
}

#[test]
fn test_dimension_comparison() {
    let small = VectorDimension::new(384);
    let large = VectorDimension::new(1536);

    assert!(small < large);
    assert!(large <= MAX_DIMENSION);
}

#[test]
fn test_dimension_equality() {
    let dim1 = VectorDimension::new(512);
    let dim2 = VectorDimension::new(512);
    let dim3 = VectorDimension::new(1024);

    assert_eq!(dim1, dim2);
    assert_ne!(dim1, dim3);
}

#[test]
fn test_dimension_display() {
    let dim = VectorDimension::new(1536);
    assert_eq!(format!("{}", dim), "1536");
}

#[test]
fn test_dimension_debug() {
    let dim = VectorDimension::new(384);
    assert_eq!(format!("{:?}", dim), "VectorDimension(384)");
}

#[test]
fn test_is_zero() {
    assert!(VectorDimension::new(0).is_zero());
    assert!(!VectorDimension::new(1).is_zero());
}

#[test]
fn test_exceeds_max() {
    assert!(!VectorDimension::new(1000).exceeds_max());
    assert!(!MAX_DIMENSION.exceeds_max());
    assert!(VectorDimension::new(100_001).exceeds_max());
}

#[test]
fn test_default() {
    let dim = VectorDimension::default();
    assert_eq!(dim.as_usize(), 0);
}

#[test]
fn test_copy_semantics() {
    let dim1 = VectorDimension::new(256);
    let dim2 = dim1; // Copy, not move
    assert_eq!(dim1, dim2); // Both still valid
}

#[test]
fn test_hash() {
    use std::collections::HashSet;

    let mut set = HashSet::new();
    set.insert(VectorDimension::new(384));
    set.insert(VectorDimension::new(768));
    set.insert(VectorDimension::new(384)); // Duplicate

    assert_eq!(set.len(), 2);
}

// ========================================================================
// Cosine Similarity Tests
// ========================================================================

#[test]
fn test_cosine_similarity_identical_vectors() {
    let a = vec![1.0, 2.0, 3.0];
    let b = vec![1.0, 2.0, 3.0];
    let sim = cosine_similarity(&a, &b).unwrap();
    assert!(
        (sim - 1.0).abs() < 1e-6,
        "Identical vectors should have similarity 1.0"
    );
}

#[test]
fn test_cosine_similarity_opposite_vectors() {
    let a = vec![1.0, 2.0, 3.0];
    let b = vec![-1.0, -2.0, -3.0];
    let sim = cosine_similarity(&a, &b).unwrap();
    assert!(
        (sim + 1.0).abs() < 1e-6,
        "Opposite vectors should have similarity -1.0"
    );
}

#[test]
fn test_cosine_similarity_orthogonal_vectors() {
    let a = vec![1.0, 0.0];
    let b = vec![0.0, 1.0];
    let sim = cosine_similarity(&a, &b).unwrap();
    assert!(
        sim.abs() < 1e-6,
        "Orthogonal vectors should have similarity 0.0"
    );
}

#[test]
fn test_cosine_similarity_3d_orthogonal() {
    let a = vec![1.0, 0.0, 0.0];
    let b = vec![0.0, 1.0, 0.0];
    let sim = cosine_similarity(&a, &b).unwrap();
    assert!(sim.abs() < 1e-6);

    let c = vec![0.0, 0.0, 1.0];
    let sim_ac = cosine_similarity(&a, &c).unwrap();
    assert!(sim_ac.abs() < 1e-6);
}

#[test]
fn test_cosine_similarity_known_angle() {
    // 45 degree angle: cos(45°) ≈ 0.7071
    let a = vec![1.0, 0.0];
    let b = vec![1.0, 1.0];
    let sim = cosine_similarity(&a, &b).unwrap();
    let expected = 1.0 / 2.0_f32.sqrt(); // cos(45°)
    assert!((sim - expected).abs() < 1e-6);
}

#[test]
fn test_cosine_similarity_dimension_mismatch() {
    let a = vec![1.0, 2.0, 3.0];
    let b = vec![1.0, 2.0];
    let result = cosine_similarity(&a, &b);
    assert!(result.is_err());
}

#[test]
fn test_cosine_similarity_empty_vectors() {
    let a: Vec<f32> = vec![];
    let b: Vec<f32> = vec![];
    let sim = cosine_similarity(&a, &b).unwrap();
    assert_eq!(sim, 0.0);
}

#[test]
fn test_cosine_similarity_zero_vector() {
    let a = vec![0.0, 0.0, 0.0];
    let b = vec![1.0, 2.0, 3.0];
    let sim = cosine_similarity(&a, &b).unwrap();
    assert_eq!(sim, 0.0, "Zero vector should result in similarity 0.0");
}

#[test]
fn test_cosine_similarity_both_zero_vectors() {
    let a = vec![0.0, 0.0];
    let b = vec![0.0, 0.0];
    let sim = cosine_similarity(&a, &b).unwrap();
    assert_eq!(sim, 0.0);
}

#[test]
fn test_cosine_similarity_unit_vectors() {
    // Unit vectors should give same result as non-unit
    let a = vec![3.0, 4.0]; // magnitude 5
    let b = vec![4.0, 3.0]; // magnitude 5
    let sim1 = cosine_similarity(&a, &b).unwrap();

    // Normalize manually
    let a_norm = vec![3.0 / 5.0, 4.0 / 5.0];
    let b_norm = vec![4.0 / 5.0, 3.0 / 5.0];
    let sim2 = cosine_similarity(&a_norm, &b_norm).unwrap();

    assert!((sim1 - sim2).abs() < 1e-6);
}

#[test]
fn test_cosine_similarity_negative_values() {
    let a = vec![-1.0, -2.0, 3.0];
    let b = vec![1.0, -2.0, -3.0];
    let sim = cosine_similarity(&a, &b).unwrap();
    // dot = -1 + 4 - 9 = -6
    // mag_a = sqrt(1 + 4 + 9) = sqrt(14)
    // mag_b = sqrt(1 + 4 + 9) = sqrt(14)
    // sim = -6 / 14 ≈ -0.4286
    let expected = -6.0 / 14.0;
    assert!((sim - expected).abs() < 1e-6);
}

#[test]
fn test_cosine_similarity_single_element() {
    let a = vec![5.0];
    let b = vec![3.0];
    let sim = cosine_similarity(&a, &b).unwrap();
    assert!(
        (sim - 1.0).abs() < 1e-6,
        "Parallel 1D vectors should have similarity 1.0"
    );

    let c = vec![-3.0];
    let sim_neg = cosine_similarity(&a, &c).unwrap();
    assert!(
        (sim_neg + 1.0).abs() < 1e-6,
        "Anti-parallel 1D vectors should have similarity -1.0"
    );
}

#[test]
fn test_cosine_similarity_symmetry() {
    let a = vec![1.0, 2.0, 3.0, 4.0];
    let b = vec![4.0, 3.0, 2.0, 1.0];
    let sim_ab = cosine_similarity(&a, &b).unwrap();
    let sim_ba = cosine_similarity(&b, &a).unwrap();
    assert!(
        (sim_ab - sim_ba).abs() < 1e-6,
        "Cosine similarity should be symmetric"
    );
}

#[test]
fn test_cosine_similarity_range() {
    // Various test cases to ensure result is always in [-1, 1]
    let test_cases = vec![
        (vec![1.0, 0.0], vec![1.0, 0.0]),
        (vec![1.0, 0.0], vec![-1.0, 0.0]),
        (vec![1.0, 0.0], vec![0.0, 1.0]),
        (vec![1.0, 1.0, 1.0], vec![2.0, 3.0, 4.0]),
        (vec![-1.0, -2.0], vec![3.0, 4.0]),
    ];

    for (a, b) in test_cases {
        let sim = cosine_similarity(&a, &b).unwrap();
        assert!(
            (-1.0..=1.0).contains(&sim),
            "Similarity {} is out of range [-1, 1] for vectors {:?} and {:?}",
            sim,
            a,
            b
        );
    }
}

// ========================================================================
// Large Dimension Tests
// ========================================================================

#[test]
fn test_cosine_similarity_large_dimension_1536() {
    // OpenAI text-embedding-3-small dimension
    let dim = 1536;
    let a: Vec<f32> = (0..dim).map(|i| (i as f32).sin()).collect();
    let b: Vec<f32> = (0..dim).map(|i| (i as f32).cos()).collect();

    let sim = cosine_similarity(&a, &b).unwrap();
    // Sine and cosine are approximately orthogonal over many periods
    assert!(
        sim.abs() < 0.1,
        "Expected near-orthogonal vectors at dim={}, got sim={}",
        dim,
        sim
    );
}

#[test]
fn test_cosine_similarity_large_dimension_3072() {
    // OpenAI text-embedding-3-large dimension
    let dim = 3072;
    let a: Vec<f32> = (0..dim).map(|i| (i as f32 * 0.1).sin()).collect();
    let b: Vec<f32> = (0..dim).map(|i| (i as f32 * 0.1).sin()).collect();

    let sim = cosine_similarity(&a, &b).unwrap();
    // Identical vectors should have similarity 1.0
    assert!(
        (sim - 1.0).abs() < 1e-5,
        "Expected self-similarity of 1.0 at dim={}, got {}",
        dim,
        sim
    );
}

#[test]
fn test_cosine_similarity_large_dimension_opposite() {
    let dim = 1536;
    let a: Vec<f32> = (0..dim).map(|i| (i as f32 * 0.01).cos()).collect();
    let b: Vec<f32> = a.iter().map(|x| -x).collect();

    let sim = cosine_similarity(&a, &b).unwrap();
    // Opposite vectors should have similarity -1.0
    assert!(
        (sim + 1.0).abs() < 1e-5,
        "Expected opposite similarity of -1.0 at dim={}, got {}",
        dim,
        sim
    );
}

#[test]
fn test_cosine_similarity_overflow_resilience() {
    // Regression test for intermediate overflow in magnitude calculation.
    // Values around 4.5e9 result in squared magnitude approx 2.0e19.
    // Product of squared magnitudes would be approx 4.0e38, which exceeds f32::MAX (3.4e38).
    // This previously caused the magnitude to be INF, resulting in similarity 0.0.

    let val = 4.5e9_f32;
    let a = vec![val];
    let b = vec![val];

    // Verify squared magnitude is finite but large
    let mag_sq: f32 = a.iter().map(|x| x * x).sum();
    assert!(mag_sq.is_finite(), "Squared magnitude should be finite");
    assert!(
        mag_sq > 1.8e19,
        "Squared magnitude should be large enough to trigger overflow risk"
    );

    // Verify product of squared magnitudes WOULD overflow
    assert!(
        (mag_sq * mag_sq).is_infinite(),
        "Product of squared magnitudes should overflow"
    );

    let sim = cosine_similarity(&a, &b).unwrap();

    assert!(
        (sim - 1.0).abs() < 1e-6,
        "Should correctly compute similarity 1.0 even with large values, got {}",
        sim
    );
}

// ========================================================================
// NaN/Inf Propagation Tests
// ========================================================================

#[test]
fn test_cosine_similarity_nan_propagation() {
    let a = vec![f32::NAN, 1.0];
    let b = vec![1.0, 1.0];
    let sim = cosine_similarity(&a, &b).unwrap();
    assert!(sim.is_nan(), "NaN in input should propagate to output");
}

#[test]
fn test_cosine_similarity_nan_in_second_vector() {
    let a = vec![1.0, 1.0];
    let b = vec![1.0, f32::NAN];
    let sim = cosine_similarity(&a, &b).unwrap();
    assert!(
        sim.is_nan(),
        "NaN in second vector should propagate to output"
    );
}

#[test]
fn test_cosine_similarity_inf_propagation() {
    let a = vec![f32::INFINITY, 1.0];
    let b = vec![1.0, 1.0];
    let sim = cosine_similarity(&a, &b).unwrap();
    // Inf * finite = Inf, and the computation will result in Inf/Inf = NaN
    // or a valid number depending on the exact math
    assert!(
        sim.is_nan() || sim.is_infinite() || (-1.0..=1.0).contains(&sim),
        "Inf should propagate in some form, got {}",
        sim
    );
}

#[test]
fn test_cosine_similarity_neg_inf_propagation() {
    let a = vec![f32::NEG_INFINITY, 1.0];
    let b = vec![1.0, 1.0];
    let sim = cosine_similarity(&a, &b).unwrap();
    assert!(
        sim.is_nan() || sim.is_infinite() || (-1.0..=1.0).contains(&sim),
        "Negative Inf should propagate in some form, got {}",
        sim
    );
}

#[test]
fn test_cosine_similarity_both_inf_same_sign() {
    let a = vec![f32::INFINITY, 0.0];
    let b = vec![f32::INFINITY, 0.0];
    let sim = cosine_similarity(&a, &b).unwrap();
    // Inf * Inf = Inf, sqrt(Inf * Inf) = Inf, Inf/Inf = NaN
    assert!(sim.is_nan(), "Inf/Inf should be NaN, got {}", sim);
}

// ========================================================================
// Normalized Cosine Similarity Tests
// ========================================================================
//
// Note: These tests use the public `normalize` function imported via super::*

#[test]
fn test_cosine_similarity_normalized_identical() {
    let a = normalize(&[1.0, 2.0, 3.0]);
    let sim = cosine_similarity_normalized(&a, &a).unwrap();
    assert!((sim - 1.0).abs() < 1e-6, "Self-similarity should be 1.0");
}

#[test]
fn test_cosine_similarity_normalized_opposite() {
    let a = normalize(&[1.0, 0.0]);
    let b = normalize(&[-1.0, 0.0]);
    let sim = cosine_similarity_normalized(&a, &b).unwrap();
    assert!(
        (sim + 1.0).abs() < 1e-6,
        "Opposite vectors should have similarity -1.0"
    );
}

#[test]
fn test_cosine_similarity_normalized_orthogonal() {
    let a = vec![1.0, 0.0, 0.0]; // Already unit
    let b = vec![0.0, 1.0, 0.0]; // Already unit
    let sim = cosine_similarity_normalized(&a, &b).unwrap();
    assert!(
        sim.abs() < 1e-6,
        "Orthogonal unit vectors should have similarity 0.0"
    );
}

#[test]
fn test_cosine_similarity_normalized_45_degrees() {
    // cos(45°) = 1/sqrt(2) ≈ 0.707
    let a = vec![1.0, 0.0];
    let b = normalize(&[1.0, 1.0]);
    let sim = cosine_similarity_normalized(&a, &b).unwrap();
    let expected = 1.0 / 2.0_f32.sqrt();
    assert!(
        (sim - expected).abs() < 1e-5,
        "Expected {}, got {}",
        expected,
        sim
    );
}

#[test]
fn test_cosine_similarity_normalized_matches_general() {
    let a_raw = vec![1.0, 2.0, 3.0, 4.0];
    let b_raw = vec![4.0, 3.0, 2.0, 1.0];

    // General cosine similarity
    let sim_general = cosine_similarity(&a_raw, &b_raw).unwrap();

    // Normalized version
    let a_norm = normalize(&a_raw);
    let b_norm = normalize(&b_raw);
    let sim_normalized = cosine_similarity_normalized(&a_norm, &b_norm).unwrap();

    assert!(
        (sim_general - sim_normalized).abs() < 1e-5,
        "General ({}) and normalized ({}) should match",
        sim_general,
        sim_normalized
    );
}

#[test]
fn test_cosine_similarity_normalized_dimension_mismatch() {
    let a = vec![1.0, 0.0, 0.0];
    let b = vec![1.0, 0.0];
    let result = cosine_similarity_normalized(&a, &b);
    assert!(result.is_err());
}

#[test]
fn test_cosine_similarity_normalized_empty() {
    let a: Vec<f32> = vec![];
    let b: Vec<f32> = vec![];
    let sim = cosine_similarity_normalized(&a, &b).unwrap();
    assert_eq!(sim, 0.0);
}

#[test]
fn test_cosine_similarity_normalized_high_dimension() {
    // Test with a higher dimension to exercise SIMD paths
    let dim = 384; // Sentence Transformers dimension
    let a: Vec<f32> = (0..dim).map(|i| (i as f32) / dim as f32).collect();
    let b: Vec<f32> = (0..dim).map(|i| ((dim - i) as f32) / dim as f32).collect();

    let a_norm = normalize(&a);
    let b_norm = normalize(&b);

    let sim = cosine_similarity_normalized(&a_norm, &b_norm).unwrap();
    let sim_general = cosine_similarity(&a, &b).unwrap();

    assert!(
        (sim - sim_general).abs() < 1e-4,
        "High-dim: general ({}) vs normalized ({})",
        sim_general,
        sim
    );
}

// ========================================================================
// Euclidean Distance Tests
// ========================================================================

#[test]
fn test_euclidean_distance_3_4_5_triangle() {
    // Classic 3-4-5 right triangle
    let a = vec![0.0, 0.0];
    let b = vec![3.0, 4.0];
    let dist = euclidean_distance(&a, &b).unwrap();
    assert!(
        (dist - 5.0).abs() < 1e-6,
        "3-4-5 triangle distance should be 5.0, got {}",
        dist
    );
}

#[test]
fn test_squared_euclidean_distance_3_4_5_triangle() {
    let a = vec![0.0, 0.0];
    let b = vec![3.0, 4.0];
    let dist_sq = squared_euclidean_distance(&a, &b).unwrap();
    assert!(
        (dist_sq - 25.0).abs() < 1e-6,
        "3² + 4² should be 25, got {}",
        dist_sq
    );
}

#[test]
fn test_euclidean_distance_same_point() {
    let a = vec![1.0, 2.0, 3.0];
    let dist = euclidean_distance(&a, &a).unwrap();
    assert!(
        dist.abs() < 1e-6,
        "Distance to self should be 0, got {}",
        dist
    );
}

#[test]
fn test_squared_euclidean_distance_same_point() {
    let a = vec![1.0, 2.0, 3.0];
    let dist_sq = squared_euclidean_distance(&a, &a).unwrap();
    assert!(
        dist_sq.abs() < 1e-6,
        "Squared distance to self should be 0, got {}",
        dist_sq
    );
}

#[test]
fn test_euclidean_distance_dimension_mismatch() {
    let a = vec![1.0, 2.0, 3.0];
    let b = vec![1.0, 2.0];
    let result = euclidean_distance(&a, &b);
    assert!(result.is_err());
}

#[test]
fn test_squared_euclidean_distance_dimension_mismatch() {
    let a = vec![1.0, 2.0, 3.0];
    let b = vec![1.0, 2.0];
    let result = squared_euclidean_distance(&a, &b);
    assert!(result.is_err());
}

#[test]
fn test_euclidean_distance_empty_vectors() {
    let a: Vec<f32> = vec![];
    let b: Vec<f32> = vec![];
    let dist = euclidean_distance(&a, &b).unwrap();
    assert_eq!(dist, 0.0);
}

#[test]
fn test_squared_euclidean_distance_empty_vectors() {
    let a: Vec<f32> = vec![];
    let b: Vec<f32> = vec![];
    let dist_sq = squared_euclidean_distance(&a, &b).unwrap();
    assert_eq!(dist_sq, 0.0);
}

#[test]
fn test_euclidean_distance_symmetry() {
    let a = vec![1.0, 2.0, 3.0, 4.0];
    let b = vec![4.0, 3.0, 2.0, 1.0];
    let dist_ab = euclidean_distance(&a, &b).unwrap();
    let dist_ba = euclidean_distance(&b, &a).unwrap();
    assert!(
        (dist_ab - dist_ba).abs() < 1e-6,
        "Euclidean distance should be symmetric"
    );
}

#[test]
fn test_squared_euclidean_distance_symmetry() {
    let a = vec![1.0, 2.0, 3.0, 4.0];
    let b = vec![4.0, 3.0, 2.0, 1.0];
    let dist_sq_ab = squared_euclidean_distance(&a, &b).unwrap();
    let dist_sq_ba = squared_euclidean_distance(&b, &a).unwrap();
    assert!(
        (dist_sq_ab - dist_sq_ba).abs() < 1e-6,
        "Squared Euclidean distance should be symmetric"
    );
}

#[test]
fn test_euclidean_distance_single_dimension() {
    let a = vec![5.0];
    let b = vec![2.0];
    let dist = euclidean_distance(&a, &b).unwrap();
    assert!(
        (dist - 3.0).abs() < 1e-6,
        "1D distance should be |5 - 2| = 3, got {}",
        dist
    );
}

#[test]
fn test_euclidean_distance_negative_values() {
    let a = vec![-1.0, -2.0];
    let b = vec![2.0, 2.0];
    let dist = euclidean_distance(&a, &b).unwrap();
    // sqrt((2 - -1)² + (2 - -2)²) = sqrt(9 + 16) = 5
    assert!(
        (dist - 5.0).abs() < 1e-6,
        "Distance with negative values should be 5.0, got {}",
        dist
    );
}

#[test]
fn test_euclidean_distance_3d() {
    // Distance from (0,0,0) to (1,2,2)
    let a = vec![0.0, 0.0, 0.0];
    let b = vec![1.0, 2.0, 2.0];
    let dist = euclidean_distance(&a, &b).unwrap();
    // sqrt(1 + 4 + 4) = sqrt(9) = 3
    assert!(
        (dist - 3.0).abs() < 1e-6,
        "3D distance should be 3.0, got {}",
        dist
    );
}

#[test]
fn test_euclidean_vs_squared_relationship() {
    let a = vec![1.0, 2.0, 3.0, 4.0, 5.0];
    let b = vec![5.0, 4.0, 3.0, 2.0, 1.0];
    let dist = euclidean_distance(&a, &b).unwrap();
    let dist_sq = squared_euclidean_distance(&a, &b).unwrap();
    assert!(
        (dist * dist - dist_sq).abs() < 1e-5,
        "euclidean² should equal squared_euclidean: {}² vs {}",
        dist,
        dist_sq
    );
}

#[test]
fn test_euclidean_distance_large_dimension_384() {
    // Sentence Transformers dimension
    let dim = 384;
    let a: Vec<f32> = (0..dim).map(|i| (i as f32).sin()).collect();
    let b: Vec<f32> = (0..dim).map(|i| (i as f32).cos()).collect();

    let dist = euclidean_distance(&a, &b).unwrap();
    let dist_sq = squared_euclidean_distance(&a, &b).unwrap();

    assert!(dist >= 0.0, "Distance should be non-negative");
    assert!(dist_sq >= 0.0, "Squared distance should be non-negative");
    assert!(
        (dist * dist - dist_sq).abs() < 1e-4,
        "Relationship should hold at high dimension"
    );
}

#[test]
fn test_euclidean_distance_large_dimension_1536() {
    // OpenAI text-embedding-3-small dimension
    let dim = 1536;
    let a: Vec<f32> = (0..dim).map(|i| (i as f32 * 0.01).sin()).collect();
    let b: Vec<f32> = (0..dim).map(|i| (i as f32 * 0.01).cos()).collect();

    let dist = euclidean_distance(&a, &b).unwrap();
    let dist_sq = squared_euclidean_distance(&a, &b).unwrap();

    assert!(dist >= 0.0, "Distance should be non-negative");
    assert!(
        (dist * dist - dist_sq).abs() < 1e-3,
        "Relationship should hold at dim={}: {}² vs {}",
        dim,
        dist,
        dist_sq
    );
}

#[test]
fn test_squared_euclidean_distance_preserves_ordering() {
    // Squared distance should preserve distance ordering for comparisons
    let query = vec![0.0, 0.0];
    let near = vec![1.0, 1.0];
    let far = vec![3.0, 4.0];

    let dist_near = euclidean_distance(&query, &near).unwrap();
    let dist_far = euclidean_distance(&query, &far).unwrap();
    let dist_sq_near = squared_euclidean_distance(&query, &near).unwrap();
    let dist_sq_far = squared_euclidean_distance(&query, &far).unwrap();

    // If near < far in distance, should also be true for squared distance
    assert!(dist_near < dist_far);
    assert!(dist_sq_near < dist_sq_far);
}

#[test]
fn test_euclidean_distance_unit_axis() {
    // Distance along unit axes
    let origin = vec![0.0, 0.0, 0.0];
    let x_axis = vec![1.0, 0.0, 0.0];
    let y_axis = vec![0.0, 1.0, 0.0];
    let z_axis = vec![0.0, 0.0, 1.0];

    assert!((euclidean_distance(&origin, &x_axis).unwrap() - 1.0).abs() < 1e-6);
    assert!((euclidean_distance(&origin, &y_axis).unwrap() - 1.0).abs() < 1e-6);
    assert!((euclidean_distance(&origin, &z_axis).unwrap() - 1.0).abs() < 1e-6);
}

// ========================================================================
// Dot Product Tests
// ========================================================================

#[test]
fn test_dot_product_basic() {
    // 1×4 + 2×5 + 3×6 = 4 + 10 + 18 = 32
    let a = vec![1.0, 2.0, 3.0];
    let b = vec![4.0, 5.0, 6.0];
    let result = dot_product(&a, &b).unwrap();
    assert!(
        (result - 32.0).abs() < 1e-6,
        "Dot product should be 32, got {}",
        result
    );
}

#[test]
fn test_dot_product_self_equals_squared_magnitude() {
    // dot(a, a) = ||a||²
    let a = vec![3.0, 4.0];
    let self_dot = dot_product(&a, &a).unwrap();
    // 3² + 4² = 9 + 16 = 25
    assert!(
        (self_dot - 25.0).abs() < 1e-6,
        "Self dot product should be 25, got {}",
        self_dot
    );
}

#[test]
fn test_dot_product_orthogonal_vectors() {
    // Orthogonal vectors have dot product 0
    let a = vec![1.0, 0.0];
    let b = vec![0.0, 1.0];
    let result = dot_product(&a, &b).unwrap();
    assert!(
        result.abs() < 1e-6,
        "Orthogonal vectors should have dot product 0, got {}",
        result
    );
}

#[test]
fn test_dot_product_orthogonal_3d() {
    let x = vec![1.0, 0.0, 0.0];
    let y = vec![0.0, 1.0, 0.0];
    let z = vec![0.0, 0.0, 1.0];

    assert!(dot_product(&x, &y).unwrap().abs() < 1e-6);
    assert!(dot_product(&y, &z).unwrap().abs() < 1e-6);
    assert!(dot_product(&x, &z).unwrap().abs() < 1e-6);
}

#[test]
fn test_dot_product_symmetry() {
    let a = vec![1.0, 2.0, 3.0, 4.0];
    let b = vec![4.0, 3.0, 2.0, 1.0];
    let dot_ab = dot_product(&a, &b).unwrap();
    let dot_ba = dot_product(&b, &a).unwrap();
    assert!(
        (dot_ab - dot_ba).abs() < 1e-6,
        "Dot product should be symmetric: {} vs {}",
        dot_ab,
        dot_ba
    );
}

#[test]
fn test_dot_product_dimension_mismatch() {
    let a = vec![1.0, 2.0, 3.0];
    let b = vec![1.0, 2.0];
    let result = dot_product(&a, &b);
    assert!(result.is_err());
}

#[test]
fn test_dot_product_empty_vectors() {
    let a: Vec<f32> = vec![];
    let b: Vec<f32> = vec![];
    let result = dot_product(&a, &b).unwrap();
    assert_eq!(result, 0.0);
}

#[test]
fn test_dot_product_single_element() {
    let a = vec![5.0];
    let b = vec![3.0];
    let result = dot_product(&a, &b).unwrap();
    assert!(
        (result - 15.0).abs() < 1e-6,
        "Single element dot product should be 15, got {}",
        result
    );
}

#[test]
fn test_dot_product_negative_values() {
    let a = vec![-1.0, 2.0, -3.0];
    let b = vec![4.0, -5.0, 6.0];
    // -1×4 + 2×(-5) + (-3)×6 = -4 - 10 - 18 = -32
    let result = dot_product(&a, &b).unwrap();
    assert!(
        (result + 32.0).abs() < 1e-6,
        "Dot product should be -32, got {}",
        result
    );
}

#[test]
fn test_dot_product_zero_vector() {
    let a = vec![0.0, 0.0, 0.0];
    let b = vec![1.0, 2.0, 3.0];
    let result = dot_product(&a, &b).unwrap();
    assert!(
        result.abs() < 1e-6,
        "Dot product with zero vector should be 0, got {}",
        result
    );
}

#[test]
fn test_dot_product_parallel_same_direction() {
    // Parallel vectors in same direction: dot = ||a|| × ||b||
    let a = vec![3.0, 0.0];
    let b = vec![4.0, 0.0];
    let result = dot_product(&a, &b).unwrap();
    // 3 × 4 = 12
    assert!(
        (result - 12.0).abs() < 1e-6,
        "Parallel same direction dot product should be 12, got {}",
        result
    );
}

#[test]
fn test_dot_product_parallel_opposite_direction() {
    // Parallel vectors in opposite direction: dot = -||a|| × ||b||
    let a = vec![3.0, 0.0];
    let b = vec![-4.0, 0.0];
    let result = dot_product(&a, &b).unwrap();
    // 3 × (-4) = -12
    assert!(
        (result + 12.0).abs() < 1e-6,
        "Parallel opposite direction dot product should be -12, got {}",
        result
    );
}

#[test]
fn test_dot_product_large_dimension_384() {
    // Sentence Transformers dimension
    let dim = 384;
    let a: Vec<f32> = (0..dim).map(|i| (i as f32).sin()).collect();
    let b: Vec<f32> = (0..dim).map(|i| (i as f32).cos()).collect();

    let result = dot_product(&a, &b).unwrap();
    // Just verify it runs and produces a finite result
    assert!(result.is_finite(), "Dot product should be finite");
}

#[test]
fn test_dot_product_large_dimension_1536() {
    // OpenAI text-embedding-3-small dimension
    let dim = 1536;
    let a: Vec<f32> = (0..dim).map(|i| (i as f32 * 0.01).sin()).collect();
    let b: Vec<f32> = (0..dim).map(|i| (i as f32 * 0.01).cos()).collect();

    let result = dot_product(&a, &b).unwrap();
    assert!(
        result.is_finite(),
        "Large dimension dot product should be finite"
    );
}

#[test]
fn test_dot_product_large_dimension_self() {
    // Self dot product at large dimension
    let dim = 1536;
    let a: Vec<f32> = (0..dim).map(|i| (i as f32 * 0.01).sin()).collect();

    let self_dot = dot_product(&a, &a).unwrap();
    // Self dot should equal sum of squares
    let expected: f32 = a.iter().map(|x| x * x).sum();
    assert!(
        (self_dot - expected).abs() < 1e-3,
        "Self dot at dim={} should equal sum of squares: {} vs {}",
        dim,
        self_dot,
        expected
    );
}

#[test]
fn test_dot_product_nan_propagation() {
    let a = vec![f32::NAN, 1.0];
    let b = vec![1.0, 1.0];
    let result = dot_product(&a, &b).unwrap();
    assert!(result.is_nan(), "NaN in input should propagate to output");
}

#[test]
fn test_dot_product_inf_propagation() {
    let a = vec![f32::INFINITY, 1.0];
    let b = vec![1.0, 1.0];
    let result = dot_product(&a, &b).unwrap();
    assert!(
        result.is_infinite() && result > 0.0,
        "Positive Inf should propagate, got {}",
        result
    );
}

#[test]
fn test_dot_product_neg_inf_propagation() {
    let a = vec![f32::NEG_INFINITY, 1.0];
    let b = vec![1.0, 1.0];
    let result = dot_product(&a, &b).unwrap();
    assert!(
        result.is_infinite() && result < 0.0,
        "Negative Inf should propagate, got {}",
        result
    );
}

#[test]
fn test_dot_product_matches_manual_calculation() {
    // Verify against manual calculation for various sizes
    for size in [1, 3, 7, 8, 15, 16, 17, 31, 32, 33, 100] {
        let a: Vec<f32> = (0..size).map(|i| i as f32).collect();
        let b: Vec<f32> = (0..size).map(|i| (size - i) as f32).collect();

        let simd_result = dot_product(&a, &b).unwrap();
        let manual_result: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();

        assert!(
            (simd_result - manual_result).abs() < 1e-4,
            "SIMD and manual should match at size {}: {} vs {}",
            size,
            simd_result,
            manual_result
        );
    }
}

#[test]
fn test_dot_product_simd_boundary_cases() {
    // Test at SIMD boundaries (multiples of 4 and 8)
    for size in [4, 8, 12, 16, 24, 32, 64, 128] {
        let a: Vec<f32> = (0..size).map(|i| (i as f32 * 0.1).sin()).collect();
        let b: Vec<f32> = (0..size).map(|i| (i as f32 * 0.1).cos()).collect();

        let simd_result = dot_product(&a, &b).unwrap();
        let expected: f32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();

        assert!(
            (simd_result - expected).abs() < 1e-5,
            "SIMD boundary case failed at size {}: {} vs {}",
            size,
            simd_result,
            expected
        );
    }
}

// ========================================================================
// Magnitude Tests
// ========================================================================

#[test]
fn test_magnitude_3_4_triangle() {
    // Classic 3-4-5 right triangle
    let v = vec![3.0, 4.0];
    let mag = magnitude(&v);
    assert!(
        (mag - 5.0).abs() < 1e-6,
        "Magnitude of [3, 4] should be 5, got {}",
        mag
    );
}

#[test]
fn test_magnitude_unit_vectors() {
    let unit_x = vec![1.0, 0.0, 0.0];
    let unit_y = vec![0.0, 1.0, 0.0];
    let unit_z = vec![0.0, 0.0, 1.0];

    assert!((magnitude(&unit_x) - 1.0).abs() < 1e-6);
    assert!((magnitude(&unit_y) - 1.0).abs() < 1e-6);
    assert!((magnitude(&unit_z) - 1.0).abs() < 1e-6);
}

#[test]
fn test_magnitude_zero_vector() {
    let v = vec![0.0, 0.0, 0.0];
    assert_eq!(magnitude(&v), 0.0);
}

#[test]
fn test_magnitude_empty_vector() {
    let v: Vec<f32> = vec![];
    assert_eq!(magnitude(&v), 0.0);
}

#[test]
fn test_magnitude_single_element() {
    assert!((magnitude(&[5.0]) - 5.0).abs() < 1e-6);
    assert!((magnitude(&[-5.0]) - 5.0).abs() < 1e-6);
}

#[test]
fn test_magnitude_negative_components() {
    let v = vec![-3.0, -4.0];
    assert!(
        (magnitude(&v) - 5.0).abs() < 1e-6,
        "Magnitude should be positive regardless of component signs"
    );
}

#[test]
fn test_magnitude_large_dimension() {
    // Vector of all 1s with dimension n has magnitude sqrt(n)
    let n = 1536;
    let v: Vec<f32> = vec![1.0; n];
    let expected = (n as f32).sqrt();
    assert!(
        (magnitude(&v) - expected).abs() < 1e-4,
        "Magnitude of {} 1s should be sqrt({}), got {}",
        n,
        n,
        magnitude(&v)
    );
}

// ========================================================================
// Squared Magnitude Tests
// ========================================================================

#[test]
fn test_squared_magnitude_3_4_triangle() {
    let v = vec![3.0, 4.0];
    let sq_mag = squared_magnitude(&v);
    assert!(
        (sq_mag - 25.0).abs() < 1e-6,
        "Squared magnitude of [3, 4] should be 25, got {}",
        sq_mag
    );
}

#[test]
fn test_squared_magnitude_zero_vector() {
    let v = vec![0.0, 0.0, 0.0];
    assert_eq!(squared_magnitude(&v), 0.0);
}

#[test]
fn test_squared_magnitude_empty_vector() {
    let v: Vec<f32> = vec![];
    assert_eq!(squared_magnitude(&v), 0.0);
}

#[test]
fn test_squared_magnitude_vs_magnitude() {
    let v = vec![1.0, 2.0, 3.0, 4.0];
    let mag = magnitude(&v);
    let sq_mag = squared_magnitude(&v);
    let diff = (mag * mag - sq_mag).abs();
    assert!(
        diff < 1e-5,
        "squared_magnitude should equal magnitude²: mag²={}, sq_mag={}, diff={}",
        mag * mag,
        sq_mag,
        diff
    );
}

// ========================================================================
// Normalize Tests
// ========================================================================

#[test]
fn test_normalize_3_4_triangle() {
    let v = vec![3.0, 4.0];
    let unit = normalize(&v);
    assert!((unit[0] - 0.6).abs() < 1e-6);
    assert!((unit[1] - 0.8).abs() < 1e-6);
    assert!((magnitude(&unit) - 1.0).abs() < 1e-6);
}

#[test]
fn test_normalize_already_unit() {
    let v = vec![1.0, 0.0, 0.0];
    let unit = normalize(&v);
    assert!((unit[0] - 1.0).abs() < 1e-6);
    assert!(unit[1].abs() < 1e-6);
    assert!(unit[2].abs() < 1e-6);
}

#[test]
fn test_normalize_zero_vector() {
    let v = vec![0.0, 0.0, 0.0];
    let unit = normalize(&v);
    // Zero vector should return zero vector
    assert_eq!(unit, vec![0.0, 0.0, 0.0]);
}

#[test]
fn test_normalize_empty_vector() {
    let v: Vec<f32> = vec![];
    let unit = normalize(&v);
    assert!(unit.is_empty());
}

#[test]
fn test_normalize_negative_components() {
    let v = vec![-3.0, -4.0];
    let unit = normalize(&v);
    assert!((unit[0] - (-0.6)).abs() < 1e-6);
    assert!((unit[1] - (-0.8)).abs() < 1e-6);
    assert!((magnitude(&unit) - 1.0).abs() < 1e-6);
}

#[test]
fn test_normalize_mixed_sign_components() {
    // Test mixed positive and negative components: [3, -4] has magnitude 5
    let v = vec![3.0, -4.0];
    let unit = normalize(&v);
    assert!((unit[0] - 0.6).abs() < 1e-6);
    assert!((unit[1] - (-0.8)).abs() < 1e-6);
    assert!((magnitude(&unit) - 1.0).abs() < 1e-6);

    // Verify sign is preserved
    assert!(unit[0] > 0.0, "First component should remain positive");
    assert!(unit[1] < 0.0, "Second component should remain negative");
}

#[test]
fn test_normalize_preserves_direction() {
    let v = vec![2.0, 4.0, 6.0];
    let unit = normalize(&v);
    // Ratios should be preserved: 1:2:3
    let ratio_1_2 = unit[0] / unit[1];
    let ratio_1_3 = unit[0] / unit[2];
    assert!((ratio_1_2 - 0.5).abs() < 1e-6);
    assert!((ratio_1_3 - (1.0 / 3.0)).abs() < 1e-6);
}

#[test]
fn test_normalize_large_dimension() {
    let n = 1536;
    let v: Vec<f32> = (0..n).map(|i| (i as f32 * 0.1).sin()).collect();
    let unit = normalize(&v);
    assert!(
        (magnitude(&unit) - 1.0).abs() < 1e-5,
        "Normalized vector should have magnitude 1.0, got {}",
        magnitude(&unit)
    );
}

// ========================================================================
// Normalize In-Place Tests
// ========================================================================

#[test]
fn test_normalize_in_place_3_4_triangle() {
    let mut v = vec![3.0, 4.0];
    normalize_in_place(&mut v);
    assert!((v[0] - 0.6).abs() < 1e-6);
    assert!((v[1] - 0.8).abs() < 1e-6);
    assert!((magnitude(&v) - 1.0).abs() < 1e-6);
}

#[test]
fn test_normalize_in_place_zero_vector() {
    let mut v = vec![0.0, 0.0, 0.0];
    normalize_in_place(&mut v);
    // Zero vector should remain unchanged
    assert_eq!(v, vec![0.0, 0.0, 0.0]);
}

#[test]
fn test_normalize_in_place_tiny_vector() {
    // Vector with squared magnitude 1e-16.
    // Previous threshold was 1e-14 (so it was zeroed).
    // New threshold is 1e-25 (so it should be normalized).
    let mut v = vec![1e-8_f32];
    normalize_in_place(&mut v);
    // Should be normalized to [1.0]
    assert!((v[0] - 1.0).abs() < 1e-6);
}

#[test]
fn test_normalize_in_place_empty_vector() {
    let mut v: Vec<f32> = vec![];
    normalize_in_place(&mut v);
    assert!(v.is_empty());
}

#[test]
fn test_normalize_in_place_matches_normalize() {
    let v = vec![1.0, 2.0, 3.0, 4.0, 5.0];
    let expected = normalize(&v);

    let mut v_copy = v.clone();
    normalize_in_place(&mut v_copy);

    for (a, b) in v_copy.iter().zip(expected.iter()) {
        assert!((a - b).abs() < 1e-6);
    }
}

#[test]
fn test_normalize_in_place_large_dimension() {
    let n = 1536;
    let mut v: Vec<f32> = (0..n).map(|i| (i as f32 * 0.1).cos()).collect();
    normalize_in_place(&mut v);
    assert!(
        (magnitude(&v) - 1.0).abs() < 1e-5,
        "In-place normalized vector should have magnitude 1.0, got {}",
        magnitude(&v)
    );
}

// ========================================================================
// Is Normalized Tests
// ========================================================================

#[test]
fn test_is_normalized_unit_vectors() {
    assert!(is_normalized(&[1.0, 0.0, 0.0], 1e-6));
    assert!(is_normalized(&[0.0, 1.0, 0.0], 1e-6));
    assert!(is_normalized(&[0.0, 0.0, 1.0], 1e-6));
}

#[test]
fn test_is_normalized_normalized_vector() {
    let v = normalize(&[3.0, 4.0]);
    assert!(is_normalized(&v, 1e-6));
}

#[test]
fn test_is_normalized_non_unit_vector() {
    assert!(!is_normalized(&[3.0, 4.0], 1e-6)); // magnitude = 5
    assert!(!is_normalized(&[2.0, 0.0, 0.0], 1e-6)); // magnitude = 2
}

#[test]
fn test_is_normalized_zero_vector() {
    // Zero vector has magnitude 0, which is not 1
    assert!(!is_normalized(&[0.0, 0.0, 0.0], 1e-6));
}

#[test]
fn test_is_normalized_tolerance() {
    // Vector with magnitude 1.0001 should pass with 1e-3 tolerance
    let v = vec![1.0001, 0.0, 0.0];
    assert!(!is_normalized(&v, 1e-6));
    assert!(is_normalized(&v, 1e-3));
}

#[test]
fn test_is_normalized_diagonal() {
    // Unit diagonal in 3D: each component = 1/sqrt(3)
    let c = 1.0 / 3.0_f32.sqrt();
    let v = vec![c, c, c];
    assert!(is_normalized(&v, 1e-6));
}

#[test]
fn test_is_normalized_default() {
    // Unnormalized vector
    assert!(!is_normalized_default(&[3.0, 4.0]));
    assert!(!is_normalized_default(&[2.0, 0.0, 0.0]));

    // Normalized vectors
    assert!(is_normalized_default(&[1.0, 0.0, 0.0]));
    assert!(is_normalized_default(&[0.0, 1.0, 0.0]));
    assert!(is_normalized_default(&[0.0, 0.0, 1.0]));

    let v = normalize(&[3.0, 4.0]);
    assert!(is_normalized_default(&v));

    // Zero vector
    assert!(!is_normalized_default(&[0.0, 0.0, 0.0]));

    // Edge cases with explicit bounds checking
    // NORMALIZATION_TOLERANCE is 1e-6
    // Within bounds
    let valid_plus = [1.0 + 1e-7, 0.0];
    assert!(is_normalized_default(&valid_plus));

    let valid_minus = [1.0 - 1e-7, 0.0];
    assert!(is_normalized_default(&valid_minus));

    // Outside bounds
    let invalid_plus = [1.0 + 1e-5, 0.0];
    assert!(!is_normalized_default(&invalid_plus));

    let invalid_minus = [1.0 - 1e-5, 0.0];
    assert!(!is_normalized_default(&invalid_minus));
}

// ========================================================================
// DistanceMetric Tests
// ========================================================================

#[test]
fn test_distance_metric_default() {
    let metric = DistanceMetric::default();
    assert_eq!(metric, DistanceMetric::Cosine);
}

#[test]
fn test_distance_metric_cosine_identical_vectors() {
    let a = vec![1.0, 2.0, 3.0];
    let b = vec![1.0, 2.0, 3.0];

    // Identical vectors: similarity = 1, distance = 0
    let similarity = DistanceMetric::Cosine.compute_similarity(&a, &b).unwrap();
    let distance = DistanceMetric::Cosine.compute_distance(&a, &b).unwrap();

    assert!((similarity - 1.0).abs() < 1e-6);
    assert!((distance - 0.0).abs() < 1e-6);
}

#[test]
fn test_distance_metric_cosine_opposite_vectors() {
    let a = vec![1.0, 0.0, 0.0];
    let b = vec![-1.0, 0.0, 0.0];

    // Opposite vectors: similarity = -1, distance = 2
    let similarity = DistanceMetric::Cosine.compute_similarity(&a, &b).unwrap();
    let distance = DistanceMetric::Cosine.compute_distance(&a, &b).unwrap();

    assert!((similarity - (-1.0)).abs() < 1e-6);
    assert!((distance - 2.0).abs() < 1e-6);
}

#[test]
fn test_distance_metric_cosine_orthogonal_vectors() {
    let a = vec![1.0, 0.0, 0.0];
    let b = vec![0.0, 1.0, 0.0];

    // Orthogonal vectors: similarity = 0, distance = 1
    let similarity = DistanceMetric::Cosine.compute_similarity(&a, &b).unwrap();
    let distance = DistanceMetric::Cosine.compute_distance(&a, &b).unwrap();

    assert!((similarity - 0.0).abs() < 1e-6);
    assert!((distance - 1.0).abs() < 1e-6);
}

#[test]
fn test_distance_metric_euclidean_identical_vectors() {
    let a = vec![1.0, 2.0, 3.0];
    let b = vec![1.0, 2.0, 3.0];

    // Identical vectors: distance = 0, similarity = 1
    let distance = DistanceMetric::Euclidean.compute_distance(&a, &b).unwrap();
    let similarity = DistanceMetric::Euclidean
        .compute_similarity(&a, &b)
        .unwrap();

    assert!((distance - 0.0).abs() < 1e-6);
    assert!((similarity - 1.0).abs() < 1e-6);
}

#[test]
fn test_distance_metric_euclidean_unit_distance() {
    let a = vec![0.0, 0.0];
    let b = vec![1.0, 0.0];

    // Distance = 1, similarity = 1/(1+1) = 0.5
    let distance = DistanceMetric::Euclidean.compute_distance(&a, &b).unwrap();
    let similarity = DistanceMetric::Euclidean
        .compute_similarity(&a, &b)
        .unwrap();

    assert!((distance - 1.0).abs() < 1e-6);
    assert!((similarity - 0.5).abs() < 1e-6);
}

#[test]
fn test_distance_metric_euclidean_3_4_5_triangle() {
    let a = vec![0.0, 0.0];
    let b = vec![3.0, 4.0];

    // Distance = 5, similarity = 1/(1+5) = 1/6
    let distance = DistanceMetric::Euclidean.compute_distance(&a, &b).unwrap();
    let similarity = DistanceMetric::Euclidean
        .compute_similarity(&a, &b)
        .unwrap();

    assert!((distance - 5.0).abs() < 1e-6);
    assert!((similarity - (1.0 / 6.0)).abs() < 1e-6);
}

#[test]
fn test_distance_metric_dot_product_identical_unit_vectors() {
    let a = vec![1.0, 0.0, 0.0];
    let b = vec![1.0, 0.0, 0.0];

    // Unit vectors: dot = 1, distance = 0
    let similarity = DistanceMetric::DotProduct
        .compute_similarity(&a, &b)
        .unwrap();
    let distance = DistanceMetric::DotProduct.compute_distance(&a, &b).unwrap();

    assert!((similarity - 1.0).abs() < 1e-6);
    assert!((distance - 0.0).abs() < 1e-6);
}

#[test]
fn test_distance_metric_dot_product_orthogonal_vectors() {
    let a = vec![1.0, 0.0, 0.0];
    let b = vec![0.0, 1.0, 0.0];

    // Orthogonal: dot = 0, distance = 1
    let similarity = DistanceMetric::DotProduct
        .compute_similarity(&a, &b)
        .unwrap();
    let distance = DistanceMetric::DotProduct.compute_distance(&a, &b).unwrap();

    assert!((similarity - 0.0).abs() < 1e-6);
    assert!((distance - 1.0).abs() < 1e-6);
}

#[test]
fn test_distance_metric_dot_product_opposite_vectors() {
    let a = vec![1.0, 0.0, 0.0];
    let b = vec![-1.0, 0.0, 0.0];

    // Opposite: dot = -1, distance = 2
    let similarity = DistanceMetric::DotProduct
        .compute_similarity(&a, &b)
        .unwrap();
    let distance = DistanceMetric::DotProduct.compute_distance(&a, &b).unwrap();

    assert!((similarity - (-1.0)).abs() < 1e-6);
    assert!((distance - 2.0).abs() < 1e-6);
}

#[test]
fn test_distance_metric_dimension_mismatch() {
    let a = vec![1.0, 2.0, 3.0];
    let b = vec![1.0, 2.0];

    // All metrics should return an error for mismatched dimensions
    assert!(DistanceMetric::Cosine.compute_distance(&a, &b).is_err());
    assert!(DistanceMetric::Cosine.compute_similarity(&a, &b).is_err());
    assert!(DistanceMetric::Euclidean.compute_distance(&a, &b).is_err());
    assert!(
        DistanceMetric::Euclidean
            .compute_similarity(&a, &b)
            .is_err()
    );
    assert!(DistanceMetric::DotProduct.compute_distance(&a, &b).is_err());
    assert!(
        DistanceMetric::DotProduct
            .compute_similarity(&a, &b)
            .is_err()
    );
}

#[test]
fn test_distance_metric_name() {
    assert_eq!(DistanceMetric::Cosine.name(), "cosine");
    assert_eq!(DistanceMetric::Euclidean.name(), "euclidean");
    assert_eq!(DistanceMetric::DotProduct.name(), "dot_product");
}

#[test]
fn test_distance_metric_display() {
    assert_eq!(format!("{}", DistanceMetric::Cosine), "cosine");
    assert_eq!(format!("{}", DistanceMetric::Euclidean), "euclidean");
    assert_eq!(format!("{}", DistanceMetric::DotProduct), "dot_product");
}

#[test]
fn test_distance_metric_requires_normalized() {
    assert!(!DistanceMetric::Cosine.requires_normalized_vectors());
    assert!(!DistanceMetric::Euclidean.requires_normalized_vectors());
    assert!(DistanceMetric::DotProduct.requires_normalized_vectors());
}

#[test]
fn test_distance_metric_clone_copy() {
    let metric = DistanceMetric::Cosine;
    // Both Clone and Copy traits work - use Copy (implicit)
    let copied1 = metric;
    let copied2 = metric;

    assert_eq!(metric, copied1);
    assert_eq!(metric, copied2);
}

#[test]
fn test_distance_metric_debug() {
    assert_eq!(format!("{:?}", DistanceMetric::Cosine), "Cosine");
    assert_eq!(format!("{:?}", DistanceMetric::Euclidean), "Euclidean");
    assert_eq!(format!("{:?}", DistanceMetric::DotProduct), "DotProduct");
}

#[test]
fn test_distance_metric_hash() {
    use std::collections::HashSet;
    let mut set = HashSet::new();
    set.insert(DistanceMetric::Cosine);
    set.insert(DistanceMetric::Euclidean);
    set.insert(DistanceMetric::DotProduct);
    assert_eq!(set.len(), 3);
}

#[test]
fn test_distance_metric_consistency() {
    // For normalized vectors, cosine similarity should equal dot product
    let a = normalize(&[3.0, 4.0]);
    let b = normalize(&[1.0, 0.0]);

    let cosine_sim = DistanceMetric::Cosine.compute_similarity(&a, &b).unwrap();
    let dot_sim = DistanceMetric::DotProduct
        .compute_similarity(&a, &b)
        .unwrap();

    assert!(
        (cosine_sim - dot_sim).abs() < 1e-5,
        "For normalized vectors, cosine ({}) should equal dot product ({})",
        cosine_sim,
        dot_sim
    );
}

#[test]
fn test_distance_metric_all_metrics_same_order() {
    // All metrics should agree on which of two vectors is more similar to a query
    let query = vec![1.0, 0.5, 0.0];
    let closer = vec![0.9, 0.4, 0.1];
    let farther = vec![0.1, 0.9, 0.8];

    // Cosine
    let cosine_closer = DistanceMetric::Cosine
        .compute_similarity(&query, &closer)
        .unwrap();
    let cosine_farther = DistanceMetric::Cosine
        .compute_similarity(&query, &farther)
        .unwrap();
    assert!(
        cosine_closer > cosine_farther,
        "Cosine: {} should be > {}",
        cosine_closer,
        cosine_farther
    );

    // Euclidean
    let eucl_closer = DistanceMetric::Euclidean
        .compute_distance(&query, &closer)
        .unwrap();
    let eucl_farther = DistanceMetric::Euclidean
        .compute_distance(&query, &farther)
        .unwrap();
    assert!(
        eucl_closer < eucl_farther,
        "Euclidean: {} should be < {}",
        eucl_closer,
        eucl_farther
    );

    // Dot Product
    let dot_closer = DistanceMetric::DotProduct
        .compute_similarity(&query, &closer)
        .unwrap();
    let dot_farther = DistanceMetric::DotProduct
        .compute_similarity(&query, &farther)
        .unwrap();
    assert!(
        dot_closer > dot_farther,
        "DotProduct: {} should be > {}",
        dot_closer,
        dot_farther
    );
}

// ========================================================================
// Vector Validation Tests
// ========================================================================

#[test]
fn test_validate_vector_valid() {
    let v = vec![1.0, 2.0, 3.0, 4.0, 5.0];
    assert!(validate_vector(&v).is_ok());
}

#[test]
fn test_validate_vector_empty() {
    let v: Vec<f32> = vec![];
    assert!(validate_vector(&v).is_ok());
}

#[test]
fn test_validate_vector_single_element() {
    let v = vec![42.0];
    assert!(validate_vector(&v).is_ok());
}

#[test]
fn test_validate_vector_negative_and_zero() {
    let v = vec![-1.0, 0.0, 1.0, -0.0];
    assert!(validate_vector(&v).is_ok());
}

#[test]
fn test_validate_vector_nan_single() {
    let v = vec![1.0, f32::NAN, 3.0];
    let result = validate_vector(&v);
    assert!(result.is_err());
    match result {
        Err(Error::Vector(VectorError::ContainsNaN { count })) => {
            assert_eq!(count, 1);
        }
        _ => panic!("Expected ContainsNaN error"),
    }
}

#[test]
fn test_validate_vector_nan_multiple() {
    let v = vec![f32::NAN, 1.0, f32::NAN, 2.0, f32::NAN];
    let result = validate_vector(&v);
    assert!(result.is_err());
    match result {
        Err(Error::Vector(VectorError::ContainsNaN { count })) => {
            assert_eq!(count, 3);
        }
        _ => panic!("Expected ContainsNaN error with count 3"),
    }
}

#[test]
fn test_validate_vector_infinity_positive() {
    let v = vec![1.0, f32::INFINITY, 3.0];
    let result = validate_vector(&v);
    assert!(result.is_err());
    match result {
        Err(Error::Vector(VectorError::ContainsInfinity { count })) => {
            assert_eq!(count, 1);
        }
        _ => panic!("Expected ContainsInfinity error"),
    }
}

#[test]
fn test_validate_vector_infinity_negative() {
    let v = vec![1.0, f32::NEG_INFINITY, 3.0];
    let result = validate_vector(&v);
    assert!(result.is_err());
    match result {
        Err(Error::Vector(VectorError::ContainsInfinity { count })) => {
            assert_eq!(count, 1);
        }
        _ => panic!("Expected ContainsInfinity error"),
    }
}

#[test]
fn test_validate_vector_infinity_multiple() {
    let v = vec![f32::INFINITY, 1.0, f32::NEG_INFINITY];
    let result = validate_vector(&v);
    assert!(result.is_err());
    match result {
        Err(Error::Vector(VectorError::ContainsInfinity { count })) => {
            assert_eq!(count, 2);
        }
        _ => panic!("Expected ContainsInfinity error with count 2"),
    }
}

#[test]
fn test_validate_vector_nan_takes_precedence() {
    // When both NaN and Infinity are present, NaN error should be returned first
    let v = vec![f32::NAN, f32::INFINITY];
    let result = validate_vector(&v);
    assert!(result.is_err());
    match result {
        Err(Error::Vector(VectorError::ContainsNaN { count })) => {
            assert_eq!(count, 1);
        }
        _ => panic!("Expected ContainsNaN error (NaN takes precedence over Infinity)"),
    }
}

#[test]
fn test_validate_vector_subnormal() {
    // Subnormal (denormalized) numbers should be valid
    let v = vec![1e-45 / 2.0, 1.0];
    assert!(validate_vector(&v).is_ok());
}

#[test]
fn test_validate_vector_max_min_values() {
    // Extreme but finite values should be valid
    let v = vec![f32::MAX, f32::MIN, 1.0];
    assert!(validate_vector(&v).is_ok());
}

// ========================================================================
// Dimension Match Tests
// ========================================================================

#[test]
fn test_check_dimensions_match_equal() {
    let a = vec![1.0, 2.0, 3.0];
    let b = vec![4.0, 5.0, 6.0];
    assert!(check_dimensions_match(&a, &b).is_ok());
}

#[test]
fn test_check_dimensions_match_empty() {
    let a: Vec<f32> = vec![];
    let b: Vec<f32> = vec![];
    assert!(check_dimensions_match(&a, &b).is_ok());
}

#[test]
fn test_check_dimensions_match_single() {
    let a = vec![1.0];
    let b = vec![2.0];
    assert!(check_dimensions_match(&a, &b).is_ok());
}

#[test]
fn test_check_dimensions_match_unequal() {
    let a = vec![1.0, 2.0, 3.0];
    let b = vec![1.0, 2.0];
    let result = check_dimensions_match(&a, &b);
    assert!(result.is_err());
    match result {
        Err(Error::Vector(VectorError::DimensionMismatch { expected, actual })) => {
            assert_eq!(expected, 3);
            assert_eq!(actual, 2);
        }
        _ => panic!("Expected DimensionMismatch error"),
    }
}

#[test]
fn test_check_dimensions_match_unequal_reversed() {
    let a = vec![1.0, 2.0];
    let b = vec![1.0, 2.0, 3.0];
    let result = check_dimensions_match(&a, &b);
    assert!(result.is_err());
    match result {
        Err(Error::Vector(VectorError::DimensionMismatch { expected, actual })) => {
            assert_eq!(expected, 2);
            assert_eq!(actual, 3);
        }
        _ => panic!("Expected DimensionMismatch error"),
    }
}

#[test]
fn test_check_dimensions_match_empty_vs_nonempty() {
    let a: Vec<f32> = vec![];
    let b = vec![1.0];
    let result = check_dimensions_match(&a, &b);
    assert!(result.is_err());
    match result {
        Err(Error::Vector(VectorError::DimensionMismatch { expected, actual })) => {
            assert_eq!(expected, 0);
            assert_eq!(actual, 1);
        }
        _ => panic!("Expected DimensionMismatch error"),
    }
}

// ========================================================================
// Validate Vector with Bounds Tests
// ========================================================================

#[test]
fn test_validate_vector_with_bounds_valid() {
    let v = vec![1.0, 2.0, 3.0];
    assert!(validate_vector_with_bounds(&v, 10).is_ok());
}

#[test]
fn test_validate_vector_with_bounds_exact() {
    let v = vec![1.0, 2.0, 3.0];
    assert!(validate_vector_with_bounds(&v, 3).is_ok());
}

#[test]
fn test_validate_vector_with_bounds_too_large() {
    let v = vec![1.0, 2.0, 3.0];
    let result = validate_vector_with_bounds(&v, 2);
    assert!(result.is_err());
    match result {
        Err(Error::Vector(VectorError::DimensionTooLarge {
            dimension,
            max_allowed,
        })) => {
            assert_eq!(dimension, 3);
            assert_eq!(max_allowed, 2);
        }
        _ => panic!("Expected DimensionTooLarge error"),
    }
}

#[test]
fn test_validate_vector_with_bounds_empty() {
    let v: Vec<f32> = vec![];
    assert!(validate_vector_with_bounds(&v, 0).is_ok());
}

#[test]
fn test_validate_vector_with_bounds_nan() {
    // NaN should be detected even if dimension is within bounds
    let v = vec![f32::NAN, 2.0];
    let result = validate_vector_with_bounds(&v, 10);
    assert!(result.is_err());
    assert!(matches!(
        result,
        Err(Error::Vector(VectorError::ContainsNaN { .. }))
    ));
}

#[test]
fn test_validate_vector_with_bounds_dimension_checked_first() {
    // If dimension exceeds bounds, that error should be returned
    // even if the vector also contains NaN
    let v = vec![f32::NAN, 2.0, 3.0, 4.0];
    let result = validate_vector_with_bounds(&v, 2);
    assert!(result.is_err());
    assert!(matches!(
        result,
        Err(Error::Vector(VectorError::DimensionTooLarge { .. }))
    ));
}

// ========================================================================
// SIMD Coverage Tests
// ========================================================================

#[test]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn test_simd_explicit_coverage() {
    // This test explicitly calls internal SIMD functions to ensure code coverage
    // for safety assertions, even if the runtime dispatcher favors one instruction set.
    let a = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
    let b = vec![8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0];

    // 1. Test SSE2 (Always available on x86_64, usually available on x86)
    if is_x86_feature_detected!("sse2") {
        unsafe {
            // dot_and_magnitudes_sse2
            let (dot, mag_a, mag_b) = super::simd::x86_ops::dot_and_magnitudes_sse2(&a, &b);
            // Expected: 1*8 + ... = 120.0
            assert!((dot - 120.0).abs() < 1e-5);
            assert!(mag_a > 0.0);
            assert!(mag_b > 0.0);

            // dot_product_sse2
            let dot_prod = super::simd::x86_ops::dot_product_sse2(&a, &b);
            assert!((dot - dot_prod).abs() < 1e-5);

            // squared_diff_sum_sse2
            let sq_diff = super::simd::x86_ops::squared_diff_sum_sse2(&a, &b);
            assert!(sq_diff >= 0.0);

            // scale_in_place_sse2
            let mut v = a.clone();
            super::simd::x86_ops::scale_in_place_sse2(&mut v, 2.0);
            assert!((v[0] - 2.0).abs() < 1e-5);
        }
    }

    // 2. Test AVX2 (Conditional)
    // We explicitly test this branch even if the dispatcher might prefer it,
    // to ensure the specific function logic is correct.
    if is_x86_feature_detected!("avx2") {
        unsafe {
            // scale_in_place_avx2 only needs AVX2
            let mut v = a.clone();
            super::simd::x86_ops::scale_in_place_avx2(&mut v, 2.0);
            assert!((v[0] - 2.0).abs() < 1e-5);

            // Others need FMA + AVX2
            if is_x86_feature_detected!("fma") {
                // dot_and_magnitudes_avx2
                let (dot, mag_a, _mag_b) = super::simd::x86_ops::dot_and_magnitudes_avx2(&a, &b);
                assert!((dot - 120.0).abs() < 1e-5);
                assert!(mag_a > 0.0);

                // dot_product_avx2
                let dot_prod = super::simd::x86_ops::dot_product_avx2(&a, &b);
                assert!((dot - dot_prod).abs() < 1e-5);

                // squared_diff_sum_avx2
                let sq_diff = super::simd::x86_ops::squared_diff_sum_avx2(&a, &b);
                assert!(sq_diff >= 0.0);
            }
        }
    }
}

#[test]
fn test_normalize_small_vector_preserves_direction() {
    let v = vec![1.0e-8_f32];
    let normalized = normalize(&v);
    let mag = magnitude(&normalized);
    assert!(
        (mag - 1.0).abs() < 1e-6,
        "Small vector should be normalized to unit length"
    );
    assert!((normalized[0] - 1.0).abs() < 1e-6);
}

#[test]
fn test_cosine_similarity_small_vectors() {
    let a = vec![1.0e-8_f32];
    let b = vec![1.0e-8_f32];
    let sim = cosine_similarity(&a, &b).unwrap();
    assert!(
        (sim - 1.0).abs() < 1e-6,
        "Small identical vectors should have similarity 1.0"
    );
}

#[test]
fn test_cosine_similarity_mixed_magnitude() {
    let a = vec![1.0e-8_f32, 0.0];
    let b = vec![1.0, 0.0];
    let sim = cosine_similarity(&a, &b).unwrap();
    assert!(
        (sim - 1.0).abs() < 1e-6,
        "Small vector collinear with large vector should have similarity 1.0"
    );
}

#[test]
fn test_scalar_fallback_explicit_coverage() {
    // Explicitly test scalar fallbacks to ensure code coverage regardless of CPU features
    let a = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
    let b = vec![8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0];

    // dot_and_magnitudes_scalar
    let (dot, mag_a, mag_b) = super::simd::dot_and_magnitudes_scalar(&a, &b);
    // dot = 1*8 + 2*7 + ... = 8 + 14 + 18 + 20 + 20 + 18 + 14 + 8 = 120
    assert!((dot - 120.0).abs() < 1e-5);
    assert!(mag_a > 0.0);
    assert!(mag_b > 0.0);

    // dot_product_scalar
    let dot_prod = super::simd::dot_product_scalar(&a, &b);
    assert!((dot - dot_prod).abs() < 1e-5);

    // squared_diff_sum_scalar
    let sq_diff = super::simd::squared_diff_sum_scalar(&a, &b);
    assert!(sq_diff >= 0.0);

    // scale_in_place_scalar
    let mut v = a.clone();
    super::simd::scale_in_place_scalar(&mut v, 2.0);
    assert!((v[0] - 2.0).abs() < 1e-5);
}

// ============================================================================
// Property-Based Tests
// ============================================================================

mod proptests {
    use super::*;
    use proptest::prelude::*;

    // ========================================================================
    // Tolerance Choice Documentation
    // ========================================================================
    //
    // We use 1e-5 absolute tolerance for property tests. This was chosen based on:
    //
    // 1. **f32 precision limits**: f32 has ~7 decimal digits of precision.
    //    For values in [-100, 100] range with up to 100 dimensions, accumulated
    //    error from multiply-add operations is bounded by roughly:
    //    - Per operation: ~1e-7 relative error (f32 epsilon)
    //    - 100 operations: ~1e-5 accumulated error (sqrt(n) * epsilon for random errors)
    //
    // 2. **SIMD vs scalar consistency**: Different code paths (AVX2, SSE2, scalar)
    //    may produce slightly different results due to operation ordering.
    //    1e-5 tolerance accounts for these differences.
    //
    // 3. **Mathematical invariants**: Cosine similarity is bounded to [-1, 1],
    //    so 1e-5 represents a relative error of 0.001% at worst.
    //
    // For applications requiring tighter bounds, normalize vectors first
    // (which reduces magnitude-related accumulation errors).
    // ========================================================================

    /// Tolerance for property-based tests.
    ///
    /// See module-level documentation for rationale behind this choice.
    const PROPTEST_TOLERANCE: f32 = 1e-5;

    // Strategy to generate non-empty vectors of the same length
    fn same_length_vectors(max_len: usize) -> impl Strategy<Value = (Vec<f32>, Vec<f32>)> {
        (1..=max_len).prop_flat_map(|len| {
            (
                prop::collection::vec(-100.0f32..100.0f32, len),
                prop::collection::vec(-100.0f32..100.0f32, len),
            )
        })
    }

    proptest! {
        #[test]
        fn prop_cosine_similarity_is_symmetric(
            (a, b) in same_length_vectors(100)
        ) {
            let sim_ab = cosine_similarity(&a, &b).unwrap();
            let sim_ba = cosine_similarity(&b, &a).unwrap();
            prop_assert!((sim_ab - sim_ba).abs() < PROPTEST_TOLERANCE);
        }

        #[test]
        fn prop_cosine_similarity_in_range(
            (a, b) in same_length_vectors(100)
        ) {
            let sim = cosine_similarity(&a, &b).unwrap();
            // Handle NaN case (can occur with extreme values)
            if !sim.is_nan() {
                // Result is clamped, so should always be in [-1, 1]
                // Allow tiny tolerance for floating-point edge cases
                let min = -1.0 - PROPTEST_TOLERANCE;
                let max = 1.0 + PROPTEST_TOLERANCE;
                prop_assert!((min..=max).contains(&sim),
                    "Similarity {} out of range for {:?} and {:?}", sim, a, b);
            }
        }

        #[test]
        fn prop_cosine_similarity_self_is_one(
            a in prop::collection::vec(-100.0f32..100.0f32, 1..100usize)
        ) {
            // Skip zero vectors
            let magnitude_sq: f32 = a.iter().map(|x| x * x).sum();
            if magnitude_sq > 1e-10 {
                let sim = cosine_similarity(&a, &a).unwrap();
                prop_assert!((sim - 1.0).abs() < PROPTEST_TOLERANCE,
                    "Self-similarity should be 1.0, got {} for {:?}", sim, a);
            }
        }

        #[test]
        fn prop_cosine_similarity_negation_flips_sign(
            a in prop::collection::vec(-100.0f32..100.0f32, 1..100usize)
        ) {
            // Skip zero vectors
            let magnitude_sq: f32 = a.iter().map(|x| x * x).sum();
            if magnitude_sq > 1e-10 {
                let neg_a: Vec<f32> = a.iter().map(|x| -x).collect();
                let sim = cosine_similarity(&a, &neg_a).unwrap();
                prop_assert!((sim + 1.0).abs() < PROPTEST_TOLERANCE,
                    "Negation similarity should be -1.0, got {} for {:?}", sim, a);
            }
        }

        #[test]
        fn prop_cosine_similarity_scale_invariant(
            (a, b) in same_length_vectors(50),
            scale in 0.1f32..10.0f32
        ) {
            // Skip if either vector is near-zero
            let mag_a: f32 = a.iter().map(|x| x * x).sum();
            let mag_b: f32 = b.iter().map(|x| x * x).sum();
            if mag_a > 1e-10 && mag_b > 1e-10 {
                let sim1 = cosine_similarity(&a, &b).unwrap();

                let scaled_a: Vec<f32> = a.iter().map(|x| x * scale).collect();
                let sim2 = cosine_similarity(&scaled_a, &b).unwrap();

                // Cosine similarity should be scale-invariant.
                //
                // Why 10x tolerance? Scaling introduces additional error sources:
                // 1. The scaling multiplication itself: len extra multiply operations
                // 2. Magnitude changes: scaled vectors have different magnitudes,
                //    potentially causing different rounding in the sqrt and division
                // 3. For scale factors near the edges (0.1 or 10.0), the magnitude
                //    difference is up to 100x, affecting numerical stability
                //
                // Empirically, 10x base tolerance handles these cases while still
                // catching genuine scale invariance violations.
                if !sim1.is_nan() && !sim2.is_nan() {
                    prop_assert!((sim1 - sim2).abs() < PROPTEST_TOLERANCE * 10.0,
                        "Scale invariance failed: {} vs {} for scale {}", sim1, sim2, scale);
                }
            }
        }

        // ====================================================================
        // Euclidean Distance Property Tests
        // ====================================================================

        #[test]
        fn prop_euclidean_distance_is_non_negative(
            (a, b) in same_length_vectors(100)
        ) {
            let dist = euclidean_distance(&a, &b).unwrap();
            prop_assert!(dist >= 0.0, "Distance should be non-negative, got {}", dist);
        }

        #[test]
        fn prop_squared_euclidean_distance_is_non_negative(
            (a, b) in same_length_vectors(100)
        ) {
            let dist_sq = squared_euclidean_distance(&a, &b).unwrap();
            prop_assert!(dist_sq >= 0.0, "Squared distance should be non-negative, got {}", dist_sq);
        }

        #[test]
        fn prop_euclidean_distance_is_symmetric(
            (a, b) in same_length_vectors(100)
        ) {
            let dist_ab = euclidean_distance(&a, &b).unwrap();
            let dist_ba = euclidean_distance(&b, &a).unwrap();
            prop_assert!((dist_ab - dist_ba).abs() < PROPTEST_TOLERANCE,
                "Euclidean distance should be symmetric: {} vs {}", dist_ab, dist_ba);
        }

        #[test]
        fn prop_squared_euclidean_distance_is_symmetric(
            (a, b) in same_length_vectors(100)
        ) {
            let dist_sq_ab = squared_euclidean_distance(&a, &b).unwrap();
            let dist_sq_ba = squared_euclidean_distance(&b, &a).unwrap();
            prop_assert!((dist_sq_ab - dist_sq_ba).abs() < PROPTEST_TOLERANCE,
                "Squared Euclidean distance should be symmetric: {} vs {}", dist_sq_ab, dist_sq_ba);
        }

        #[test]
        fn prop_euclidean_distance_self_is_zero(
            a in prop::collection::vec(-100.0f32..100.0f32, 1..100usize)
        ) {
            let dist = euclidean_distance(&a, &a).unwrap();
            prop_assert!(dist.abs() < PROPTEST_TOLERANCE,
                "Distance to self should be 0, got {} for {:?}", dist, a);
        }

        #[test]
        fn prop_squared_euclidean_distance_self_is_zero(
            a in prop::collection::vec(-100.0f32..100.0f32, 1..100usize)
        ) {
            let dist_sq = squared_euclidean_distance(&a, &a).unwrap();
            prop_assert!(dist_sq.abs() < PROPTEST_TOLERANCE,
                "Squared distance to self should be 0, got {} for {:?}", dist_sq, a);
        }

        #[test]
        fn prop_euclidean_squared_relationship(
            (a, b) in same_length_vectors(100)
        ) {
            let dist = euclidean_distance(&a, &b).unwrap();
            let dist_sq = squared_euclidean_distance(&a, &b).unwrap();
            // dist² should equal dist_sq
            // Use relative tolerance for larger values
            let tolerance = PROPTEST_TOLERANCE * 100.0 + dist_sq * 1e-5;
            prop_assert!((dist * dist - dist_sq).abs() < tolerance,
                "euclidean² ({}) should equal squared_euclidean ({})", dist * dist, dist_sq);
        }

        #[test]
        fn prop_euclidean_distance_triangle_inequality(
            a in prop::collection::vec(-50.0f32..50.0f32, 1..50usize),
            b in prop::collection::vec(-50.0f32..50.0f32, 1..50usize),
            c in prop::collection::vec(-50.0f32..50.0f32, 1..50usize)
        ) {
            // Triangle inequality: d(a,c) <= d(a,b) + d(b,c)
            // Only test if all vectors have same length
            if a.len() == b.len() && b.len() == c.len() {
                let d_ab = euclidean_distance(&a, &b).unwrap();
                let d_bc = euclidean_distance(&b, &c).unwrap();
                let d_ac = euclidean_distance(&a, &c).unwrap();

                // Allow small tolerance for floating-point errors
                let tolerance = PROPTEST_TOLERANCE * 100.0;
                prop_assert!(d_ac <= d_ab + d_bc + tolerance,
                    "Triangle inequality violated: d(a,c)={} > d(a,b)={} + d(b,c)={}",
                    d_ac, d_ab, d_bc);
            }
        }

        // ====================================================================
        // Dot Product Property Tests
        // ====================================================================

        #[test]
        fn prop_dot_product_is_symmetric(
            (a, b) in same_length_vectors(100)
        ) {
            let dot_ab = dot_product(&a, &b).unwrap();
            let dot_ba = dot_product(&b, &a).unwrap();
            prop_assert!((dot_ab - dot_ba).abs() < PROPTEST_TOLERANCE,
                "Dot product should be symmetric: {} vs {}", dot_ab, dot_ba);
        }

        #[test]
        fn prop_dot_product_self_equals_squared_magnitude(
            a in prop::collection::vec(-100.0f32..100.0f32, 1..100usize)
        ) {
            let self_dot = dot_product(&a, &a).unwrap();
            // Self dot product should equal sum of squares (squared magnitude)
            let expected: f32 = a.iter().map(|x| x * x).sum();

            // Use relative tolerance for larger values
            let tolerance = PROPTEST_TOLERANCE * 100.0 + expected * 1e-5;
            prop_assert!((self_dot - expected).abs() < tolerance,
                "Self dot product should equal squared magnitude: {} vs {}", self_dot, expected);
        }

        #[test]
        fn prop_dot_product_with_zero_vector(
            a in prop::collection::vec(-100.0f32..100.0f32, 1..100usize)
        ) {
            let zeros: Vec<f32> = vec![0.0; a.len()];
            let result = dot_product(&a, &zeros).unwrap();
            prop_assert!(result.abs() < PROPTEST_TOLERANCE,
                "Dot product with zero vector should be 0, got {}", result);
        }

        #[test]
        fn prop_dot_product_bilinearity_scalar(
            (a, b) in same_length_vectors(50),
            scale in 0.1f32..10.0f32
        ) {
            // Scalar multiplication: dot(c*a, b) = c * dot(a, b)
            let dot_ab = dot_product(&a, &b).unwrap();
            let scaled_a: Vec<f32> = a.iter().map(|x| x * scale).collect();
            let dot_scaled = dot_product(&scaled_a, &b).unwrap();

            // Use tolerance based on intermediate value magnitudes.
            //
            // Key insight: when vectors have mixed +/- values, catastrophic
            // cancellation occurs. Large intermediate values (e.g., 9000) can
            // cancel to give small results (e.g., 16). The floating-point error
            // is bounded by the intermediate magnitudes, not the final result.
            //
            // Example: sum of products might be [+9000, -8500, +500, -984, ...]
            // giving final result of ~16, but error is proportional to ~9000.
            //
            // Solution: base tolerance on sum of absolute products, which
            // represents the "scale" of computation regardless of cancellation.
            let expected = scale * dot_ab;
            let sum_abs_products: f32 = a.iter()
                .zip(b.iter())
                .map(|(x, y)| (x * y).abs())
                .sum();
            // Error is proportional to intermediate magnitudes * scale * f32 epsilon
            // Use 1e-5 relative to intermediate values (conservative for f32)
            let tolerance = PROPTEST_TOLERANCE * 100.0 + sum_abs_products * scale * 1e-5;
            prop_assert!((dot_scaled - expected).abs() < tolerance,
                "Scalar bilinearity failed: dot({}*a, b)={} vs {}*dot(a,b)={}",
                scale, dot_scaled, scale, expected);
        }

        // ====================================================================
        // Normalization Property Tests
        // ====================================================================

        #[test]
        fn prop_normalized_vector_has_unit_magnitude(
            v in prop::collection::vec(-100.0f32..100.0f32, 1..100usize)
        ) {
            // Skip zero vectors using SIMD squared_magnitude
            let sq_mag = squared_magnitude(&v);
            if sq_mag > 1e-10 {
                let unit = normalize(&v);
                let mag = magnitude(&unit);
                prop_assert!((mag - 1.0).abs() < PROPTEST_TOLERANCE,
                    "Normalized vector should have magnitude 1.0, got {} for {:?}", mag, v);
            }
        }

        #[test]
        fn prop_normalize_in_place_has_unit_magnitude(
            v in prop::collection::vec(-100.0f32..100.0f32, 1..100usize)
        ) {
            // Skip zero vectors using SIMD squared_magnitude
            let sq_mag = squared_magnitude(&v);
            if sq_mag > 1e-10 {
                let mut v_copy = v.clone();
                normalize_in_place(&mut v_copy);
                let mag = magnitude(&v_copy);
                prop_assert!((mag - 1.0).abs() < PROPTEST_TOLERANCE,
                    "In-place normalized vector should have magnitude 1.0, got {}", mag);
            }
        }

        #[test]
        fn prop_normalize_matches_normalize_in_place(
            v in prop::collection::vec(-100.0f32..100.0f32, 1..100usize)
        ) {
            let unit = normalize(&v);
            let mut v_copy = v.clone();
            normalize_in_place(&mut v_copy);

            for (a, b) in unit.iter().zip(v_copy.iter()) {
                prop_assert!((a - b).abs() < PROPTEST_TOLERANCE,
                    "normalize and normalize_in_place should produce same result");
            }
        }

        #[test]
        fn prop_magnitude_is_non_negative(
            v in prop::collection::vec(-100.0f32..100.0f32, 0..100usize)
        ) {
            let mag = magnitude(&v);
            prop_assert!(mag >= 0.0, "Magnitude should be non-negative, got {}", mag);
        }

        #[test]
        fn prop_squared_magnitude_is_non_negative(
            v in prop::collection::vec(-100.0f32..100.0f32, 0..100usize)
        ) {
            let sq_mag = squared_magnitude(&v);
            prop_assert!(sq_mag >= 0.0, "Squared magnitude should be non-negative, got {}", sq_mag);
        }

        #[test]
        fn prop_magnitude_squared_relationship(
            v in prop::collection::vec(-100.0f32..100.0f32, 1..100usize)
        ) {
            let mag = magnitude(&v);
            let sq_mag = squared_magnitude(&v);
            // magnitude² should equal squared_magnitude
            // Use relative tolerance to avoid scale-dependent thresholds
            let diff = (mag * mag - sq_mag).abs();
            let relative_tolerance = 1e-5; // 0.001% relative error
            let threshold = sq_mag.max(1.0) * relative_tolerance;
            prop_assert!(diff < threshold,
                "magnitude² ({}) should equal squared_magnitude ({}), diff={}, threshold={}",
                mag * mag, sq_mag, diff, threshold);
        }

        #[test]
        fn prop_normalize_preserves_direction(
            v in prop::collection::vec(-100.0f32..100.0f32, 2..50usize)
        ) {
            // Skip zero or near-zero vectors using SIMD squared_magnitude
            let sq_mag = squared_magnitude(&v);
            if sq_mag > 1e-6 {
                let unit = normalize(&v);
                // Cosine similarity between original and normalized should be 1.0
                let sim = cosine_similarity(&v, &unit).unwrap();
                if !sim.is_nan() {
                    prop_assert!((sim - 1.0).abs() < PROPTEST_TOLERANCE * 10.0,
                        "Normalized vector should have same direction: sim = {}", sim);
                }
            }
        }

        #[test]
        fn prop_is_normalized_after_normalize(
            v in prop::collection::vec(-100.0f32..100.0f32, 1..100usize)
        ) {
            // Skip zero vectors using SIMD squared_magnitude
            let sq_mag = squared_magnitude(&v);
            if sq_mag > 1e-10 {
                let unit = normalize(&v);
                // Use 1e-5 tolerance matching PROPTEST_TOLERANCE
                prop_assert!(is_normalized(&unit, PROPTEST_TOLERANCE),
                    "Normalized vector should pass is_normalized check");
            }
        }
    }
}

// ========== New Error Handling Tests for Coverage ==========

#[test]
fn test_validate_vector_nan_rejection() {
    let vector_with_nan = vec![1.0, 2.0, f32::NAN, 4.0];

    let result = validate_vector(&vector_with_nan);

    assert!(result.is_err());
    assert!(
        matches!(
            result.unwrap_err(),
            crate::core::error::Error::Vector(crate::core::error::VectorError::ContainsNaN {
                count: 1
            })
        ),
        "Expected ContainsNaN error with count=1"
    );
}

#[test]
fn test_validate_vector_infinity_rejection() {
    let vector_with_inf = vec![1.0, 2.0, f32::INFINITY, 4.0];

    let result = validate_vector(&vector_with_inf);

    assert!(
        result.is_err(),
        "validate_vector should reject infinity values"
    );
    assert!(
        matches!(
            result.unwrap_err(),
            crate::core::error::Error::Vector(crate::core::error::VectorError::ContainsInfinity {
                count: 1
            })
        ),
        "Expected ContainsInfinity error with count=1"
    );
}

#[test]
fn test_cosine_similarity_zero_magnitude_handling() {
    let zero_vector = vec![0.0, 0.0, 0.0];
    let normal_vector = vec![1.0, 2.0, 3.0];

    // The implementation returns 0.0 for zero magnitude vectors.
    let result = cosine_similarity(&zero_vector, &normal_vector);

    match result {
        Ok(sim) => {
            assert_eq!(sim, 0.0, "Cosine similarity with zero vector should be 0.0");
        }
        Err(e) => {
            panic!(
                "Expected Ok(0.0) for zero magnitude vector, but got Err: {}",
                e
            );
        }
    }
}

// ========================================================================
// SparseVec Tests
// ========================================================================

#[test]
fn test_sparse_vec_creation_valid() {
    let sparse = SparseVec::new(vec![0, 2, 5], vec![1.0, 2.0, 3.0], 10).unwrap();
    assert_eq!(sparse.nnz(), 3);
    assert_eq!(sparse.dimension(), 10);
    assert_eq!(sparse.indices(), &[0, 2, 5]);
    assert_eq!(sparse.values(), &[1.0, 2.0, 3.0]);
}

#[test]
fn test_sparse_vec_empty() {
    let sparse = SparseVec::new(vec![], vec![], 10).unwrap();
    assert_eq!(sparse.nnz(), 0);
    assert_eq!(sparse.dimension(), 10);
    assert_eq!(sparse.indices(), &[] as &[u32]);
    assert_eq!(sparse.values(), &[] as &[f32]);
}

#[test]
fn test_sparse_vec_sorts_indices() {
    // Provide unsorted indices - should be sorted after construction
    let sparse = SparseVec::new(vec![5, 1, 3], vec![1.0, 2.0, 3.0], 10).unwrap();
    assert_eq!(sparse.indices(), &[1, 3, 5]);
    assert_eq!(sparse.values(), &[2.0, 3.0, 1.0]); // Values reordered to match sorted indices
}

#[test]
fn test_sparse_vec_dimension_mismatch() {
    // indices.len() != values.len()
    let result = SparseVec::new(vec![0, 1], vec![1.0], 10);
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        Error::Vector(VectorError::DimensionMismatch { .. })
    ));
}

#[test]
fn test_sparse_vec_index_out_of_bounds() {
    // Index 10 is out of bounds for dimension 10 (valid indices: 0-9)
    let result = SparseVec::new(vec![0, 10], vec![1.0, 2.0], 10);
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        Error::Vector(VectorError::InvalidSparseVector { .. })
    ));
}

#[test]
fn test_sparse_vec_duplicate_indices() {
    let result = SparseVec::new(vec![0, 1, 1], vec![1.0, 2.0, 3.0], 10);
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        Error::Vector(VectorError::InvalidSparseVector { .. })
    ));
}

#[test]
fn test_sparse_vec_zero_value() {
    // Sparse vectors should not store zero values
    let result = SparseVec::new(vec![0, 1, 2], vec![1.0, 0.0, 3.0], 10);
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        Error::Vector(VectorError::InvalidSparseVector { .. })
    ));
}

#[test]
fn test_sparse_vec_nan_value() {
    let result = SparseVec::new(vec![0, 1], vec![1.0, f32::NAN], 10);
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        Error::Vector(VectorError::ContainsNaN { .. })
    ));
}

#[test]
fn test_sparse_vec_infinity_value() {
    let result = SparseVec::new(vec![0, 1], vec![1.0, f32::INFINITY], 10);
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        Error::Vector(VectorError::ContainsInfinity { .. })
    ));
}

#[test]
fn test_sparse_vec_dimension_too_large() {
    let result = SparseVec::new(vec![0], vec![1.0], MAX_VECTOR_DIMENSIONS as u32 + 1);
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        Error::Vector(VectorError::DimensionTooLarge { .. })
    ));
}

#[test]
fn test_sparse_vec_to_dense() {
    let sparse = SparseVec::new(vec![1, 3, 5], vec![1.5, 2.5, 3.5], 7).unwrap();
    let dense = sparse.to_dense();
    assert_eq!(dense, vec![0.0, 1.5, 0.0, 2.5, 0.0, 3.5, 0.0]);
}

#[test]
fn test_sparse_vec_to_dense_empty() {
    let sparse = SparseVec::new(vec![], vec![], 5).unwrap();
    let dense = sparse.to_dense();
    assert_eq!(dense, vec![0.0, 0.0, 0.0, 0.0, 0.0]);
}

#[test]
fn test_sparse_vec_squared_magnitude() {
    let sparse = SparseVec::new(vec![0, 1, 2], vec![1.0, 2.0, 2.0], 5).unwrap();
    // magnitude² = 1² + 2² + 2² = 1 + 4 + 4 = 9
    assert_eq!(sparse.squared_magnitude(), 9.0);
}

#[test]
fn test_sparse_vec_magnitude() {
    let sparse = SparseVec::new(vec![0, 1], vec![3.0, 4.0], 5).unwrap();
    // magnitude = sqrt(3² + 4²) = sqrt(9 + 16) = 5.0
    assert_eq!(sparse.magnitude(), 5.0);
}

#[test]
fn test_sparse_vec_magnitude_empty() {
    let sparse = SparseVec::new(vec![], vec![], 10).unwrap();
    assert_eq!(sparse.magnitude(), 0.0);
    assert_eq!(sparse.squared_magnitude(), 0.0);
}

#[test]
fn test_sparse_vec_clone() {
    let sparse1 = SparseVec::new(vec![0, 2], vec![1.0, 2.0], 5).unwrap();
    let sparse2 = sparse1.clone();
    // Use approx_eq instead of == due to floating-point concerns
    assert!(
        sparse1.approx_eq(&sparse2, 1e-10),
        "Cloned sparse vector should be approximately equal to original"
    );
    assert_eq!(sparse1.indices(), sparse2.indices());
    assert_eq!(sparse1.values(), sparse2.values());
}

#[test]
fn test_sparse_vec_approx_eq() {
    let a = SparseVec::new(vec![0, 2], vec![1.0, 2.0], 5).unwrap();
    let b = SparseVec::new(vec![0, 2], vec![1.0000001, 2.0000001], 5).unwrap();

    // Small floating-point differences should be tolerated with appropriate epsilon
    assert!(
        a.approx_eq(&b, 1e-5),
        "Vectors with small floating-point differences should be approximately equal"
    );
    assert!(
        !a.approx_eq(&b, 1e-10),
        "Vectors should not be equal with very strict epsilon"
    );

    // Different dimensions
    let c = SparseVec::new(vec![0, 2], vec![1.0, 2.0], 10).unwrap();
    assert!(
        !a.approx_eq(&c, 1e-5),
        "Vectors with different dimensions should not be equal"
    );

    // Different indices
    let d = SparseVec::new(vec![0, 3], vec![1.0, 2.0], 5).unwrap();
    assert!(
        !a.approx_eq(&d, 1e-5),
        "Vectors with different indices should not be equal"
    );

    // Different values
    let e = SparseVec::new(vec![0, 2], vec![1.0, 3.0], 5).unwrap();
    assert!(
        !a.approx_eq(&e, 1e-5),
        "Vectors with significantly different values should not be equal"
    );
}

#[test]
fn test_sparse_vec_debug() {
    let sparse = SparseVec::new(vec![0, 2], vec![1.0, 2.0], 5).unwrap();
    let debug_str = format!("{:?}", sparse);
    assert!(debug_str.contains("SparseVec"));
}

#[test]
fn test_sparse_vec_single_element() {
    let sparse = SparseVec::new(vec![5], vec![1.0], 10).unwrap();
    assert_eq!(sparse.nnz(), 1);
    assert_eq!(sparse.dimension(), 10);
    let dense = sparse.to_dense();
    assert_eq!(
        dense,
        vec![0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]
    );
}

#[test]
fn test_sparse_vec_bm25_like() {
    // Simulate a BM25-style sparse vector (typical for information retrieval)
    // Only a few terms are present in a document out of a large vocabulary
    let sparse = SparseVec::new(
        vec![10, 42, 100, 257],
        vec![2.5, 1.8, 3.2, 1.2],
        10000, // Large vocabulary size
    )
    .unwrap();

    assert_eq!(sparse.nnz(), 4);
    assert_eq!(sparse.dimension(), 10000);
    // Verify memory efficiency: only storing 4 non-zero values instead of 10000
}

#[test]
fn test_sparse_vec_negative_values() {
    // Sparse vectors can have negative values
    let sparse = SparseVec::new(vec![0, 2, 4], vec![-1.0, 2.0, -3.0], 5).unwrap();
    assert_eq!(sparse.values(), &[-1.0, 2.0, -3.0]);
    let dense = sparse.to_dense();
    assert_eq!(dense, vec![-1.0, 0.0, 2.0, 0.0, -3.0]);
}

// ========================================================================
// Sparse Vector Similarity Function Tests
// ========================================================================

#[test]
fn test_sparse_dot_product_basic() {
    // Sparse vectors: [1, 0, 2, 0, 0] and [0, 0, 3, 0, 4]
    let a = SparseVec::new(vec![0, 2], vec![1.0, 2.0], 5).unwrap();
    let b = SparseVec::new(vec![2, 4], vec![3.0, 4.0], 5).unwrap();

    // Only index 2 overlaps: 2.0 * 3.0 = 6.0
    let dot = sparse_dot_product(&a, &b).unwrap();
    assert_eq!(dot, 6.0);
}

#[test]
fn test_sparse_dot_product_no_overlap() {
    // Sparse vectors with no overlapping indices
    let a = SparseVec::new(vec![0, 1], vec![1.0, 2.0], 10).unwrap();
    let b = SparseVec::new(vec![5, 6], vec![3.0, 4.0], 10).unwrap();

    let dot = sparse_dot_product(&a, &b).unwrap();
    assert_eq!(dot, 0.0);
}

#[test]
fn test_sparse_dot_product_complete_overlap() {
    // Sparse vectors with complete overlap
    let a = SparseVec::new(vec![0, 2, 4], vec![1.0, 2.0, 3.0], 5).unwrap();
    let b = SparseVec::new(vec![0, 2, 4], vec![2.0, 3.0, 4.0], 5).unwrap();

    // 1*2 + 2*3 + 3*4 = 2 + 6 + 12 = 20
    let dot = sparse_dot_product(&a, &b).unwrap();
    assert_eq!(dot, 20.0);
}

#[test]
fn test_sparse_dot_product_empty() {
    let a = SparseVec::new(vec![], vec![], 10).unwrap();
    let b = SparseVec::new(vec![0, 5], vec![1.0, 2.0], 10).unwrap();

    let dot = sparse_dot_product(&a, &b).unwrap();
    assert_eq!(dot, 0.0);
}

#[test]
fn test_sparse_dot_product_different_dimensions() {
    // Vectors with different dimensions should fail
    let a = SparseVec::new(vec![0, 2], vec![1.0, 2.0], 5).unwrap();
    let b = SparseVec::new(vec![2, 4], vec![3.0, 4.0], 10).unwrap();

    let result = sparse_dot_product(&a, &b);
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        Error::Vector(VectorError::DimensionMismatch { .. })
    ));
}

#[test]
fn test_sparse_cosine_similarity_identical() {
    let a = SparseVec::new(vec![0, 2], vec![1.0, 1.0], 5).unwrap();
    let b = SparseVec::new(vec![0, 2], vec![1.0, 1.0], 5).unwrap();

    // Identical vectors have cosine similarity = 1.0
    let sim = sparse_cosine_similarity(&a, &b).unwrap();
    assert!((sim - 1.0).abs() < 1e-6);
}

#[test]
fn test_sparse_cosine_similarity_orthogonal() {
    // Orthogonal sparse vectors (no overlapping indices)
    let a = SparseVec::new(vec![0, 1], vec![1.0, 1.0], 5).unwrap();
    let b = SparseVec::new(vec![3, 4], vec![1.0, 1.0], 5).unwrap();

    // Orthogonal vectors have cosine similarity = 0.0
    let sim = sparse_cosine_similarity(&a, &b).unwrap();
    assert_eq!(sim, 0.0);
}

#[test]
fn test_sparse_cosine_similarity_opposite() {
    let a = SparseVec::new(vec![0, 2], vec![1.0, 2.0], 5).unwrap();
    let b = SparseVec::new(vec![0, 2], vec![-1.0, -2.0], 5).unwrap();

    // Opposite vectors have cosine similarity = -1.0
    let sim = sparse_cosine_similarity(&a, &b).unwrap();
    assert!((sim + 1.0).abs() < 1e-6);
}

#[test]
fn test_sparse_cosine_similarity_zero_magnitude() {
    let a = SparseVec::new(vec![], vec![], 10).unwrap(); // Zero vector
    let b = SparseVec::new(vec![0, 1], vec![1.0, 2.0], 10).unwrap();

    // Zero magnitude should return 0.0
    let sim = sparse_cosine_similarity(&a, &b).unwrap();
    assert_eq!(sim, 0.0);
}

#[test]
fn test_sparse_squared_euclidean_distance_basic() {
    let a = SparseVec::new(vec![0], vec![3.0], 5).unwrap();
    let b = SparseVec::new(vec![], vec![], 5).unwrap(); // Zero vector (all zeros)

    // Distance from [3,0,0,0,0] to [0,0,0,0,0] = 9
    let dist_sq = sparse_squared_euclidean_distance(&a, &b).unwrap();
    assert_eq!(dist_sq, 9.0);
}

#[test]
fn test_sparse_squared_euclidean_distance_identical() {
    let a = SparseVec::new(vec![0, 2, 4], vec![1.0, 2.0, 3.0], 5).unwrap();
    let b = a.clone();

    let dist_sq = sparse_squared_euclidean_distance(&a, &b).unwrap();
    assert_eq!(dist_sq, 0.0);
}

#[test]
fn test_sparse_squared_euclidean_distance_dimension_mismatch() {
    let a = SparseVec::new(vec![0], vec![1.0], 5).unwrap();
    let b = SparseVec::new(vec![0], vec![1.0], 10).unwrap();

    let result = sparse_squared_euclidean_distance(&a, &b);
    assert!(result.is_err());
    assert!(matches!(
        result.unwrap_err(),
        Error::Vector(VectorError::DimensionMismatch { .. })
    ));
}

#[test]
fn test_sparse_euclidean_distance_basic() {
    let a = SparseVec::new(vec![0], vec![3.0], 5).unwrap();
    let b = SparseVec::new(vec![], vec![], 5).unwrap(); // Zero vector (all zeros)

    // Distance from [3,0,0,0,0] to [0,0,0,0,0] = 3.0
    let dist = sparse_euclidean_distance(&a, &b).unwrap();
    assert_eq!(dist, 3.0);
}

#[test]
fn test_sparse_euclidean_distance_pythagorean() {
    // Test Pythagorean triple: 3-4-5
    let a = SparseVec::new(vec![0, 1], vec![3.0, 4.0], 5).unwrap();
    let b = SparseVec::new(vec![], vec![], 5).unwrap(); // Zero vector

    // Distance should be 5.0
    let dist = sparse_euclidean_distance(&a, &b).unwrap();
    assert_eq!(dist, 5.0);
}

#[test]
fn test_sparse_similarity_with_bm25_like_vectors() {
    // Simulate BM25 document vectors
    let doc1 = SparseVec::new(vec![10, 42, 100, 257], vec![2.5, 1.8, 3.2, 1.2], 10000).unwrap();
    let doc2 = SparseVec::new(vec![10, 50, 100, 300], vec![2.3, 1.5, 3.0, 1.0], 10000).unwrap();

    // These documents overlap at indices 10 and 100
    let dot = sparse_dot_product(&doc1, &doc2).unwrap();
    assert!(dot > 0.0); // Should have positive dot product

    let sim = sparse_cosine_similarity(&doc1, &doc2).unwrap();
    assert!(sim > 0.0); // Should have positive similarity
    assert!(sim <= 1.0); // Should be <= 1.0
}

#[test]
fn test_sparse_vs_dense_dot_product_equivalence() {
    // Verify sparse and dense implementations give same results
    let sparse_a = SparseVec::new(vec![1, 3, 5], vec![1.0, 2.0, 3.0], 7).unwrap();
    let sparse_b = SparseVec::new(vec![0, 1, 5], vec![2.0, 3.0, 4.0], 7).unwrap();

    let sparse_dot = sparse_dot_product(&sparse_a, &sparse_b).unwrap();

    // Convert to dense and compute
    let dense_a = sparse_a.to_dense();
    let dense_b = sparse_b.to_dense();
    let dense_dot = dot_product(&dense_a, &dense_b).unwrap();

    assert!((sparse_dot - dense_dot).abs() < 1e-6);
}

#[test]
fn test_sparse_vs_dense_cosine_similarity_equivalence() {
    let sparse_a = SparseVec::new(vec![0, 2, 4], vec![1.0, 2.0, 3.0], 6).unwrap();
    let sparse_b = SparseVec::new(vec![1, 2, 5], vec![1.0, 3.0, 2.0], 6).unwrap();

    let sparse_sim = sparse_cosine_similarity(&sparse_a, &sparse_b).unwrap();

    let dense_a = sparse_a.to_dense();
    let dense_b = sparse_b.to_dense();
    let dense_sim = cosine_similarity(&dense_a, &dense_b).unwrap();

    assert!((sparse_sim - dense_sim).abs() < 1e-6);
}

#[test]
fn test_sparse_vs_dense_euclidean_distance_equivalence() {
    let sparse_a = SparseVec::new(vec![0, 3], vec![1.0, 2.0], 5).unwrap();
    let sparse_b = SparseVec::new(vec![1, 3], vec![1.0, 4.0], 5).unwrap();

    let sparse_dist = sparse_euclidean_distance(&sparse_a, &sparse_b).unwrap();

    let dense_a = sparse_a.to_dense();
    let dense_b = sparse_b.to_dense();
    let dense_dist = euclidean_distance(&dense_a, &dense_b).unwrap();

    assert!((sparse_dist - dense_dist).abs() < 1e-5);
}

#[test]
#[should_panic]
fn test_internal_safety_in_release() {
    let a = vec![1.0; 4];
    let b = vec![1.0; 3]; // Mismatch
    // This calls dot_and_magnitudes internally
    // We use dot_and_magnitudes because it is one of the functions we are hardening
    let _ = super::simd::dot_and_magnitudes(&a, &b);
}

#[test]
#[should_panic]
fn test_dot_and_magnitudes_mismatch_panics() {
    let a = vec![1.0, 2.0];
    let b = vec![1.0, 2.0, 3.0];
    // This function is private but visible to child modules
    let _ = super::simd::dot_and_magnitudes(&a, &b);
}

#[test]
#[should_panic]
fn test_squared_diff_sum_mismatch_panics() {
    let a = vec![1.0, 2.0];
    let b = vec![1.0, 2.0, 3.0];
    let _ = super::simd::squared_diff_sum(&a, &b);
}

#[test]
#[should_panic]
fn test_dot_product_sum_mismatch_panics() {
    let a = vec![1.0, 2.0];
    let b = vec![1.0, 2.0, 3.0];
    let _ = super::simd::dot_product_sum(&a, &b);
}

#[test]
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn test_simd_mismatched_lengths_safety() {
    let a = vec![1.0; 8];
    let b = vec![1.0; 9];

    // Test SSE2 if available (baseline for x86_64)
    if is_x86_feature_detected!("sse2") {
        let result = std::panic::catch_unwind(|| unsafe {
            super::simd::x86_ops::dot_and_magnitudes_sse2(&a, &b)
        });
        assert!(
            result.is_err(),
            "SSE2 dot_and_magnitudes should panic on mismatch"
        );

        let result =
            std::panic::catch_unwind(|| unsafe { super::simd::x86_ops::dot_product_sse2(&a, &b) });
        assert!(result.is_err(), "SSE2 dot_product should panic on mismatch");

        let result = std::panic::catch_unwind(|| unsafe {
            super::simd::x86_ops::squared_diff_sum_sse2(&a, &b)
        });
        assert!(
            result.is_err(),
            "SSE2 squared_diff_sum should panic on mismatch"
        );
    }

    // Test AVX2 if available
    if is_x86_feature_detected!("avx2") && is_x86_feature_detected!("fma") {
        let result = std::panic::catch_unwind(|| unsafe {
            super::simd::x86_ops::dot_and_magnitudes_avx2(&a, &b)
        });
        assert!(
            result.is_err(),
            "AVX2 dot_and_magnitudes should panic on mismatch"
        );

        let result =
            std::panic::catch_unwind(|| unsafe { super::simd::x86_ops::dot_product_avx2(&a, &b) });
        assert!(result.is_err(), "AVX2 dot_product should panic on mismatch");

        let result = std::panic::catch_unwind(|| unsafe {
            super::simd::x86_ops::squared_diff_sum_avx2(&a, &b)
        });
        assert!(
            result.is_err(),
            "AVX2 squared_diff_sum should panic on mismatch"
        );
    }
}

#[test]
fn test_sparse_squared_euclidean_distance_edge_cases() {
    struct TestCase {
        name: &'static str,
        a_indices: Vec<u32>,
        a_values: Vec<f32>,
        b_indices: Vec<u32>,
        b_values: Vec<f32>,
        expected: f32,
    }

    let cases = vec![
        TestCase {
            name: "Both zero vectors",
            a_indices: vec![],
            a_values: vec![],
            b_indices: vec![],
            b_values: vec![],
            expected: 0.0,
        },
        TestCase {
            name: "Negative overlapping values",
            a_indices: vec![0, 2],
            a_values: vec![-1.0, -2.0],
            b_indices: vec![0, 2],
            b_values: vec![-1.0, -2.0],
            expected: 0.0,
        },
        TestCase {
            name: "Orthogonal vectors",
            a_indices: vec![0, 1],
            a_values: vec![1.0, 2.0],
            b_indices: vec![2, 3],
            b_values: vec![3.0, 4.0],
            expected: 1.0 + 4.0 + 9.0 + 16.0, // 30.0
        },
        TestCase {
            name: "Negative and positive vectors",
            a_indices: vec![0, 1],
            a_values: vec![1.0, -1.0],
            b_indices: vec![0, 1],
            b_values: vec![-1.0, 1.0],
            expected: 4.0 + 4.0, // 8.0
        },
        TestCase {
            name: "Subnormal values",
            a_indices: vec![0],
            a_values: vec![1e-45],
            b_indices: vec![0],
            b_values: vec![-1e-45],
            expected: (2.0 * 1e-45) * (2.0 * 1e-45),
        },
    ];

    for case in cases {
        let a = SparseVec::new(case.a_indices, case.a_values, 10).unwrap();
        let b = SparseVec::new(case.b_indices, case.b_values, 10).unwrap();

        let dist_sq = sparse_squared_euclidean_distance(&a, &b).unwrap();
        assert!(
            (dist_sq - case.expected).abs() < 1e-6 || (dist_sq == case.expected),
            "Test '{}' failed: expected {}, got {}",
            case.name,
            case.expected,
            dist_sq
        );
    }
}