polydat-core 0.13.0

Polydat runtime: value model, graph compiler, execution engines, kernels
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
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Vector dataset access nodes via the `vectordata` crate.
//!
//! Each node takes a dataset source string (URL, local path, or
//! catalog name) as a const parameter and loads the dataset handle at
//! construction time.
//!
//! Source specifier formats:
//! - `"dataset"` — catalog lookup, uses default profile
//! - `"dataset:profile"` — catalog lookup with explicit profile
//! - `"https://..."` — direct URL
//! - `"/path/to/dir"` — local filesystem path
//!
//! ## Prebuffering
//!
//! Use `dataset_prebuffer("source")` to eagerly download all facets
//! for a dataset before workload execution. After prebuffering, data
//! access uses local mmap readers (zero HTTP overhead).
//!
//! ## Cache-aware loading
//!
//! For catalog-resolved datasets, the loader checks the local cache
//! at `~/.cache/vectordata/<dataset>/` before issuing HTTP requests.
//! Prebuffering populates this cache; subsequent loads are local.
//!
//! Feature-gated behind `vectordata`.
//!
//! ## Upstream API reference
//!
//! See the vectordata consumer guide for the full dataset access,
//! catalog, caching, and fetch model — the crate's `AGENTS.md`,
//! rendered as `vectordata::_agents`:
//! <https://docs.rs/vectordata/latest/vectordata/_agents/index.html>

use std::sync::{Arc, LazyLock};

use crate::library::support::cache::OnceCache;

/// The small predicated dataset vectordata embeds for tests: 190 base
/// vectors and 10 queries with record metadata, a layout that types
/// every field, a mixed predicate set, the rows each predicate admits
/// and all three ground truths. [`predicated`](fixtures::predicated)
/// writes it to a directory, which a source string then names by path.
/// It is regenerated from the dataset pipeline, so a test asserts
/// properties of it and not particular rows.
#[cfg(feature = "vectordata-fixtures")]
pub mod fixtures {
    pub use vectordata::fixtures::{PREDICATED_DEPTH, PREDICATED_PROFILES, predicated};
}

use vectordata::binding::{BindType, Binder, Layout, Nullability};
use vectordata::catalog::{Catalog, CatalogSources};
use vectordata::dataset::facet::FacetShape;
use vectordata::fetch::{FetchRequest, LogMeter};
use vectordata::ground_truth::{AdmittedRows, GroundTruth, OrdinalSet, TruthKind};
use vectordata::predicate_forms::FormCensus;

// By path, not by name: the node macro names each node's type after
// its function, and `predicate_forms` and `record_forms` are nodes.
use crate::dataset_value as dv;
use vectordata::{TestDataGroup, TestDataView, TestDataViewExt, VectorReader, VvecReader};

/// Global cache for loaded dataset groups keyed by source string.
/// Ensures each dataset is loaded exactly once regardless of how many
/// node functions reference it. The race-free init pattern lives in
/// [`crate::library::support::cache::OnceCache`].
static DATASET_CACHE: LazyLock<OnceCache<String, Arc<TestDataGroup>>> =
    LazyLock::new(OnceCache::new);

/// Type-erased facet cache: (source, profile, facet) → Arc<dyn Any + Send + Sync>.
/// Ensures each reader (of any element type) is opened exactly once
/// and shared across all node instances that reference the same data.
/// The concrete type inside is `Arc<UniformDataset<T>>` or `Arc<Ivvec32Dataset>`
/// or `Arc<GenericFacetDataset>`. The race-free init pattern lives
/// in [`OnceCache`].
type FacetCache = OnceCache<(String, String, String), Arc<dyn std::any::Any + Send + Sync>>;
static FACET_CACHE: LazyLock<FacetCache> = LazyLock::new(OnceCache::new);

/// Whole-dataset prebuffer cache keyed by source string. Wraps
/// [`do_dataset_prebuffer_inner`] so N fibers all calling
/// `dataset_prebuffer("ds:profile")` at init time serialize on
/// one OnceLock and share the resulting handle. Without this,
/// each fiber's own kernel-init pass invokes the real prebuffer
/// body and they all race into the manifest walk + per-facet
/// download — exactly the thundering herd we hit. The inner
/// caches (DATASET_CACHE, FACET_CACHE) only protect the
/// group-resolve and per-facet-reader steps, not the outer
/// "walk every facet and pull all chunks" work.
static PREBUFFER_CACHE: LazyLock<OnceCache<String, Arc<DatasetHandle>>> =
    LazyLock::new(OnceCache::new);

// =================================================================
// Dataset resolution — catalog-aware, cache-aware
// =================================================================

/// Parse a source specifier into (dataset, profile_name).
///
/// Supports `"dataset:profile"` syntax. If no colon is present,
/// the profile defaults to `"default"`. The dataset is a catalog name
/// or a path to a dataset on disk (its directory or its
/// `dataset.yaml`): a path that exists is a path, whatever punctuation
/// it holds, which is the rule vectordata's own specs follow. So a
/// source that exists is the dataset with the default profile, and
/// otherwise a source whose text before its last colon exists is that
/// dataset with the profile after it.
fn parse_source_specifier(source: &str) -> (&str, &str) {
    // Don't split on colon in URLs
    if source.starts_with("http://") || source.starts_with("https://") {
        return (source, "default");
    }
    if is_dataset_path(source) {
        return (source, "default");
    }
    if let Some(pos) = source.rfind(':')
        && is_dataset_path(&source[..pos])
    {
        return (&source[..pos], &source[pos + 1..]);
    }
    if let Some(pos) = source.find(':') {
        (&source[..pos], &source[pos + 1..])
    } else {
        (source, "default")
    }
}

/// Whether `dataset` names a dataset on disk rather than in a catalog:
/// a path that exists.
fn is_dataset_path(dataset: &str) -> bool {
    !dataset.is_empty() && std::path::Path::new(dataset).exists()
}

/// Run a synchronous body that may internally drive
/// `reqwest::blocking` (and thus spin up a private tokio
/// runtime per HTTP request). If we're sitting on an outer
/// async runtime — we are, in every per-cycle and per-phase
/// path — the inner runtime panics on drop with "Cannot drop a
/// runtime in a context where blocking is not allowed".
/// `block_in_place` parks the outer multi-thread worker for
/// the duration of the call so the inner runtime sees a
/// non-async drop context. Falls back to a direct call when no
/// runtime is current (e.g. unit tests). Single helper used by
/// all three vectordata-facing entry points
/// ([`load_dataset_group`], [`load_uniform_facet`],
/// [`GenericFacetDataset::load`]).
fn run_blocking_io<R>(body: impl FnOnce() -> R) -> R {
    // tokio rides the `vectordata` feature: without the crate there is
    // no HTTP client to park a worker for.
    #[cfg(feature = "vectordata")]
    if tokio::runtime::Handle::try_current().is_ok() {
        return tokio::task::block_in_place(body);
    }
    body()
}

/// Load a dataset group by catalog name or by path.
///
/// A name goes through the vectordata catalog API: `catalog.open(name)`
/// handles catalog discovery, cache resolution, and download
/// transparently. A path that exists is opened where it is.
pub(crate) fn load_dataset_group(source: &str) -> Result<Arc<TestDataGroup>, String> {
    let (dataset_name, _profile) = parse_source_specifier(source);
    // Both keys (dataset name and full source spec) point at the
    // same `Arc<TestDataGroup>`; the `OnceCache` slot for one is
    // primed by the other on first hit.
    DATASET_CACHE.get_or_init(dataset_name.to_string(), || {
        run_blocking_io(|| {
            let opened = if is_dataset_path(dataset_name) {
                TestDataGroup::load(dataset_name)
            } else {
                Catalog::of(&CatalogSources::new().configure_default()).open(dataset_name)
            };
            opened
                .map(Arc::new)
                .map_err(|e| format!("failed to load dataset '{dataset_name}': {e}"))
        })
    })
}

// =================================================================
// Dataset handles — loaded once at node construction, shared via Arc
// =================================================================

/// Generic handle to a loaded uniform vector facet. Thread-safe, random-access.
/// Supports any element type provided by the vectordata API (f32, f64,
/// i32, i16, u8, i8, u16, u32, u64, i64, f16).
pub(crate) struct UniformDataset<T: Send + Sync + 'static> {
    reader: Arc<dyn VectorReader<T>>,
    count: usize,
    dim: usize,
    /// The facet read as ground truth, when it is a neighbor-indices
    /// facet: vectordata's reader of a row's live neighbors and of the
    /// facet's coverage, or the reason it refuses the profile. `None`
    /// for every other facet.
    truth: Option<Result<GroundTruth, String>>,
}

/// Cache-aware loader for uniform vector facets.
/// Returns a shared `Arc<UniformDataset<T>>`, creating and caching it
/// on first access. Subsequent loads for the same (source, profile, facet)
/// return the cached instance.
fn load_uniform_facet<T: Send + Sync + 'static>(
    source: &str,
    profile: &str,
    facet: &str,
    open_fn: impl FnOnce(
        &dyn TestDataView,
    ) -> std::result::Result<Arc<dyn VectorReader<T>>, vectordata::Error>,
    truth: Option<TruthKind>,
) -> Result<Arc<UniformDataset<T>>, String> {
    let key = (source.to_string(), profile.to_string(), facet.to_string());
    let any = FACET_CACHE.get_or_init(key, || {
        let group = load_dataset_group(source)?;
        let view = group
            .profile(profile)
            .ok_or_else(|| format!("profile '{profile}' not found in '{source}'"))?;
        // Audit: log the open *before* `open_fn` runs so the
        // line appears even if the open errors. Inside
        // `get_or_init`'s closure, this fires exactly once per
        // (source, profile, facet) — the prior shape logged
        // once per concurrent miss (storms of N for N fibers).
        crate::library::support::audit::record_opened(
            parse_source_specifier(source).0,
            profile,
            facet,
            "uniform",
        );
        let reader = run_blocking_io(|| open_fn(view.as_ref()))
            .map_err(|e| format!("failed to access {facet} from '{source}': {e}"))?;
        let count = reader.count();
        let dim = reader.dim();
        // A profile vectordata refuses as ground truth still reads as
        // fixed-width rows, so the refusal is kept for the nodes that
        // ask for live neighbors or coverage, and reported by them.
        let truth = truth.map(|kind| {
            run_blocking_io(|| GroundTruth::open(view.as_ref(), kind)).map_err(|e| e.to_string())
        });
        let arc: Arc<UniformDataset<T>> = Arc::new(UniformDataset {
            reader,
            count,
            dim,
            truth,
        });
        Ok(arc as Arc<dyn std::any::Any + Send + Sync>)
    })?;
    any.downcast::<UniformDataset<T>>().map_err(|_| {
        format!(
            "facet cache type mismatch for '{source}:{profile}/{facet}' — \
             this should be impossible; please file a bug."
        )
    })
}

// Type aliases for backward compatibility
type F32Dataset = UniformDataset<f32>;
type I32Dataset = UniformDataset<i32>;

impl F32Dataset {
    fn load(source: &str, profile: &str, facet: &str) -> Result<Arc<Self>, String> {
        let facet_name = facet.to_string();
        load_uniform_facet(
            source,
            profile,
            facet,
            move |view| match facet_name.as_str() {
                "base" => view.base_vectors_as(),
                "query" => view.query_vectors_as(),
                "neighbor_distances" => view.neighbor_distances_as(),
                "filtered_neighbor_distances" | "prefiltered_neighbor_distances" => {
                    view.prefiltered_neighbor_distances_as()
                }
                "postfiltered_neighbor_distances" => view.postfiltered_neighbor_distances_as(),
                other => Err(vectordata::Error::MissingFacet(format!(
                    "unknown f32 facet: '{other}'"
                ))),
            },
            None,
        )
    }
}

impl I32Dataset {
    fn load(source: &str, profile: &str, facet: &str) -> Result<Arc<Self>, String> {
        let facet_name = facet.to_string();
        let truth = match facet {
            "neighbor_indices" => Some(TruthKind::Unfiltered),
            "filtered_neighbor_indices" | "prefiltered_neighbor_indices" => {
                Some(TruthKind::Prefiltered)
            }
            "postfiltered_neighbor_indices" => Some(TruthKind::Postfiltered),
            _ => None,
        };
        let open = move |view: &dyn TestDataView| match facet_name.as_str() {
            "neighbor_indices" => view.neighbor_indices_as(),
            "filtered_neighbor_indices" | "prefiltered_neighbor_indices" => {
                view.prefiltered_neighbor_indices_as()
            }
            "postfiltered_neighbor_indices" => view.postfiltered_neighbor_indices_as(),
            other => Err(vectordata::Error::MissingFacet(format!(
                "unknown i32 facet: '{other}'"
            ))),
        };
        load_uniform_facet(source, profile, facet, open, truth)
    }
}

// =================================================================
// Dataset handle — typed enum wrapping all per-facet dataset shapes
// =================================================================
//
// Per type_system.md §1.8: `dataset_open(source, facet)` is
// the resolver node; per-cycle accessors take a handle wire and
// downcast to the concrete variant they expect. A single Value
// variant `Value::Handle(Arc<dyn Any>)` carries any of the
// concrete shapes — the enum below is what's actually inside the
// Arc, and accessors `match` on the variant.
//
// One handle may be opened against multiple facets at the
// `dataset_open` boundary (the user calls `dataset_open(spec,
// "base")` vs. `dataset_open(spec, "query")` and gets two
// distinct handles); the downstream accessor matches on whatever
// variant came back.

/// Typed wrapper around a resolved dataset facet or group. Held
/// inside `Value::Handle` as `Arc<DatasetHandle>` and downcast by
/// accessor nodes via [`Value::as_handle::<DatasetHandle>()`].
/// Cloning a `Value::Handle` is one `Arc::clone` — one atomic
/// increment, no allocation — which is the design contract this
/// enum exists to satisfy.
#[derive(Clone)]
pub(crate) enum DatasetHandle {
    /// Uniform `f32` vector facet (base, query, neighbor_distances,
    /// and the filtered, prefiltered and postfiltered neighbor
    /// distances).
    F32(Arc<F32Dataset>),
    /// Uniform `i32` vector facet (neighbor_indices, and the filtered,
    /// prefiltered and postfiltered neighbor indices).
    I32(Arc<I32Dataset>),
    /// Variable-length `i32` facet (metadata_results).
    Ivvec32(Arc<Ivvec32Dataset>),
    /// Type-erased generic-typed scalar facet (metadata_content,
    /// metadata_predicates, ...).
    Generic(Arc<GenericFacetDataset>),
    /// The `metadata_content` facet of a dataset that publishes it as
    /// records: one record of named, typed fields per base vector, with
    /// the layout that types them.
    Records(Arc<RecordDataset>),
    /// The `metadata_predicates` facet of a dataset that publishes it
    /// as records: one predicate per query, with the forms they take.
    Predicates(Arc<dv::PredicateForms>),
    /// Dataset-group handle — used by group-level metadata
    /// accessors (`dataset_profile_count`, `dataset_facets`,
    /// `dataset_distance_function`, ...) that operate on the
    /// `TestDataGroup` before any profile/facet is chosen.
    Group(Arc<TestDataGroup>),
    /// Prebuffered-and-resident dataset, returned by
    /// `dataset_prebuffer(source)`. Carries both the group and
    /// the source spec: a facet accessor opens its facet from
    /// `<source>:<profile>` (`query_vector_at(prebuffered, q)`
    /// reads the `query` facet), and a group accessor reads the
    /// group. [`DatasetHandle::resolve_facet`] and
    /// [`DatasetHandle::resolve_group`] are those two readings.
    ///
    /// The `group` field also keeps the prebuffered `TestDataGroup`
    /// alive for the duration of the handle — vectordata's
    /// internal storage cache is keyed off the group instance,
    /// so dropping the group prematurely would force per-facet
    /// readers to re-open against transport.
    Prebuffered {
        group: Arc<TestDataGroup>,
        source: String,
    },
}

impl DatasetHandle {
    fn open(source: &str, facet: &str) -> Result<Self, String> {
        let (_, profile) = parse_source_specifier(source);
        match facet {
            "base"
            | "query"
            | "neighbor_distances"
            | "filtered_neighbor_distances"
            | "prefiltered_neighbor_distances"
            | "postfiltered_neighbor_distances" => {
                F32Dataset::load(source, profile, facet).map(DatasetHandle::F32)
            }
            "neighbor_indices"
            | "filtered_neighbor_indices"
            | "prefiltered_neighbor_indices"
            | "postfiltered_neighbor_indices" => {
                I32Dataset::load(source, profile, facet).map(DatasetHandle::I32)
            }
            "metadata_results" => Ivvec32Dataset::load(source, profile).map(DatasetHandle::Ivvec32),
            // A dataset publishes its metadata either as one scalar per
            // base vector or as a record of fields per base vector;
            // the profile says which, and each has its own reader.
            MetadataContentFacet::FACET
                if facet_shape(source, profile, facet) == Some(FacetShape::Records) =>
            {
                RecordDataset::load(source, profile).map(DatasetHandle::Records)
            }
            MetadataPredicatesFacet::FACET
                if facet_shape(source, profile, facet) == Some(FacetShape::Records) =>
            {
                load_predicate_forms(source, profile).map(DatasetHandle::Predicates)
            }
            // Anything else routes through GenericFacetDataset (typed
            // scalar reader), which covers a scalar metadata_content,
            // metadata_predicates, and any future scalar facet.
            _ => GenericFacetDataset::load(source, profile, facet).map(DatasetHandle::Generic),
        }
    }

    fn open_group(source: &str) -> Result<Self, String> {
        load_dataset_group(source).map(DatasetHandle::Group)
    }
}

/// `dataset_open(source: str, facet: str) -> Handle`
///
/// The single resolver node. Provenance follows its two wire
/// inputs; when both are scope-extern constants (the iter-var
/// case), this evaluates exactly once at iteration entry and
/// stays cached for every cycle in that iteration. When source
/// or facet is cycle-time, it re-evaluates accordingly.
///
/// All per-cycle accessors take the resulting handle on a wire
/// — the catalog/HTTP/mmap path is never on the cycle hot path.
///
/// A resolve failure panics with the underlying error rather than
/// yielding `Value::None`, so a catalog miss cannot degrade into a
/// garbage value downstream: the engine's `enrich_eval_panic` adds
/// node provenance, `eval_const_expr` traps the panic into
/// `Result::Err`, and `evaluate_spec` propagates it as a
/// clause-level diagnostic.
#[crate::polydat_node(category = RealData)]
fn dataset_open(source: &str, facet: &str) -> Arc<DatasetHandle> {
    match DatasetHandle::open(source, facet) {
        Ok(h) => Arc::new(h),
        Err(e) => {
            let msg = format!("dataset_open: failed to resolve '{source}' facet='{facet}': {e}");
            crate::library::support::audit::error(&msg);
            panic!("{msg}");
        }
    }
}

/// `dataset_group_open(source: str) -> Handle`
///
/// Group-level resolver. Returns a handle wrapping `Arc<TestDataGroup>`
/// — used by group-level metadata accessors (`dataset_profile_count`,
/// `dataset_facets`, ...) that operate on the dataset as a whole
/// before any profile/facet is selected.
///
/// A resolve failure panics, as in `dataset_open` and for the
/// same reason.
#[crate::polydat_node(category = RealData)]
fn dataset_group_open(source: &str) -> Arc<DatasetHandle> {
    match DatasetHandle::open_group(source) {
        Ok(h) => Arc::new(h),
        Err(e) => {
            let msg = format!("dataset_group_open: failed to resolve '{source}': {e}");
            crate::library::support::audit::error(&msg);
            panic!("{msg}");
        }
    }
}

// =================================================================
// Base vector nodes
// =================================================================

// All indexed-accessor nodes share the same shape: a handle wire
// and an `index` wire (u64). A source string in the handle
// position is promoted to `dataset_open(source, "<facet>")` for
// the facet the accessor names, and the facet reader is opened
// once per (source, profile, facet) through `FACET_CACHE`, so
// the per-cycle work is the facet read alone.

// =================================================================
// Per-cycle indexed accessors
// =================================================================

/// Resolve a Prebuffered handle to a specific-facet handle by
/// opening the named facet via the existing FACET_CACHE path
/// (which is `OnceCache`-backed — concurrent callers serialize
/// per (source, profile, facet)). For non-Prebuffered handles
/// this is a borrow-through; the macro callers use the result as
/// `&DatasetHandle` regardless of which arm fires.
///
/// Lives on `DatasetHandle` so the resolution logic — and the
/// "what does Prebuffered mean to a per-facet accessor" question
/// — sits next to the variant declaration.
impl DatasetHandle {
    fn resolve_facet<'a>(&'a self, facet: &str) -> std::borrow::Cow<'a, DatasetHandle> {
        match self {
            DatasetHandle::Prebuffered { source, .. } => match DatasetHandle::open(source, facet) {
                Ok(opened) => std::borrow::Cow::Owned(opened),
                Err(e) => panic!(
                    "DatasetHandle::resolve_facet: failed to open \
                         '{facet}' from prebuffered '{source}': {e}"
                ),
            },
            _ => std::borrow::Cow::Borrowed(self),
        }
    }

    /// The dataset group a group accessor reads: the group of a
    /// `dataset_group_open` handle, or the group a prebuffered handle
    /// carries. A facet handle has no group, and asking one for it
    /// panics with the handle's kind.
    fn resolve_group(&self) -> &TestDataGroup {
        match self {
            DatasetHandle::Group(g) | DatasetHandle::Prebuffered { group: g, .. } => g.as_ref(),
            other => panic!(
                "expected a group or prebuffered handle, got {}",
                dataset_handle_kind(other)
            ),
        }
    }
}

/// The facet each accessor opens, as a type.
///
/// A node states its facet twice — in the auto-resolver that splices
/// `dataset_open(_, "<facet>")` when the source is a string, and in
/// the `resolve_facet` call that follows a prebuffered handle — and
/// both readings come from here, so the two cannot drift apart.
macro_rules! facet_kind {
    ($name:ident, $facet:literal) => {
        /// The `
        #[doc = $facet]
        /// ` facet of a dataset.
        pub struct $name;
        impl $name {
            /// The facet's name, as `dataset_open` takes it.
            pub const FACET: &'static str = $facet;
        }
        impl crate::derive_support::ResolverKind for $name {
            const RESOLVER: crate::dsl::registry::DefaultResolver =
                crate::dsl::registry::DefaultResolver::Facet($facet);
        }
    };
}

facet_kind!(BaseFacet, "base");
facet_kind!(QueryFacet, "query");
facet_kind!(NeighborIndicesFacet, "neighbor_indices");
facet_kind!(NeighborDistancesFacet, "neighbor_distances");
facet_kind!(FilteredNeighborIndicesFacet, "filtered_neighbor_indices");
facet_kind!(
    FilteredNeighborDistancesFacet,
    "filtered_neighbor_distances"
);
facet_kind!(
    PrefilteredNeighborIndicesFacet,
    "prefiltered_neighbor_indices"
);
facet_kind!(
    PrefilteredNeighborDistancesFacet,
    "prefiltered_neighbor_distances"
);
facet_kind!(
    PostfilteredNeighborIndicesFacet,
    "postfiltered_neighbor_indices"
);
facet_kind!(
    PostfilteredNeighborDistancesFacet,
    "postfiltered_neighbor_distances"
);
facet_kind!(MetadataResultsFacet, "metadata_results");
facet_kind!(MetadataContentFacet, "metadata_content");
facet_kind!(MetadataPredicatesFacet, "metadata_predicates");

/// A handle wire that carries its facet in its type.
type Facet<R> = crate::derive_support::Resolved<R, DatasetHandle>;

/// A handle wire on the dataset group rather than one of its facets.
type Group = crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>;

/// The record count of a facet handle, opening `facet` first when the
/// handle is prebuffered. `who` names the caller in the diagnostics,
/// which is what the reader needs to see when a workload asks a
/// facet for a count it cannot give.
fn facet_record_count(h: &DatasetHandle, who: &str, facet: &str) -> u64 {
    match h.resolve_facet(facet).as_ref() {
        DatasetHandle::F32(d) => d.count as u64,
        DatasetHandle::I32(d) => d.count as u64,
        DatasetHandle::Ivvec32(d) => d.count as u64,
        DatasetHandle::Generic(d) => d.count as u64,
        DatasetHandle::Records(d) => d.count,
        DatasetHandle::Predicates(d) => d.census.count(),
        other => panic!(
            "{who}: expected a facet handle, got {}",
            dataset_handle_kind(other)
        ),
    }
}

/// The `f32` record at `index`, as the typed vector it is.
fn f32_vec_typed(h: &DatasetHandle, index: usize) -> crate::ast::SliceArc<f32> {
    match h {
        DatasetHandle::F32(d) => slice_arc_from_uniform(d, index),
        other => panic!(
            "expected F32 dataset handle, got {}",
            dataset_handle_kind(other)
        ),
    }
}

/// The `i32` record at `index`, as the typed vector it is.
fn i32_vec_typed(h: &DatasetHandle, index: usize) -> crate::ast::SliceArc<i32> {
    match h {
        DatasetHandle::I32(d) => slice_arc_from_uniform(d, index),
        other => panic!(
            "expected I32 dataset handle, got {}",
            dataset_handle_kind(other)
        ),
    }
}

fn ivvec32_vec_typed(h: &DatasetHandle, index: usize) -> crate::ast::SliceArc<i32> {
    match h {
        // Variable-length records — vectordata's trait doesn't expose
        // a zero-copy slice path for these (per-record dim is read
        // from the file), so we always allocate. One Vec<i32> per
        // cycle; same bound as the upstream trait API.
        DatasetHandle::Ivvec32(d) => {
            if d.count == 0 {
                return crate::ast::SliceArc::from_vec(Vec::<i32>::new());
            }
            let query = index % d.count;
            let v = match &d.reader {
                Some(reader) => reader.get(query).unwrap_or_default(),
                // The slab encoding has no list reader: the list is
                // the admitted rows, read out in order.
                None => d
                    .admitted_rows("metadata_results_at")
                    .get(query)
                    .unwrap_or_else(|e| panic!("metadata_results_at: {e}"))
                    .iter()
                    .map(|ordinal| {
                        i32::try_from(ordinal).unwrap_or_else(|_| {
                            panic!(
                                "metadata_results_at: base position {ordinal} is outside the \
                                 i32 range; read the rows with `admitted_rows_at`"
                            )
                        })
                    })
                    .collect(),
            };
            crate::ast::SliceArc::from_vec(v)
        }
        other => panic!(
            "expected Ivvec32 dataset handle, got {}",
            dataset_handle_kind(other)
        ),
    }
}

/// Build a [`SliceArc<T>`] from any uniform-stride dataset at
/// `index`. One generic helper serves every element type — element type is
/// erased by the upstream `VectorReader<T>` trait, and `SliceArc`
/// is element-type-generic, so one body suffices for `f32`,
/// `i32`, and any other element type the trait supports.
///
/// Tries the zero-copy `VectorReader::get_slice` path first —
/// that returns a borrow into the mmap'd file pages, kept alive
/// by the `Arc<UniformDataset<T>>` that we move into the
/// `SliceArc` as owner. No allocation, no element decoding, no
/// copy.
///
/// Falls back to `VectorReader::get(idx) -> Vec<T>` for readers
/// that don't support zero-copy (HTTP-backed, or merkle-cached
/// storage that hasn't been promoted to mmap yet); that path
/// allocates one `Vec<T>` per cycle.
fn slice_arc_from_uniform<T>(d: &Arc<UniformDataset<T>>, index: usize) -> crate::ast::SliceArc<T>
where
    T: Send + Sync + Copy + 'static,
{
    if d.count == 0 {
        return crate::ast::SliceArc::from_vec(Vec::<T>::new());
    }
    let idx = index % d.count;
    if let Some(slice) = d.reader.get_slice(idx) {
        // SAFETY: the slice points into the mmap pages owned by
        // `d`'s reader; cloning `d` into the `SliceArc`'s owner
        // keeps the mmap alive for as long as the slice is held.
        let ptr_len = (slice.as_ptr(), slice.len());
        let owner = d.clone();
        let owner_dyn: Arc<dyn std::any::Any + Send + Sync> = owner;
        return unsafe {
            crate::ast::SliceArc::from_borrowed(
                owner_dyn,
                std::slice::from_raw_parts(ptr_len.0, ptr_len.1),
            )
        };
    }
    crate::ast::SliceArc::from_vec(d.reader.get(idx).unwrap_or_default())
}

fn dataset_handle_kind(h: &DatasetHandle) -> &'static str {
    match h {
        DatasetHandle::F32(_) => "F32",
        DatasetHandle::I32(_) => "I32",
        DatasetHandle::Ivvec32(_) => "Ivvec32",
        DatasetHandle::Generic(_) => "Generic",
        DatasetHandle::Records(_) => "Records",
        DatasetHandle::Predicates(_) => "Predicates",
        DatasetHandle::Group(_) => "Group",
        DatasetHandle::Prebuffered { .. } => "Prebuffered",
    }
}

/// Access an `f32` vector by index, returning a typed `VecF32`.
/// Reads the base facet of a source string or prebuffered handle,
/// and whatever facet an opened F32 handle names.
///
/// Signature: `vector_at(handle, index: u64) -> VecF32`
#[crate::polydat_node(category = RealData)]
fn vector_at(handle: Facet<BaseFacet>, index: u64) -> crate::ast::SliceArc<f32> {
    f32_vec_typed(
        handle.resolve_facet(BaseFacet::FACET).as_ref(),
        index as usize,
    )
}

/// Access a query vector by index. Reads the query facet of a
/// source string or prebuffered handle, as `vector_at` reads the
/// base facet.
///
/// Signature: `query_vector_at(handle, index: u64) -> VecF32`
#[crate::polydat_node(category = RealData)]
fn query_vector_at(handle: Facet<QueryFacet>, index: u64) -> crate::ast::SliceArc<f32> {
    f32_vec_typed(
        handle.resolve_facet(QueryFacet::FACET).as_ref(),
        index as usize,
    )
}

/// Access ground-truth neighbor indices for a query. Expects an
/// I32 handle.
///
/// Signature: `neighbor_indices_at(handle, index: u64) -> VecI32`
#[crate::polydat_node(category = RealData)]
fn neighbor_indices_at(
    handle: Facet<NeighborIndicesFacet>,
    index: u64,
) -> crate::ast::SliceArc<i32> {
    i32_vec_typed(
        handle.resolve_facet(NeighborIndicesFacet::FACET).as_ref(),
        index as usize,
    )
}

/// Access ground-truth neighbor distances for a query. Expects an
/// F32 handle.
///
/// Signature: `neighbor_distances_at(handle, index: u64) -> VecF32`
#[crate::polydat_node(category = RealData)]
fn neighbor_distances_at(
    handle: Facet<NeighborDistancesFacet>,
    index: u64,
) -> crate::ast::SliceArc<f32> {
    f32_vec_typed(
        handle.resolve_facet(NeighborDistancesFacet::FACET).as_ref(),
        index as usize,
    )
}

/// Access filtered ground-truth neighbor indices. Expects an I32
/// handle. `filtered_neighbor_indices` is the legacy name of the
/// prefiltered facet, so this reads what
/// `prefiltered_neighbor_indices_at` reads.
///
/// Signature: `filtered_neighbor_indices_at(handle, index: u64) -> VecI32`
#[crate::polydat_node(category = RealData)]
fn filtered_neighbor_indices_at(
    handle: Facet<FilteredNeighborIndicesFacet>,
    index: u64,
) -> crate::ast::SliceArc<i32> {
    i32_vec_typed(
        handle
            .resolve_facet(FilteredNeighborIndicesFacet::FACET)
            .as_ref(),
        index as usize,
    )
}

/// Access filtered ground-truth neighbor distances. Expects an F32
/// handle. `filtered_neighbor_distances` is the legacy name of the
/// prefiltered facet, so this reads what
/// `prefiltered_neighbor_distances_at` reads.
///
/// Signature: `filtered_neighbor_distances_at(handle, index: u64) -> VecF32`
#[crate::polydat_node(category = RealData)]
fn filtered_neighbor_distances_at(
    handle: Facet<FilteredNeighborDistancesFacet>,
    index: u64,
) -> crate::ast::SliceArc<f32> {
    f32_vec_typed(
        handle
            .resolve_facet(FilteredNeighborDistancesFacet::FACET)
            .as_ref(),
        index as usize,
    )
}

/// Access the prefiltered ground-truth neighbor indices of a query:
/// its nearest neighbors among the base vectors its predicate admits,
/// nearest first. A row with fewer admitted vectors than the facet's
/// depth is padded with `-1`. Expects an I32 handle.
///
/// Signature: `prefiltered_neighbor_indices_at(handle, index: u64) -> VecI32`
#[crate::polydat_node(category = RealData)]
fn prefiltered_neighbor_indices_at(
    handle: Facet<PrefilteredNeighborIndicesFacet>,
    index: u64,
) -> crate::ast::SliceArc<i32> {
    i32_vec_typed(
        handle
            .resolve_facet(PrefilteredNeighborIndicesFacet::FACET)
            .as_ref(),
        index as usize,
    )
}

/// Access the distances of a query's prefiltered ground-truth
/// neighbors, in the order of `prefiltered_neighbor_indices_at`.
/// Expects an F32 handle.
///
/// Signature: `prefiltered_neighbor_distances_at(handle, index: u64) -> VecF32`
#[crate::polydat_node(category = RealData)]
fn prefiltered_neighbor_distances_at(
    handle: Facet<PrefilteredNeighborDistancesFacet>,
    index: u64,
) -> crate::ast::SliceArc<f32> {
    f32_vec_typed(
        handle
            .resolve_facet(PrefilteredNeighborDistancesFacet::FACET)
            .as_ref(),
        index as usize,
    )
}

/// Access the postfiltered ground-truth neighbor indices of a query:
/// its unfiltered nearest neighbors with those its predicate does not
/// admit removed, in rank order. A row with fewer survivors than the
/// facet's depth is padded with `-1`. Expects an I32 handle.
///
/// Signature: `postfiltered_neighbor_indices_at(handle, index: u64) -> VecI32`
#[crate::polydat_node(category = RealData)]
fn postfiltered_neighbor_indices_at(
    handle: Facet<PostfilteredNeighborIndicesFacet>,
    index: u64,
) -> crate::ast::SliceArc<i32> {
    i32_vec_typed(
        handle
            .resolve_facet(PostfilteredNeighborIndicesFacet::FACET)
            .as_ref(),
        index as usize,
    )
}

/// Access the distances of a query's postfiltered ground-truth
/// neighbors, in the order of `postfiltered_neighbor_indices_at`.
/// Expects an F32 handle.
///
/// Signature: `postfiltered_neighbor_distances_at(handle, index: u64) -> VecF32`
#[crate::polydat_node(category = RealData)]
fn postfiltered_neighbor_distances_at(
    handle: Facet<PostfilteredNeighborDistancesFacet>,
    index: u64,
) -> crate::ast::SliceArc<f32> {
    f32_vec_typed(
        handle
            .resolve_facet(PostfilteredNeighborDistancesFacet::FACET)
            .as_ref(),
        index as usize,
    )
}

// =================================================================
// Ground truth as vectordata reads it: live neighbors and coverage
// =================================================================
//
// What a ground-truth row means is vectordata's definition
// (`vectordata::ground_truth`): a row's live neighbors are its entries
// before the first negative one, and the rest is padding. These nodes
// hand on what vectordata's reader answers and decide nothing
// themselves. That a dataset's rows meet the definition is verified
// where the dataset is published, so nothing is checked per read.
//
// The coverage answers are properties of the facet and the depth, so
// each is computed once per scope, replays, and agrees on every engine
// and every fiber, as `metadata_count_of` does.

/// vectordata's ground-truth reader for the neighbor-indices handle
/// `h`. `who` names the calling node in the diagnostics. A profile
/// vectordata refuses as ground truth, such as one whose base window
/// does not start at zero under a filtered facet, is refused here with
/// vectordata's reason.
fn ground_truth<'a>(h: &'a DatasetHandle, who: &str) -> &'a GroundTruth {
    let DatasetHandle::I32(d) = h else {
        panic!(
            "{who}: expected a neighbor-indices handle, got {}",
            dataset_handle_kind(h)
        );
    };
    match &d.truth {
        Some(Ok(truth)) => truth,
        Some(Err(e)) => panic!("{who}: {e}"),
        None => panic!("{who}: the handle is not of a ground-truth facet"),
    }
}

/// The live neighbors of query `index` in `truth`, nearest first. The
/// query index wraps modulo the facet's rows, as the fixed-width
/// accessors' does.
fn live_neighbors(truth: &GroundTruth, index: u64, who: &str) -> crate::ast::SliceArc<i64> {
    let queries = truth.queries();
    if queries == 0 {
        return crate::ast::SliceArc::from_vec(Vec::new());
    }
    let neighbors = truth
        .neighbors(index as usize % queries)
        .unwrap_or_else(|e| panic!("{who}: {e}"));
    crate::ast::SliceArc::from_vec(neighbors.into_iter().map(|n| n as i64).collect())
}

/// The number of live neighbors of query `index` in `truth`.
fn live_depth(truth: &GroundTruth, index: u64, who: &str) -> u64 {
    let queries = truth.queries();
    if queries == 0 {
        return 0;
    }
    truth
        .depth(index as usize % queries)
        .unwrap_or_else(|e| panic!("{who}: {e}")) as u64
}

/// vectordata's coverage of `truth` at depth `k`. A depth vectordata
/// cannot answer for, zero or deeper than the facet, is its error.
fn coverage(truth: &GroundTruth, k: u64, who: &str) -> vectordata::ground_truth::Coverage {
    let depth = usize::try_from(k).unwrap_or(usize::MAX);
    run_blocking_io(|| truth.coverage(depth, &mut vectordata::NoProgress))
        .unwrap_or_else(|e| panic!("{who}: {e}"))
}

/// Generate the live-neighbor and coverage nodes of one ground-truth
/// facet. Each is a registered node of its own, so its documentation
/// and its facet are stated where it is declared.
macro_rules! ground_truth_nodes {
    (
        facet: $facet:ident,
        truth: $truth:literal,
        live_indices: $live_indices:ident,
        live_depth: $live_depth:ident,
        full_rows: $full_rows:ident,
        empty_rows: $empty_rows:ident,
        recall_ceiling: $recall_ceiling:ident $(,)?
    ) => {
        /// The live neighbors of a query in the
        #[doc = $truth]
        /// ground truth: the base positions its row names, nearest
        /// first, without the padding a row carries when it has fewer
        /// neighbors than the facet is deep. As long as the row's live
        /// depth, so shorter than the facet's width for a padded row
        /// and empty for a query with no neighbor.
        #[crate::polydat_node(category = RealData)]
        fn $live_indices(handle: Facet<$facet>, index: u64) -> crate::ast::SliceArc<i64> {
            let h = handle.resolve_facet($facet::FACET);
            let who = stringify!($live_indices);
            live_neighbors(ground_truth(h.as_ref(), who), index, who)
        }

        /// How many live neighbors a query has in the
        #[doc = $truth]
        /// ground truth: the length of its row before the padding.
        #[crate::polydat_node(category = RealData)]
        fn $live_depth(handle: Facet<$facet>, index: u64) -> u64 {
            let h = handle.resolve_facet($facet::FACET);
            let who = stringify!($live_depth);
            live_depth(ground_truth(h.as_ref(), who), index, who)
        }

        /// How many queries have at least `k` live neighbors in the
        #[doc = $truth]
        /// ground truth, as vectordata counts its coverage. A depth of
        /// zero, or deeper than the facet, is refused.
        #[crate::polydat_node(category = RealData)]
        fn $full_rows(handle: Facet<$facet>, k: u64) -> u64 {
            let h = handle.resolve_facet($facet::FACET);
            let who = stringify!($full_rows);
            coverage(ground_truth(h.as_ref(), who), k, who).full
        }

        /// How many queries have no live neighbor in the
        #[doc = $truth]
        /// ground truth, as vectordata counts its coverage. A depth of
        /// zero, or deeper than the facet, is refused.
        #[crate::polydat_node(category = RealData)]
        fn $empty_rows(handle: Facet<$facet>, k: u64) -> u64 {
            let h = handle.resolve_facet($facet::FACET);
            let who = stringify!($empty_rows);
            coverage(ground_truth(h.as_ref(), who), k, who).empty
        }

        /// The recall at `k` a perfect search would score against the
        #[doc = $truth]
        /// ground truth when every query is scored out of `k`:
        /// vectordata's coverage ceiling. 1.0 when every query has `k`
        /// neighbors, and less by the share of slots no neighbor
        /// exists for. A depth of zero, or deeper than the facet, is
        /// refused.
        #[crate::polydat_node(category = RealData)]
        fn $recall_ceiling(handle: Facet<$facet>, k: u64) -> f64 {
            let h = handle.resolve_facet($facet::FACET);
            let who = stringify!($recall_ceiling);
            coverage(ground_truth(h.as_ref(), who), k, who).ceiling()
        }
    };
}

ground_truth_nodes! {
    facet: NeighborIndicesFacet,
    truth: "unfiltered (`neighbor_indices`)",
    live_indices: neighbor_live_indices_at,
    live_depth: neighbor_live_depth_at,
    full_rows: neighbor_full_rows,
    empty_rows: neighbor_empty_rows,
    recall_ceiling: neighbor_recall_ceiling,
}

ground_truth_nodes! {
    facet: PrefilteredNeighborIndicesFacet,
    truth: "prefiltered (`prefiltered_neighbor_indices`)",
    live_indices: prefiltered_neighbor_live_indices_at,
    live_depth: prefiltered_neighbor_live_depth_at,
    full_rows: prefiltered_neighbor_full_rows,
    empty_rows: prefiltered_neighbor_empty_rows,
    recall_ceiling: prefiltered_neighbor_recall_ceiling,
}

ground_truth_nodes! {
    facet: PostfilteredNeighborIndicesFacet,
    truth: "postfiltered (`postfiltered_neighbor_indices`)",
    live_indices: postfiltered_neighbor_live_indices_at,
    live_depth: postfiltered_neighbor_live_depth_at,
    full_rows: postfiltered_neighbor_full_rows,
    empty_rows: postfiltered_neighbor_empty_rows,
    recall_ceiling: postfiltered_neighbor_recall_ceiling,
}

// =================================================================
// Metadata nodes (constant per dataset)
// =================================================================

// =================================================================
// Per-handle metadata nodes
// =================================================================
//
// Take `(handle: Handle)` and read shape/metadata directly from the
// resolved dataset. Provenance bounded by the handle, which itself
// is bounded by the resolver's externs — so these collapse to a
// single per-iteration eval chain via the standard provenance
// caching. No per-cycle work.

/// Return the dimensionality (`f32` count per record) of a
/// vector facet handle.
///
/// Signature: `vector_dim(handle) -> (u64)`
#[crate::polydat_node(category = RealData)]
fn vector_dim(handle: Facet<BaseFacet>) -> u64 {
    match handle.resolve_facet(BaseFacet::FACET).as_ref() {
        DatasetHandle::F32(d) => d.dim as u64,
        DatasetHandle::I32(d) => d.dim as u64,
        _ => 0,
    }
}

/// Return the count of records in the facet a handle was opened
/// against. This is the canonical "how many vectors / queries /
/// neighbor-rows" accessor — `vector_count(base_handle)` for
/// base vectors, `vector_count(query_handle)` for query
/// vectors, etc. A source string or prebuffered handle counts
/// the base facet.
///
/// Signature: `vector_count(handle) -> (u64)`
#[crate::polydat_node(category = RealData)]
fn vector_count(handle: Facet<BaseFacet>) -> u64 {
    facet_record_count(&handle, "vector_count", BaseFacet::FACET)
}

/// Return the count of query vectors. Counts the query facet of a
/// source string or prebuffered handle, as `vector_count` counts
/// the base facet.
///
/// Signature: `query_count(handle) -> (u64)`
#[crate::polydat_node(category = RealData)]
fn query_count(handle: Facet<QueryFacet>) -> u64 {
    // `query_count(prebuffered)` is a legitimate idiom in the
    // pvs_query workload (`cursor q = range(0, query_count(...))`),
    // so the prebuffered case resolves the query facet and reads
    // its count, through the same OnceCache-backed open the
    // per-cycle accessors use.
    facet_record_count(&handle, "query_count", QueryFacet::FACET)
}

/// Return the per-record neighbor count (k) for an I32
/// neighbor-indices handle.
///
/// Signature: `neighbor_count(handle) -> (u64)`
#[crate::polydat_node(category = RealData)]
fn neighbor_count(handle: Facet<NeighborIndicesFacet>) -> u64 {
    match handle.resolve_facet(NeighborIndicesFacet::FACET).as_ref() {
        DatasetHandle::I32(d) => d.dim as u64,
        _ => 0,
    }
}

/// Return the dataset's distance function (e.g., "COSINE",
/// "EUCLIDEAN"). Operates on the dataset group; takes a group or
/// prebuffered handle.
///
/// Signature: `dataset_distance_function(group) -> (str)`
#[crate::polydat_node(category = RealData)]
fn dataset_distance_function(group: Group) -> String {
    let group = group.resolve_group();
    let raw = group
        .attribute("distance_function")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown");
    match raw.to_uppercase().as_str() {
        "L2" | "EUCLIDEAN" => "EUCLIDEAN",
        "L1" | "MANHATTAN" => "MANHATTAN",
        "COSINE" => "COSINE",
        "DOT_PRODUCT" | "DOTPRODUCT" | "DOT" | "INNER_PRODUCT" | "IP" => "DOT_PRODUCT",
        _ => raw,
    }
    .to_string()
}

// =================================================================
// Metadata facet nodes
// =================================================================

/// Handle to the `metadata_results` facet: the base positions each
/// query's predicate admits. A dataset publishes it as variable-length
/// `i32` lists or as a slab of records, and both are read here.
pub(crate) struct Ivvec32Dataset {
    /// The list reader, for the variable-length encoding; `None` for a
    /// slab of records, which is read through `admitted`.
    reader: Option<Arc<dyn VvecReader<i32>>>,
    count: usize,
    /// The facet read as the rows each query's predicate admits:
    /// vectordata's reader of a row as a set that is not read until it
    /// is asked, or the reason it refuses the profile.
    admitted: Result<AdmittedRows, String>,
}

impl Ivvec32Dataset {
    /// vectordata's reader of the admitted rows, for the node `who`,
    /// or its reason for refusing the profile.
    fn admitted_rows(&self, who: &str) -> &AdmittedRows {
        self.admitted
            .as_ref()
            .unwrap_or_else(|e| panic!("{who}: {e}"))
    }

    fn load(source: &str, profile: &str) -> Result<Arc<Self>, String> {
        let key = (
            source.to_string(),
            profile.to_string(),
            "metadata_results".to_string(),
        );
        let any = FACET_CACHE.get_or_init(key, || {
            let group = load_dataset_group(source)?;
            let view = group
                .profile(profile)
                .ok_or_else(|| format!("profile '{profile}' not found in '{source}'"))?;
            crate::library::support::audit::record_opened(
                parse_source_specifier(source).0,
                profile,
                "metadata_results",
                "ivvec32",
            );
            // A remote variable-length facet published without its
            // `IDXFOR__` offset index can only be opened from every
            // byte; the fetching open downloads it whole, with progress,
            // where a plain open refuses.
            let failed =
                |e: String| format!("failed to access metadata_results from '{source}': {e}");
            let records = view.facet_shape("metadata_results").ok() == Some(FacetShape::Records);
            let reader = if records {
                None
            } else {
                Some(
                    run_blocking_io(|| {
                        view.metadata_results_fetching_as(&mut fetch_meter(&format!(
                            "open {source}"
                        )))
                    })
                    .map_err(|e| failed(e.to_string()))?,
                )
            };
            // A profile vectordata refuses for the set still reads as
            // lists, so the refusal is kept for the node that asks for
            // the set, and reported by it. A slab has no other reader,
            // so there the refusal is the facet's.
            let admitted =
                run_blocking_io(|| AdmittedRows::open(view.as_ref())).map_err(|e| e.to_string());
            let count = match (&reader, &admitted) {
                (Some(reader), _) => reader.count(),
                (None, Ok(admitted)) => admitted.queries(),
                (None, Err(e)) => return Err(failed(e.clone())),
            };
            let arc: Arc<Self> = Arc::new(Self {
                reader,
                count,
                admitted,
            });
            Ok(arc as Arc<dyn std::any::Any + Send + Sync>)
        })?;
        any.downcast::<Self>().map_err(|_| {
            format!("facet cache type mismatch for '{source}:{profile}/metadata_results'")
        })
    }
}

/// Access metadata indices (variable-length matching base ordinals
/// per query) at an index. Expects an Ivvec32 handle.
///
/// Signature: `metadata_results_at(handle, index: u64) -> VecI32`
#[crate::polydat_node(category = RealData)]
fn metadata_results_at(
    handle: Facet<MetadataResultsFacet>,
    index: u64,
) -> crate::ast::SliceArc<i32> {
    ivvec32_vec_typed(
        handle.resolve_facet(MetadataResultsFacet::FACET).as_ref(),
        index as usize,
    )
}

/// Return the length of one metadata_results record without
/// loading the data (reads only the 4-byte header). Expects an
/// Ivvec32 handle.
///
/// Signature: `metadata_results_len_at(handle, index: u64) -> (u64)`
#[crate::polydat_node(category = RealData)]
fn metadata_results_len_at(handle: Facet<MetadataResultsFacet>, index: u64) -> u64 {
    match handle.resolve_facet(MetadataResultsFacet::FACET).as_ref() {
        DatasetHandle::Ivvec32(d) if d.count > 0 => {
            let query = index as usize % d.count;
            match &d.reader {
                Some(reader) => reader.dim_at(query).unwrap_or(0) as u64,
                None => d
                    .admitted_rows("metadata_results_len_at")
                    .count_at(query)
                    .unwrap_or_else(|e| panic!("metadata_results_len_at: {e}"))
                    as u64,
            }
        }
        _ => 0,
    }
}

/// The base positions the predicate of query `index` admits, as a set:
/// vectordata's admitted-row set over the query's `metadata_results`
/// record, on an `admitted_rows` wire. Where `metadata_results_at`
/// puts the whole list on a wire, this is a handle to the record that
/// reads nothing until it is asked, by `admitted_rows_contain`, by
/// `admitted_rows_len`, or by a host that keeps the value and asks it
/// directly (`Value::Dataset(DatasetValue::AdmittedRows(set))`, where
/// `set` is vectordata's `OrdinalSet`). Holding one keeps the record's
/// storage open. The query index wraps modulo the facet's rows. A
/// profile whose base window does not start at zero is refused with
/// vectordata's reason.
///
/// That a record's positions are ascending and within the base is the
/// dataset's guarantee, verified where it is published; nothing is
/// checked here.
///
/// Signature: `admitted_rows_at(handle, index: u64) -> (admitted_rows)`
#[crate::polydat_node(category = RealData)]
fn admitted_rows_at(handle: Facet<MetadataResultsFacet>, index: u64) -> dv::Shared<OrdinalSet> {
    let who = "admitted_rows_at";
    let h = handle.resolve_facet(MetadataResultsFacet::FACET);
    let DatasetHandle::Ivvec32(d) = h.as_ref() else {
        panic!(
            "{who}: expected a metadata_results handle, got {}",
            dataset_handle_kind(h.as_ref())
        );
    };
    let admitted = d.admitted_rows(who);
    let queries = admitted.queries();
    assert!(queries > 0, "{who}: the facet has no rows");
    let set = admitted
        .get(index as usize % queries)
        .unwrap_or_else(|e| panic!("{who}: {e}"));
    dv::Shared(Arc::new(set))
}

/// Whether the admitted rows `rows`, from `admitted_rows_at`, hold the
/// base position `ordinal`: whether the query's predicate admits that
/// base vector.
///
/// Signature: `admitted_rows_contain(rows: admitted_rows, ordinal: u64) -> (bool)`
#[crate::polydat_node(category = RealData)]
fn admitted_rows_contain(rows: dv::Shared<OrdinalSet>, ordinal: u64) -> bool {
    rows.contains(ordinal)
}

/// How many base positions the admitted rows `rows`, from
/// `admitted_rows_at`, hold.
///
/// Signature: `admitted_rows_len(rows: admitted_rows) -> (u64)`
#[crate::polydat_node(category = RealData)]
fn admitted_rows_len(rows: dv::Shared<OrdinalSet>) -> u64 {
    rows.len() as u64
}

/// Return the metadata indices count (number of predicate result
/// sets). Expects an Ivvec32 handle.
#[crate::polydat_node(category = RealData)]
fn metadata_results_count(handle: Facet<MetadataResultsFacet>) -> u64 {
    match handle.resolve_facet(MetadataResultsFacet::FACET).as_ref() {
        DatasetHandle::Ivvec32(d) => d.count as u64,
        _ => 0,
    }
}

/// Report which facets are available for the default profile of
/// a dataset group as a comma-separated list. Expects a group or
/// prebuffered handle.
///
/// Signature: `dataset_facets(group) -> (str)`
#[crate::polydat_node(category = RealData)]
fn dataset_facets(group: Group) -> String {
    let group = group.resolve_group();
    // Use the default profile — group-level callers want a
    // dataset-wide manifest; specific profile facets come via
    // `profile_facets(group, idx)`.
    let names = group.profile_names();
    if let Some(first) = names.first()
        && let Some(view) = group.profile(first)
    {
        let manifest = view.facet_manifest();
        let mut names: Vec<&String> = manifest.keys().collect();
        names.sort();
        return names
            .iter()
            .map(|s| s.as_str())
            .collect::<Vec<_>>()
            .join(", ");
    }
    String::new()
}

// =================================================================
// Profile enumeration — discover and iterate over dataset profiles
// =================================================================
//
// Group-level: take a Group handle, read the dataset's sorted profile
// list. Sort order is canonical (by base_count via `profile_sort_by_size`)
// and computed once per group via the underlying TestDataGroup.

/// Total number of profiles in a dataset group.
///
/// Signature: `dataset_profile_count(group) -> (u64)`
#[crate::polydat_node(category = RealData)]
fn dataset_profile_count(group: Group) -> u64 {
    group.resolve_group().profile_names().len() as u64
}

/// Comma-separated list of all profile names in canonical sort
/// order (by base_count).
///
/// Signature: `dataset_profile_names(group) -> (str)`
#[crate::polydat_node(category = RealData)]
fn dataset_profile_names(group: Group) -> String {
    group.resolve_group().profile_names().join(", ")
}

/// Return profile names matching a prefix, comma-separated.
///
/// Signature: `matching_profiles(group, prefix: str) -> (str)`
///
/// If prefix is empty, returns all profiles. Used by `for_each:`
/// phase templates to discover profiles dynamically.
///
/// `group` declares its source-string auto-resolver via the
/// `Resolved<GroupResolver, _>` marker wrapper — the macro reads
/// `<Resolved<GroupResolver, DatasetHandle> as Wire>::RESOLVER` at
/// codegen and emits the matching `FuncSig.default_resolver`
/// (`DefaultResolver::Group`). The spliced `dataset_group_open` yields
/// the canonical `Value::Handle(Arc<DatasetHandle>)`, so the wire is
/// resolved as `DatasetHandle` and the group is taken via
/// `DatasetHandle::resolve_group` (downcasting straight to
/// `TestDataGroup` would fail — the handle is always the unified
/// `DatasetHandle` enum).
#[crate::polydat_node(category = RealData)]
fn matching_profiles(
    group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
    prefix: &str,
) -> String {
    let group: &TestDataGroup = group.resolve_group();
    let all = group.profile_names();
    let mut matched: Vec<&str> = if prefix.is_empty() {
        all.iter().map(|s| s.as_str()).collect()
    } else {
        all.iter()
            .filter(|s| s.starts_with(prefix))
            .map(|s| s.as_str())
            .collect()
    };
    // Natural-order sort: alphabetic with numeric runs
    // compared as numbers so `label_03` sorts before
    // `label_10`. The upstream `group.profile_names()`
    // orders by `base_count` (vectordata's choice — useful
    // for index-based lookups), but `for_each` iteration
    // wants stable, human-natural order so users see
    // label_01, label_02, label_03 instead of whatever the
    // size-sort happens to produce.
    matched.sort_by(|a, b| natural_cmp(a, b));
    matched.join(",")
}

/// Natural ordering: split each string into alternating text
/// and numeric runs and compare run-by-run, comparing numeric
/// runs as integers. Beats lexicographic on `label_03` vs
/// `label_10` (lex: "10" < "3"; natural: 3 < 10).
fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
    let mut ai = a.chars().peekable();
    let mut bi = b.chars().peekable();
    loop {
        match (ai.peek().copied(), bi.peek().copied()) {
            (None, None) => return std::cmp::Ordering::Equal,
            (None, _) => return std::cmp::Ordering::Less,
            (_, None) => return std::cmp::Ordering::Greater,
            (Some(ac), Some(bc)) => {
                if ac.is_ascii_digit() && bc.is_ascii_digit() {
                    let mut na: u64 = 0;
                    while let Some(c) = ai.peek().copied()
                        && c.is_ascii_digit()
                    {
                        na = na
                            .saturating_mul(10)
                            .saturating_add((c as u8 - b'0') as u64);
                        ai.next();
                    }
                    let mut nb: u64 = 0;
                    while let Some(c) = bi.peek().copied()
                        && c.is_ascii_digit()
                    {
                        nb = nb
                            .saturating_mul(10)
                            .saturating_add((c as u8 - b'0') as u64);
                        bi.next();
                    }
                    match na.cmp(&nb) {
                        std::cmp::Ordering::Equal => continue,
                        non_eq => return non_eq,
                    }
                } else {
                    match ac.cmp(&bc) {
                        std::cmp::Ordering::Equal => {
                            ai.next();
                            bi.next();
                        }
                        non_eq => return non_eq,
                    }
                }
            }
        }
    }
}

/// Look up a profile name by index from the canonical sorted list.
///
/// Signature: `dataset_profile_name_at(group, index: u64) -> (str)`
///
/// Index wraps modulo the number of profiles.
#[crate::polydat_node(category = RealData)]
fn dataset_profile_name_at(
    group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
    index: u64,
) -> String {
    let group: &TestDataGroup = group.resolve_group();
    let names = group.profile_names();
    if names.is_empty() {
        String::new()
    } else {
        names[(index as usize) % names.len()].clone()
    }
}

/// Return the base vector count for the profile at a given index.
///
/// Signature: `profile_base_count(group, index: u64) -> (u64)`
#[crate::polydat_node(category = RealData)]
fn profile_base_count(
    group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
    index: u64,
) -> u64 {
    let group: &TestDataGroup = group.resolve_group();
    let names = group.profile_names();
    if names.is_empty() {
        0
    } else {
        let name = &names[(index as usize) % names.len()];
        group
            .profile(name)
            .and_then(|view| view.base_count())
            .unwrap_or(0)
    }
}

/// Return the comma-separated facet list for the profile at a given index.
///
/// Signature: `profile_facets(group, index: u64) -> (str)`
#[crate::polydat_node(category = RealData)]
fn profile_facets(
    group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
    index: u64,
) -> String {
    let group: &TestDataGroup = group.resolve_group();
    let names = group.profile_names();
    if names.is_empty() {
        String::new()
    } else {
        let name = &names[(index as usize) % names.len()];
        match group.profile(name) {
            Some(view) => {
                let manifest = view.facet_manifest();
                let mut fnames: Vec<&String> = manifest.keys().collect();
                fnames.sort();
                fnames
                    .iter()
                    .map(|s| s.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            }
            None => String::new(),
        }
    }
}

/// Partition a dataset's vector space by its **profiles matching a
/// pattern**, treated as cumulative size tiers (a partition source,
/// cursor_partitions.md §7.1). One partition per masked profile, in canonical
/// (base-count-ascending) order: partition `k` spans
/// `[prev_masked_base_count, this_masked_base_count)` — exactly the
/// vectors added at that tier — so a sweep's "load only the increment
/// since the previously loaded set" is just the partition's
/// `[start_of(p), end_of(p))`, and a partition inherently knows its
/// start (no cross-iteration carry needed). `idx_of(p)` is the 0-based
/// masked position (pairs with `matching_profile_name_at` to address
/// the tier's own ground-truth facets); `count_of(p)` is the number of
/// masked tiers; `base_extent` is the largest masked tier's size.
///
/// `pattern` follows the literal / glob / regex promotion of
/// [`crate::library::support::pattern::compile_pattern`]; `*` (or any pattern that
/// matches all names) selects every profile.
///
/// Signature: `profile_partitions(group, pattern: str) -> (PartitionList)`
#[crate::polydat_node(category = RealData)]
fn profile_partitions(
    group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
    pattern: &str,
) -> crate::derive_support::Ext<crate::iteration::cursor_partition::PartitionList> {
    let group: &TestDataGroup = group.resolve_group();
    let parts = build_profile_partitions(group, pattern);
    crate::derive_support::Ext(crate::iteration::cursor_partition::PartitionList::new(
        parts,
    ))
}

/// Build the cumulative size-tier partitions for the profiles of `group`
/// matching `pattern` (literal/glob/regex promotion). Shared by the
/// [`profile_partitions`] node and the comprehension-source desugaring
/// in `iteration::comprehension::eval` so a `for: "p in
/// profile_partitions(...)"` sweep produces identical partitions either
/// way. Partition `k` spans `[prev masked base_count, this base_count)`.
/// The masked profile size-tiers for `group` matching `pattern`, in
/// canonical (base-count-ascending) order: `(name, cumulative_base_count)`
/// for each matching profile WITH a non-zero base count. Profiles with no
/// base facet, or a zero count, are skipped — they would otherwise emit a
/// degenerate empty `[prev, prev)` partition (and a query against an empty
/// tier). Shared by [`build_profile_partitions`] and
/// [`matching_profile_name_at`] so a partition's `idx_of(p)` and the tier
/// name resolve against the SAME masked sequence.
fn masked_profile_tiers(group: &TestDataGroup, pattern: &str) -> Vec<(String, u64)> {
    let (re, _) = crate::library::support::pattern::compile_pattern(pattern)
        .unwrap_or_else(|e| panic!("profile pattern: {e}"));
    group
        .profile_names()
        .iter()
        .filter(|n| re.is_match(n))
        .filter_map(|n| {
            group
                .profile(n)
                .and_then(|v| v.base_count())
                .filter(|&c| c > 0)
                .map(|c| (n.clone(), c))
        })
        .collect()
}

pub(crate) fn build_profile_partitions(
    group: &TestDataGroup,
    pattern: &str,
) -> Vec<crate::iteration::cursor_partition::Partition> {
    // Masked size-tiers (matching profiles with a non-zero base count),
    // canonical (ascending) order — skipping zero-count profiles avoids a
    // degenerate empty first partition.
    let masked: Vec<u64> = masked_profile_tiers(group, pattern)
        .into_iter()
        .map(|(_, c)| c)
        .collect();
    let base_extent = masked.last().copied().unwrap_or(0);
    let count = masked.len() as u64;
    let pct = |o: u64| {
        if base_extent == 0 {
            0.0
        } else {
            (o as f64 / base_extent as f64) * 100.0
        }
    };
    let mut parts: Vec<crate::iteration::cursor_partition::Partition> =
        Vec::with_capacity(masked.len());
    let mut prev: u64 = 0;
    for (k, &this) in masked.iter().enumerate() {
        parts.push(crate::iteration::cursor_partition::Partition {
            idx: k as u64,
            count,
            start_ord: prev,
            end_ord: this,
            start_pct: pct(prev),
            end_pct: pct(this),
            base_extent,
        });
        prev = this;
    }
    parts
}

/// Name of the `index`-th profile **matching `pattern`**, in canonical
/// (base-count-ascending) order. Pairs with `profile_partitions`'s
/// masked-position `idx_of` so a sweep can prebuffer the active tier's
/// own ground-truth facets (`dataset_prebuffer(str_concat("ds:", name))`).
/// `pattern` follows the literal / glob / regex promotion; the index
/// wraps modulo the number of matching profiles; empty string if none
/// match.
///
/// Signature: `matching_profile_name_at(group, pattern: str, index: u64) -> (str)`
#[crate::polydat_node(category = RealData)]
fn matching_profile_name_at(
    group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
    pattern: &str,
    index: u64,
) -> String {
    let group: &TestDataGroup = group.resolve_group();
    // Same masked sequence `profile_partitions` uses (matching profiles
    // with a non-zero base count, canonical order), so `idx_of(p)` from a
    // partition resolves to the right tier name.
    let tiers = masked_profile_tiers(group, pattern);
    if tiers.is_empty() {
        String::new()
    } else {
        tiers[(index as usize) % tiers.len()].0.clone()
    }
}

// =================================================================
// Prebuffering — eagerly download dataset facets before workload run
// =================================================================

/// Eagerly download all facets for a dataset profile into the
/// local cache, returning a dataset handle that every facet
/// accessor and every group accessor takes as its first
/// argument. After this returns, every subsequent facet read
/// served by [`vectordata::TestDataView`] hits the merkle-
/// verified mmap fast path with no further network traffic.
///
/// Signature: `dataset_prebuffer(source) -> Handle`
///
/// **Why a handle, not a count.** Returning a value the
/// downstream accessors *consume* makes prebuffer part of
/// the dataflow graph: DCE keeps the chain alive because
/// `vector_at(prebuffered, q)` needs `prebuffered` to be
/// resolvable, which forces evaluation. A binding such as
/// `init prebuffered = dataset_prebuffer(...)` whose result
/// nothing reads is pruned, so a workload threads the handle
/// through its accessors.
///
/// `source` is the canonical `dataset:profile` string. The
/// returned handle names the dataset rather than one facet: a
/// facet accessor opens its own facet of `source` from it
/// (`DatasetHandle::resolve_facet`), and a group accessor
/// (`dataset_facets`, `dataset_distance_function`, ...) reads
/// the dataset's group (`DatasetHandle::resolve_group`).
///
/// A dataset that does not resolve yields no handle, and the
/// resolve error goes to the audit log. A profile the dataset
/// lacks, or a facet whose download fails, is logged there too
/// and still yields the handle: prebuffering is a best-effort
/// warm-up, and an accessor that then reads a missing facet
/// fails with that facet's own error.
#[crate::polydat_node(category = RealData)]
fn dataset_prebuffer(source: &str) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
    // The const binding contract (evaluation_model.md §"Const
    // Binding Contract") means this runs exactly once per scope
    // activation: the activation kernel pulls the binding and the host propagates the result to every
    // fiber. PREBUFFER_CACHE is belt-and-suspenders: it serializes
    // anyone who reaches here by another path, so a per-source
    // thundering herd is structurally impossible whatever the caller
    // does.
    match PREBUFFER_CACHE.get_or_init(source.to_string(), || {
        // Only the first concurrent caller for this source runs the
        // inner body — the audit "entered" event reflects that one
        // download, not per-caller noise.
        crate::library::support::audit::record_prebuffer_entered(source);
        do_dataset_prebuffer_inner(source)
    }) {
        Ok(handle) => Some(handle as Arc<dyn std::any::Any + Send + Sync>),
        Err(_) => None,
    }
}

/// Inner body of [`dataset_prebuffer`]. Runs **at most once
/// per (source, process)** under the [`PREBUFFER_CACHE`] OnceLock.
fn do_dataset_prebuffer_inner(source: &str) -> Result<Arc<DatasetHandle>, String> {
    // Every exit after the group resolves returns a prebuffered
    // handle, so the downstream `*_at(prebuffered, q)` accessors can
    // resolve. A failed download still hands back the handle — the
    // accessors then read through the transport, and the operator
    // sees the prebuffer error in the audit log.
    let group = match load_dataset_group(source) {
        Ok(g) => g,
        Err(e) => {
            let msg = format!("dataset_prebuffer: cannot resolve '{source}': {e}");
            crate::library::support::audit::error(&msg);
            // No group → no handle to hand back. Sticky error in
            // the cache; downstream accessors will produce a
            // diagnostic when they fail to downcast.
            return Err(msg);
        }
    };
    let group_for_handle = group.clone();
    let (_, profile) = parse_source_specifier(source);
    let view = match group.profile(profile) {
        Some(v) => v,
        None => {
            crate::library::support::audit::error(&format!(
                "dataset_prebuffer: profile '{profile}' not found in '{source}'"
            ));
            return Ok(Arc::new(DatasetHandle::Prebuffered {
                group: group_for_handle,
                source: source.to_string(),
            }));
        }
    };
    // One fetch over every facet that holds data: vectordata plans
    // each facet, refuses a run the cache directory cannot hold
    // before any byte moves, and skips chunks already resident.
    // [`fetch_meter`] reports the run through the audit channel,
    // throttled so a multi-gigabyte facet doesn't spew thousands of
    // lines into session.log.
    //
    // Audit instrumentation: log every facet the fetch *covers* with
    // its key (`source:profile/facet`). Compared against the
    // `vectordata: opened …` lines emitted by [`load_uniform_facet`] /
    // [`GenericFacetDataset::load`], this surfaces any facet the
    // workload reads at cycle time that prebuffer did NOT pull — the
    // typical cause of a "still hitting HTTP after prebuffer" symptom.
    //
    // `fetch` drives `reqwest::blocking`, which spins up a private
    // tokio runtime per request; `run_blocking_io` parks the outer
    // worker so dropping that inner runtime doesn't panic. Same
    // pattern as `load_dataset_group` and `load_uniform_facet`.
    let mut meter = fetch_meter(&format!("prebuffer {source}"));
    let facet_count = match run_blocking_io(|| view.fetch(&FetchRequest::all(), &mut meter)) {
        Ok(report) => {
            for fetched in &report.facets {
                crate::library::support::audit::record_prebuffered(
                    parse_source_specifier(source).0,
                    profile,
                    &fetched.id.facet,
                );
            }
            report.facets.len() as u64
        }
        Err(e) => {
            crate::library::support::audit::warn(&format!(
                "dataset_prebuffer: download error for '{source}': {e}"
            ));
            0
        }
    };
    crate::library::support::audit::log_prebuffer_summary(
        parse_source_specifier(source).0,
        profile,
        facet_count,
    );
    Ok(Arc::new(DatasetHandle::Prebuffered {
        group: group_for_handle,
        source: source.to_string(),
    }))
}

/// The progress meter for a fetch, titled `title`: whole lines on the
/// audit channel — a line as each facet starts and finishes, and a
/// progress line per 10% of the run but at most one per 10s — and
/// nothing for data already in the cache.
fn fetch_meter(title: &str) -> LogMeter {
    LogMeter::to_lines(title, |level, line| {
        crate::library::support::audit::log(level.into(), line)
    })
    .min_interval(std::time::Duration::from_secs(10))
    .quiet_when_resident(true)
}

// =================================================================
// Generic facet access — type-aware scalar/vector readers
// =================================================================

/// A type-erased facet reader that reads values as i64.
/// Uses [`TestDataViewExt::facet_as`] at `i64`, which widens every
/// integer element type (u8, i32, …) and serves local and remote
/// facets through the same cache.
pub(crate) struct GenericFacetDataset {
    reader: Arc<dyn VectorReader<i64>>,
    count: usize,
}

impl GenericFacetDataset {
    fn load(source: &str, profile: &str, facet: &str) -> Result<Arc<Self>, String> {
        let key = (source.to_string(), profile.to_string(), facet.to_string());
        let any = FACET_CACHE.get_or_init(key, || {
            let group = load_dataset_group(source)?;
            let view = group
                .profile(profile)
                .ok_or_else(|| format!("profile '{profile}' not found in '{source}'"))?;
            crate::library::support::audit::record_opened(
                parse_source_specifier(source).0,
                profile,
                facet,
                "generic-typed",
            );
            let reader = run_blocking_io(|| view.facet_as::<i64>(facet))
                .map_err(|e| format!("failed to open {facet} from '{source}:{profile}': {e}"))?;
            let count = reader.count();
            let arc: Arc<Self> = Arc::new(Self { reader, count });
            Ok(arc as Arc<dyn std::any::Any + Send + Sync>)
        })?;
        any.downcast::<Self>()
            .map_err(|_| format!("facet cache type mismatch for '{source}:{profile}/{facet}'"))
    }

    fn get_scalar(&self, index: usize) -> i64 {
        if self.count == 0 {
            return 0;
        }
        let index = index % self.count;
        match self.reader.get_slice(index) {
            Some(record) => record.first().copied().unwrap_or(0),
            None => self
                .reader
                .get(index)
                .ok()
                .and_then(|record| record.first().copied())
                .unwrap_or(0),
        }
    }

    fn format_scalar(&self, index: usize) -> String {
        self.get_scalar(index).to_string()
    }
}

// Generic-facet readers (typed scalar). Take a Generic handle and
// read the i64-cast value at the requested index.
/// The scalar of a Generic facet at `idx`, rendered.
fn generic_str_typed(h: &DatasetHandle, idx: usize) -> String {
    match h {
        DatasetHandle::Generic(d) => d.format_scalar(idx),
        DatasetHandle::Records(_) => panic!("{}", RECORDS_NOT_SCALARS),
        DatasetHandle::Predicates(_) => panic!("{}", PREDICATES_NOT_SCALARS),
        _ => String::new(),
    }
}

// =================================================================
// Record metadata: one named, typed field of a record per base vector
// =================================================================
//
// A dataset may publish `metadata_content` as records. A field of a
// record is read in two steps, so that everything about the field is
// settled once, before the first cycle:
//
//   age_field := record_field_i64(source, "age")   // a constant
//   age := record_i64_at(age_field, row)           // per cycle
//
// The first resolves the name to a position in the layout and refuses
// a field the layout lacks, one of another type, and one the dataset
// declares may be null. It has only constant inputs, so it runs when
// the program is built and its refusal is a build error. The second
// reads that position of the record at an ordinal and checks nothing:
// that every record carries the layout's fields at the layout's types
// is the dataset's guarantee, verified where it is published.

/// What a scalar node says of a predicate facet that holds records.
const PREDICATES_NOT_SCALARS: &str = "the metadata_predicates facet of this profile holds one \
     predicate record per query, not one scalar; read it as structure with `predicate_forms` and \
     `predicate_at`, or as text with `predicate_text_at`";

/// What a scalar node says of a facet that holds records.
const RECORDS_NOT_SCALARS: &str = "the metadata_content facet of this profile holds records, not \
     one scalar per base vector; read a field of a record with a `record_field_*` node and its \
     `record_*_at` accessor";

/// Whether `facet` of `source`'s profile holds records or fixed-width
/// elements, as the profile declares it; `None` when the dataset, the
/// profile or the facet cannot be found, which the reader that is then
/// tried reports in its own words.
fn facet_shape(source: &str, profile: &str, facet: &str) -> Option<FacetShape> {
    let group = load_dataset_group(source).ok()?;
    let view = group.profile(profile)?;
    view.facet_shape(facet).ok()
}

/// The `metadata_content` facet of a profile that publishes it as
/// records: the facet's forms (its layout, the binder over every field
/// and the records), and how many records there are.
pub(crate) struct RecordDataset {
    forms: Arc<dv::RecordForms>,
    count: u64,
}

/// What opening a record facet of `source`'s profile needs: the
/// profile's view, and the name the diagnostics give the dataset.
fn record_view(source: &str, profile: &str) -> Result<(Arc<dyn TestDataView>, String), String> {
    let group = load_dataset_group(source)?;
    let view = group
        .profile(profile)
        .ok_or_else(|| format!("profile '{profile}' not found in '{source}'"))?;
    Ok((
        view,
        format!("{}:{profile}", parse_source_specifier(source).0),
    ))
}

/// The layout of a profile's metadata records, with a warning when the
/// dataset declares none and it is learned from the first record.
fn resolve_layout(view: &dyn TestDataView, origin: &str) -> Result<Layout, String> {
    let layout = Layout::resolve(view).map_err(|e| e.to_string())?;
    if !layout.source().is_declared() {
        crate::library::support::audit::warn(&format!(
            "metadata_content of '{origin}' declares no layout; its fields are typed from {}, \
             which cannot type a field that is null there or a container that is empty there",
            layout.source()
        ));
    }
    Ok(layout)
}

impl RecordDataset {
    fn load(source: &str, profile: &str) -> Result<Arc<Self>, String> {
        let facet_name = MetadataContentFacet::FACET;
        let key = (
            source.to_string(),
            profile.to_string(),
            format!("records:{facet_name}"),
        );
        let any = FACET_CACHE.get_or_init(key, || {
            let (view, origin) = record_view(source, profile)?;
            crate::library::support::audit::record_opened(
                parse_source_specifier(source).0,
                profile,
                facet_name,
                "records",
            );
            let (records, layout, count) = run_blocking_io(|| {
                let records = view
                    .open_facet_records(facet_name)
                    .map_err(|e| e.to_string())?;
                let layout = resolve_layout(view.as_ref(), &origin)?;
                let count = records.count().map_err(|e| e.to_string())?;
                Ok::<_, String>((records, layout, count))
            })
            .map_err(|e| format!("failed to open {facet_name} from '{origin}': {e}"))?;
            let arc: Arc<Self> = Arc::new(Self {
                forms: Arc::new(dv::RecordForms::new(layout, records, origin)),
                count,
            });
            Ok(arc as Arc<dyn std::any::Any + Send + Sync>)
        })?;
        any.downcast::<Self>().map_err(|_| {
            format!("facet cache type mismatch for '{source}:{profile}/records:{facet_name}'")
        })
    }
}

/// The forms of a profile's `metadata_predicates` records: every
/// predicate read once, each distinct form recorded with its template
/// and count, beside the layout its conditions bind against. Surveyed
/// once per source and profile and shared by every fiber.
fn load_predicate_forms(source: &str, profile: &str) -> Result<Arc<dv::PredicateForms>, String> {
    let facet_name = MetadataPredicatesFacet::FACET;
    let key = (
        source.to_string(),
        profile.to_string(),
        format!("records:{facet_name}"),
    );
    let any = FACET_CACHE.get_or_init(key, || {
        let (view, origin) = record_view(source, profile)?;
        crate::library::support::audit::record_opened(
            parse_source_specifier(source).0,
            profile,
            facet_name,
            "records",
        );
        let (predicates, layout, census) = run_blocking_io(|| {
            let predicates = view
                .open_facet_records(facet_name)
                .map_err(|e| e.to_string())?;
            let layout = resolve_layout(view.as_ref(), &origin)?;
            let census = FormCensus::of_facet(&predicates, &mut vectordata::NoProgress)
                .map_err(|e| e.to_string())?;
            Ok::<_, String>((predicates, layout, census))
        })
        .map_err(|e| format!("failed to open {facet_name} from '{origin}': {e}"))?;
        let arc = Arc::new(dv::PredicateForms::new(census, layout, predicates, origin));
        Ok(arc as Arc<dyn std::any::Any + Send + Sync>)
    })?;
    any.downcast::<dv::PredicateForms>().map_err(|_| {
        format!("facet cache type mismatch for '{source}:{profile}/records:{facet_name}'")
    })
}

/// The wire type a record field is read as.
#[derive(Clone, Copy, PartialEq, Eq)]
enum FieldWire {
    Str,
    Bool,
    I64,
    F64,
    Bytes,
}

impl FieldWire {
    /// The port type keyword, for diagnostics.
    fn keyword(self) -> &'static str {
        match self {
            FieldWire::Str => "str",
            FieldWire::Bool => "bool",
            FieldWire::I64 => "i64",
            FieldWire::F64 => "f64",
            FieldWire::Bytes => "bytes",
        }
    }

    /// Whether a field the layout types as `bind` reads as this wire
    /// type: the type itself or a lossless widening of it. A type with
    /// a meaning of its own, such as a timestamp or an identifier, is
    /// not the integer, text or bytes it is stored as.
    fn carries(self, bind: &BindType) -> bool {
        match self {
            FieldWire::Str => matches!(bind, BindType::Text | BindType::Ascii),
            FieldWire::Bool => matches!(bind, BindType::Bool),
            FieldWire::I64 => {
                matches!(bind, BindType::Int16 | BindType::Int32 | BindType::Int64)
            }
            FieldWire::F64 => {
                matches!(
                    bind,
                    BindType::Float16 | BindType::Float32 | BindType::Float64
                )
            }
            FieldWire::Bytes => matches!(bind, BindType::Blob),
        }
    }
}

/// One field of a record facet, resolved: where it sits in a record
/// and the wire type it reads as. What a `record_field_*` node yields
/// and a `record_*_at` node reads through.
pub(crate) struct RecordField {
    records: Arc<RecordDataset>,
    /// Picks the field out of a record by its position.
    binder: Binder,
    name: String,
    wire: FieldWire,
}

/// Resolve `field` of the record facet `h` as `wire`, for the node
/// `who`. Refuses a facet that does not hold records, a field the
/// layout lacks, one whose type is not `wire`'s, one whose type the
/// layout does not establish, and one the dataset declares may be
/// null.
fn resolve_record_field(
    h: &DatasetHandle,
    field: &str,
    wire: FieldWire,
    who: &str,
) -> Arc<dyn std::any::Any + Send + Sync> {
    let records = match h {
        DatasetHandle::Records(d) => d.clone(),
        DatasetHandle::Generic(_) => panic!(
            "{who}: the metadata_content facet of this profile holds one scalar per base vector, \
             not records with named fields; read it with `metadata_value_at`"
        ),
        other => panic!(
            "{who}: expected a metadata_content handle, got {}",
            dataset_handle_kind(other)
        ),
    };
    let layout = &records.forms.layout;
    let origin = &records.forms.origin;
    let Some(position) = layout.position_of(field) else {
        panic!(
            "{who}: the records of '{origin}' have no field `{field}`; they have {}",
            layout.names().join(", ")
        );
    };
    let bind = &layout.types()[position];
    if layout.unproven().contains(&field) {
        panic!(
            "{who}: the layout of '{origin}', learned from {}, does not establish the type of \
             `{field}`",
            layout.source()
        );
    }
    if !wire.carries(bind) {
        panic!(
            "{who}: field `{field}` of '{origin}' is {bind:?}, which does not read as {}",
            wire.keyword()
        );
    }
    if layout.nullability()[position] == Nullability::Nullable {
        panic!(
            "{who}: field `{field}` of '{origin}' is declared nullable, and a {} wire has no \
             null; a nullable field is not read as a scalar",
            wire.keyword()
        );
    }
    let binder = Binder::select(layout, &[field]).unwrap_or_else(|e| panic!("{who}: {e}"));
    Arc::new(RecordField {
        records,
        binder,
        name: field.to_string(),
        wire,
    })
}

/// Read the resolved field `handle` of the record at `index`, for the
/// node `who`, which reads fields resolved as `wire`. The record index
/// wraps modulo the record count, as the other accessors' does.
/// Nothing about the record is checked: `get` reads the field as its
/// declared type.
fn read_record_field<R>(
    handle: &Arc<dyn std::any::Any + Send + Sync>,
    index: u64,
    wire: FieldWire,
    who: &str,
    get: impl Fn(&vectordata::formats::mnode::scan::Field<'_>) -> Option<R>,
) -> R {
    let Some(field) = handle.downcast_ref::<RecordField>() else {
        panic!("{who}: expected a field resolved by a `record_field_*` node");
    };
    assert!(
        field.wire == wire,
        "{who}: field `{}` was resolved as {}, and this node reads {}",
        field.name,
        field.wire.keyword(),
        wire.keyword()
    );
    let records = &field.records;
    let origin = &records.forms.origin;
    assert!(records.count > 0, "{who}: '{origin}' has no records");
    let ordinal = index % records.count;
    let record = records
        .forms
        .records
        .record_bytes(ordinal)
        .unwrap_or_else(|e| panic!("{who}: record {ordinal} of '{origin}': {e}"));
    let mut value = None;
    field
        .binder
        .bind_each(&record, |_, f| value = get(&f))
        .unwrap_or_else(|e| panic!("{who}: record {ordinal} of '{origin}': {e}"));
    value.unwrap_or_else(|| {
        panic!(
            "{who}: record {ordinal} of '{origin}' does not hold `{}` as the {} its layout \
             declares",
            field.name,
            wire.keyword()
        )
    })
}

/// Resolve a text field of a dataset's metadata records, for
/// `record_str_at` to read. The name is resolved to its position in
/// the layout here, once. Refused when the records have no such field,
/// when the field is not text, and when the dataset declares it may be
/// null. Expects the metadata_content facet of a profile that
/// publishes records.
///
/// Signature: `record_field_str(handle, field: str) -> (handle)`
#[crate::polydat_node(category = RealData)]
fn record_field_str(
    handle: Facet<MetadataContentFacet>,
    field: &str,
) -> Arc<dyn std::any::Any + Send + Sync> {
    let h = handle.resolve_facet(MetadataContentFacet::FACET);
    resolve_record_field(h.as_ref(), field, FieldWire::Str, "record_field_str")
}

/// Resolve a boolean field of a dataset's metadata records, for
/// `record_bool_at` to read. Refused when the records have no such
/// field, when the field is not a boolean, and when the dataset
/// declares it may be null.
///
/// Signature: `record_field_bool(handle, field: str) -> (handle)`
#[crate::polydat_node(category = RealData)]
fn record_field_bool(
    handle: Facet<MetadataContentFacet>,
    field: &str,
) -> Arc<dyn std::any::Any + Send + Sync> {
    let h = handle.resolve_facet(MetadataContentFacet::FACET);
    resolve_record_field(h.as_ref(), field, FieldWire::Bool, "record_field_bool")
}

/// Resolve an integer field of a dataset's metadata records, for
/// `record_i64_at` to read. A 16-bit or 32-bit field reads as `i64`
/// without loss. Refused when the records have no such field, when the
/// field is not an integer, and when the dataset declares it may be
/// null.
///
/// Signature: `record_field_i64(handle, field: str) -> (handle)`
#[crate::polydat_node(category = RealData)]
fn record_field_i64(
    handle: Facet<MetadataContentFacet>,
    field: &str,
) -> Arc<dyn std::any::Any + Send + Sync> {
    let h = handle.resolve_facet(MetadataContentFacet::FACET);
    resolve_record_field(h.as_ref(), field, FieldWire::I64, "record_field_i64")
}

/// Resolve a floating-point field of a dataset's metadata records, for
/// `record_f64_at` to read. A 16-bit or 32-bit field reads as `f64`
/// without loss. Refused when the records have no such field, when the
/// field is not a float, and when the dataset declares it may be null.
///
/// Signature: `record_field_f64(handle, field: str) -> (handle)`
#[crate::polydat_node(category = RealData)]
fn record_field_f64(
    handle: Facet<MetadataContentFacet>,
    field: &str,
) -> Arc<dyn std::any::Any + Send + Sync> {
    let h = handle.resolve_facet(MetadataContentFacet::FACET);
    resolve_record_field(h.as_ref(), field, FieldWire::F64, "record_field_f64")
}

/// Resolve a bytes field of a dataset's metadata records, for
/// `record_bytes_at` to read. Refused when the records have no such
/// field, when the field is not a blob, and when the dataset declares
/// it may be null.
///
/// Signature: `record_field_bytes(handle, field: str) -> (handle)`
#[crate::polydat_node(category = RealData)]
fn record_field_bytes(
    handle: Facet<MetadataContentFacet>,
    field: &str,
) -> Arc<dyn std::any::Any + Send + Sync> {
    let h = handle.resolve_facet(MetadataContentFacet::FACET);
    resolve_record_field(h.as_ref(), field, FieldWire::Bytes, "record_field_bytes")
}

/// The text field `field`, resolved by `record_field_str`, of the
/// metadata record at `index`. Nothing is checked per record.
///
/// Signature: `record_str_at(field: handle, index: u64) -> (str)`
#[crate::polydat_node(category = RealData)]
fn record_str_at(field: Arc<dyn std::any::Any + Send + Sync>, index: u64) -> String {
    read_record_field(&field, index, FieldWire::Str, "record_str_at", |f| {
        f.as_str().map(str::to_string)
    })
}

/// The boolean field `field`, resolved by `record_field_bool`, of the
/// metadata record at `index`. Nothing is checked per record.
///
/// Signature: `record_bool_at(field: handle, index: u64) -> (bool)`
#[crate::polydat_node(category = RealData)]
fn record_bool_at(field: Arc<dyn std::any::Any + Send + Sync>, index: u64) -> bool {
    read_record_field(&field, index, FieldWire::Bool, "record_bool_at", |f| {
        f.as_bool()
    })
}

/// The integer field `field`, resolved by `record_field_i64`, of the
/// metadata record at `index`. Nothing is checked per record.
///
/// Signature: `record_i64_at(field: handle, index: u64) -> (i64)`
#[crate::polydat_node(category = RealData)]
fn record_i64_at(field: Arc<dyn std::any::Any + Send + Sync>, index: u64) -> i64 {
    read_record_field(&field, index, FieldWire::I64, "record_i64_at", |f| {
        f.as_i64()
    })
}

/// The floating-point field `field`, resolved by `record_field_f64`,
/// of the metadata record at `index`. Nothing is checked per record.
///
/// Signature: `record_f64_at(field: handle, index: u64) -> (f64)`
#[crate::polydat_node(category = RealData)]
fn record_f64_at(field: Arc<dyn std::any::Any + Send + Sync>, index: u64) -> f64 {
    read_record_field(&field, index, FieldWire::F64, "record_f64_at", |f| {
        f.as_f64()
    })
}

/// The bytes field `field`, resolved by `record_field_bytes`, of the
/// metadata record at `index`. Nothing is checked per record.
///
/// Signature: `record_bytes_at(field: handle, index: u64) -> (bytes)`
#[crate::polydat_node(category = RealData)]
fn record_bytes_at(field: Arc<dyn std::any::Any + Send + Sync>, index: u64) -> Vec<u8> {
    read_record_field(&field, index, FieldWire::Bytes, "record_bytes_at", |f| {
        f.as_bytes().map(<[u8]>::to_vec)
    })
}

// =================================================================
// Dataset records as structure: forms and fragments
// =================================================================
//
// A dataset's predicates and metadata records reach a host by one of
// two pathways, which are distinct in the type system. As structure,
// here: a `forms` constant and a `fragment` per cycle, carrying
// vectordata's own types, for a host that prepares a statement per
// form and binds records to it without parsing text. As text, in the
// next section: a `str` rendered by a packaged vernacular the program
// names.
//
//   forms := predicate_forms(source)        // a constant, type forms
//   filter := predicate_at(forms, query)    // per cycle, type fragment
//
// The first has only constant inputs, so the facet is surveyed when
// the program is built and never again. The second names a predicate
// by its form's index and its ordinal: it reads no record and
// allocates nothing. A host learns which forms a fragment wire can
// carry, before any cycle, from the program
// (`Kernel::dataset_sources`).

/// The predicate records of the handle `h`, for the node `who`.
/// Refuses a predicate facet that holds one scalar per query.
fn predicate_records<'a>(h: &'a DatasetHandle, who: &str) -> &'a Arc<dv::PredicateForms> {
    match h {
        DatasetHandle::Predicates(forms) => forms,
        DatasetHandle::Generic(_) => panic!(
            "{who}: the metadata_predicates facet of this profile holds one scalar per query, \
             not predicate records; read it with `predicate_value_at`"
        ),
        other => panic!(
            "{who}: expected a metadata_predicates handle, got {}",
            dataset_handle_kind(other)
        ),
    }
}

/// The metadata records of the handle `h`, for the node `who`. Refuses
/// a metadata facet that holds one scalar per base vector.
fn metadata_records<'a>(h: &'a DatasetHandle, who: &str) -> &'a Arc<RecordDataset> {
    match h {
        DatasetHandle::Records(records) => records,
        DatasetHandle::Generic(_) => panic!(
            "{who}: the metadata_content facet of this profile holds one scalar per base vector, \
             not records with named fields; read it with `metadata_value_at`"
        ),
        other => panic!(
            "{who}: expected a metadata_content handle, got {}",
            dataset_handle_kind(other)
        ),
    }
}

/// The forms of a dataset's predicates: every distinct form its
/// `metadata_predicates` records take, with the form's template and
/// count, the form of the predicate at each ordinal, the strata the
/// facet publishes, and the layout of the metadata records the
/// conditions bind against. A constant: the facet is read once, when
/// the program is built.
///
/// A form the layout cannot bind is not refused here. It is in the
/// forms with its count, and a host that compiles each form's binder
/// (`form.binder(&forms.layout)`) gets its reason, so it can report
/// every such form together with those its own dialect cannot express.
///
/// Signature: `predicate_forms(handle) -> (forms)`
#[crate::polydat_node(category = RealData)]
fn predicate_forms(handle: Facet<MetadataPredicatesFacet>) -> dv::Shared<dv::PredicateForms> {
    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
    dv::Shared(predicate_records(h.as_ref(), "predicate_forms").clone())
}

/// The predicate of query `index`, as structure: which of `forms` it
/// takes, and its ordinal. A host selects the statement it prepared
/// for that form and binds the predicate's record through the form's
/// binder. Nothing is read and nothing is allocated here. The query
/// index wraps modulo the facet's predicates.
///
/// Signature: `predicate_at(forms: forms, index: u64) -> (fragment)`
#[crate::polydat_node(category = RealData)]
fn predicate_at(forms: dv::Shared<dv::PredicateForms>, index: u64) -> dv::PredicateFragment {
    let count = forms.census.count();
    assert!(
        count > 0,
        "predicate_at: '{}' has no predicates",
        forms.origin
    );
    let ordinal = index % count;
    let form = forms
        .census
        .form_at(ordinal)
        .expect("an ordinal below the census's count has a form");
    dv::PredicateFragment::new(forms.0, form as u32, ordinal)
}

/// The distinct keys of the forms a dataset's predicates take, sorted
/// and comma-joined: every value `predicate_form_at` gives. A constant,
/// so it is read when the program is built.
///
/// Refused when any form of the facet has no key (it holds a
/// disjunction, or addresses a field by index), with the form and the
/// reason. A program that labels by form declares this constant to be
/// refused when it is built, before any cycle, where
/// `predicate_form_at` alone is refused at its first evaluation.
///
/// Signature: `predicate_form_keys(handle) -> (str)`
#[crate::polydat_node(category = RealData)]
fn predicate_form_keys(handle: Facet<MetadataPredicatesFacet>) -> String {
    let who = "predicate_form_keys";
    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
    predicate_records(h.as_ref(), who)
        .form_keys()
        .unwrap_or_else(|reason| panic!("{who}: {reason}"))
        .join(",")
}

/// The key of the form the predicate of query `index` takes, such as
/// `citation_percentile.range_topic_l3.eq`: the identifier the dataset
/// publishes for the form, the same for every query of the form, so it
/// labels a series. Read from `forms`; no facet is read and the query
/// index wraps modulo the facet's predicates.
///
/// Refused when any form of the facet has no key (it holds a
/// disjunction, or addresses a field by index), whichever form the
/// query takes, with the form and the reason, at the first
/// evaluation; `predicate_form_keys` is refused for the same facet
/// when the program is built.
///
/// Signature: `predicate_form_at(forms: forms, index: u64) -> (str)`
#[crate::polydat_node(category = RealData)]
fn predicate_form_at(forms: dv::Shared<dv::PredicateForms>, index: u64) -> String {
    let ordinal = index % forms.census.count().max(1);
    forms
        .form_key_at(ordinal)
        .unwrap_or_else(|reason| panic!("predicate_form_at: {reason}"))
        .to_string()
}

/// The form of a dataset's metadata records: the layout that names and
/// types a record's fields, with the binder that reads every field in
/// layout order. A record facet has this one form. A constant.
///
/// Signature: `record_forms(handle) -> (forms)`
#[crate::polydat_node(category = RealData)]
fn record_forms(handle: Facet<MetadataContentFacet>) -> dv::Shared<dv::RecordForms> {
    let h = handle.resolve_facet(MetadataContentFacet::FACET);
    dv::Shared(metadata_records(h.as_ref(), "record_forms").forms.clone())
}

/// The metadata record of base vector `index`, as structure: its
/// ordinal among the records `forms` describes. A host binds the
/// record's fields through `forms.binder` to the statement it prepared
/// from the layout. Nothing is read and nothing is allocated here. The
/// index wraps modulo the record count.
///
/// Signature: `record_at(forms: forms, index: u64) -> (fragment)`
#[crate::polydat_node(category = RealData)]
fn record_at(forms: dv::Shared<dv::RecordForms>, index: u64) -> dv::RecordFragment {
    let count = forms
        .records
        .count()
        .unwrap_or_else(|e| panic!("record_at: '{}': {e}", forms.origin));
    assert!(count > 0, "record_at: '{}' has no records", forms.origin);
    dv::RecordFragment::new(forms.0, index % count)
}

/// The names of the fields of a dataset's metadata records, in layout
/// order, comma-joined: what a column list or an iteration over the
/// fields takes. A constant.
///
/// Signature: `record_field_names(handle) -> (str)`
#[crate::polydat_node(category = RealData)]
fn record_field_names(handle: Facet<MetadataContentFacet>) -> String {
    let h = handle.resolve_facet(MetadataContentFacet::FACET);
    metadata_records(h.as_ref(), "record_field_names")
        .forms
        .layout
        .names()
        .join(",")
}

/// The metadata fields a dataset's predicates constrain, sorted and
/// comma-joined: the fields a target indexes to serve them. A
/// constant.
///
/// Signature: `predicate_field_names(handle) -> (str)`
#[crate::polydat_node(category = RealData)]
fn predicate_field_names(handle: Facet<MetadataPredicatesFacet>) -> String {
    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
    let forms = predicate_records(h.as_ref(), "predicate_field_names");
    forms
        .census
        .fields()
        .into_iter()
        .collect::<Vec<_>>()
        .join(",")
}

/// The strata of a predicate facet, for the node `who`; refused when
/// the facet publishes none.
fn predicate_strata<'a>(
    forms: &'a dv::PredicateForms,
    who: &str,
) -> &'a vectordata::predicate_forms::PredicateStrata {
    forms.census.strata().unwrap_or_else(|| {
        panic!(
            "{who}: the predicates of '{}' publish no family or selectivity",
            forms.origin
        )
    })
}

/// The distinct families of a dataset's predicates, sorted and
/// comma-joined, or empty when the facet publishes none. A constant.
///
/// Signature: `predicate_families(handle) -> (str)`
#[crate::polydat_node(category = RealData)]
fn predicate_families(handle: Facet<MetadataPredicatesFacet>) -> String {
    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
    let forms = predicate_records(h.as_ref(), "predicate_families");
    forms
        .census
        .strata()
        .map_or_else(String::new, |strata| strata.families().join(","))
}

/// The distinct selectivity bands of a dataset's predicates, widest
/// first and comma-joined, or empty when the facet publishes none. A
/// constant.
///
/// Signature: `predicate_bands(handle) -> (str)`
#[crate::polydat_node(category = RealData)]
fn predicate_bands(handle: Facet<MetadataPredicatesFacet>) -> String {
    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
    let forms = predicate_records(h.as_ref(), "predicate_bands");
    forms
        .census
        .strata()
        .map_or_else(String::new, |strata| strata.bands().join(","))
}

/// The family of the predicate of query `index`, one of
/// `predicate_families`. Refused when the facet publishes no strata.
/// The query index wraps modulo the facet's predicates.
///
/// Signature: `predicate_family_at(handle, index: u64) -> (str)`
#[crate::polydat_node(category = RealData)]
fn predicate_family_at(handle: Facet<MetadataPredicatesFacet>, index: u64) -> String {
    let who = "predicate_family_at";
    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
    let forms = predicate_records(h.as_ref(), who);
    let ordinal = index % forms.census.count().max(1);
    predicate_strata(forms, who)
        .family_at(ordinal)
        .unwrap_or_else(|| panic!("{who}: '{}' has no predicate {ordinal}", forms.origin))
        .to_string()
}

/// The selectivity band of the predicate of query `index`, one of
/// `predicate_bands`, or empty for a predicate whose recorded
/// selectivity no band is read from. Refused when the facet publishes
/// no strata. The query index wraps modulo the facet's predicates.
///
/// Signature: `predicate_band_at(handle, index: u64) -> (str)`
#[crate::polydat_node(category = RealData)]
fn predicate_band_at(handle: Facet<MetadataPredicatesFacet>, index: u64) -> String {
    let who = "predicate_band_at";
    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
    let forms = predicate_records(h.as_ref(), who);
    let ordinal = index % forms.census.count().max(1);
    predicate_strata(forms, who)
        .band_at(ordinal)
        .unwrap_or_default()
        .to_string()
}

// =================================================================
// Dataset records as text, in a packaged vernacular
// =================================================================
//
// The other pathway: a record or a predicate rendered as text by one
// of the vernaculars vectordata packages, named by the program. The
// result is a `str` like any other. It is the form for a statement
// that is not prepared and for display, and it carries no structure.

/// The packaged renderer `vernacular`, for the node `who`; an unknown
/// name is refused with the names that exist.
fn vernacular_codec(
    vernacular: &str,
    who: &str,
) -> Box<dyn vectordata::records::RecordCodec<Out = String>> {
    vectordata::records::codec_by_name(vernacular).unwrap_or_else(|| {
        panic!(
            "{who}: no packaged vernacular is named `{vernacular}`; the names are {}",
            vectordata::records::codec_names().join(", ")
        )
    })
}

/// The metadata record of base vector `index`, rendered as text by the
/// packaged vernacular `vernacular`. An unknown vernacular is refused
/// with the names that exist. The index wraps modulo the record count.
///
/// Signature: `record_text_at(handle, vernacular: str, index: u64) -> (str)`
#[crate::polydat_node(category = RealData)]
fn record_text_at(handle: Facet<MetadataContentFacet>, vernacular: &str, index: u64) -> String {
    let who = "record_text_at";
    let h = handle.resolve_facet(MetadataContentFacet::FACET);
    let records = metadata_records(h.as_ref(), who);
    let origin = &records.forms.origin;
    assert!(records.count > 0, "{who}: '{origin}' has no records");
    let ordinal = index % records.count;
    records
        .forms
        .records
        .decode(vernacular_codec(vernacular, who))
        .get(ordinal)
        .unwrap_or_else(|e| panic!("{who}: record {ordinal} of '{origin}': {e}"))
}

/// The predicate of query `index`, rendered as text by the packaged
/// vernacular `vernacular`, comparands inline. An unknown vernacular is
/// refused with the names that exist. The query index wraps modulo the
/// facet's predicates.
///
/// Signature: `predicate_text_at(handle, vernacular: str, index: u64) -> (str)`
#[crate::polydat_node(category = RealData)]
fn predicate_text_at(
    handle: Facet<MetadataPredicatesFacet>,
    vernacular: &str,
    index: u64,
) -> String {
    let who = "predicate_text_at";
    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
    let forms = predicate_records(h.as_ref(), who);
    let origin = &forms.origin;
    let count = forms.census.count();
    assert!(count > 0, "{who}: '{origin}' has no predicates");
    let ordinal = index % count;
    forms
        .predicates
        .decode(vernacular_codec(vernacular, who))
        .get(ordinal)
        .unwrap_or_else(|e| panic!("{who}: predicate {ordinal} of '{origin}': {e}"))
}

/// The layout of a dataset's metadata records, rendered as text by the
/// packaged vernacular `vernacular`: the text one record stands for,
/// such as a schema's column definitions, before any record is read. A
/// constant. An unknown vernacular is refused with the names that
/// exist.
///
/// Signature: `record_layout_text(handle, vernacular: str) -> (str)`
#[crate::polydat_node(category = RealData)]
fn record_layout_text(handle: Facet<MetadataContentFacet>, vernacular: &str) -> String {
    use vectordata::records::RecordCodec;
    let who = "record_layout_text";
    let h = handle.resolve_facet(MetadataContentFacet::FACET);
    let records = metadata_records(h.as_ref(), who);
    let exemplar = vectordata::formats::anode::encode(&records.forms.layout.exemplar());
    vernacular_codec(vernacular, who)
        .decode(&exemplar)
        .unwrap_or_else(|e| panic!("{who}: the layout of '{}': {e}", records.forms.origin))
}

/// Access a metadata value per base ordinal. Expects a Generic
/// handle opened against the `metadata_content` facet.
///
/// Signature: `metadata_value_at(handle, index: u64) -> (str)`
#[crate::polydat_node(category = RealData)]
fn metadata_value_at(handle: Facet<MetadataContentFacet>, index: u64) -> String {
    generic_str_typed(
        handle.resolve_facet(MetadataContentFacet::FACET).as_ref(),
        index as usize,
    )
}

/// Access a predicate value per query ordinal. Expects a Generic
/// handle opened against the `metadata_predicates` facet.
///
/// Signature: `predicate_value_at(handle, index: u64) -> (str)`
#[crate::polydat_node(category = RealData)]
fn predicate_value_at(handle: Facet<MetadataPredicatesFacet>, index: u64) -> String {
    generic_str_typed(
        handle
            .resolve_facet(MetadataPredicatesFacet::FACET)
            .as_ref(),
        index as usize,
    )
}

/// Count of metadata content records. Expects a Generic handle.
///
/// Signature: `metadata_content_count(handle) -> (u64)`
#[crate::polydat_node(category = RealData)]
fn metadata_content_count(handle: Facet<MetadataContentFacet>) -> u64 {
    match handle.resolve_facet(MetadataContentFacet::FACET).as_ref() {
        DatasetHandle::Generic(d) => d.count as u64,
        DatasetHandle::Records(d) => d.count,
        _ => 0,
    }
}

// ── Counting a facet's matching records ─────────────────────────────

/// How many scalars of a Generic facet equal `value`.
///
/// A linear read of the facet, which is what the question is: the
/// reader holds the values and nothing indexes them by content. Both
/// callers below pass a handle and a value that are fixed for a scope,
/// so the count is computed once at scope init and reused, the way the
/// facet itself is loaded once.
/// How many scalars of a Generic facet equal `value`.
fn generic_count_typed(h: &DatasetHandle, value: i64) -> u64 {
    match h {
        DatasetHandle::Generic(d) => {
            (0..d.count).filter(|i| d.get_scalar(*i) == value).count() as u64
        }
        DatasetHandle::Records(_) => panic!("{}", RECORDS_NOT_SCALARS),
        DatasetHandle::Predicates(_) => panic!("{}", PREDICATES_NOT_SCALARS),
        _ => 0,
    }
}

/// How many records carry the metadata value `value`.
///
/// The per-label cardinality the recall audit compares against a
/// profile's declared count: not a counter advancing as records are
/// visited, but a property of the facet and the value, so it
/// replays and agrees on every engine and every fiber
/// (docs/design/runtime_model.md §9.1).
///
/// `metadata_value_at(handle, i)` formats the same scalar as text,
/// so a host comparing labels as strings and one counting them
/// here are reading one facet.
#[crate::polydat_node(category = RealData)]
fn metadata_count_of(handle: Facet<MetadataContentFacet>, value: i64) -> u64 {
    generic_count_typed(
        handle.resolve_facet(MetadataContentFacet::FACET).as_ref(),
        value,
    )
}

/// How many queries carry the predicate value `value`.
///
/// The denominator of a per-predicate recall figure, and the bound
/// on a rank within one predicate's queries.
///
/// Signature: `predicate_count_of(handle, value: i64) -> (u64)`
#[crate::polydat_node(category = RealData)]
fn predicate_count_of(handle: Facet<MetadataPredicatesFacet>, value: i64) -> u64 {
    generic_count_typed(
        handle
            .resolve_facet(MetadataPredicatesFacet::FACET)
            .as_ref(),
        value,
    )
}

// ── Listing a facet's matching records ──────────────────────────────

/// The indices of a Generic facet whose scalar equals `value`,
/// ascending.
///
/// The same linear read as [`generic_count_typed`], keeping the
/// indices it counts, so a list's length is the matching count, and
/// the list is computed once at scope init and reused the same way.
/// An index past `i32::MAX` is a facet larger than a `vec_i32`
/// addresses and fails by name rather than wrapping.
fn generic_ordinals_typed(node: &str, h: &DatasetHandle, value: i64) -> Vec<i32> {
    match h {
        DatasetHandle::Generic(d) => (0..d.count)
            .filter(|i| d.get_scalar(*i) == value)
            .map(|i| {
                i32::try_from(i)
                    .unwrap_or_else(|_| panic!("{node}: ordinal {i} is outside the i32 range"))
            })
            .collect(),
        DatasetHandle::Records(_) => panic!("{node}: {RECORDS_NOT_SCALARS}"),
        DatasetHandle::Predicates(_) => panic!("{node}: {PREDICATES_NOT_SCALARS}"),
        _ => Vec::new(),
    }
}

/// The base ordinals whose metadata value is `value`, ascending.
///
/// The list whose length `metadata_count_of(handle, value)` is. The
/// record at local row `l` among those carrying `value` has global
/// ordinal `vec_at_i32(metadata_ordinals_of(handle, value), l)`
/// (docs/design/runtime_model.md §9.1).
#[crate::polydat_node(category = RealData)]
fn metadata_ordinals_of(handle: Facet<MetadataContentFacet>, value: i64) -> Vec<i32> {
    generic_ordinals_typed(
        "metadata_ordinals_of",
        handle.resolve_facet(MetadataContentFacet::FACET).as_ref(),
        value,
    )
}

/// The query ordinals whose predicate value is `value`, ascending.
///
/// The list whose length `predicate_count_of(handle, value)` is.
#[crate::polydat_node(category = RealData)]
fn predicate_ordinals_of(handle: Facet<MetadataPredicatesFacet>, value: i64) -> Vec<i32> {
    generic_ordinals_typed(
        "predicate_ordinals_of",
        handle
            .resolve_facet(MetadataPredicatesFacet::FACET)
            .as_ref(),
        value,
    )
}

// =========================================================================
// Cursor-sugar handlers
// =========================================================================
//
// Three sugar forms recognized by this module — none of them
// known to the core compiler, which dispatches generically
// through `dsl::cursor_sugar`. Each desugars to a synthetic
// `range(0, vector_count|query_count(...))` constructor plus
// auxiliary bindings:
//
//   - `__<cursor>_prebuffer := dataset_prebuffer("ds:profile")`
//     loaded once at init time so cycle-time accessor calls hit
//     prefetched memory.
//   - `<cursor>__vector := vector_at("ds:profile", <cursor>__ordinal)`
//     (or `query_vector_at` for the query
//     facet) — published as the cursor's `vector` projection so
//     workloads can reference `<cursor>.vector`.
//
// Forms:
//   - `vectordata_source(dataset, profile, facet)` — explicit facet
//   - `vectordata_base(dataset, profile)`           — facet = "base"
//   - `vectordata_query(dataset, profile)`          — facet = "query"
//
// Facet-specific projections like `metadata` / `ground_truth` /
// `predicate` stay explicit (the user writes
// `meta := metadata_value_at(<cursor>.ordinal, "ds:profile")` by
// hand) because their existence is dataset-conditional — not
// every dataset declares a metadata column or a predicate facet.

#[cfg(feature = "vectordata")]
fn vectordata_sugar(
    source_name: &str,
    constructor: &crate::dsl::ast::Expr,
) -> Result<Option<crate::dsl::cursor_sugar::CursorSugar>, String> {
    use crate::dsl::ast::{Arg, CallExpr, Expr};
    use crate::dsl::compile::positional_str_lit;
    use crate::dsl::cursor_sugar::{AuxBinding, CursorSugar};

    let Expr::Call(call) = constructor else {
        return Ok(None);
    };

    let (dataset, profile, facet) = match call.func.as_str() {
        "vectordata_source" => {
            let d = positional_str_lit(call.args.first()).ok_or_else(|| format!(
                "cursor '{source_name}': vectordata_source(dataset, profile, facet) — first arg must be a string literal"
            ))?;
            let p = positional_str_lit(call.args.get(1)).ok_or_else(|| format!(
                "cursor '{source_name}': vectordata_source(dataset, profile, facet) — second arg must be a string literal"
            ))?;
            let f = positional_str_lit(call.args.get(2)).ok_or_else(|| format!(
                "cursor '{source_name}': vectordata_source(dataset, profile, facet) — third arg must be a string literal (\"base\" or \"query\")"
            ))?;
            (d, p, f)
        }
        "vectordata_base" | "vectordata_query" => {
            let f = call.func.strip_prefix("vectordata_").unwrap().to_string();
            let d = positional_str_lit(call.args.first()).ok_or_else(|| format!(
                "cursor '{source_name}': {}(dataset, profile) — first arg must be a string literal",
                call.func,
            ))?;
            let p = positional_str_lit(call.args.get(1)).ok_or_else(|| format!(
                "cursor '{source_name}': {}(dataset, profile) — second arg must be a string literal",
                call.func,
            ))?;
            (d, p, f)
        }
        _ => return Ok(None),
    };

    if facet != "base" && facet != "query" {
        return Err(format!(
            "cursor '{source_name}': vectordata facet must be \"base\" or \"query\", got \"{facet}\""
        ));
    }
    let (count_func, vector_func) = match facet.as_str() {
        "base" => ("vector_count", "vector_at"),
        "query" => ("query_count", "query_vector_at"),
        _ => unreachable!(),
    };

    let combined = format!("{dataset}:{profile}");
    let span = call.span;
    let lit = |s: String| Expr::StringLit(s, span);
    let positional = |e: Expr| Arg::Positional(e);

    let effective_constructor = Expr::Call(CallExpr {
        func: "range".into(),
        args: vec![
            positional(Expr::IntLit(0, span)),
            positional(Expr::Call(CallExpr {
                func: count_func.into(),
                args: vec![positional(lit(combined.clone()))],
                span,
            })),
        ],
        span,
    });

    let prebuffer_binding = AuxBinding {
        name: format!("__{source_name}_prebuffer"),
        value: Expr::Call(CallExpr {
            func: "dataset_prebuffer".into(),
            args: vec![positional(lit(combined.clone()))],
            span,
        }),
        projection: None,
    };

    // Cursor sugar emits the call in (handle, index) order. The
    // combined source string auto-promotes to the right facet handle
    // through the wire's default resolver (library_catalog.md
    // "Shapes", `Resolved<R, T>`).
    let vector_binding = AuxBinding {
        name: format!("{source_name}__vector"),
        value: Expr::Call(CallExpr {
            func: vector_func.into(),
            args: vec![
                positional(lit(combined)),
                positional(Expr::Ident(format!("{source_name}__ordinal"), span)),
            ],
            span,
        }),
        projection: Some(("vector".into(), crate::ast::PortType::VecF32)),
    };

    Ok(Some(CursorSugar {
        effective_constructor,
        aux_bindings: vec![prebuffer_binding, vector_binding],
    }))
}

#[cfg(feature = "vectordata")]
inventory::submit! {
    crate::dsl::cursor_sugar::CursorSugarRegistration {
        handler: vectordata_sugar,
        name: "vectordata",
    }
}

#[cfg(test)]
mod count_of_tests {
    use super::*;
    use crate::ast::{PolydatNode, PortType, Slot};
    use crate::dsl::registry::DefaultResolver;

    /// The ports the compiler types a call against: a handle and a
    /// signed value in, a count out. The value is `i64` because that is
    /// what the facet stores; a caller with a literal reaches it
    /// through `to_i64`, since an integer literal is a `u64` and the
    /// adapter catalog will not heal that pair.
    #[test]
    fn the_count_of_nodes_take_a_handle_and_a_signed_value() {
        for node in [
            Box::new(MetadataCountOf::new()) as Box<dyn PolydatNode>,
            Box::new(PredicateCountOf::new()) as Box<dyn PolydatNode>,
        ] {
            let meta = node.meta();
            assert_eq!(meta.outs.len(), 1);
            assert_eq!(meta.outs[0].typ, PortType::U64, "{}", meta.name);
            assert_eq!(meta.ins.len(), 2, "{}", meta.name);
            let Slot::Wire(handle) = &meta.ins[0] else {
                panic!("{}: the first input is a wire", meta.name)
            };
            let Slot::Wire(value) = &meta.ins[1] else {
                panic!("{}: the second input is a wire", meta.name)
            };
            assert_eq!(handle.typ, PortType::Handle, "{}", meta.name);
            assert_eq!(value.typ, PortType::I64, "{}", meta.name);
        }
    }

    /// The ordinals nodes take the same handle and value as the counts
    /// and give a `vec_i32` of ordinals.
    #[test]
    fn the_ordinals_of_nodes_take_what_the_counts_take() {
        for node in [
            Box::new(MetadataOrdinalsOf::new()) as Box<dyn PolydatNode>,
            Box::new(PredicateOrdinalsOf::new()) as Box<dyn PolydatNode>,
        ] {
            let meta = node.meta();
            assert_eq!(meta.outs.len(), 1);
            assert_eq!(meta.outs[0].typ, PortType::VecI32, "{}", meta.name);
            let types: Vec<PortType> = meta
                .ins
                .iter()
                .map(|s| match s {
                    Slot::Wire(w) => w.typ,
                    _ => panic!("{}: every input is a wire", meta.name),
                })
                .collect();
            assert_eq!(types, [PortType::Handle, PortType::I64], "{}", meta.name);
        }
    }

    /// A handle of the wrong shape answers zero rather than failing.
    /// The facets these read are scalar ones; a caller that opened a
    /// vector facet by mistake gets a count of nothing, which is the
    /// same answer the facet's own readers give for a shape they do not
    /// hold.
    #[test]
    fn a_handle_of_another_shape_counts_nothing() {
        let group_shaped = DatasetHandle::Prebuffered {
            group: match load_dataset_group("nonexistent:profile") {
                Ok(g) => g,
                // No dataset available in this environment: the
                // fallback is still exercised through the match arm
                // below, which is what this test is about.
                Err(_) => return,
            },
            source: "nonexistent:profile".into(),
        };
        assert_eq!(generic_count_typed(&group_shaped, 1), 0);
        assert!(generic_ordinals_typed("test", &group_shaped, 1).is_empty());
    }

    /// Both names resolve through the registry and carry a default
    /// resolver, so `metadata_count_of("ds:profile", v)` promotes the
    /// source string to the right facet the way its neighbours do.
    #[test]
    fn both_names_are_registered_with_a_facet_resolver() {
        for (name, facet) in [
            ("metadata_count_of", "metadata_content"),
            ("predicate_count_of", "metadata_predicates"),
            ("metadata_ordinals_of", "metadata_content"),
            ("predicate_ordinals_of", "metadata_predicates"),
        ] {
            let sig = crate::dsl::registry::lookup(name)
                .unwrap_or_else(|| panic!("{name} is registered"));
            assert_eq!(sig.outputs, 1, "{name}");
            assert_eq!(sig.params.len(), 2, "{name}");
            // The facet comes from the handle argument's type, so
            // this is the resolver the macro read off `Facet<_>`.
            match sig.default_resolver {
                Some(DefaultResolver::Facet(f)) => assert_eq!(f, facet, "{name}"),
                other => panic!("{name}: expected a facet resolver, got {other:?}"),
            }
        }
    }
}