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
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
//! A DERIVED INDEX's emission — the expansion that carries an identity it did not mint.
//!
//! A full-text index, an embedding index and a family of artifacts are one shape with three
//! storages: each subscribes to exactly one upstream, holds one document per message it saw, and is
//! addressed by THAT MESSAGE's key. *The key is not its to mint* — so there is no `id` field, no
//! `*Key` struct and no `*Lineage` struct in this emission, and the two address types a record
//! declares are here as PROJECTIONS of the upstream's instead.
//!
//! ```ignore
//! #[ingraph::fulltext(upstream(node = "asr::Segment", title = "speaker", body = "text"))]
//! pub struct SearchDocument {
//! #[ingraph(searchable)] title: String,
//! #[ingraph(searchable)] body: String,
//! }
//! ```
//!
//! # The two halves the compiler checks, and why neither could be checked here
//!
//! A macro holds tokens. The upstream is another declaration's, and two macro expansions cannot see
//! each other — so nothing about `asr::Segment` is knowable at the moment this expansion is written.
//! Both facts the declaration asserts are therefore EMITTED for rustc to resolve, each at the string
//! the author wrote:
//!
//! | asserted | emitted | refused as |
//! |---|---|---|
//! | the upstream is a node | the entity binding's own bound | `E0412` unresolved · `E0277` not a node |
//! | a projection names a field of it | [`IndexModel::projections`] | `E0609` no field · `E0616` private · `E0308` wrong type |
//!
//! A DIRECT FIELD READ rather than an accessor call, and that was the fork: a record's accessor is
//! spelled four ways depending on the projection its own declaration asked for — `x`, `x_ref`,
//! `x_slice` — and this expansion cannot see which. The field's name is the one spelling that does
//! not vary, which is also why the pivot stamps `pub(crate)` on a declaration's fields: the read has
//! to be legal from the module the index was declared in.
//!
//! # What it does NOT emit, and the absences are not eras
//!
//! No `*Key`, no `*Lineage`, no row, no wire face and no order — a derived index stores documents in
//! an engine of its own rather than rows in a database, and every one of those is the row half of a
//! record.
//!
//! WHICH engines hold the documents IS emitted, and it is per FIELD: each `(elected field × declared
//! engine)` becomes a slot marker at module scope, and a `fanout` field gets the door that writes all
//! of them at once. See [`crate::engine`] for the semantics — several engines are portability, the
//! default is single-write, and the marker is the one departure. What is still nobody's here is the
//! READ side's fan-and-fuse, which is the face round's.
use quote::{format_ident, quote, quote_spanned};
use syn::spanned::Spanned as _;
use crate::{
emit::{framework, leading, wide_signature},
engine::{Engine, EngineKind, FieldEngines, Road, Slot},
extension::Extension,
method::{Door, DoorOrigin, Emitted, Origin, Owner, fan_door, fold_accessor},
model::{
Column, Conversion, Declared, GraphqlKind, NodeKind, Role, TracingLevel, borrowed_key,
elected_marker, one_storage_marker,
},
prefix::EmissionPrefix,
};
#[cfg(test)]
mod answer_seats;
#[cfg(test)]
mod answers;
#[cfg(test)]
mod audits;
#[cfg(test)]
mod bones;
#[cfg(test)]
mod by_key;
#[cfg(test)]
mod citizen;
#[cfg(test)]
mod depth;
#[cfg(test)]
mod elections;
#[cfg(test)]
mod engines;
#[cfg(test)]
mod habitats;
#[cfg(test)]
mod hydrated;
#[cfg(test)]
mod k_seat;
#[cfg(test)]
mod kind_audits;
#[cfg(test)]
mod knobs;
#[cfg(test)]
mod rename_resolution;
#[cfg(test)]
mod roads;
#[cfg(test)]
mod set_question_wire;
#[cfg(test)]
mod similar;
#[cfg(test)]
mod similar_set;
#[cfg(test)]
mod similar_set_wire;
#[cfg(test)]
mod subscriber;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tiers;
#[cfg(test)]
mod tracing_tests;
/// HOW a retrieve tells two of this index's keys apart — the `dedup(…)` word.
///
/// A retrieve dedupes the engine's hit stream BY KEY, first sighting winning, because the store
/// faces are open traits and no backend owes uniqueness across the sources sharing a slot. What a
/// declaration chooses here is not whether that happens; it is the MECHANISM, and the mechanism is a
/// BOUNDS choice on the key type:
///
/// | word | the emitted method names | the key must satisfy |
/// |---|---|---|
/// | `dedup(hash)` | `HashSeen` | `Hash + Eq` |
/// | `dedup(eq)` | `EqSeen` | `PartialEq` |
///
/// A CLOSED unit enum, because the vocabulary is the FRAMEWORK's: each word names one of the
/// framework's own membership implementations, and a fourth mechanism is an arm here plus an
/// implementor there rather than a redesign. That is the crate's rule for a framework-owned
/// vocabulary, and the open surface is one level down — a third party's KEY joins by implementing
/// `Hash` or `PartialEq`, which it already does.
///
/// [`Hash`](Self::Hash) is the default when the word is absent: every key a node macro emits today
/// is built from the closed segment vocabulary and every member of it hashes, so the default always
/// compiles. `eq` is the escape for a key that cannot — a float in an address, a foreign type with
/// no `Hash` impl — and it asks less of the type, which is why the choice is declared rather than
/// fixed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Dedup {
/// `dedup(hash)` — membership through a `HashSet`.
#[default]
Hash,
/// `dedup(eq)` — membership through a list walked by field-wise equality.
Eq,
}
impl Dedup {
/// The WORD, as a declaration writes it inside `dedup(…)`.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Hash => "hash",
Self::Eq => "eq",
}
}
/// Every word this grammar admits, for the front end that lists them in a refusal.
///
/// One list rather than a sentence per message, so a fourth mechanism reaches every refusal by
/// arriving here.
pub const WORDS: [&'static str; 2] = [Self::Hash.as_str(), Self::Eq.as_str()];
/// The framework membership the emitted methods name.
const fn membership(self) -> &'static str {
match self {
Self::Hash => "HashSeen",
Self::Eq => "EqSeen",
}
}
/// The framework JOIN the emitted fused doors name — the same word, one family over.
///
/// A fold's join answers *have I already placed this root* and a dedup's membership answers *have
/// I already admitted this key*; both ask the KEY for the same thing, so a declaration reached for
/// `eq` because its key cannot hash must not be closed out of fusion for that reason. The rows
/// move together for [`accumulator`](Self::accumulator)'s stated reason.
///
/// Read at TWO GRAINS: an index tier spends it on its own fused doors, and a graph root spends it
/// on its three ([`crate::graph`]). The root's key is a PREFIX of its members' keys and inherits
/// the property rather than escaping it, so the two grains name one row rather than each carrying
/// a copy of it.
pub(crate) const fn join(self) -> &'static str {
match self {
Self::Hash => "HashJoin",
Self::Eq => "EqJoin",
}
}
/// The framework ACCUMULATOR the emitted set door names — [`membership`](Self::membership)'s twin,
/// one grain over.
///
/// The same word picks both, because both ask the KEY for the same thing. A declaration reached
/// for `eq` because its key cannot hash, and the set road must not be closed to it for that
/// reason; a declaration on `hash` must not silently pay a linear scan there either. So the two
/// rows move together, and a third mechanism arrives in both at once.
const fn accumulator(self) -> &'static str {
match self {
Self::Hash => "HashBests",
Self::Eq => "EqBests",
}
}
/// What the key must satisfy for this mechanism — the `where` clause the emitted methods carry.
///
/// Written here rather than assembled at each emission site, so the choice and its cost are one
/// line and cannot drift apart. [`join`](Self::join)'s twin, and read at the same two grains: the
/// row a root's fused door states about its ROOT parameter is this one.
///
/// `Clone` is on BOTH rows and is the mechanism's own price rather than either word's: a
/// membership owns the keys it has seen and the survivor list owns them too, so one of the two
/// holds a copy. What the DECLARATION is choosing is the other half — `Hash + Eq` against
/// `PartialEq`.
pub(crate) fn admits(self) -> proc_macro2::TokenStream {
match self {
Self::Hash => quote!(::core::hash::Hash + ::core::cmp::Eq + ::core::clone::Clone),
Self::Eq => quote!(::core::cmp::PartialEq + ::core::clone::Clone),
}
}
}
/// WHICH FOLD an election declared — a shipped CITIZEN by its word, or a type by its PATH.
///
/// # Two spellings, and the split is the crossing this whole family is built on
///
/// `semantics(fold(sum))` names one of the framework's own, BARE and in parentheses, which is the
/// spelling every framework-owned mechanism word in this grammar takes — `dedup(hash)` is the same
/// shape one family over. `semantics(fold = "app::MyFold")` names a type the DECLARING CRATE owns,
/// QUOTED, which is the spelling every reference to somebody else's declaration takes. So the
/// closed half and the open half are told apart by the shape of the value rather than by a rule a
/// reader has to remember: mint bare, refer quoted.
///
/// # The shorthand's vocabulary is the DEFAULT-ABLE citizens, and that is not an arbitrary two
///
/// The emission builds a declared fold through [`Default`] — it holds a word or a path and no value
/// — so a citizen reachable by word is one that can be built from nothing. `Sum` and `Max` are; a
/// `Weighted` is not, its weights being checked against a query the declaration cannot see. `Mean`
/// is not a citizen at all: the word is withdrawn, and a fold that divides is one somebody writes
/// where they can see their own absences. Both are refused BY NAME rather than as unknown words,
/// because an author who wrote either had a coherent idea.
#[derive(Debug, Clone)]
pub enum Fold {
/// `fold(sum)` — `Σⱼ bⱼ`, the shipped default, named explicitly.
Sum,
/// `fold(max)` — `maxⱼ bⱼ`.
Max,
/// `fold = "app::MyFold"` — a type the declaring crate owns, carried VERBATIM and resolved nowhere
/// in this crate: a path naming nothing is `E0412` at the string its author wrote, and a type
/// that does not fold this engine's currency is `E0277` where the fold is constructed.
Custom(syn::Path),
}
impl Fold {
/// The two shorthand WORDS, in the order a refusal lists them.
///
/// One list rather than a sentence per message, so a third default-able citizen reaches every
/// refusal by arriving here.
pub const WORDS: [&'static str; 2] = ["sum", "max"];
/// The citizen a shorthand word names, or [`None`] where the word is not one of them.
#[must_use]
pub fn shipped(word: &str) -> Option<Self> {
match word {
"sum" => Some(Self::Sum),
"max" => Some(Self::Max),
_ => None,
}
}
}
/// WHAT AN ELECTED FIELD HOLDS, as its own LABEL states it — `embedding` or `list(embedding)`.
///
/// # The label is what the EXPANSION reads, and it is a WORD because a macro holds tokens
///
/// An earlier round read this off the field's TYPE: peel a `Vec<…>`, and what is left says one or
/// many. That is a guess at a meaning only rustc has — wrong for `type ClipFrames = Vec<…>`, wrong
/// for a re-export renamed on the way in, and wrong for every carrier not literally spelled `Vec`.
/// So the declaration STATES it, exactly as a record's field states its kind, and the type-read is
/// gone from this crate entirely.
///
/// # It restates NO fact, which is what dissolves the *disagreement refusal* worry
///
/// The label carries no width, no element and no space — those are the type's, projected through
/// [`EmbeddingMarker`] at rustc time. What it carries is STRUCTURAL INTENT: which faces this
/// declaration emits and which doors it grows. So the two readers cannot disagree about a fact,
/// only about a shape, and that disagreement is settled by the compiler rather than by this crate:
/// the emission states the label's claim as a bound, and a label that lied is `E0277` carrying a
/// sentence that names both sides.
///
/// # `list(embedding)` and not `set(embedding)`
///
/// The container word is the ordered, duplicate-bearing one, because that is what a set election IS:
/// its members are stored under ORDINALS, and `set` in this grammar's collection vocabulary promises
/// unordered-and-deduplicated, which the structure does not have. The word `set` stays reserved for
/// a true unordered container.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElectionLabel {
/// `embedding` — one embedding, the form every declaration written before the set arrived has.
Embedding,
/// `list(embedding)` — a per-entity SET, variable in length, EMPTY being legal.
///
/// An empty set is a legal value and is never similarity-matched: a collection has no null state,
/// so *no members* is what a record with nothing to index says, and a knn over its column simply
/// does not reach it.
List,
}
impl ElectionLabel {
/// The label as a DECLARATION writes it, which is also how a refusal quotes it.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Embedding => "embedding",
Self::List => "list(embedding)",
}
}
/// The framework MULTIPLICITY marker this label claims — the type an emitted audit holds the
/// field's own type to.
#[must_use]
pub const fn multiplicity(self) -> &'static str {
match self {
Self::Embedding => "One",
Self::List => "Set",
}
}
/// The framework AUDIT this label is stated as, spanned at the election word.
///
/// A function rather than the projection bound itself, for the reason the audit's own doc gives:
/// `Multiplicity = One` reports `E0271`, a type mismatch, and the `on_unimplemented` attribute
/// rides unsatisfied TRAIT bounds only — so the claim is spelled as a trait that can carry the
/// sentence.
#[must_use]
pub const fn audit(self) -> &'static str {
match self {
Self::Embedding => "elects_one",
Self::List => "elects_a_set",
}
}
/// Whether this label states a SET — the one question the emission asks it twice, at the write
/// face and at the door.
#[must_use]
pub const fn is_set(self) -> bool {
matches!(self, Self::List)
}
}
/// WHICH field of a vector declaration a knn runs over — one `#[ingraph(knn)]` marker's answer.
///
/// # The type states the SHAPE; the ROLE is declared
///
/// `Embedding<E, N>` says a field holds `N` coordinates of `E`. It does not say *this is the field
/// this index indexes*, and welding that onto the type would make **an embedding you store and do
/// not index** undeclarable — a shape real nodes have, a caption vector kept for hydration beside
/// the image vector the knn runs over. Role and shape are two facts, and the record for a role is a
/// MARKER. It is the split the three-layer law draws between a field and its accessor, one family
/// over: one fact, one record.
///
/// So a vector declaration may hold any number of embedding-typed fields; the ones wearing the
/// marker are elected; the rest are ordinary payload — stored, hydrated, never reached by a knn.
///
/// # N ELECTIONS, and the slot is one PER (field × engine)
///
/// Any number of fields may wear it, and every election is queryable. That is the shape real nodes
/// have — an upstream operator producing two vectors, or a storage node accumulating the embeddings
/// of several compute nodes it subscribes.
///
/// The geometry that carries them USED to be one slot holding N vector columns, on the keystone
/// *one declaration, one slot*. The engine grammar moved that keystone: a slot is `(field × engine)`
/// now (see [`Slot`]), because the per-slot laws are per-corpus and two fields sharing one corpus
/// move each other's scores. What did NOT move is the column axis one grain finer — a slot may still
/// hold several columns of one field's own geometry, and `VectorRead::knn`'s selector still says
/// which. Electing the same field twice is not a case either way: a marker is written on the field it
/// elects, so a second one is the ordinary declared-twice refusal.
///
/// # MANDATORY, including where exactly one embedding field exists
///
/// At least one, and there is no unambiguous-single fallback; the absence is the design rather than
/// an unbuilt convenience. A fallback would readmit type-inference as a silent mechanism, so a
/// declaration's meaning would shift when a SECOND embedding field arrived elsewhere in the struct —
/// the index silently indexing a field nobody elected. *必须指定* is a property of the signature or
/// it is a property of the documentation, which is the argument that made a retrieve's floor a
/// positional parameter rather than an option with a default.
///
/// # ON THE FIELD, and that is what buys the spans
///
/// The marker is a token of the field's own attribute, and the field's TYPE is the next token along.
/// So *this is not an `Embedding<E, N>`* refuses AT THE TYPE — the half a reader has to go and edit
/// — where the retired head word named the field from outside and could only land on its own ident.
#[derive(Debug, Clone)]
pub struct Elected {
/// The elected field, carrying the ident's own span — which is where both refusals about it land.
pub field: syn::Ident,
/// ONE embedding or a SET of them, as the FIELD's own label states it — see [`ElectionLabel`].
pub label: ElectionLabel,
/// The field's declared type, VERBATIM and unread.
///
/// Every emitted projection goes through it — `<#ty as EmbeddingMarker>::…` — so the tokens are
/// the declaration's and a type with no impl is `E0277` at the author's own spelling, carrying the
/// trait's teaching sentence rather than one this crate guessed at.
pub ty: syn::Type,
/// `semantics(fold(sum))` / `semantics(fold = "app::MyFold")` — this election's DECLARATION-LEVEL
/// fold, and [`None`] where it wrote none and takes the shipped default.
///
/// # The KEY is the semantic KIND, and the value is an implementation
///
/// A *semantics* is a kind of decision a query makes, and the FOLD — how `m` per-query numbers
/// become one — is the first of them. So the word is keyed: the key names the kind, out of a
/// vocabulary this framework closes, and the value names an IMPLEMENTATION, out of a set nobody
/// closes. A second kind arrives as a second key and collides with nothing.
///
/// # It is the ELECTION's, and only a SET election has one
///
/// A single embedding has one best per query vector, so there is nothing to fold and the word is
/// refused on an `embedding`-labelled field by name. The chain it takes part in is
/// *query explicit > this > the shipped `Sum`*.
pub fold: Option<Fold>,
/// `knn(searchable(tower = "…"))` — the TOWER a question is walked through to reach this
/// column, and [`None`] where the election wrote none.
///
/// # It is the SUGAR's word, and this emission spends none of it
///
/// A road here does not change one token of what [`IndexModel::emit`] writes. What reads it is the
/// front end, which forges the `#[ingraph::search]` recipe the author would otherwise have
/// written by hand and puts it through the unchanged recipe pipeline — so the model carries the
/// word for the same reason it carries every other one: a second front end must be able to state
/// the same declaration.
///
/// A TYPE and not a path, matching the arm word it becomes: the tower is a type this pass cannot
/// resolve, and every claim about it — that it IS a tower, what it is asked, what it answers, and
/// whether that answer meets these coordinates — is the compiler's at the binding.
pub tower_road: Option<syn::Type>,
}
impl Elected {
/// One election, as the front end read it: the field, its label, its type and its fold.
///
/// PLAIN, for the model's own reason — nothing is parsed here and nothing is checked, so the
/// derive today and a manifest front end later build the same one.
///
/// # NOTHING IS READ OFF THE TYPE
///
/// An earlier round read `E`, `N` and `S` out of the field's spelling, after stripping a `Vec<…>`
/// to find out how many of them there were. That is a macro guessing at a meaning only rustc has:
/// `type ClipFrames = Vec<Embedding<f32, 768, Clip>>` read as *not an embedding*, and a downstream
/// carrier read as nothing at all. The reader is gone, the shape comes from the LABEL, and every
/// other fact is projected through `EmbeddingMarker` in the emission.
#[must_use]
pub const fn new(
field: syn::Ident,
label: ElectionLabel,
ty: syn::Type,
fold: Option<Fold>,
) -> Self {
Self {
field,
label,
ty,
fold,
tower_road: None,
}
}
/// The TOWER ROAD this election named — [`Elected::tower_road`], set.
///
/// Beside [`new`](Self::new) rather than inside it, because the road is the ONE word of an
/// election that most declarations do not write: a fifth parameter would put a `None` at every
/// call site that has nothing to say, which is a token a reader has to decode rather than one
/// that carries a fact.
#[must_use]
pub fn asked_through(mut self, tower: syn::Type) -> Self {
self.tower_road = Some(tower);
self
}
}
/// A LABELLED FIELD no election names — the field, its type and the label it wrote.
///
/// See [`IndexModel::labelled`] for why one is accepted at all. It carries no `fold`: that word
/// qualifies an ELECTION, and this field is not one.
#[derive(Debug, Clone)]
pub struct Labelled {
/// The field, carrying the ident's own span.
pub field: syn::Ident,
/// ONE embedding or a SET of them, as the field's label states it.
pub label: ElectionLabel,
/// The field's declared type, VERBATIM and unread — what the audit is written against.
pub ty: syn::Type,
}
impl Labelled {
/// One labelled field, as the front end read it.
#[must_use]
pub const fn new(field: syn::Ident, label: ElectionLabel, ty: syn::Type) -> Self {
Self { field, label, ty }
}
}
/// ONE SUBJECT a retrieve answers about — the pair of method names it is spelled under, and the
/// grain it queries at.
///
/// It exists because the two retrieving kinds differ in CARDINALITY and not only in flavour, and
/// because ONE kind now differs from itself: a full-text declaration has a whole-subject subject and
/// one per elected field, and an embedding declaration has one per elected column. Collapsing them
/// here rather than at the emission is what keeps the pair of methods ONE `quote!` — so the shared
/// half of the pipeline cannot drift between the kinds, which is the parity claim the flavour test
/// pins.
struct Subject<'a> {
/// Tier A's emitted name.
keys: syn::Ident,
/// Tier B's emitted name.
whole: syn::Ident,
/// What the doc line adds to name this subject — empty where there is nothing to distinguish.
about: String,
/// WHICH grain this subject asks at, and it is the one thing the two kinds' subjects disagree
/// about.
grain: Grain<'a>,
}
/// WHAT a subject narrows to — the third axis beside the pair's names and its doc line.
///
/// The two retrieving kinds narrow at different grains and by different mechanisms, and this is
/// where that is stated once: a knn is told a [`VectorColumn`] and a search is handed a
/// [`FulltextSubset`], so an emission reading this enum writes the right call for each without a
/// second `match` on the node's kind.
enum Grain<'a> {
/// The whole subject — every searchable column the slot holds. The full-text kind's unsuffixed
/// pair, and the `All` the seam takes.
Whole,
/// ONE searchable field, by name — the full-text kind's per-field pair, which mints a one-element
/// subset rather than taking one.
Column(&'a syn::Ident),
/// ONE ELECTION's coordinates — the vector kind's per-field pair, which mints its own
/// `VectorColumn`.
Election(&'a Elected),
}
/// WHICH QUERY FIELD one election mounts, and the engines the resolver behind it names.
///
/// Two arms because the two roads call two different doors with two different answer shapes — a
/// ranked list of addresses against ONE store, and a fused one across every store a fanned field is
/// written to. The engines are carried rather than re-derived, so the predicate that CHOSE the road
/// and the emission that writes it cannot come to disagree about which legs are in it.
///
/// Named for the ROAD rather than for the door, because a road is the pair *(what a client sends,
/// what it reads back)* and the door is one call inside it.
enum AnswerRoad<'a> {
/// ONE TYPED ENGINE, unfanned, over a UNIT election — `retrieve_keys_by_<field>` and
/// `retrieve_similar_by_<field>`, answering `[<Key>Match!]!`.
Plain(&'a Engine),
/// The SAME ENGINE over a SET election — the question road unchanged, and the BY-EXAMPLE road
/// answering `[<Key>FoldedMatch!]!` out of `retrieve_similar_by_<field>_with`.
///
/// A road of its own rather than a flag on [`Plain`](Self::Plain), because the two differ in what
/// their by-example half ANSWERS: one hit shape carries a rank and the other carries `m`
/// per-stream sightings, and a shape that hung off a boolean read at the leg would be the label
/// decided twice.
Set(&'a Engine),
/// EVERY LEG of a fanned slot, all typed — `vector_fuse_by_<field>`, answering the fused hit.
Fanned(Vec<&'a Engine>),
}
/// A validated derived index: which storage it is, what it draws from, and the fields it declares.
///
/// PLAIN, for [`RecordModel`](crate::model::RecordModel)'s reason — public fields, no constructor,
/// nothing that parses — so the derive today and a manifest front end later build the same one.
#[derive(Debug, Clone)]
pub struct IndexModel {
/// The EMISSION NAMESPACE this declaration's minted names wear.
///
/// [`EmissionPrefix::INGRAPH`] for everything `ingraph`'s own front ends build, and a domain
/// framework's own mark for a model `mediagraph-codegen` or its successors build — see
/// [`crate::prefix`] for what the seat covers and why it is a field rather than a constant.
pub prefix: EmissionPrefix,
/// The index's own name — the declaration this model came from.
pub index: syn::Ident,
/// WHICH of the three storages this is.
///
/// Spent on the sentences a front end writes, on which SEAM the emitted doors name — a full-text
/// engine or a vector one — and on nothing else this emission does: all three mint the one-storage
/// marker and all three carry the upstream's key. WHICH engines hold the documents is no longer
/// read off the kind at all: it is [`engines`](Self::engines), declared per field.
pub kind: NodeKind,
/// How visible the index is, and therefore how visible each emitted method is.
///
/// Mirrored rather than fixed at `pub`, exactly as a record's: no one can widen a type they did
/// not declare.
pub vis: syn::Visibility,
/// The path to the `ingraph` crate itself — `::ingraph` unless `crate = "…"` named another.
pub krate: syn::Path,
/// The ONE upstream this index draws from, and what it takes from it.
///
/// One rather than a list: several upstreams key a derived index by an ENUM over their keys, and
/// the field that carries it is a different field of a different type. The model holds what this
/// emission spends.
pub source: Upstream,
/// The dedup MECHANISM a retrieve over this index runs — the `dedup(…)` word, or its default.
///
/// Spent by the two emitted retrieve methods and by nothing else, which is also why it is on the
/// model rather than on [`Upstream`]: it is a property of how this node ANSWERS, not of where its
/// documents came from.
pub dedup: Dedup,
/// WHICH fields a knn over this index may run over — every `knn`-marked field, on the one kind
/// that has any.
///
/// NON-EMPTY on every VECTOR declaration and EMPTY on the other two, and the asymmetry is the
/// marker's own: it is mandatory where it applies and refused by name where it does not, so a
/// front end that produced an empty list for a vector has already refused the declaration. In
/// DECLARED order, which is the order the emitted columns and the record face are written in.
///
/// A LIST rather than one, because a declaration may elect several and each is queryable — see
/// [`Elected`] for the geometry that carries them and for why the role is declared rather than
/// read off the type.
pub embeddings: Vec<Elected>,
/// Every LABELLED field NO election names — the forward declarations, in declared order.
///
/// # A label on payload is ACCEPTED, and that is a ruling rather than an oversight
///
/// The label states a STRUCTURAL fact about a field — one embedding, or a set of them — and the
/// party that will spend it is not only the query side. A storage layer that lays a set out
/// differently from a single vector, or that carries a weight per member, reads the same fact
/// about a field nothing queries. So a labelled field with no election is a declaration made
/// EARLY rather than a word nobody reads, and this crate's usual refusal — *a word parsed into a
/// model nothing spends is a promise rather than a rule* — does not reach it.
///
/// What the acceptance does NOT buy is a face: no column, no door, no projection. The election
/// marker is still what grows those, and a labelled payload field is hydrated by its own accessor
/// exactly as an unlabelled one is.
///
/// ACCEPTED IS NOT UNEXAMINED. The label's claim is audited here as it is on an election, so a
/// payload field labelled `list(embedding)` over a single embedding is `E0277` at its own type.
pub labelled: Vec<Labelled>,
/// WHICH fields a search over this index runs over — every `searchable`-marked field, on the one
/// kind that has any.
///
/// [`embeddings`](Self::embeddings)' mirror one kind over, and the same law: NON-EMPTY on every
/// FULL-TEXT declaration, EMPTY on the other two, in DECLARED order.
///
/// # Idents rather than an [`Elected`], and the asymmetry is the ENGINE's rather than this model's
///
/// An election carries what the EMISSION has to read off it, and the two kinds hand over different
/// amounts. A knn's column is opened at an element and a width, so `Elected` carries `E`, `N` and
/// the space it lives in — every one read off the field's own type, all three spent on the query
/// type the emitted pair takes. A search takes a STRING, and what a searched field must BE is not
/// this crate's to say: [`FulltextRecord::Document`](https://docs.rs/ingraph) is deliberately
/// bound by nothing, *what a document must be is the searching engine's question*. So the name is
/// the whole of what a full-text election has to carry, and inventing a shape for it here would
/// answer that question for engines that have not arrived.
///
/// What it is SPENT on is BOTH halves of the read face. The whole-subject pair's doc line names
/// the fields it searches — the sentence that used to say *every projection* — and each name in
/// this list also mints its own `retrieve_keys_by_<field>` / `retrieve_by_<field>` pair, at vector
/// parity, narrowing to a one-column `FulltextSubset`. The selector the per-field doors waited on
/// is the seam's now: `FulltextRead::search` takes the subset beside the query.
pub searchable: Vec<syn::Ident>,
/// WHERE each elected field is written — one entry per election, in declared order, carrying the
/// engine blocks that field wore and whether all of them are live at once.
///
/// ONE list over BOTH kinds, kept in step with the elections above by construction: the engine
/// grammar is one grammar, and a knn's field and a search's field name their engines alike. An
/// election that named NO engine has an entry with an empty list — declaring none is legal, and
/// means the deployment says instead, which is what a record with no `persist(…)` means one family
/// over.
///
/// See [`engine`](crate::engine) for the semantics this carries: several blocks are declared
/// PORTABILITY, the default is SINGLE-WRITE, and [`fanout`](FieldEngines::fanout) is the one
/// departure.
pub engines: Vec<FieldEngines>,
/// WHERE an ARTIFACT FAMILY's objects are written — the engine blocks a `blob` declaration wrote
/// at its HEAD, beside `upstream(…)`.
///
/// NON-EMPTY only on a blob, and the reason it is a second list rather than an entry in
/// [`engines`](Self::engines) is that the GRAIN differs. A slot on the other two kinds is
/// `(field × engine)`, because a declaration elects several fields and each is searched
/// independently; an artifact family elects nothing and holds ONE object per message, so its slot
/// is `(declaration × engine)` and the head is the only position coarse enough to name it. Writing
/// blob engines on a field would have asked which of a payload's fields the object is — a question
/// with no answer.
///
/// The SEMANTICS are the field grammar's, unchanged: several blocks are declared PORTABILITY, the
/// deployment selects, and the default is SINGLE-WRITE. `fanout` is NOT among them — see the
/// `fanout` refusal on this kind, which names the deferral rather than pretending the word is
/// unknown.
///
/// EMPTY is legal and means the deployment says instead, exactly as a record with no `persist(…)`
/// does one family over.
pub stores: Vec<Engine>,
/// HOW this family's addresses END — the `extension` word, in whichever of its forms was written.
///
/// [`None`] is the OMITTED form and a real one: extensionless storage, which a heterogeneous
/// family takes at zero tax, its per-entry type travelling as metadata or as the host channel's
/// `Content-Type`. It is not *unset* — there is nothing to set it to.
///
/// NON-`None` only on a blob; `extension` on the other two kinds is refused by name.
pub extension: Option<Extension>,
/// WHETHER this family's BYTES may travel beside its address — the bare `data` word at the head.
///
/// An artifact family answers an ADDRESS, and the whole kind is built around that posture: what a
/// caller is handed is where the object lives, and going to get it is a second hop against the
/// store. On a family of large objects that is the only sane answer — nothing wants a video
/// inlined into a response. On a family of small ones the hop costs more than the bytes it fetches,
/// and a thumbnail served as an address alone is a round trip bought for nothing.
///
/// `data` is where a declaration says which of the two it is. WRITTEN, this family's object may be
/// served inline — base64, BESIDE the address rather than instead of it, so nothing a caller could
/// already reach stops being reachable. OMITTED, the address is the whole of what is served, and
/// that is a real form rather than an unset field: it is the default because it is the one that
/// cannot hand anybody a payload they did not ask for.
///
/// A BOOL because the word carries nothing — no value and no block, since *these bytes may be
/// served* has no knob inside it. MAY rather than WILL is the deliberate half: what a DECLARATION
/// can settle is whether inline bytes are on the table for this family at all.
///
/// `false` on the other two kinds ALWAYS — `data` there is refused by name, for
/// [`data_wrong_kind`]'s reason.
pub data: bool,
/// Whether this declaration's upstream is an ENTITY, so its dressed answer family mounts the KEYS
/// TIER ALONE — the `keys` word.
///
/// # The word declares a TIER FACT, and the two clocks are why one exists at all
///
/// A dressed election answers each road twice: the KEYS tier hands back addresses and touches no
/// store, the HYDRATED tier hands back the upstream's whole entities and reads them out of one.
/// The hydrated pair projects `<Upstream as Hydrates>::Db`, whose impl only a record with a
/// queryable row emits — so which tiers this declaration can mount is decided by which RUNG of the
/// record ladder its upstream sits on, and the two derives cannot see each other.
///
/// `false` — a RECORD upstream — mounts BOTH, unconditionally and with no word to write: rows are
/// a record's essence now, so storage is guaranteed and hydration can never miss. `true` — an
/// ENTITY upstream — mounts the keys tier, which is the pure-engine deployment's honest home: a
/// search surface over a node whose messages land in no database anywhere.
///
/// A declaration that has an entity upstream and writes NO word is not silently narrowed. The
/// hydrated demand is emitted, the compiler cannot satisfy it, and the `E0277` lands at
/// `upstream(node = "…")` carrying `Hydrates`' own sentence — which names both exits, persist the
/// upstream or wear the word. Guessing here would be this crate deciding a deployment's storage
/// posture from what happens to compile.
///
/// `false` on `blob` ALWAYS: an artifact family answers an address rather than a ranking, so it
/// mounts no tier pair for the word to narrow, and the word is refused there by name.
pub keys: bool,
/// **WHETHER THIS DECLARATION LAUNCHES** — the bare `subscribe` word at the head.
///
/// `false` is the HAND ROAD and it is the shipped one: the declaration mints its corpora, its
/// slot markers and its search doors, and a deployment fills those corpora through the branded
/// handle itself. Every expansion this crate wrote before the word existed is that road, and none
/// of them moves — subscription is purely additive, so the emission below is the only thing the
/// word adds and nothing it touches is rewritten.
///
/// `true` mints a NODE beside the declaration — see
/// [`subscriber`](IndexModel::subscriber) — which the deployment mounts like any other, and which
/// receives the upstream's messages, projects them per this declaration's own `upstream(…)`
/// entries, and lands them in the corpora this declaration already names.
///
/// `false` on every kind but `fulltext`, where the word is refused by name: the write lane is a
/// per-family seam and the full-text one is the family with a live engine behind it.
pub subscribe: bool,
/// WHICH GRAPHQL BACKENDS this declaration is dressed for — see [`IndexGraphql`] for the law the
/// word states.
///
/// [`None`] is *no wire face*, and it is a real form rather than an unset field: a declaration
/// with no block emits every Rust type and every door it would otherwise emit, and emits no wire
/// impl for any of them. Nothing is missing programmatically — what is missing is a schema, which
/// is what a backend-only search pipeline wants.
pub graphql: Option<IndexGraphql>,
/// THE CONTAINER TIER's numbers — `limit`, `depth` and `ceiling` written at the head.
///
/// Empty is the ordinary state and means the framework's own answers stand; see [`Numbers`] for
/// the trichotomy the three words divide into, and [`wire_first`](Self::wire_first) /
/// [`pool_depth`](Self::pool_depth) / [`declared_ceiling`](Self::declared_ceiling) for the three
/// chains that read them.
pub numbers: Numbers,
/// THE ELECTION TIER's numbers, one entry per field that wrote one — in the order the declaration
/// wrote the fields.
///
/// A field with nothing written on it has NO entry rather than an empty one, so the list is
/// exactly what a declaration said and a chain that finds nothing falls to the container.
pub field_numbers: Vec<FieldNumbers>,
/// WHAT THIS DECLARATION'S MINTED RUST TYPES ARE CALLED — see [`IndexRename`].
///
/// [`None`] is *the declaration's own ident is the base*, which is where this family started and
/// is what every declaration written before the word arrived means.
pub rename: Option<IndexRename>,
/// WHAT THIS FAMILY'S CORPUS IS CALLED WHERE IT IS STORED — the `slot = "…"` word, blob only.
///
/// # A DURABLE name, which is the whole reason it is not the Rust `rename`
///
/// The slot is the directory an artifact family's objects live under, and it survives every
/// rebuild: two deployments of one declaration address the same objects because they agree on
/// this string. So it is deliberately NOT moved by [`rename`](Self::rename) — a Rust word
/// repointing a live store would be a rename that loses data — and it is deliberately additive:
/// the DEFAULT stays `snake_case(<declaration name>)`, which is what every family written before
/// the word arrived is stored under.
///
/// [`None`] is that default rather than an unset field. Non-`None` only on a blob: the other two
/// kinds' slots are `(field × engine)` pairings and a declaration-level word is the wrong grain
/// for one, which the front end says by name.
pub slot: Option<syn::LitStr>,
/// EVERY field the index declares, in declared order — the injected key field is NOT among them,
/// being the emitter's rather than the declaration's.
///
/// A [`Column`] rather than a [`Field`](crate::model::Field), for
/// [`FieldsModel`](crate::fields::FieldsModel)'s reason: a `Field` carries `identity` and a
/// `reference`, and every field here is on the same side of an identity it does not hold.
pub fields: Vec<Column>,
}
/// The upstream a derived index draws from, and which of its fields each of the index's own is read
/// out of.
#[derive(Debug, Clone)]
pub struct Upstream {
/// The upstream node, as the declaration spelled it.
///
/// Carried VERBATIM and resolved nowhere in this crate. It is emitted, and the spans it carries
/// are the authored string's — so every error about it lands where the author can edit it.
pub node: syn::Path,
/// One entry per field of the index, in declared order.
pub projections: Vec<Projected>,
}
/// One field of the index, and the upstream field it is read out of.
#[derive(Debug, Clone)]
pub struct Projected {
/// The INDEX's own field.
pub field: syn::Ident,
/// The UPSTREAM's field, carrying the span of the string that named it — which is the span every
/// refusal about this projection lands at.
pub from: syn::Ident,
/// The index field's declared type, which is the audit's RETURN type: a projection that reads the
/// wrong shape out of the upstream is `E0308` here rather than a mismatch inside a store.
pub ty: syn::Type,
}
/// WHICH GRAPHQL BACKENDS DRESS THIS DECLARATION — the `graphql(…)` block, or [`None`] where the
/// declaration named none.
///
/// # The word gates the SKIN and never the BONES
///
/// Without a block the RUST surface emits WHOLE: the doors, the packages, the evidence, the
/// selector and the [`Fusable`](https://docs.rs/ingraph) binding are all there, and a pipeline
/// driven from Rust is missing nothing. What the word buys is one backend's WIRE IMPLS over those
/// same types — the hand-written `InputType` / `@oneOf` / enum faces, and the registry entries the
/// SDL is read out of.
///
/// That is why a backend WORD is what the block holds rather than a bare `graphql`: the framework
/// renders through several, the types are backend-NEUTRAL, and each declared word adds one skin over
/// the one set of bones. The `__<backend>_` ident prefix is what keeps two coexisting skins from
/// colliding, and it is reserved per backend for exactly this.
#[derive(Debug, Clone)]
pub struct IndexGraphql {
/// The backends this declaration named, in the order it wrote them.
///
/// A LIST rather than one, because the block is *which skins*, and a declaration that grows a
/// second word grows a second skin over the types it already had. EMPTY is the bare `graphql`
/// spelling, which names no backend and therefore dresses nothing — refused at the front end,
/// where the sentence can name the words on offer.
pub backends: Vec<IndexBackend>,
}
impl IndexGraphql {
/// A block naming ONE backend — the shape a declaration writing `graphql(async_graphql)` builds.
#[must_use]
pub fn of(kind: GraphqlKind) -> Self {
Self {
backends: vec![IndexBackend::of(kind)],
}
}
/// Whether this declaration named `kind`.
#[must_use]
pub fn renders(&self, kind: GraphqlKind) -> bool {
self.backends.iter().any(|backend| backend.kind == kind)
}
/// `kind`'s block, or [`None`] where this declaration named that backend nowhere.
#[must_use]
pub fn skin(&self, kind: GraphqlKind) -> Option<&IndexBackend> {
self.backends.iter().find(|backend| backend.kind == kind)
}
}
/// THE FOUR NUMBERS a declaration writes about its own doors — the BONES tier of the wire road's
/// number design.
///
/// ```text
/// #[ingraph::vector(upstream(…), limit = 50, depth = 200, ceiling = 1000)] the CONTAINER
/// pub struct Shots {
/// #[ingraph(list(embedding), knn, lance, limit = 10, streams = 16)] the ELECTION
/// clips: Vec<Embedding<f32, 4, Clip>>,
/// }
/// ```
///
/// # The TRICHOTOMY, which is what makes several words rather than one
///
/// `limit` and `depth` are PREFERENCES — an author's semantic defaults for every door of the thing
/// they are written on, and a request may write past either. `ceiling` and `streams` are PROTECTION
/// — the #293-B ruling's WALL and the 2026-08-16 SET ruling's stream guard, upper bounds on what any
/// one request may cost this deployment, which a request may never rewrite because a bound the
/// requester can rewrite binds nothing.
///
/// The two families sit in one struct because they are written in one position and read by one
/// chain; what keeps them apart is where each is SPENT — a preference lands as an SDL default a
/// client overrides, and neither protective number reaches any wire row at all.
///
/// # The two protective words bound two INDEPENDENT axes, which is why there are two
///
/// `ceiling` caps HOW DEEP one stream is walked and `streams` caps HOW MANY streams there are. The
/// ruling that minted the second said so in the user's own words — *一词多义* — and the measurement
/// behind it is that one number cannot serve both: a per-stream depth of 500 under a stream cap of 16
/// is unspellable as a single widened ceiling.
///
/// # `NonZeroU32` and not a plain integer, at both tiers
///
/// The door family's currency is `NonZeroUsize` and a declaration's is `NonZeroU32` — the width
/// `route_depth` already takes a wall at, chosen there because a declaration writes a number a
/// person typed rather than a machine's address space. A zero is UNREPRESENTABLE rather than
/// refused twice over: `limit = 0` asks for an answer with no rows, which the retype round made a
/// type error everywhere else in this family.
///
/// # And `first` is still not one of these
///
/// `first` is the SAME NUMBER as `limit` wearing GraphQL's own spelling, so it lives in the skin
/// block ([`IndexBackend::first`], [`ElectionBackend::first`]) and never here. Q6a's own sentence:
/// *first 是 graphql 的术语*.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Numbers {
/// `limit = N` — how many rows a door of this thing answers with when nothing asks otherwise.
pub limit: Option<core::num::NonZeroU32>,
/// `depth = N` — how deep each stream behind a fold is fetched when nothing asks otherwise.
///
/// [`None`] falls to the limit chain, which is the same deferral `Route::depth` spells one grain
/// up: there is no number that means *as deep as whatever is below me*.
pub depth: Option<core::num::NonZeroU32>,
/// `ceiling = N` — the WALL, and the one number here a request can never reach.
///
/// [`None`] is the AUTHOR'S INFORMED OPENNESS rather than a gap the framework fills: the engine's
/// own corpus clamp is the final safety, exactly as the #293-B ruling states it.
pub ceiling: Option<core::num::NonZeroU32>,
/// `streams = N` — HOW MANY QUERY VECTORS one request may ask a `_with` road with.
///
/// PROTECTION beside [`ceiling`](Self::ceiling) rather than a preference beside `limit`: the
/// number bounds what a REQUEST states, so a request able to rewrite it would bound nothing. Past
/// it is a REFUSAL naming the count and never a clamp — the ruled clamp-vs-refuse line is *clamp
/// preferences, refuse mutilated questions*, and dropping query vectors answers a different
/// question under the same name.
///
/// It guards the `_with` QUESTION road ALONE. The by-example set road's `m` comes out of the
/// example's own stored set, which is this deployment's own data rather than anything a request
/// can inflate — see [`IndexModel::similar_set_leg`], whose doc states the same absence.
///
/// [`None`] is `ceiling`'s own reading of an unwritten word: no guard is emitted at all, and the
/// road is byte-for-byte what it was before the word existed.
///
/// The wire ROW called `streams` on a set hit is a DIFFERENT word in a different vocabulary — see
/// `ingraph_derive::index::FLOOR_WORDS`, where it is the framework's own answer row and is refused
/// every rename. One concept, a bones word and a wire surface, which is `depth`'s own precedent.
pub streams: Option<core::num::NonZeroU32>,
}
impl Numbers {
/// Whether this tier wrote nothing at all — the ordinary state, and what a front end builds for a
/// declaration that names no number.
#[must_use]
pub const fn is_empty(&self) -> bool {
self.limit.is_none() && self.depth.is_none() && self.ceiling.is_none() && self.streams.is_none()
}
}
/// **THE FRAMEWORK'S OWN ANSWER TO *HOW MANY*** — the floor of the wire default's chain, and the
/// number a schema publishes where no tier of a declaration wrote one.
///
/// Twenty, on the Q6a/Q6b ruling's own words (*框架默认就设置 20 吧*). It is a CODEGEN constant and
/// not a runtime one, which is the whole of why it may exist at all: what spends it is
/// [`IndexModel::wire_first`], whose answer becomes an SDL LITERAL — so the number is written into
/// the schema at expansion and no door, seam or fold ever reads it. The homelessness #292-E ruled
/// deliberate ends exactly here and nowhere wider: `DEFAULT_LIMIT` does not come back to the seam.
pub const FRAMEWORK_LIMIT: core::num::NonZeroU32 = match core::num::NonZeroU32::new(20) {
Some(twenty) => twenty,
None => panic!("twenty is not zero"),
};
/// ONE FIELD's numbers, and the skins that dress them — the ELECTION tier.
///
/// A list parallel to [`FieldEngines`](crate::engine::FieldEngines) rather than a member of
/// [`Elected`], and the reason is that BOTH KINDS elect: a vector declaration's elections are
/// [`Elected`] values and a full-text declaration's are bare idents
/// ([`searchable`](IndexModel::searchable)), so a per-field fact both kinds carry has no one struct
/// to sit inside. The engine list solved that same problem the same way, and one shape for
/// per-field facts is what keeps a reader from having to learn two.
#[derive(Debug, Clone)]
pub struct FieldNumbers {
/// The election these numbers are about.
pub field: syn::Ident,
/// What this field wrote — the BONES tier's own words.
pub numbers: Numbers,
/// `graphql(<backend>(first = N))` ON THE FIELD — the SKIN tier, one entry per backend named.
pub skins: Vec<ElectionBackend>,
}
impl FieldNumbers {
/// A field's entry with nothing written on it.
#[must_use]
pub fn of(field: syn::Ident) -> Self {
Self {
field,
numbers: Numbers::default(),
skins: Vec::new(),
}
}
/// `kind`'s block on this field, or [`None`] where the field named that backend nowhere.
#[must_use]
pub fn skin(&self, kind: GraphqlKind) -> Option<&ElectionBackend> {
self.skins.iter().find(|backend| backend.kind == kind)
}
}
/// ONE backend's block on an ELECTION — `graphql(async_graphql(first = 20, keys(rename = "…")))`.
///
/// The field-level twin of [`IndexBackend`], and it exists for that one's reason: a wire default is
/// the SKIN's fact, so it lives in the block that names the skin, and a second backend sets its own
/// without touching the first's.
///
/// # ONE GRAMMAR FOR EVERY NAME SEAT, and `first` is not one of them
///
/// The 2026-08-16 ruling, in the user's own words — *不要有糖, 糖留给以后其他东西, rename 不值得一个
/// 糖*. Every seat here that names something is a BLOCK carrying a bare `rename = "…"` row, so a
/// reader who has learnt one has learnt all of them and the flat position stays free for whatever
/// later earns it. [`first`](Self::first) keeps its flat spelling because it is a COUNT: there is no
/// name for a `rename` row to carry, and `first(rename = 20)` would be a sentence about renaming a
/// number.
///
/// # The seats split by WHAT each names: two TYPES and five ROADS
///
/// [`question`](Self::question) and [`engines`](Self::engines) name TYPES this election mints — the
/// two a request builds by hand. The five road seats name QUERY FIELDS, one per road an election can
/// mount, which is [`Field`]'s own vocabulary read as a grammar: five roads, five words, and no
/// composition between any two of them.
#[derive(Debug, Clone)]
pub struct ElectionBackend {
/// The backend this block dresses the election for.
pub kind: GraphqlKind,
/// `first = N` — the GraphQL-term spelling of the number [`Numbers::limit`] carries, and the
/// literal this field's query arguments publish as their SDL default.
///
/// SKIN and never bones: `first` is GraphQL's own word for *how many*, so it has no business at a
/// Rust-facing tier — a hand-caller's number is the positional `limit` the doors already take.
///
/// FLAT where every neighbour is a block, and the asymmetry is the ruling's: a block exists to
/// hold a `rename` row, and a count has no name to move.
pub first: Option<core::num::NonZeroU32>,
/// `question(rename = "…")` — what this backend calls `<Index><Field>Question`, the `@oneOf` a
/// request names a point with.
///
/// # The TYPE moves and the ARGUMENT WORD does not, which is law 3's whole line
///
/// The parameter is spelled `question:` in every schema this framework writes, on every road, at
/// every declaration — the UNIFORM FLOOR, and the argument words are Relay's precedent read one
/// grain down. What a client cannot predict is the type BEHIND that argument, because it is minted
/// per election and per declaration; that one is nameable, and this is the seat.
///
/// A [`syn::LitStr`] on the 2026-08-13 ruling every SDL rename in this workspace carries: the word
/// names a type in GraphQL's own namespace and nothing in Rust, so a Rust keyword is an ordinary
/// word here.
pub question: Option<syn::LitStr>,
/// `engines(rename = "…")` — what this backend calls `<Index><Field>Engines`, the PRODUCT a fused
/// read states one floor per leg in.
///
/// [`question`](Self::question)'s twin over the other per-election argument type, and PLURAL for
/// the shape it names: the selector beside it is a SUM over one leg and this names them ALL,
/// because a fused road walks every leg and each one needs a floor in its own currency.
///
/// Distinct from [`IndexBackend::engine`], which names the `@oneOf` SELECTOR at the head. The two
/// words differ by a letter and name two shapes; the near-miss line is what tells an author which
/// position they are at.
pub engines: Option<syn::LitStr>,
/// `sighting(rename = "…")` — what this backend calls `<Index><Field>Sighting`, the wire UNION a
/// fused answer's evidence list holds.
///
/// # An ANSWER-side type, which is why it is a seat rather than a floor word
///
/// The two seats above name types a REQUEST builds; this one names a type a request READS. Both
/// are the same KIND of name and are nameable for the same reason: the union is minted per
/// election and per declaration, so no client could predict it, while the uniform floor covers the
/// ROW WORDS a client writes (`score`, `evidence`, `node`) rather than the types behind them.
///
/// The ARMS take no seat of their own. Each is `<Index><Field><Engine>Sighting`, derived from the
/// leg's own word, so one word here would move a SET of types — exactly the shape
/// [`IndexBackend::engine`] is refused for on a declaration that types two fields. A declaration
/// that wants the arms moved moves the leg words, which are its own.
pub sighting: Option<syn::LitStr>,
/// `fused_key_match(rename = "…")` — what this backend calls `<Index><Field>FusedKeyMatch`, the
/// ROW a fused read answers with: the address, the fused score, and the evidence list.
///
/// [`sighting`](Self::sighting)'s twin over the other half of the fused answer, and a seat of its
/// own for the reason every road pair in this block has two: the two types are two names in one
/// namespace, and a declaration that renamed the union has said nothing about the row carrying it.
///
/// The word is SNAKE-CASED where its neighbours are single nouns, which is the minted name read
/// back: `FusedKeyMatch` is three words, and a word spelling only one of them would name a type
/// its author could not find.
pub fused_key_match: Option<syn::LitStr>,
/// `keys(rename = "…")` — what this backend calls the KEYS query field this election publishes,
/// replacing the derived `<index>By<Field>Keys` VERBATIM.
///
/// # A FIELD name, which is why it is not the type-renaming axis
///
/// [`IndexRename`] moves RUST types and the two seats above move SDL type names; a query field is
/// neither. It is a name in the ROOT's own namespace, where every mounted declaration's fields
/// meet — so two declarations electing a field of the same name are the collision this word
/// exists to break, and it has to be sayable per field and per backend.
///
/// A [`syn::LitStr`] and never an ident, on the 2026-08-13 ruling the type-level renames already
/// carry. Carried VERBATIM — the derived name is composed from three parts and a word that
/// replaced only one of them would be a rename an author could not predict.
pub keys: Option<syn::LitStr>,
/// `hydrated(rename = "…")` — the same word over the TIER BELOW that road: `<index>By<Field>`,
/// the question answered with the upstream's whole entities.
///
/// A SEAT OF ITS OWN and never a composition off [`keys`](Self::keys), which is what the verbatim
/// law forces: a declared word is carried exactly as written, so a name derived from the keys
/// word — `clipNeighbours` → `clipNeighboursHydrated` — would be a rename its author could not
/// predict from what they typed. Two names in one namespace need two words or none.
pub hydrated: Option<syn::LitStr>,
/// `fused(rename = "…")` — the same word over the FUSED keys field, which exists where the
/// election is fanned across two or more typed stores.
///
/// A separate seat because the two fields are two names in one namespace: a declaration renaming
/// its plain road has said nothing about its fused one, and a single word would have to move both
/// or neither.
pub fused: Option<syn::LitStr>,
/// `similar(rename = "…")` — the same word over the BY-EXAMPLE keys field, which exists wherever
/// the plain road does.
///
/// The seats above's own argument, read one road further: the by-example field is a name in the
/// same root namespace, and a declaration that renamed the road asked with a QUESTION has said
/// nothing about the road asked with a KEY. It cannot share the fused word either — a fanned
/// election publishes both, so one word would have to move two live names at once.
pub similar: Option<syn::LitStr>,
/// `similar_hydrated(rename = "…")` — the by-example road's own tier below: `<index>SimilarBy<Field>`.
///
/// [`hydrated`](Self::hydrated)'s reason unchanged. It is ONE seat over TWO emitted shapes — the
/// single-vector road and the SET road — because a declaration publishes one or the other and
/// never both, so *which shape ran* is not a question a name has to answer.
pub similar_hydrated: Option<syn::LitStr>,
}
impl ElectionBackend {
/// A backend named on a field and nothing else said about it.
#[must_use]
pub const fn of(kind: GraphqlKind) -> Self {
Self {
kind,
first: None,
question: None,
engines: None,
sighting: None,
fused_key_match: None,
keys: None,
hydrated: None,
fused: None,
similar: None,
similar_hydrated: None,
}
}
/// What this block calls `which`'s query field, or [`None`] where it named that road nothing.
///
/// The ROAD LOOKUP, spelled once: [`Field`] is a closed five and so are the seats, so a road added
/// to one without the other is a `non_exhaustive`-free match arm the compiler asks about here
/// rather than a name silently falling back to the derived one.
#[must_use]
pub fn road(&self, which: Field) -> Option<&syn::LitStr> {
match which {
Field::Keys => self.keys.as_ref(),
Field::Hydrated => self.hydrated.as_ref(),
Field::Fused => self.fused.as_ref(),
Field::Similar => self.similar.as_ref(),
Field::SimilarHydrated => self.similar_hydrated.as_ref(),
}
}
}
/// ONE backend's block inside a derived index's `graphql(…)`.
///
/// # Every name here is a SKIN's, and none of them moves a Rust type
///
/// The axis law, as the model holds it: a name is the SKIN's fact, so it lives in the block that
/// names the skin — one block per backend, and a second backend renames its own schema without
/// touching the first's. The Rust family is re-based by the TOP-LEVEL `rename`, which never appears
/// in here.
///
/// # THE RECORD-SIDE PLACEMENT AUDIT, and the divergence it found
///
/// The round asked for this comparison and for the divergence to be aligned or written down. It is
/// written down, because the two families differ in the fact that decides the placement.
///
/// A RECORD's SDL renames sit at the DOMAIN level of its own `graphql(…)` — `rename`, `plural`,
/// `output(rename = …)`, `key`/`filter`/`order_by(rename = …)`, `connection`, `edge`. Its BACKEND
/// block accepts a `rename` too, and that word is parsed and never read: the record's own note says
/// so out loud — *kept because the grammar takes it, and unread because the emitted types are ONE
/// per record: the SDL is identical whichever Rust library serves it*.
///
/// So the record's placement is not a competing design; it is the same design under a premise this
/// family does not share. A record emits one set of wire types and asserts every backend renders
/// them identically, which makes a domain-level name correct and a backend-level one redundant. A
/// derived index's ruled posture is the opposite — one skin per word, coexisting, kept apart by the
/// `__<backend>_` ident prefix — and under that premise a domain-level SDL name would be a name
/// asserted across skins that are free to differ.
///
/// ALIGNING would mean moving the record's live renames into its backend block, which is a change
/// to the record's grammar and to every declaration that writes one; it is out of this round's
/// scope and is recorded rather than done. What this family does NOT do is copy the record's dead
/// word: there is no domain-level SDL rename here, so nothing in this grammar is parsed and
/// discarded.
#[derive(Debug, Clone)]
pub struct IndexBackend {
/// The backend this block dresses the declaration for.
pub kind: GraphqlKind,
/// `prefix = "…"` — the BASE this backend's whole SDL type family is built on.
///
/// # The WORD is `prefix` because the seat is a STEM
///
/// **`rename` names ONE thing verbatim; `prefix` re-stems a FAMILY.** This seat names no type
/// literally: the emitted types are `<base>FuseOptions`, `<base>FusedEvidence` and their siblings,
/// so what a declaration writes here is composed with a suffix and is upper-camel-cased at the type
/// positions where GraphQL's own convention is. There is no schema name equal to what an author
/// types at this position, which is the whole of why `rename` was the wrong word for it. A word
/// that names ONE type outright is a per-face override below, and those are carried verbatim under
/// their own `rename` rows.
///
/// `rename` at this position is refused BY NAME, pointing here — see `ingraph-derive`'s
/// `index_backend`, where the correction and its did-you-mean are written.
///
/// A `LitStr` and never an ident, on the 2026-08-13 ruling: this word names types in GraphQL's
/// own namespace and nothing in Rust, so a Rust keyword is an ordinary word here.
pub prefix: Option<syn::LitStr>,
/// `options(rename = "…")` — what this backend calls the package a client CONFIGURES a retrieve
/// with, whichever of the binding table's shapes that is.
///
/// The FACE and not every options package: a tier's `Fusable::Options` is the one a parent and a
/// client name, and the per-slot packages inside it are interior — re-based by the base above and
/// named by nothing here.
pub options: Option<syn::LitStr>,
/// `question(rename = "…")` — the sister tree's face, by the same table.
pub question: Option<syn::LitStr>,
/// `engine(rename = "…")` — what this backend calls the `@oneOf` selector over the typed engines.
pub engine: Option<syn::LitStr>,
/// `first = N` — the CONTAINER tier's SDL default for every query argument this skin publishes,
/// and the GraphQL-term spelling of the same number [`Numbers::limit`] carries in Rust vocabulary.
///
/// The bones/skin split ruled in Q6a: a container names `limit` and `depth` because those are the
/// words a Rust door is called with, and it names `first` HERE because that is the word a schema
/// publishes. Unwritten, the chain falls to the bones beside it — see
/// [`wire_first`](IndexModel::wire_first), which is the one place the whole order is spelled.
pub first: Option<core::num::NonZeroU32>,
//
// THE FOURTH FACE IS NOT HERE, and its absence is a measurement rather than an omission — one
// that was RE-TAKEN when the fanned road grew an answer face, and narrowed by what it found.
//
// `fused(rename = "…")` at THIS position would name `<Index>FusedEvidence<S₁, …>`, the TIER's
// fused door's evidence. That door mounts no query field: `answer_roads` walks ELECTIONS, and
// `Door::Fused`/`Door::FusedSimilar` appear in the method roster and in the Rust impl and nowhere
// on a schema. So nothing on its answer side reaches SDL, and the word would move a name that is
// not published.
//
// A fused answer DOES reach a schema now, one grain down: `vector_fuse_by_<field>` publishes
// `<Index><Field>Sighting` — a MINTED wire union, one arm per leg — beside
// `<Index><Field>FusedKeyMatch`, and the slot's evidence enum crosses INTO that union while keeping
// its own Rust-only name. Those are per-ELECTION types, so a word here would be a head word over
// a SET of them, which is exactly the shape [`engine`](Self::engine) is refused for on a
// declaration that types two fields.
//
// The word is therefore still refused at the front end, with the narrowed reason rather than the
// old one, and it opens the day the TIER's fused door mounts a road of its own. The measurement
// is pinned in `fuse::skins::the_tier_fused_door_publishes_nothing_for_a_word_to_move`, which
// reads BOTH halves so that the next arrival cannot be silent the way this one was.
}
impl IndexBackend {
/// A backend named and nothing else said about it — the `graphql(async_graphql)` spelling.
#[must_use]
pub const fn of(kind: GraphqlKind) -> Self {
Self {
kind,
prefix: None,
options: None,
question: None,
engine: None,
first: None,
}
}
}
/// WHAT THIS DECLARATION'S MINTED RUST TYPES ARE CALLED — the top-level `rename` word, in whichever
/// of its two forms it was written.
///
/// # The BONES axis, and it never appears in a backend block
///
/// These are RUST names: the packages, the vocabularies, the evidence, the selector and the markers
/// this expansion lands in the declaring scope. A skin's names are [`IndexBackend`]'s, and the two
/// never cross — a schema rename that moved a Rust type would make one declaration's API depend on
/// which backends happened to be compiled in.
///
/// The declaration's OWN struct name is never among them. It is the author's item, sitting in the
/// author's file; nothing here renames what somebody wrote.
///
/// # Two forms, and they are exclusive for [`Extension`]'s reason
///
/// The `extension` word's precedent, one grammar over: a single fact is a key-value and a structured
/// one is a block, and writing both at one position is refused as a repeat. `rename = "ShotSearch"`
/// re-bases the WHOLE family; `rename(fuse_options = "MyKnobs", …)` names individual mints.
#[derive(Debug, Clone)]
pub enum IndexRename {
/// `rename = "ShotSearch"` — the base every minted name is built on, replacing the declaration's
/// own ident at the head of each.
Base(syn::Ident),
/// `rename(<piece> = "…", …)` — one entry per mint the declaration named, in written order.
Pieces(Vec<(RenamePiece, syn::Ident)>),
}
impl IndexRename {
/// The BASE this family is built on, or [`None`] where the declaration named pieces instead.
#[must_use]
pub const fn base(&self) -> Option<&syn::Ident> {
match self {
Self::Base(base) => Some(base),
Self::Pieces(_) => None,
}
}
/// What the declaration called `piece`, or [`None`] where it named that one nothing.
#[must_use]
pub fn piece(&self, piece: RenamePiece) -> Option<&syn::Ident> {
match self {
Self::Base(_) => None,
Self::Pieces(named) => named
.iter()
.find_map(|(named, spelled)| (*named == piece).then_some(spelled)),
}
}
}
/// WHICH MINT a `rename(…)` entry is about — the CLOSED vocabulary, read off the emitted-types
/// roster.
///
/// # Every word here names a type this declaration has AT MOST ONE of, and that is the whole rule
///
/// A word names an individual mint, so it can only exist where *which one* has an answer. These
/// seven do: a declaration mints one options package a parent absorbs, one question package, one
/// evidence enum, one column vocabulary, one engine selector.
///
/// The mints that are PER-FIELD or PER-SLOT — a slot's own options and question, a leg's options, a
/// fold vocabulary, an election marker, a slot marker — are named by no word here and are covered by
/// [`IndexRename::Base`] instead. A word for one of them would have to carry a field and an engine
/// beside it, which is a grammar this round did not rule; the front end refuses each by name and
/// says which form reaches it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RenamePiece {
/// `<Index>FuseOptions` — a vector tier's multi-route options package.
FuseOptions,
/// `<Index>FuseQuestion` — its sister.
FuseQuestion,
/// `<Index>FulltextOptions` — a full-text tier's options package.
FulltextOptions,
/// `<Index>FulltextQuestion` — its sister.
FulltextQuestion,
/// `<Index>FusedEvidence` — which routes agreed about a fused root.
Evidence,
/// `<Stem>EngineInput` — the `@oneOf` over the engines this declaration TYPED.
EngineInput,
/// `<Index>Column` — the full-text column vocabulary.
Column,
}
impl RenamePiece {
/// Every word, in the order a refusal lists them — which is also the order the near-miss line
/// measures a typo against.
pub const ALL: [Self; 7] = [
Self::FuseOptions,
Self::FuseQuestion,
Self::FulltextOptions,
Self::FulltextQuestion,
Self::Evidence,
Self::EngineInput,
Self::Column,
];
/// The word a declaration writes.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::FuseOptions => "fuse_options",
Self::FuseQuestion => "fuse_question",
Self::FulltextOptions => "fulltext_options",
Self::FulltextQuestion => "fulltext_question",
Self::Evidence => "evidence",
Self::EngineInput => "engine_input",
Self::Column => "column",
}
}
/// The word a path names, if it names one.
#[must_use]
pub fn of(path: &syn::Path) -> Option<Self> {
Self::ALL
.into_iter()
.find(|word| path.is_ident(word.as_str()))
}
/// What a refusal calls the type this word is about.
#[must_use]
pub const fn what(self) -> &'static str {
match self {
Self::FuseOptions => "the multi-route options package a parent absorbs",
Self::FuseQuestion => "the multi-route question package",
Self::FulltextOptions => "the full-text options package",
Self::FulltextQuestion => "the full-text question package",
Self::Evidence => "the evidence a fused door answers with",
Self::EngineInput => "the `@oneOf` over the engines this declaration typed",
Self::Column => "the column vocabulary a full-text retrieve narrows with",
}
}
}
/// The `data` word itself, spelled once.
///
/// Here rather than in the front end that reads it, for
/// [`EXTENSION`](crate::extension::EXTENSION)'s reason: the derive is one front end and a manifest
/// is meant to be another, and a word spelled once per front end is a word that can come to mean
/// two things without anybody editing either of them.
pub const DATA: &str = "data";
/// What an author who wrote `data` on the wrong kind is told.
///
/// The SENTENCE lives beside the model it fills rather than in the walk that pushes it, because the
/// fact it states is this crate's: [`IndexModel::data`] is `false` on the two retrieving kinds by
/// construction, and the reason it can never be anything else is exactly what a front end has to
/// say out loud when it refuses the word.
#[must_use]
pub fn data_wrong_kind(kind: NodeKind) -> String {
format!(
"`data` is an ARTIFACT FAMILY's word and {article} {noun} has no bytes to send — the word says \
a stored OBJECT may ride inline, base64, beside the address that names it, and this \
declaration stores no object and mints no address to put one beside: its documents live inside \
an engine, and what it hands back is a RANKING over keys",
article = kind.article(),
noun = kind.noun(),
)
}
impl IndexModel {
/// THE BASE EVERY MINTED NAME IS BUILT ON — the top-level `rename`'s word, or the declaration's
/// own ident.
///
/// The one place the two are chosen between, so that a name minted anywhere in this crate cannot
/// be built on the wrong one. NOT the same question as *what is this type called*: the
/// declaration's own ident is what an `impl … for` writes and what a doc link points at, and it
/// never moves.
#[must_use]
pub fn base(&self) -> &syn::Ident {
self
.rename
.as_ref()
.and_then(IndexRename::base)
.unwrap_or(&self.index)
}
/// The whole expansion: the one-storage marker at module scope, and everything else inside the
/// anonymous `const` this crate puts every impl in.
///
/// The marker CANNOT move inside that const — see
/// [`one_storage_marker`](crate::model::one_storage_marker); two of them in two anonymous consts
/// are two items in two scopes and collide with nothing at all.
#[must_use]
pub fn emit(&self) -> proc_macro2::TokenStream {
let index = &self.index;
let marker = one_storage_marker(&self.prefix, index);
let elections = self.elections();
let slots = self.slot_markers();
let carrier = self.carrier();
let binding = self.binding();
let projections = self.projections();
let embedding = self.vector_record();
let geometry = self.geometry_bindings();
let folds = self.declared_folds();
let audits = self.label_audits();
let kinds = self.resource_audits();
let roads = self.roads();
let retrieve = self.retrieve();
let emits = self.emits_binding();
let fans = self.fanouts();
// LAYER TWO's DECLARATION HALF, at module scope with the markers: `Describe<R>` is a trait impl
// and lands anywhere, but the blueprints it carries name the SLOT MARKERS' own durable names and
// read like the declaration's own surface, so they go where a reader looks for what this
// declaration owns.
let habitats = self.habitats();
// The FUSION TREE, at module scope with the markers: a package is a type a CLIENT builds, so it
// has to be spellable from the scope the declaration was written in. See `crate::fuse` for the
// binding table and for the presence law that makes this empty on a kind that does not retrieve.
let tier = self.tier().emit();
let capability = self.capability();
let bridge = self.artifact_bridge();
let citizen = self.citizen();
// THE SUBSCRIBER, at module scope with the markers: it is a TYPE a deployment mounts by name,
// so it has to be spellable from the scope the declaration was written in — the query unit's
// and the fusion tree's own reason, at the write side.
let subscriber = self.subscriber();
quote! {
#[doc(hidden)]
#[allow(dead_code, non_upper_case_globals)]
const #marker: () = ();
#elections
#slots
#habitats
#fans
#tier
#citizen
#subscriber
const _: () = {
#carrier
#binding
#projections
#geometry
// THE CAPABILITY IMPL rides INSIDE the anonymous const, beside the geometry bindings it
// projects the elected widths through: a trait impl is global whatever scope it is written
// in, and those two consts are nameable only here.
#capability
#embedding
#folds
#audits
#kinds
#roads
#retrieve
#emits
#bridge
};
}
}
/// **THE QUERY UNIT** this declaration mints — `<Decl>Queries`, the mountable home of its search
/// root fields, and the [`Graphql`] binding that seats it.
///
/// # It is the RECORD's citizenship, at a retrieving declaration
///
/// The Q1 ruling, whose whole content is that there is NO second mounting mechanism: a `vector` or
/// `fulltext` declaration wearing `graphql(async_graphql)` joins the three laws a record already
/// lives under — the unit law (`Graphql::Query`, a root assembles UNITS), the graph root's emitted
/// `MergedObject` (a member's unit joins the projection list), and the door-citizen state law
/// (the resource's own `Shared<R>` citizen, handed over with `.data(…)`).
///
/// # The road to the seat is ONE projection, as an interface's is
///
/// A record is reached `<<R as Transformer>::Graphql as Graphql>::Query`, because a record's wire
/// face is a member of its entity binding. A retrieving declaration binds `Transformer::Graphql =
/// ()` — its wire face is a RANKING rather than a predicate, which is a different surface from the
/// one that binding describes — so it implements [`Graphql`] DIRECTLY and a root projects
/// `<M as Graphql>::Query`. The SEAT is the same seat; only the road to it is shorter.
///
/// This paragraph used to say *a retrieving declaration implements no `Transformer` — it is not a
/// launchable node*, and BOTH halves of that were false by the time it was read again. The
/// [`binding`](Self::binding) has emitted a `Transformer` impl for as long as an index has carried
/// its upstream's key, and [`subscriber`](Self::subscriber) now mints a launchable node beside a
/// declaration that wears `subscribe`. What is still true is the only thing this section needs:
/// the projection through `Transformer::Graphql` reaches `()` here, so the road to the seat is the
/// direct one.
///
/// # Both halves of the face bind the EMPTY PRODUCT, and that is an answer
///
/// `GraphqlInput` is a predicate and an order, and `GraphqlOutput::Key` is the address a stored
/// row is paged by. A retrieving declaration is asked by neither: its whole request surface is the
/// question and options packages its fusion tree already mints, and its answer surface is the hits
/// its doors hand back. So the two record-shaped halves have nothing to name, and `()` is what the
/// framework's own absent forms are spelled with — the same statement `Graphql::Query = ()` makes
/// at the member beside them.
///
/// # UNGATED, like every emitted wire type's declaration
///
/// `type Query = <Decl>Queries` is bound in an ungated impl, so a unit that existed only where
/// async-graphql does would leave that binding naming nothing in every other build. The FACE — the
/// `#[Object]` impl carrying the fields — rides the gate, in a const block of its own.
///
/// Empty where the declaration named no backend: a model that dressed nothing must not even reach
/// for the macro that asks whether the feature is on, which is the presence law this family's
/// skins already hold.
pub(crate) fn citizen(&self) -> proc_macro2::TokenStream {
if !self.mounts() {
return proc_macro2::TokenStream::new();
}
let vis = &self.vis;
let index = &self.index;
let name = self.queries_name();
let face = framework(&self.krate, &["transform"], "Graphql");
let answers = self.answers();
let doc = crate::emit::leading(&format!(
"The root fields [`{index}`] answers — its search doors, as one mountable value.\n\nMounted by folding it into a graph's root query; it holds nothing and reaches its store through the `Shared<R>` citizen the schema was built with."
));
quote! {
#[doc = #doc]
#[derive(
::core::fmt::Debug,
::core::clone::Clone,
::core::marker::Copy,
::core::default::Default,
)]
#vis struct #name;
#[automatically_derived]
impl #face for #index {
// THE EMPTY PRODUCT ON BOTH RECORD-SHAPED HALVES — see this emission's own note: a
// retrieving declaration is asked by no predicate and ordered by no column, so what a
// record's face is built around has nothing to name here.
type Input = ();
type Output = ();
type Query = #name;
}
#answers
}
}
/// **WHETHER THIS DECLARATION MOUNTS AT ALL** — a retrieving kind wearing a backend word.
///
/// The presence law at the tier that mints the unit: a declaration with no `graphql(…)` block
/// emits every Rust door and package it would otherwise emit, and mints no citizenship — which is
/// exactly what a backend-only search pipeline wants.
#[must_use]
pub fn mounts(&self) -> bool {
matches!(self.kind, NodeKind::Fulltext | NodeKind::Vector)
&& self
.graphql
.as_ref()
.is_some_and(|block| block.renders(GraphqlKind::AsyncGraphql))
}
/// `<Decl>Queries` — this declaration's query unit, re-based by the BONES rename like every other
/// name it mints.
///
/// No piece word of its own, on the record unit's precedent: the unit is a Rust type a root spells
/// once and a schema never sees, so a name for it is the base's business. The base moves it because
/// the base moves the whole family — a rename that reached the packages and left this one behind
/// would put two stems in one declaring scope.
#[must_use]
pub fn queries_name(&self) -> syn::Ident {
format_ident!("{}Queries", self.base())
}
/// WHICH ROAD one election's query fields take, or [`None`] where it mounts none.
///
/// # Both roads need a TYPED engine, and that is the wall rather than a policy
///
/// A resolver's corpus lookup is `Context::data::<Shared<R>>`, a `TypeId` on a CONCRETE
/// pairing, and a resolver cannot be generic. So the `E` has to be a type this expansion can
/// spell, and the only place one is written is `lance(resource = "path::To::Lance")`. An election
/// naming its engines by word alone keeps every Rust door it had and publishes no field —
/// the presence law, at the grain where a road either has an engine or does not.
///
/// # The FANNED road needs EVERY leg typed, which is stricter than *some are*
///
/// `vector_fuse_by_<field>` is generic over one engine per LEG and the call spells them all, so a
/// slot with one untyped leg has a call this emission cannot write at all — not a road with a
/// gap in it. `slot_legs` rather than `typed` is therefore what the predicate reads, and the
/// `all` is what makes the two agree.
///
/// A SET election takes the plain road and never the fused one, which is
/// [`Tier::fanned_slots`](crate::fuse::Tier::fanned_slots)' own exclusion read at the wire: RRF
/// joins ordinals and a set election's `m` streams have no order between them to read one from,
/// so the door it would call is not emitted.
///
/// # THE LABEL PICKS THE DOOR ON BOTH PAIRS, and that is the whole of the set routing
///
/// One field NAME per (declaration × election), and the road behind it is the ELECTION's own
/// label read at expansion — the same mechanism `get_<field>` already uses to answer one embedding
/// or a whole group. `<decl>SimilarBy<Field>Keys` on a UNIT election calls
/// `retrieve_similar_by_<field>`; on a SET election it calls `retrieve_similar_by_<field>_with`.
/// `<decl>By<Field>Keys` reads the same way one road over: `retrieve_keys_by_<field>` at one
/// label, `retrieve_keys_by_<field>_with` at the other.
///
/// **It turns a runtime refusal into an answer, and that is the measurement.** The single-vector
/// by-example door reads the example's stored group and then demands exactly one of it, so a set
/// election published a field that answered `Several { held }` for every entity holding the set
/// its own declaration promised — a field that could only work where the data did not use the
/// label. Routing by the label is what makes the published name mean the same thing at both
/// labels: *the neighbours of this entity's own `<field>*`.
///
/// The QUESTION pair moved second and for a different reason: a set election is asked with `m`
/// points, so its question type's `coordinates` arm is one list deeper (the 2026-08-16 SET ruling)
/// and both tiers of the pair read it. There is ONE question type per election, so the two tiers
/// could not have been split across the two depths even if a round had wanted to.
///
/// NO NAME MOVES and none can collide. The roads are exclusive per election, so each name is
/// minted once whichever arm answers, and the declared rename seats (`keys(rename = "…")` through
/// `similar_hydrated(rename = "…")`) keep working unread by any of this.
fn answer_road<'a>(
&self,
tier: &crate::fuse::Tier<'a>,
elected: &Elected,
) -> Option<AnswerRoad<'a>> {
let legs = tier.slot_legs(elected);
if tier.fanned(elected) {
let fused = !elected.label.is_set()
&& legs.len() >= 2
&& legs.iter().all(|engine| engine.resource.is_some());
return fused.then_some(AnswerRoad::Fanned(legs));
}
match tier.typed(elected).as_slice() {
[only] if elected.label.is_set() => Some(AnswerRoad::Set(only)),
[only] => Some(AnswerRoad::Plain(only)),
_ => None,
}
}
/// **WHY THIS ELECTION PUBLISHES NO `which` QUERY FIELD**, or [`None`] where it publishes one.
///
/// # The law: seats may sit EMPTY, and a written word must point at something MINTED
///
/// An unwritten seat is a capability nobody has asked for yet and costs a declaration nothing. A
/// WRITTEN one that reaches no emitted name is a swallowed authoring error — the class this house
/// already refuses at `lineage(rename)` on a lineage-less record — because the author believes they
/// renamed a field and the schema still publishes the derived name, or publishes nothing at all.
///
/// # What it reads is the DECLARATION'S OWN SHAPE, and that is the whole of its scope
///
/// Two facts decide which roads an election mounts, and both are the declaration's:
///
/// - a FANNED election publishes the fused field alone. Its four sibling roads are not emitted,
/// because `vector_fuse_by_<field>` is the one door a multi-store election has.
/// - the head's `keys` word says the upstream is an ENTITY, so the answer family mounts the KEYS
/// tier alone and the two hydrated roads have no store to read rows out of.
///
/// # Three cases it deliberately does NOT answer, each measured
///
/// [`Field::Fused`] always answers [`None`] here. It is unmounted on a plain election exactly as
/// its siblings are on a fanned one, and auditing it is a one-line change to the match below — but
/// the round that wrote this law enumerated four roads, so the fifth is left for a ruling rather
/// than taken by symmetry.
///
/// A FULL-TEXT election mounts no query field at all: [`answer_roads`](Self::answer_roads) returns
/// nothing for that kind, so every seat on one is currently unspent. That is the ANSWER FACE not
/// having arrived for the kind rather than a shape the author chose, so a refusal there would be
/// this crate claiming the face is never coming.
///
/// An election naming its engines BY WORD ALONE publishes no field either — the portable case,
/// which is legal and means the deployment picks the engine — and the same reasoning holds: the
/// surface is absent for a reason outside the seat's own axis.
///
/// Both are recorded here rather than fixed, so the next reader inherits the measurement.
#[must_use]
pub fn unmounted(&self, field: &syn::Ident, which: Field) -> Option<&'static str> {
if self.kind != NodeKind::Vector || !self.mounts() {
return None;
}
let tier = self.tier();
let elected = self.embeddings.iter().find(|held| held.field == *field)?;
let road = self.answer_road(&tier, elected)?;
match which {
// THE FIFTH ROAD, left unaudited on purpose — see the note above.
Field::Fused => None,
_ if matches!(road, AnswerRoad::Fanned(_)) => Some(
"a FANNED election publishes its fused field and nothing else — every store this field is \
written to answers one leaderboard, and the four per-store roads are not emitted for it. \
The word this shape has is `fused(rename = \"…\")`; drop a store from the election to get \
the others back",
),
Field::Hydrated | Field::SimilarHydrated if self.keys => Some(
"this declaration wears the head's `keys` word, so its upstream is an ENTITY and the answer \
family mounts the KEYS tier alone: there is no store for a hydrated road to read whole rows \
out of, and neither hydrated field is emitted. Drop `keys` where the upstream does have \
rows, or drop this word",
),
_ => None,
}
}
/// **WHY THIS ELECTION MINTS NO `<Index><Field>Engines`**, or [`None`] where it mints one.
///
/// [`unmounted`](Self::unmounted)'s law at a TYPE seat rather than a field seat. The per-leg
/// product is minted by the fused answer and by nothing else — a fused read states one floor per
/// leg, and an election answered by one store has one leg and names it through the `@oneOf`
/// selector at the head instead.
///
/// Its sister seat `question(rename = "…")` has no such clause, and that is a MEASUREMENT rather
/// than an omission: `question_input` runs for every election that mounts a road at all, on every
/// road, so the question type is minted wherever the seat is reachable. The seat is audited and
/// found always-spent, which is a different answer from unaudited.
#[must_use]
pub fn unminted_engines(&self, field: &syn::Ident) -> Option<&'static str> {
if self.kind != NodeKind::Vector || !self.mounts() {
return None;
}
let tier = self.tier();
let elected = self.embeddings.iter().find(|held| held.field == *field)?;
let road = self.answer_road(&tier, elected)?;
if matches!(road, AnswerRoad::Fanned(_)) {
return None;
}
Some(
"`engines` names the PRODUCT a fused read states one floor per leg in, and this election is \
answered by ONE typed store: it has one leg, so there is no product to name. What names its \
engine is the `@oneOf` selector at the head — `engine(rename = \"…\")` in the declaration's \
own backend block",
)
}
/// EVERY ELECTION that mounts a query field, with the road it takes — in declared order.
fn answer_roads(&self) -> Vec<(&Elected, AnswerRoad<'_>)> {
if !self.mounts() || self.kind != NodeKind::Vector {
return Vec::new();
}
let tier = self.tier();
self
.embeddings
.iter()
.filter_map(|elected| self.answer_road(&tier, elected).map(|road| (elected, road)))
.collect()
}
/// **THE ANSWER FAMILY AND THE QUERY FIELDS** — what a client asks one election with, what it
/// reads back, and the `#[Object]` face that joins them.
///
/// # FOUR fields on a plain road: two questions, two tiers — or TWO, where the upstream is an
/// entity
///
/// One road is asked two ways — a QUESTION and an EXAMPLE KEY — and each is answered at two tiers.
/// The KEYS tier hands back addresses and touches no store; the HYDRATED tier hands back the
/// upstream's whole entities and reads them out of one. The tier noun is what tells the pair
/// apart at every road, which is [`Field::derived`]'s own law.
///
/// The hydrated half is what [`IndexModel::keys`] withholds. A record upstream mounts all four
/// unconditionally — rows are a record's essence, so hydration can never miss — and an ENTITY
/// upstream mounts the two keys fields alone, because there is no store for the other two to read
/// out of. A declaration whose upstream is an entity and which wrote no word emits the demand and
/// is refused by the compiler at `upstream(node = "…")`; nothing here guesses.
///
/// What held the hydrated pair back was ONE LINE — `ctx.data::<SqlDoor<…>>` names a database and a
/// derived index has none to name — and the line is written now:
/// [`Hydrates`](../../../ingraph/trait.Hydrates.html) is the record's own projection of where its
/// rows are read from, and this emission spends it. `ingraph/tests/hydrated_road.rs` and its
/// by-example sibling are the hand-mounts that measured the body first, and they stay as the
/// pattern an application writes when it wants a road of its own shape.
///
/// # The SPLIT: declarations outside the gate, impls inside it
///
/// Every type below is a plain `struct` or `enum` at module scope, and every async-graphql trait
/// impl over it rides `if_async_graphql!`. That is the record's own split and it is load-bearing
/// twice over: a build with no wire binding compiles the whole Rust surface, and
/// [`emitted_types`](Self::emitted_types) can enumerate names the collision refusals are measured
/// against — a name minted inside a gate would be invisible to the roster walk and visible to a
/// declaring author.
///
/// It is also why no `#[derive(Union)]` appears here. A derive is written ON a declaration, the
/// declaration is ungated, and `#[cfg_attr]` cannot stand in — that predicate asks whether the
/// DECLARING crate has a feature called `async-graphql`, which is a different manifest and usually
/// no feature at all. So the union's three impls are written out, exactly as the `@oneOf` input
/// faces beside them already are.
fn answers(&self) -> proc_macro2::TokenStream {
let roads = self.answer_roads();
let text = self.text_roads();
if roads.is_empty() && text.is_empty() {
return proc_macro2::TokenStream::new();
}
let tier = self.tier();
let ag = framework(&self.krate, &[], "async_graphql");
let shelf = crate::emit::vendored(&self.krate, "async_graphql");
let gate = framework(&self.krate, &["gate"], "if_async_graphql");
let prelude = crate::emit::wire::prelude();
let unit = self.queries_name();
// The unit's own SDL name is its Rust name: a `MergedObject` fold takes the FIELDS and never
// publishes the type that carried them, so this string reaches no schema — it is written
// because `#[Object]` takes one, on the interface unit's own precedent.
let unit_sdl = unit.to_string();
let mut declared = Vec::new();
let mut faces = Vec::new();
// THE FULL-TEXT LEGS FIRST, and they need neither a question type of their own nor an answer
// face: the tier already mints the question package and the selector, so what this road adds is
// the resolver and nothing else.
let mut legs = text;
let mut hydrated = Vec::new();
let mut elections = Vec::new();
for (elected, road) in roads {
elections.push(elected);
let (types, face) = self.question_input(&tier, elected);
declared.push(types);
faces.push(face);
match road {
AnswerRoad::Plain(engine) => {
legs.push(self.keys_leg(&tier, elected, engine));
// THE BY-EXAMPLE ROAD, beside the question road and on the SAME condition — one typed
// store. It needs nothing the plain road did not already need: the door it calls takes a
// `SlotHandle` and no `AsyncGather`, so the wall that holds tier B holds nothing here.
legs.push(self.similar_leg(&tier, elected, engine));
// THE TWO HYDRATED TWINS, held apart because they need what the two above do not: a
// STORE. They name `SqlDoor` and `SqlPooledGather`, so they exist per SQL FAMILY where
// everything beside them exists per build — see the gate pair below — and they exist at
// all only where the upstream HAS rows, which is [`IndexModel::keys`]'s whole subject.
if !self.keys {
hydrated.push(self.hydrated_leg(&tier, elected, engine));
hydrated.push(self.similar_hydrated_leg(&tier, elected, engine));
}
}
// THE LABEL MOVES BOTH PAIRS, and the question one moved last. A set election's `question`
// is `m` POINTS rather than one — the `_with` road's own wire surface, minted by the
// 2026-08-16 SET ruling — so all four legs here call a `_with` door and answer the folded
// hit. NO NAME MOVES: the four fields are the same four strings a unit election publishes.
AnswerRoad::Set(engine) => {
legs.push(self.set_keys_leg(&tier, elected, engine));
legs.push(self.similar_set_leg(&tier, elected, engine));
if !self.keys {
hydrated.push(self.set_hydrated_leg(&tier, elected, engine));
hydrated.push(self.similar_set_hydrated_leg(&tier, elected, engine));
}
}
AnswerRoad::Fanned(ref slot_legs) => {
let (types, face) = self.fused_answer(&tier, elected, slot_legs);
declared.push(types);
faces.push(face);
legs.push(self.fused_leg(&tier, elected, slot_legs));
}
}
}
let bindings = self.answer_bindings(&elections);
// THE UNIT'S FACE, WRITTEN TWICE — the `if_sqlx` pair, and the shape is forced rather than
// chosen. A type has ONE `#[Object]` impl (a second is `E0119` on `ObjectType` before any schema
// exists) and the attribute reads the impl block whole, so a gate written around one METHOD
// would be a `macro_rules!` invocation the attribute expands before and never a field. The
// serde pair's sentence at a different grain: what a macro cannot do is ADD to something that
// has already been parsed, so the block is written twice and exactly one half survives.
//
// The halves differ in the hydrated legs and in nothing else, so the shut half is byte-for-byte
// the unit a build without the SQL family already had.
let object = |also: &[proc_macro2::TokenStream]| {
quote! {
#[#ag::Object(crate = #shelf, name = #unit_sdl)]
impl #unit {
#(#legs)*
#(#also)*
}
}
};
// A declaration with NO hydrated leg gets ONE block and no pair at all, which is what keeps the
// gate honest at both ends: a purely fanned declaration's expansion is byte-for-byte what it
// was, and the projections — which demand `Hydrates` of the upstream — are written only where a
// road spends them. A demand emitted for a road that does not exist would refuse a fanned
// declaration over an unstored upstream for a field it never publishes.
let face = if hydrated.is_empty() {
object(&[])
} else {
let hydration = self.hydration_bindings();
let (whole, bare) = (object(&hydrated), object(&[]));
let sqlx = framework(&self.krate, &["gate"], "if_sqlx");
let without = framework(&self.krate, &["gate"], "if_no_sqlx");
quote! {
#sqlx! {
#hydration
#whole
}
#without! {
#bare
}
}
};
quote! {
#(#declared)*
#gate! {
const _: () = {
#prelude
#bindings
#(#faces)*
#face
};
}
}
}
/// **THE FULL-TEXT KEYS ROAD's QUERY FIELD** — one searchable field, one pointed resource, a
/// ranked list of addresses.
///
/// # It is [`keys_leg`](Self::keys_leg) with the QUESTION changed and nothing else
///
/// A vector road is asked with COORDINATES, which have a width, a space and an element and are
/// checked against the election's own geometry. A full-text road is asked with a STRING against
/// whatever grammar the engine has — `store::fulltext`'s own division — so the whole point
/// binding disappears and what is left is the text, taken off the tier's question package. The
/// floor, the numbers, the page cut and the crossing are the vector road's, unchanged, because
/// nothing about them is vector-flavoured.
///
/// # ONE FIELD PER SEARCHABLE FIELD, because a SLOT is per election
///
/// The corpus a search runs over is `(field × label)`, so two searchable fields are two corpora
/// with two universes of BM25 statistics and no handle can serve both. The whole-subject door
/// (`retrieve_keys`, `FulltextSubset::All`) is the Rust surface a caller that opened ONE slot
/// reaches; what the wire publishes is the per-field pair, whose subset the emitted door mints
/// from the field's own name.
///
/// # The SELECTOR is at the DECLARATION grain
///
/// A full-text declaration is ONE ROUTE however many fields it elects — the tier's own law — so
/// the `engine` seat is `<Index>EngineInput` rather than a per-field one. Two fields therefore
/// read their floor out of the same package, which is right: the floor is in the ENGINE's score
/// currency and both fields are held by the same engine.
fn text_keys_leg(
&self,
tier: &crate::fuse::Tier<'_>,
field: &syn::Ident,
engine: &Engine,
) -> proc_macro2::TokenStream {
let IndexModel { krate, index, .. } = self;
let ag = framework(krate, &[], "async_graphql");
let seam = framework(krate, &["store"], "FulltextEngine");
let hit = framework(krate, &["graphql"], "Match");
let crossed = framework(krate, &["graphql"], "matches");
let ranked = framework(krate, &["retrieve"], "Ranked");
let query = framework(krate, &["retrieve"], "FulltextQuery");
let connected = framework(krate, &["store"], "Connected");
let ty = engine
.resource
.as_ref()
.expect("a published full-text leg points at a resource");
let handle = self.wire_handle(ty);
let mint = self.wire_corpus(
field,
None,
engine,
ty,
&format_ident!("__ingraph_slot"),
&format_ident!("__ingraph_connection"),
);
let question = tier
.question_name()
.expect("a full-text tier mints its question");
let selector = tier
.subject_selector()
.expect("a pointed full-text declaration mints its engine selector");
let variant = format_ident!("{}", {
use heck::ToUpperCamelCase as _;
engine.word.to_string().to_upper_camel_case()
});
let key = wire_key_name();
let sdl = self.road_name(field, Field::Keys);
let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
// THE WHOLE-SUBJECT DOOR, and the per-field one is deliberately NOT called — which is the slot
// grain read at its own conclusion. A corpus is `(field × label)`, so everything inside the one
// this leg opened belongs to THIS election and `FulltextSubset::All` is the honest scope. The
// per-field door narrows by a `FulltextColumn` named after the ELECTION, which asks the backend
// to have named its column that: the shipped engine's slot schema calls its one text field
// `body` whatever elected it, so a subset spelled from the field's name is refused by the
// engine at run time. `retrieve_keys_by_<field>` remains the Rust surface for a deployment that
// opened ONE slot holding several columns.
let door = format_ident!("retrieve_keys");
let arity = wide_signature();
let numbers = self.answer_numbers(field);
// THE SCOPE — `keys_leg`'s own, one family over: the CONNECTION is the mount's manager and the
// read scope is the unit, spanned at the `resource = "…"` path the author wrote.
let scope = quote_spanned! {ty.span()=>
#connected::new(__ingraph_connection, ())
};
let (floor, options) = (
format_ident!("__ingraph_floor"),
format_ident!("__ingraph_options"),
);
let floorless = format!(
"`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
`engine: {{ {engine_word}: {{ floor: … }} }}`. There is no number this framework could put \
there instead: a score's DIRECTION belongs to the engine that measures in it, and a BM25 \
score is unbounded above.",
engine_word = engine.word,
);
let doc = leading(&format!(
"The addresses [`{index}`]'s `{field}` ranks against a question, in `{engine_word}`.",
engine_word = engine.word,
));
let ctx = crate::method::wire_method(&format_ident!("ctx"));
let (asked, chosen, first, depth) = (
crate::method::wire_method(&format_ident!("question")),
crate::method::wire_method(&format_ident!("engine")),
crate::method::wire_method(&format_ident!("first")),
crate::method::wire_method(&format_ident!("depth")),
);
let default = self
.wire_first(GraphqlKind::AsyncGraphql, Some(field))
.get();
let default = syn::LitInt::new(&default.to_string(), field.span());
quote! {
#[doc = #doc]
#[graphql(name = #sdl)]
#arity
async fn #method(
&self,
#ctx: &#ag::Context<'_>,
#[graphql(name = "question")] #asked: #question,
#[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
#[graphql(name = "first", default = #default)] #first: u32,
#[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
) -> #ag::Result<::std::vec::Vec<#hit<#key, <#ty as #seam>::Score>>> {
#numbers
// A QUESTION NOBODY ASKED IS THE EMPTY ANSWER, not the whole corpus — `participates`' law
// at the one seat this road has.
let ::core::option::Option::Some(__ingraph_text) = #question::question(&#asked) else {
return ::core::result::Result::Ok(::std::vec::Vec::new());
};
let (#floor, #options) = match #chosen {
::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
// `Option::map` OVER `Option::cloned`: the latter is inherent on BOTH `Option<&T>` and
// `Option<&mut T>`, so a path call is `E0034` at a span the author cannot edit.
::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
__ingraph_named.options(),
),
::core::option::Option::None => (
::core::option::Option::None,
::core::option::Option::None,
),
};
let ::core::option::Option::Some(#floor) = #floor else {
return ::core::result::Result::Err(#ag::Error::new(#floorless));
};
#mint
let __ingraph_query = #query::new(
::std::string::String::clone(__ingraph_text),
#floor,
);
let mut __ingraph_ranked: ::std::vec::Vec<#ranked<_, _>> = #index::#door::<#handle>(
&mut __ingraph_slot,
#scope,
&__ingraph_query,
__ingraph_fetch,
#options,
)
.await
.map_err(|__ingraph_refusal| {
#ag::Error::new(::std::string::ToString::to_string(&__ingraph_refusal))
})?;
// THE PAGE, cut after the walk: `depth` bought the FETCH and `first` is what a client asked
// to read, and the two are different numbers whenever the floor or the dedup pruned.
::std::vec::Vec::truncate(
&mut __ingraph_ranked,
::core::num::NonZeroUsize::get(__ingraph_page),
);
::core::result::Result::Ok(#crossed(
::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_ranked),
|__ingraph_hit| {
let __ingraph_key = ::core::clone::Clone::clone(#ranked::node_ref(&__ingraph_hit));
#ranked::map_node(
__ingraph_hit,
<#key as ::core::convert::From<_>>::from(__ingraph_key),
)
},
),
))
}
}
}
/// EVERY FULL-TEXT WIRE LEG this declaration publishes — one per (searchable field × POINTED leg).
///
/// An unpointed leg publishes nothing, which is the presence law this family already keeps: there
/// is no `E` for the expansion to spell, so there is no resolver to write. A declaration whose
/// legs are all unpointed mounts the Rust surface whole and no wire field at all.
fn text_roads(&self) -> Vec<proc_macro2::TokenStream> {
if !self.mounts() || self.kind != NodeKind::Fulltext {
return Vec::new();
}
let tier = self.tier();
if tier.subject_selector().is_none() {
return Vec::new();
}
self
.engines
.iter()
.filter(|declared| self.searchable.contains(&declared.field))
.flat_map(|declared| {
declared
.engines
.iter()
.filter(|engine| engine.resource.is_some())
.map(|engine| self.text_keys_leg(&tier, &declared.field, engine))
})
.collect()
}
/// The THREE PROJECTIONS every answer face reads, bound to names inside the face's own `const`.
///
/// The width lands in CONST-ARGUMENT position, where a qualified path is not a legal const
/// argument and two braced blocks of identical text are two anonymous constants that do not unify
/// — the measurement [`geometry_bindings`](Self::geometry_bindings) already made one const block
/// over. Its bindings cannot be reached from here: they live inside the expansion's OTHER
/// anonymous const, and a name in one is a name in one.
///
/// The WIRE KEY is bound here for a different reason and it is the round's one open question: a
/// hit's `node` is the upstream's ADDRESS OBJECT, whose name this expansion cannot spell — two
/// derives are blind to each other — so it is reached as a projection off the upstream path the
/// declaration wrote. Spanned at that path, so an upstream that publishes no wire face is `E0277`
/// on `upstream(node = "…")` rather than inside an expansion.
///
/// The EXAMPLE KEY is bound for that same reason at the other end of the same address: the
/// by-example road takes the upstream's OWN key, whose name this expansion cannot spell either, so
/// it is the same kind of projection at the same span. Its wire form is a second projection on top
/// — `<Key as ToGraphqlInput>::Input` — which is where the root/compound fork is decided, by the
/// RECORD's emission and never by this one.
fn answer_bindings(&self, elections: &[&Elected]) -> proc_macro2::TokenStream {
let krate = &self.krate;
let marker = framework(krate, &["election"], "EmbeddingMarker");
let shape = framework(krate, &["election"], "EmbeddingShape");
let transformer = framework(krate, &["transform"], "Transformer");
let face = framework(krate, &["transform"], "Graphql");
let output = framework(krate, &["transform"], "GraphqlOutput");
let upstream = &self.source.node;
let key = wire_key_name();
let example = example_key_name();
// SPANNED AT `upstream(node = "…")`, which is the token an author edits when the projection has
// nothing to resolve to.
let at = upstream.span();
let projected = quote_spanned! {at=>
#[allow(dead_code, non_camel_case_types)]
type #key = <<<#upstream as #transformer>::Graphql as #face>::Output as #output>::Key;
#[allow(dead_code, non_camel_case_types)]
type #example = <#upstream as #transformer>::Key;
};
let geometry = elections.iter().map(|elected| {
let (width, space, element) = answer_geometry(elected);
let ty = &elected.ty;
let at = elected.field.span();
quote_spanned! {at=>
#[allow(dead_code, non_upper_case_globals)]
const #width: usize = <<#ty as #marker>::Item as #shape>::WIDTH;
#[allow(dead_code, non_camel_case_types)]
type #space = <<#ty as #marker>::Item as #shape>::Space;
#[allow(dead_code, non_camel_case_types)]
type #element = <<#ty as #marker>::Item as #shape>::Element;
}
});
quote! {
#projected
#(#geometry)*
}
}
/// **THE QUESTION** one election is asked with — an `@oneOf` input over the ways of naming a
/// point, and today there is one of them.
///
/// # `@oneOf` at ONE arm is deliberate, and it is the selector's own argument
///
/// A choice-shaped input with one variant publishes the same shape a second modality will join —
/// `text:` walked into these coordinates by a TOWER, an `example:` key — so the day one arrives
/// it is an ADDED variant rather than a changed shape, and a client written today keeps working.
/// The engine selector beside it made that argument first and it holds here word for word.
///
/// # It is NOT the tier's `<Index><Field>VectorQuestion`, and the difference is the CARRIER
///
/// That package holds an `Embedding<E, N, S>` — the declaration's own type, width-checked at
/// construction — and `Row::rust_side` marks it as the one row of either tree with no wire form,
/// because there is no `InputType` for a width a client cannot see. This type is the wire's side
/// of the same fact: a list of coordinates, whose width is checked BY THE RESOLVER against
/// the projection, so the refusal names the field and both numbers instead of failing to parse.
///
/// # ONE LIST DEEPER ON A SET ELECTION, and that is the whole of the label's effect here
///
/// Ruled 2026-08-16. A `list(embedding)` election's question road is the `_with` road, which is
/// asked with `m` POINTS rather than one — so the SAME arm carries a list of them:
///
/// ```text
/// #[ingraph(embedding, …)] coordinates: [f32!] one point
/// #[ingraph(list(embedding), …)] coordinates: [[f32!]!] m of them
/// ```
///
/// Nothing is invented for it: the arm WORD is reused, the EMPTY list reuses `FoldedQuery`'s own
/// refusal, and the depth is the one dimension that moved. A second question TYPE would have been
/// the invention, and the label already routes the by-example road the same way.
///
/// # THE ELEMENT CROSSES ON THE ROSTER'S CARRIER, and that is a CURRENCY rather than a form
///
/// Ruled 2026-08-18. This arm published async-graphql's own `Float` for an `f32` election, because
/// the element crossed on its own face and that face is the library's. `Float` is GraphQL's
/// DOUBLE-precision scalar, so publishing an `f32` coordinate under it is a width misreported —
/// the same silence the whole scalar suite exists to end, met one road over.
///
/// The arm's wire type is `<Element as ToGraphqlInput>::Input` now: the roster carrier the element
/// already had, which for `f32` is `F32` and publishes the scalar `f32`. The constitution's
/// *currencies cross AS THEMSELVES* is what this obeys rather than what it breaks — an `f32` has a
/// name of its own in this framework, so crossing as itself IS crossing as `f32`. An election over
/// a roster carrier is unchanged, its carrier's own crossing being the identity.
///
/// The CONVERSION work is zero: the `Float` road already narrowed a double to an `f32` inside
/// async-graphql's own impl, and `F32`'s scalar narrows the same `f64` in the same place. What
/// moved is the NAME a client reads and the two total hops the arm now spells, one per coordinate.
fn question_input(
&self,
tier: &crate::fuse::Tier<'_>,
elected: &Elected,
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
let IndexModel {
vis, krate, index, ..
} = self;
let ag = framework(krate, &[], "async_graphql");
let marker = framework(krate, &["election"], "EmbeddingMarker");
let shape = framework(krate, &["election"], "EmbeddingShape");
let crossing = framework(krate, &["graphql"], "ToGraphqlInput");
let name = self.question_name(tier, elected);
let sdl = tier.packages().sdl(&name);
let ty = &elected.ty;
let (_, _, element) = answer_geometry(elected);
let field = &elected.field;
let doc = leading(&format!(
"The question [`{index}`]'s `{field}` is asked over the wire — one way of naming a point, and \
exactly one per request.\n\nA CHOICE rather than a record, on the engine selector's own \
argument: naming two ways of saying where to look is two requests, and a second way arrives \
as a second variant rather than as a changed shape."
));
// THE LABEL DECIDES THE DEPTH, and nothing else about this type: a set election's question road
// is the `_with` road, which is asked with `m` points.
let set = elected.label.is_set();
let coordinates = leading(&if set {
format!(
"The POINTS themselves, one list of coordinates each — every one as wide as `{field}` embeds \
at, which the resolver checks per point and names the offending one when it does not \
hold.\n\nAn EMPTY list is refused: a set query with no query vectors asks nothing."
)
} else {
format!(
"The point itself, coordinate by coordinate — as many as `{field}` embeds at, which the \
resolver checks and names both numbers when it does not hold."
)
});
// The ARM's HELD type and its WIRE type. They are NOT the same shape any more: the held one is
// the election's own element, spelled through the projection the declaration owns; the wire one
// is that element's ROSTER CARRIER, reached through the alias the face's const binds. See the
// currency note above for why the two parted.
let held = quote!(<<#ty as #marker>::Item as #shape>::Element);
let carrier = quote!(<#element as #crossing>::Input);
let (held, carried) = if set {
(
quote!(::std::vec::Vec<::std::vec::Vec<#held>>),
quote!(::std::vec::Vec<::std::vec::Vec<#carrier>>),
)
} else {
(
quote!(::std::vec::Vec<#held>),
quote!(::std::vec::Vec<#carrier>),
)
};
// The two hops the carrier costs, one per coordinate, spelled by depth. `cross` is the wire's
// refusal seat as well as its conversion — a carrier that cannot become its element says so in
// the reading's own sentence, which `InputValueError::custom` carries verbatim to the client.
let (crossed, carrying) = if set {
(
quote! {
let mut __ingraph_points =
::std::vec::Vec::with_capacity(::std::vec::Vec::len(&__ingraph_chosen));
for __ingraph_point in __ingraph_chosen {
let mut __ingraph_coordinates =
::std::vec::Vec::with_capacity(::std::vec::Vec::len(&__ingraph_point));
for __ingraph_coordinate in __ingraph_point {
__ingraph_coordinates.push(
<#element as #crossing>::cross(__ingraph_coordinate)
.map_err(|__ingraph_refusal| #ag::InputValueError::custom(__ingraph_refusal))?,
);
}
__ingraph_points.push(__ingraph_coordinates);
}
let __ingraph_chosen = __ingraph_points;
},
quote! {
let __ingraph_carried: #carried = ::core::iter::Iterator::collect(
::core::iter::Iterator::map(
::core::iter::IntoIterator::into_iter(__ingraph_chosen),
|__ingraph_point| ::core::iter::Iterator::collect(
::core::iter::Iterator::map(
::core::iter::IntoIterator::into_iter(__ingraph_point),
<#element as #crossing>::carry,
),
),
),
);
},
)
} else {
(
quote! {
let mut __ingraph_coordinates =
::std::vec::Vec::with_capacity(::std::vec::Vec::len(&__ingraph_chosen));
for __ingraph_coordinate in __ingraph_chosen {
__ingraph_coordinates.push(
<#element as #crossing>::cross(__ingraph_coordinate)
.map_err(|__ingraph_refusal| #ag::InputValueError::custom(__ingraph_refusal))?,
);
}
let __ingraph_chosen = __ingraph_coordinates;
},
quote! {
let __ingraph_carried: #carried = ::core::iter::Iterator::collect(
::core::iter::Iterator::map(
::core::iter::IntoIterator::into_iter(__ingraph_chosen),
<#element as #crossing>::carry,
),
);
},
)
};
let declared = quote! {
#[doc = #doc]
#[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
#vis enum #name {
#[doc = #coordinates]
Coordinates(#held),
}
};
let face = quote! {
#[automatically_derived]
impl #ag::InputType for #name {
type RawValueType = Self;
#[inline]
fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
::std::borrow::Cow::Borrowed(#sdl)
}
fn create_type_info(
__ingraph_registry: &mut #ag::registry::Registry,
) -> ::std::string::String {
__ingraph_registry.create_input_type::<Self, _>(
#ag::registry::MetaTypeId::InputObject,
|__ingraph_registry| #ag::registry::MetaType::InputObject {
name: ::std::string::String::from(#sdl),
description: ::core::option::Option::None,
input_fields: {
let mut __ingraph_fields = #ag::indexmap::IndexMap::new();
__ingraph_fields.insert(
::std::string::String::from("coordinates"),
#ag::registry::MetaInputValue {
name: ::std::string::String::from("coordinates"),
description: ::core::option::Option::None,
ty: <::core::option::Option<#carried> as #ag::InputType>::create_type_info(
__ingraph_registry,
),
deprecation: #ag::registry::Deprecation::NoDeprecated,
default_value: ::core::option::Option::None,
visible: ::core::option::Option::None,
inaccessible: false,
tags: ::std::vec::Vec::new(),
is_secret: false,
directive_invocations: ::std::vec::Vec::new(),
},
);
__ingraph_fields
},
visible: ::core::option::Option::None,
inaccessible: false,
tags: ::std::vec::Vec::new(),
rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
oneof: true,
directive_invocations: ::std::vec::Vec::new(),
},
)
}
fn parse(
__ingraph_value: ::core::option::Option<#ag::Value>,
) -> #ag::InputValueResult<Self> {
if let ::core::option::Option::Some(#ag::Value::Object(mut __ingraph_object)) =
__ingraph_value
{
// EXACTLY ONE KEY, which is the whole of what `@oneOf` means — the validator refuses a
// request naming two or none before anything runs, and this is the arm that reads the
// one it admitted.
if #ag::indexmap::IndexMap::contains_key(&__ingraph_object, "coordinates")
&& __ingraph_object.len() == 1
{
let __ingraph_chosen = <#carried as #ag::InputType>::parse(
#ag::indexmap::IndexMap::swap_remove(&mut __ingraph_object, "coordinates"),
)
.map_err(#ag::InputValueError::propagate)?;
#crossed
return ::core::result::Result::Ok(Self::Coordinates(__ingraph_chosen));
}
return ::core::result::Result::Err(#ag::InputValueError::expected_type(
#ag::Value::Object(__ingraph_object),
));
}
::core::result::Result::Err(#ag::InputValueError::expected_type(
::core::option::Option::unwrap_or_default(__ingraph_value),
))
}
fn to_value(&self) -> #ag::Value {
let mut __ingraph_map = #ag::indexmap::IndexMap::new();
match self {
Self::Coordinates(__ingraph_chosen) => {
#carrying
__ingraph_map.insert(
#ag::Name::new("coordinates"),
<#carried as #ag::InputType>::to_value(&__ingraph_carried),
);
}
}
#ag::Value::Object(__ingraph_map)
}
#[inline]
fn as_raw_value(&self) -> ::core::option::Option<&Self::RawValueType> {
::core::option::Option::Some(self)
}
}
#[automatically_derived]
impl #ag::InputObjectType for #name {}
#[automatically_derived]
impl #ag::OneofObjectType for #name {}
};
(declared, face)
}
/// `<Index><Field>Question` — re-based by the BONES rename like every other minted name.
fn question_name(&self, tier: &crate::fuse::Tier<'_>, elected: &Elected) -> syn::Ident {
format_ident!("{}Question", tier.stem(elected))
}
/// **WHAT ONE ELECTION'S QUERY FIELD IS CALLED** — the declared word verbatim, or the derived
/// name.
///
/// ```text
/// #[ingraph(embedding, knn, lance(resource = "…"),
/// graphql(async_graphql(keys(rename = "clipNeighbours"))))]
/// └── replaces the whole name
/// ```
///
/// VERBATIM, and that is the choice worth stating: the derived name is composed from three parts
/// — the declaration, the election and the road — so a word that re-cased or re-composed what an
/// author wrote would be a rename they could not predict from what they typed. The front end
/// holds it to GraphQL's own Name grammar at the literal, which is where a caret can land.
///
/// # The resolution is MEMBER, then BASE-DERIVED, then DEFAULT
///
/// The road's own word answers first. Where it wrote none, the DERIVED half reads the rename-aware
/// base, so `rename = "…"` moves the field with the rest of the family; and where the declaration
/// wrote no base either, the derived name is built on its own ident. The declared half never moves
/// with a base, being a name in the SCHEMA's namespace rather than Rust's.
///
/// # FIVE seats for five roads, which is what closed the composition question
///
/// A declared word is VERBATIM, so it cannot be composed: a seat for the keys road says nothing
/// about what its hydrated twin should be called, and deriving `clipNeighboursHydrated` from
/// `clipNeighbours` would be the composition the verbatim law refuses. Two more seats was
/// therefore the only shape a word for the hydrated roads could take, and the 2026-08-16 rename
/// ruling minted them — so the seat set and [`Field`] are now one closed five, matched by
/// [`ElectionBackend::road`] where a missing arm is a compile error rather than a silent fallback.
#[must_use]
pub fn field_name(&self, elected: &Elected, which: Field) -> String {
self.road_name(&elected.field, which)
}
/// [`field_name`](Self::field_name) over a bare ident — the shape the FULL-TEXT kind has, whose
/// elections carry a name and nothing else.
///
/// One body for both, so the rename seat a vector election reads and the one a searchable field
/// reads cannot come to disagree about which word wins.
#[must_use]
pub fn road_name(&self, field: &syn::Ident, which: Field) -> String {
self
.numbers_of(field)
.and_then(|written| written.skin(GraphqlKind::AsyncGraphql))
.and_then(|skin| skin.road(which))
.map_or_else(|| which.derived(self.base(), field), syn::LitStr::value)
}
/// **THE KEYS ROAD's QUERY FIELD** — one election, one typed store, a ranked list of addresses.
///
/// # The ANSWER is the framework's [`Match<N, S>`], and nothing is minted for it
///
/// `ingraph::Match` was written FOR this field — its own note says so — and it carries exactly
/// what a retrieve produces: the engine's score in its own currency, the engine's ordinal with
/// the pipeline's holes left in, and the thing that matched. Minting a two-row `{key, score}`
/// object beside it would have dropped the ordinal, which is the number a client continues a
/// single-shot answer from, and would have put a second hit shape in a schema that already has
/// one. The SDL name is the NODE's, computed through async-graphql's `TypeName` hook — so the
/// field answers `[<UpstreamKey>Match!]!` and two declarations over one upstream publish one hit
/// type rather than two.
///
/// # The FLOOR comes from the request, because the framework has no zero to invent
///
/// `VectorEngine::Score` is bounded by `PartialOrd` and nothing else, so `Default::default()` is
/// not spellable — and it would be wrong where it is: the walk's test is `score >= floor` on a
/// score-DESCENDING stream, and the DIRECTION of an engine's currency is the engine's. A zero is
/// neutral for a similarity and prunes the whole corpus for anything measured the other way. Every
/// emitted Rust door takes its floor positionally from its caller for exactly this reason; the
/// caller here is the request, and the ruled seat a request already has for it is the `engine`
/// selector's own `floor` row. A request that names none is REFUSED by name — 宁短不凑, the
/// ruling the mandatory floor exists for.
///
/// # `first` is the PAGE and `depth` is the FETCH, and both are capped by the wall
///
/// The door takes one number, which is both the engine's `k` and the survivor budget. So `depth`
/// spends it — how deep the stream is walked, where the floor and the dedup do their pruning —
/// and the answer is then cut to `first`. Both go through `route_depth`, which is where the
/// declared ceiling caps an ask it can never be raised past.
///
/// `first: 0` answers the empty list WITHOUT reaching the door, which is the edge-zero law: the
/// door's currency is `NonZeroUsize`, so a zero is not a smaller question but no question at all.
fn keys_leg(
&self,
tier: &crate::fuse::Tier<'_>,
elected: &Elected,
engine: &Engine,
) -> proc_macro2::TokenStream {
let IndexModel { krate, index, .. } = self;
let ag = framework(krate, &[], "async_graphql");
let seam = framework(krate, &["store"], "VectorEngine");
let hit = framework(krate, &["graphql"], "Match");
let crossed = framework(krate, &["graphql"], "matches");
let ranked = framework(krate, &["retrieve"], "Ranked");
let query = framework(krate, &["retrieve"], "VectorQuery");
let connected = framework(krate, &["store"], "Connected");
let field = &elected.field;
let ty = engine
.resource
.as_ref()
.expect("a plain road names a typed engine");
let handle = self.wire_handle(ty);
let mint = self.wire_corpus(
field,
Some(&elected.ty),
engine,
ty,
&format_ident!("__ingraph_slot"),
&format_ident!("__ingraph_connection"),
);
let question = self.question_name(tier, elected);
let selector = tier
.slot_selector(elected)
.expect("a typed election mints its engine selector");
let variant = format_ident!("{}", {
use heck::ToUpperCamelCase as _;
engine.word.to_string().to_upper_camel_case()
});
let key = wire_key_name();
let sdl = self.field_name(elected, Field::Keys);
let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
let door = Door::Keys.name(field);
let arity = wide_signature();
let numbers = self.answer_numbers(&elected.field);
let point = self.point_binding(&question, elected);
// THE SCOPE, and HALF of it stopped being a seam. The CONNECTION is the mount's own manager,
// handed back beside the corpus by the mint below — so a resolver no longer writes `&()` where
// an engine expects its store, which is what made the whole road unreadable by the shipped
// engine. The READ SCOPE is still the unit: a lease is a value only the caller that opened a
// transaction has, and a request carries none. Spanned at the `resource = "…"` path, so a
// resource whose read scope is not the unit is `E0308` naming both, ON THE WORD THE AUTHOR
// WROTE, rather than inside an expansion.
let scope = quote_spanned! {ty.span()=>
#connected::new(__ingraph_connection, ())
};
let (floor, options) = (
format_ident!("__ingraph_floor"),
format_ident!("__ingraph_options"),
);
let floorless = format!(
"`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
`engine: {{ {engine_word}: {{ floor: … }} }}`. There is no number this framework could put \
there instead: a score's DIRECTION belongs to the engine that measures in it, so a zero is \
neutral for a similarity and prunes the whole corpus for a distance.",
engine_word = engine.word,
);
let doc = leading(&format!(
"The addresses [`{index}`]'s `{field}` ranks nearest a question, in `{engine_word}`.",
engine_word = engine.word,
));
let ctx = crate::method::wire_method(&format_ident!("ctx"));
let (asked, chosen, first, depth) = (
crate::method::wire_method(&format_ident!("question")),
crate::method::wire_method(&format_ident!("engine")),
crate::method::wire_method(&format_ident!("first")),
crate::method::wire_method(&format_ident!("depth")),
);
let default = self
.wire_first(GraphqlKind::AsyncGraphql, Some(field))
.get();
let default = syn::LitInt::new(&default.to_string(), field.span());
quote! {
#[doc = #doc]
#[graphql(name = #sdl)]
#arity
async fn #method(
&self,
#ctx: &#ag::Context<'_>,
#[graphql(name = "question")] #asked: #question,
#[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
#[graphql(name = "first", default = #default)] #first: u32,
#[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
) -> #ag::Result<::std::vec::Vec<#hit<#key, <#ty as #seam>::Score>>> {
#numbers
#point
let (#floor, #options) = match #chosen {
::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
// `Option::map` OVER `Option::cloned`: the latter is inherent on BOTH `Option<&T>` and
// `Option<&mut T>`, so a path call is `E0034` at a span the author cannot edit.
::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
__ingraph_named.options(),
),
::core::option::Option::None => (
::core::option::Option::None,
::core::option::Option::None,
),
};
let ::core::option::Option::Some(#floor) = #floor else {
return ::core::result::Result::Err(#ag::Error::new(#floorless));
};
#mint
// NO TURBOFISH: every parameter of the query is decided by what it is handed — the width and
// the space ride the point, the currency rides the floor — so a spelled one would be a
// second statement of a fact the arguments already carry.
let __ingraph_query = #query::new(__ingraph_point, #floor);
let mut __ingraph_ranked: ::std::vec::Vec<#ranked<_, _>> = #index::#door::<#handle>(
&mut __ingraph_slot,
#scope,
&__ingraph_query,
__ingraph_fetch,
#options,
)
.await
.map_err(|__ingraph_refusal| {
#ag::Error::new(::std::string::ToString::to_string(&__ingraph_refusal))
})?;
// THE PAGE, cut after the walk: `depth` bought the FETCH and `first` is what a client asked
// to read, and the two are different numbers whenever the floor or the dedup pruned.
::std::vec::Vec::truncate(
&mut __ingraph_ranked,
::core::num::NonZeroUsize::get(__ingraph_page),
);
::core::result::Result::Ok(#crossed(
::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_ranked),
|__ingraph_hit| {
let __ingraph_key = ::core::clone::Clone::clone(#ranked::node_ref(&__ingraph_hit));
#ranked::map_node(
__ingraph_hit,
<#key as ::core::convert::From<_>>::from(__ingraph_key),
)
},
),
))
}
}
}
/// **THE BY-EXAMPLE ROAD's QUERY FIELD** — one election, one typed store, an EXAMPLE KEY in, the
/// ranked addresses nearest it out, without the example.
///
/// # It is emitted on the PLAIN ROAD's own condition, and nothing more is needed
///
/// `retrieve_similar_by_<field>` takes a `SlotHandle` and no `AsyncGather` — `similar`'s own
/// `the_similar_door_takes_no_store` reads that off the signature — so the wall that holds tier B
/// holds none of this. What both roads need is the same thing: an `E` this expansion can spell,
/// which is `lance(resource = "…")` and nowhere else.
///
/// # The ARGUMENT is the upstream's KEY, crossing inward through the OPERAND MAP
///
/// Ruled 2026-08-16. Two derives are blind to each other, so this expansion cannot see whether the
/// upstream is a root or a child — and it does not have to: the wire form is
/// `<Key as ToGraphqlInput>::Input`, and the RECORD's own emission decides what that is. A root
/// answers with its ID's wire form and mints no type (`similarBy…(key: Int!)`); a compound key
/// answers with the product input object beside its address object
/// (`similarBy…(key: KeyframeKeyInput!)`). Both crossings are `ToGraphqlInput::cross` here, and
/// the refusal is `refused_address` — the same word the record's own `get(id:)` refuses a wrong
/// address under, so a client reads one code for one class of mistake.
///
/// A SCALAR encoding of a compound key was refused by the same ruling: a two-column address
/// packed into one string is a format a client has to be told out of band, which is a magic string
/// at an API floor.
///
/// # TWO READ SCOPES, because the door makes TWO engine calls
///
/// The door reads the example's own embedding and then asks the `knn`, and `Connected` is
/// deliberately not `Clone` — a scope may be a lease. Both carry the MOUNT's own manager, which
/// the one lookup hands back beside the corpus, and both read scopes are the unit — spanned at
/// the `resource = "…"` path for [`keys_leg`](Self::keys_leg)'s reason: a resource whose read
/// scope is not the unit is `E0308` naming both, on the word the author wrote.
///
/// # The NUMBERS, the FLOOR and the EDGE ZERO are the plain road's, unchanged
///
/// [`answer_numbers`](Self::answer_numbers) and the `engine` selector's `floor` seat are shared
/// rather than restated, which is what keeps the two roads from drifting at the one place both
/// spend a wall. `depth` is the FETCH and `first` is the PAGE here too — and the door's own note
/// adds the by-example reading of the gap between them: the example occupies one of the fetched
/// hits whenever it is among them, so an answer one short of the fetch is ordinary.
///
/// # THIS LEG IS THE UNIT ELECTION'S, and a SET election takes its twin instead
///
/// `retrieve_similar_by_<field>` is still emitted for every election whatever its label, and this
/// leg is what calls it — but only where the label says ONE. A `list(embedding)` election's
/// published field is the same NAME reaching
/// [`similar_set_leg`](Self::similar_set_leg) instead, which calls the `_with` twin and answers
/// the set hit; see [`answer_road`](Self::answer_road) for the routing and for the runtime
/// refusal it ends. The two legs are exclusive, so nothing here has to know which one ran.
fn similar_leg(
&self,
tier: &crate::fuse::Tier<'_>,
elected: &Elected,
engine: &Engine,
) -> proc_macro2::TokenStream {
let IndexModel { krate, index, .. } = self;
let ag = framework(krate, &[], "async_graphql");
let seam = framework(krate, &["store"], "VectorEngine");
let hit = framework(krate, &["graphql"], "Match");
let crossed = framework(krate, &["graphql"], "matches");
let crossing = framework(krate, &["graphql"], "ToGraphqlInput");
let refused_address = framework(krate, &["graphql"], "refused_address");
let ranked = framework(krate, &["retrieve"], "Ranked");
let connected = framework(krate, &["store"], "Connected");
let field = &elected.field;
let ty = engine
.resource
.as_ref()
.expect("a plain road names a typed engine");
let selector = tier
.slot_selector(elected)
.expect("a typed election mints its engine selector");
let variant = format_ident!("{}", {
use heck::ToUpperCamelCase as _;
engine.word.to_string().to_upper_camel_case()
});
let key = wire_key_name();
let example = example_key_name();
let sdl = self.field_name(elected, Field::Similar);
let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
let door = Door::Similar.name(field);
let arity = wide_signature();
let numbers = self.answer_numbers(&elected.field);
// TWO of them, because the door takes two and a `Connected` is not `Clone` — the door's own
// measurement, spent here rather than restated. Both carry the MOUNT's own manager, which the
// mint below hands back beside the corpus: a stateless handle reaches its index through it, and
// taking the two from one lookup is what stops a handle and a connection coming from two mounts.
let handle = self.wire_handle(ty);
let mint = self.wire_corpus(
field,
Some(&elected.ty),
engine,
ty,
&format_ident!("__ingraph_slot"),
&format_ident!("__ingraph_connection"),
);
let own = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
let scope = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
let (floor, options) = (
format_ident!("__ingraph_floor"),
format_ident!("__ingraph_options"),
);
let floorless = format!(
"`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
`engine: {{ {engine_word}: {{ floor: … }} }}`. There is no number this framework could put \
there instead: a score's DIRECTION belongs to the engine that measures in it, so a zero is \
neutral for a similarity and prunes the whole corpus for a distance.",
engine_word = engine.word,
);
let doc = leading(&format!(
"The addresses [`{index}`]'s `{field}` ranks nearest ONE ENTITY's own `{field}`, in \
`{engine_word}` — the example itself excluded.",
engine_word = engine.word,
));
let ctx = crate::method::wire_method(&format_ident!("ctx"));
let (asked, chosen, first, depth) = (
crate::method::wire_method(&format_ident!("key")),
crate::method::wire_method(&format_ident!("engine")),
crate::method::wire_method(&format_ident!("first")),
crate::method::wire_method(&format_ident!("depth")),
);
let default = self
.wire_first(GraphqlKind::AsyncGraphql, Some(field))
.get();
let default = syn::LitInt::new(&default.to_string(), field.span());
quote! {
#[doc = #doc]
#[graphql(name = #sdl)]
#arity
async fn #method(
&self,
#ctx: &#ag::Context<'_>,
#[graphql(name = "key")] #asked: <#example as #crossing>::Input,
#[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
#[graphql(name = "first", default = #default)] #first: u32,
#[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
) -> #ag::Result<::std::vec::Vec<#hit<#key, <#ty as #seam>::Score>>> {
#numbers
// THE EXAMPLE, read off the wire — the record's own `get(id:)` crossing, at the whole
// address instead of at the id alone, and refused under the same word.
let __ingraph_example = <#example as #crossing>::cross(#asked)
.map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?;
let (#floor, #options) = match #chosen {
::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
__ingraph_named.options(),
),
::core::option::Option::None => (
::core::option::Option::None,
::core::option::Option::None,
),
};
let ::core::option::Option::Some(#floor) = #floor else {
return ::core::result::Result::Err(#ag::Error::new(#floorless));
};
#mint
let mut __ingraph_ranked: ::std::vec::Vec<#ranked<_, _>> = #index::#door::<#handle>(
&mut __ingraph_slot,
#own,
#scope,
&__ingraph_example,
#floor,
__ingraph_fetch,
#options,
)
.await
.map_err(|__ingraph_refusal| {
#ag::Error::new(::std::string::ToString::to_string(&__ingraph_refusal))
})?;
// THE PAGE, cut after the walk — the plain road's law, with one more way for the two
// numbers to differ: the example consumes a fetched hit of its own.
::std::vec::Vec::truncate(
&mut __ingraph_ranked,
::core::num::NonZeroUsize::get(__ingraph_page),
);
::core::result::Result::Ok(#crossed(
::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_ranked),
|__ingraph_hit| {
let __ingraph_key = ::core::clone::Clone::clone(#ranked::node_ref(&__ingraph_hit));
#ranked::map_node(
__ingraph_hit,
<#key as ::core::convert::From<_>>::from(__ingraph_key),
)
},
),
))
}
}
}
/// **THE THREE PROJECTIONS A HYDRATED ROAD READS** — the upstream's hydration database, the row
/// that database keeps it as, and the wire object that row raises into.
///
/// Beside [`answer_bindings`](Self::answer_bindings) rather than inside it, and the split is the
/// GATE rather than tidiness: these resolve through
/// [`Hydrates`](../../../ingraph/trait.Hydrates.html), whose impl the RECORD emits inside its own
/// database's gate, so a build carrying the wire binding and no SQL family has nothing for them to
/// name. They therefore live in the `if_sqlx!` half beside the roads that spend them, where the
/// bindings above are shared by both halves and demand nothing a keys road does not already need.
///
/// Spanned at `upstream(node = "…")` for that function's reason: an upstream that is stored nowhere,
/// dressed nowhere, or kept only in a store with no query face is `E0277` ON A TOKEN AN AUTHOR CAN
/// EDIT, carrying `Hydrates`' own sentence, rather than somewhere inside an expansion. MEASURED,
/// the caret lands on the whole `#[ingraph::vector(…)]` rather than on the string inside it — the
/// same width every projection this expansion writes is reported at — so the span written here is
/// what a narrower caret would need and not what it already has.
///
/// The DATABASE is bound once and the other two are written over it, which is what makes the door
/// a resolver opens and the row its gather reads the same store by construction — two independent
/// spellings of `<Upstream as Hydrates>::Db` is where a page could open one connection and read
/// another's columns.
fn hydration_bindings(&self) -> proc_macro2::TokenStream {
let krate = &self.krate;
let hydrates = framework(krate, &["transform"], "Hydrates");
let vocabulary = framework(krate, &["transform"], "Record");
let transformer = framework(krate, &["transform"], "Transformer");
let face = framework(krate, &["transform"], "Graphql");
let upstream = &self.source.node;
let (db, row, entity) = hydration_names();
let at = upstream.span();
quote_spanned! {at=>
#[allow(dead_code, non_camel_case_types)]
type #db = <#upstream as #hydrates>::Db;
#[allow(dead_code, non_camel_case_types)]
type #row = <#upstream as #vocabulary<#db>>::Row;
#[allow(dead_code, non_camel_case_types)]
type #entity = <<#upstream as #transformer>::Graphql as #face>::Output;
}
}
/// **THE QUESTION ROAD, HYDRATED** — the keys road's twin one tier down: the same question in, the
/// upstream's WHOLE ENTITIES out.
///
/// ```text
/// shotsByClipKeys(question: …) → [KeyframeKeyMatch!]! the ADDRESSES — no store touched
/// shotsByClip(question: …) → [KeyframeMatch!]! the ENTITIES — one pooled gather
/// ```
///
/// # It rides TIER A and a `AsyncGather`, not the emitted tier B, and the ROW is why
///
/// `retrieve_by_<field>` answers the upstream's RECORDS, and there is no `Record → Output`
/// crossing anywhere in the tree: `emit::graphql`'s `row_crossings` writes a wire object's only
/// constructor as `TryFrom<<Record as Record<Db>>::Row>`, off the stored row. So a gather that
/// answered records would hand this face a value it cannot render, whatever else it did right.
/// [`SqlPooledGather`] answers ROWS, which is the fork point both crossings hang off — and this
/// road therefore calls tier A itself and composes the fill loop over it, exactly as
/// `ingraph/tests/hydrated_road.rs` measured before there was an emitter to ask for it.
///
/// # `&Pool` and never a borrowed connection, and that is a MEASUREMENT
///
/// `ingraph/tests/wire_trio.rs` put five shapes to the compiler: every one that held a borrowed
/// `Db::Connection` across the fill loop's `await` inside a resolver is *implementation of
/// `sqlx::Acquire` is not general enough*, because async-graphql bounds every resolver future
/// `Send` and sqlx implements `Acquire<'c>` for `&'c mut Connection` at one lifetime. The gather is
/// built from the door's pool for that reason and no other.
///
/// # The PAGE is cut AT THE LOOP, where the keys road truncates after the walk
///
/// A hydrated page is counted in ENTITIES: a key whose row the store has since lost drops, so a
/// truncate over the KEYS would answer short by however many rows went missing. `filled`'s own
/// limit is that cut — it keeps pulling keys until the page is full or the stream is exhausted —
/// so `__ingraph_page` is spent there and no `Vec::truncate` follows. What `depth` bought is
/// unchanged: it is the FETCH, capped by the declared ceiling, and it is what tier A is asked for.
///
/// # THREE refusals cross under three words, because they are three parties
///
/// The ENGINE's is the declarer's type and can implement no `ToErrorCode`, so it crosses as a bare
/// sentence — the keys road's own treatment. The GATHER's is the framework's own `SqlQueryError`,
/// which names its word, so it crosses through `refused`. The ROW's is the declaration's
/// output-crossing error, which crosses through `refused_row` exactly as the record's own single
/// leg raises a row — one code for one class of mistake, whichever road a client came down.
///
/// [`SqlPooledGather`]: ../../../ingraph/struct.SqlPooledGather.html
fn hydrated_leg(
&self,
tier: &crate::fuse::Tier<'_>,
elected: &Elected,
engine: &Engine,
) -> proc_macro2::TokenStream {
let IndexModel { krate, index, .. } = self;
let ag = framework(krate, &[], "async_graphql");
let seam = framework(krate, &["store"], "VectorEngine");
let hit = framework(krate, &["graphql"], "Match");
let sql_door = framework(krate, &["graphql"], "SqlDoor");
let refused = framework(krate, &["graphql"], "refused");
let refused_row = framework(krate, &["graphql"], "refused_row");
let gather = framework(krate, &["retrieve"], "SqlPooledGather");
let fill = framework(krate, &["retrieve"], "filled");
let ranked = framework(krate, &["retrieve"], "Ranked");
let query = framework(krate, &["retrieve"], "VectorQuery");
let connected = framework(krate, &["store"], "Connected");
let field = &elected.field;
let ty = engine
.resource
.as_ref()
.expect("a plain road names a typed engine");
let handle = self.wire_handle(ty);
let mint = self.wire_corpus(
field,
Some(&elected.ty),
engine,
ty,
&format_ident!("__ingraph_slot"),
&format_ident!("__ingraph_connection"),
);
let question = self.question_name(tier, elected);
let selector = tier
.slot_selector(elected)
.expect("a typed election mints its engine selector");
let variant = format_ident!("{}", {
use heck::ToUpperCamelCase as _;
engine.word.to_string().to_upper_camel_case()
});
let (db, row, entity) = hydration_names();
let sdl = self.field_name(elected, Field::Hydrated);
let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
let door = Door::Keys.name(field);
let arity = wide_signature();
let numbers = self.answer_numbers(&elected.field);
let point = self.point_binding(&question, elected);
let scope = quote_spanned! {ty.span()=>
#connected::new(__ingraph_connection, ())
};
let (floor, options) = (
format_ident!("__ingraph_floor"),
format_ident!("__ingraph_options"),
);
let floorless = format!(
"`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
`engine: {{ {engine_word}: {{ floor: … }} }}`. There is no number this framework could put \
there instead: a score's DIRECTION belongs to the engine that measures in it, so a zero is \
neutral for a similarity and prunes the whole corpus for a distance.",
engine_word = engine.word,
);
let doc = leading(&format!(
"The WHOLE UPSTREAM ENTITIES [`{index}`]'s `{field}` ranks nearest a question, in \
`{engine_word}` — each wearing the score and the ordinal its address carried.\n\nA hit whose \
row the system of record no longer holds is absent, and the ordinal it held stays a hole: \
the page is counted in entities, so the read pulls another address rather than closing the \
gap up.",
engine_word = engine.word,
));
let ctx = crate::method::wire_method(&format_ident!("ctx"));
let (asked, chosen, first, depth) = (
crate::method::wire_method(&format_ident!("question")),
crate::method::wire_method(&format_ident!("engine")),
crate::method::wire_method(&format_ident!("first")),
crate::method::wire_method(&format_ident!("depth")),
);
let default = self
.wire_first(GraphqlKind::AsyncGraphql, Some(field))
.get();
let default = syn::LitInt::new(&default.to_string(), field.span());
quote! {
#[doc = #doc]
#[graphql(name = #sdl)]
#arity
async fn #method(
&self,
#ctx: &#ag::Context<'_>,
#[graphql(name = "question")] #asked: #question,
#[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
#[graphql(name = "first", default = #default)] #first: u32,
#[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
) -> #ag::Result<::std::vec::Vec<#hit<#entity, <#ty as #seam>::Score>>> {
#numbers
#point
let (#floor, #options) = match #chosen {
::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
__ingraph_named.options(),
),
::core::option::Option::None => (
::core::option::Option::None,
::core::option::Option::None,
),
};
let ::core::option::Option::Some(#floor) = #floor else {
return ::core::result::Result::Err(#ag::Error::new(#floorless));
};
#mint
// THE STORE DOOR, keyed on the UPSTREAM's own projection — the same door its record's root
// fields take, so a schema installs one per store and never one per road.
let __ingraph_door = #ag::Context::data::<#sql_door<#db>>(#ctx)?;
let __ingraph_query = #query::new(__ingraph_point, #floor);
let __ingraph_ranked: ::std::vec::Vec<#ranked<_, _>> = #index::#door::<#handle>(
&mut __ingraph_slot,
#scope,
&__ingraph_query,
__ingraph_fetch,
#options,
)
.await
.map_err(|__ingraph_refusal| {
#ag::Error::new(::std::string::ToString::to_string(&__ingraph_refusal))
})?;
// HELD ACROSS THE `await` BELOW: the gather owns the pool borrow and, from its first batch
// on, the one connection the rest of the page runs on — so a page cannot span two states of
// the database.
let mut __ingraph_gather = #gather::<#row, #db>::new(#sql_door::pool(__ingraph_door));
let __ingraph_filled = #fill(
__ingraph_ranked,
&mut __ingraph_gather,
::core::option::Option::None,
::core::num::NonZeroUsize::get(__ingraph_page),
)
.await
.map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
// THE ONE CROSSING, and it is the record resolver's own: the row raises onto the wire
// through the conversion its declaration wrote. The two numbers are read off the hit they
// belong to and never assembled by hand.
::core::iter::Iterator::collect(::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_filled),
|__ingraph_hit| {
let (__ingraph_score, __ingraph_rank, __ingraph_row) =
#ranked::into_components(__ingraph_hit);
::core::result::Result::map_err(
::core::result::Result::map(
<#entity as ::core::convert::TryFrom<#row>>::try_from(__ingraph_row),
|__ingraph_entity| #hit::new(__ingraph_score, __ingraph_rank, __ingraph_entity),
),
|__ingraph_refusal| #refused_row(&__ingraph_refusal),
)
},
))
}
}
}
/// **THE BY-EXAMPLE ROAD, HYDRATED** — one entity's address in, its neighbours' whole rows out,
/// the example itself excluded.
///
/// [`hydrated_leg`](Self::hydrated_leg)'s every measurement holds here word for word: the row is
/// the fork point, the pool is the surface `Send` admits, the page is cut at the loop, and the
/// three refusals cross under their three words. What differs is the ARGUMENT — the upstream's own
/// key, crossing inward through the operand map, which is [`similar_leg`](Self::similar_leg)'s own
/// ruling and is read from that leg rather than restated — and the second read scope the
/// by-example door takes, `Connected` being deliberately not `Clone`.
///
/// The exclusion is the DOOR's, so hydrating changes nothing about which keys there were: the
/// example is absent, ordinal and all.
fn similar_hydrated_leg(
&self,
tier: &crate::fuse::Tier<'_>,
elected: &Elected,
engine: &Engine,
) -> proc_macro2::TokenStream {
let IndexModel { krate, index, .. } = self;
let ag = framework(krate, &[], "async_graphql");
let seam = framework(krate, &["store"], "VectorEngine");
let hit = framework(krate, &["graphql"], "Match");
let sql_door = framework(krate, &["graphql"], "SqlDoor");
let crossing = framework(krate, &["graphql"], "ToGraphqlInput");
let refused = framework(krate, &["graphql"], "refused");
let refused_row = framework(krate, &["graphql"], "refused_row");
let refused_address = framework(krate, &["graphql"], "refused_address");
let gather = framework(krate, &["retrieve"], "SqlPooledGather");
let fill = framework(krate, &["retrieve"], "filled");
let ranked = framework(krate, &["retrieve"], "Ranked");
let connected = framework(krate, &["store"], "Connected");
let field = &elected.field;
let ty = engine
.resource
.as_ref()
.expect("a plain road names a typed engine");
let selector = tier
.slot_selector(elected)
.expect("a typed election mints its engine selector");
let variant = format_ident!("{}", {
use heck::ToUpperCamelCase as _;
engine.word.to_string().to_upper_camel_case()
});
let example = example_key_name();
let (db, row, entity) = hydration_names();
let sdl = self.field_name(elected, Field::SimilarHydrated);
let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
let door = Door::Similar.name(field);
let arity = wide_signature();
let numbers = self.answer_numbers(&elected.field);
// TWO of them, because the door takes two and a `Connected` is not `Clone`. Both carry the
// MOUNT's own manager, which the mint below hands back beside the corpus.
let handle = self.wire_handle(ty);
let mint = self.wire_corpus(
field,
Some(&elected.ty),
engine,
ty,
&format_ident!("__ingraph_slot"),
&format_ident!("__ingraph_connection"),
);
let own = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
let scope = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
let (floor, options) = (
format_ident!("__ingraph_floor"),
format_ident!("__ingraph_options"),
);
let floorless = format!(
"`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
`engine: {{ {engine_word}: {{ floor: … }} }}`. There is no number this framework could put \
there instead: a score's DIRECTION belongs to the engine that measures in it, so a zero is \
neutral for a similarity and prunes the whole corpus for a distance.",
engine_word = engine.word,
);
let doc = leading(&format!(
"The WHOLE UPSTREAM ENTITIES [`{index}`]'s `{field}` ranks nearest ONE ENTITY's own \
`{field}`, in `{engine_word}` — the example itself excluded, and each neighbour wearing the \
score and the ordinal its address carried.\n\nA neighbour whose row the system of record no \
longer holds is absent, and the ordinal it held stays a hole.",
engine_word = engine.word,
));
let ctx = crate::method::wire_method(&format_ident!("ctx"));
let (asked, chosen, first, depth) = (
crate::method::wire_method(&format_ident!("key")),
crate::method::wire_method(&format_ident!("engine")),
crate::method::wire_method(&format_ident!("first")),
crate::method::wire_method(&format_ident!("depth")),
);
let default = self
.wire_first(GraphqlKind::AsyncGraphql, Some(field))
.get();
let default = syn::LitInt::new(&default.to_string(), field.span());
quote! {
#[doc = #doc]
#[graphql(name = #sdl)]
#arity
async fn #method(
&self,
#ctx: &#ag::Context<'_>,
#[graphql(name = "key")] #asked: <#example as #crossing>::Input,
#[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
#[graphql(name = "first", default = #default)] #first: u32,
#[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
) -> #ag::Result<::std::vec::Vec<#hit<#entity, <#ty as #seam>::Score>>> {
#numbers
let __ingraph_example = <#example as #crossing>::cross(#asked)
.map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?;
let (#floor, #options) = match #chosen {
::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
__ingraph_named.options(),
),
::core::option::Option::None => (
::core::option::Option::None,
::core::option::Option::None,
),
};
let ::core::option::Option::Some(#floor) = #floor else {
return ::core::result::Result::Err(#ag::Error::new(#floorless));
};
#mint
let __ingraph_door = #ag::Context::data::<#sql_door<#db>>(#ctx)?;
let __ingraph_ranked: ::std::vec::Vec<#ranked<_, _>> = #index::#door::<#handle>(
&mut __ingraph_slot,
#own,
#scope,
&__ingraph_example,
#floor,
__ingraph_fetch,
#options,
)
.await
.map_err(|__ingraph_refusal| {
#ag::Error::new(::std::string::ToString::to_string(&__ingraph_refusal))
})?;
let mut __ingraph_gather = #gather::<#row, #db>::new(#sql_door::pool(__ingraph_door));
let __ingraph_filled = #fill(
__ingraph_ranked,
&mut __ingraph_gather,
::core::option::Option::None,
::core::num::NonZeroUsize::get(__ingraph_page),
)
.await
.map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
::core::iter::Iterator::collect(::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_filled),
|__ingraph_hit| {
let (__ingraph_score, __ingraph_rank, __ingraph_row) =
#ranked::into_components(__ingraph_hit);
::core::result::Result::map_err(
::core::result::Result::map(
<#entity as ::core::convert::TryFrom<#row>>::try_from(__ingraph_row),
|__ingraph_entity| #hit::new(__ingraph_score, __ingraph_rank, __ingraph_entity),
),
|__ingraph_refusal| #refused_row(&__ingraph_refusal),
)
},
))
}
}
}
/// **THE FOLD ONE SET ROAD RUNS UNDER**, resolved into `__ingraph_fold` and named in
/// `__ingraph_fold_name` — the deployment's installed policy, or this election's own.
///
/// ```text
/// FoldDoor<Lance, ShotsByClip> installed at launch → the deployment's
/// semantics(fold = "app::Mine") written at the election → Shots::fold_by_clip()
/// neither → Sum, which is what that accessor is
/// ```
///
/// # The REQUEST is not in that chain, and its absence is the ruling
///
/// A fold changes what the answer MEANS — `sum` rewards a result that answered many query vectors
/// adequately, `max` one that answered a single vector perfectly — so a client able to swap it per
/// query is a client able to make two answers of one corpus that cannot be compared against each
/// other. No argument is emitted for it, and a request arm stays purely additive on the day one is
/// ruled: it would be a new `@oneOf` input beside `engine`, not a change to anything written here.
///
/// # The two arms are ONE `&dyn`, and that is what keeps the door monomorphized once
///
/// The two folds are two TYPES — one erased behind the door's `Arc`, one the concrete type the
/// election declared — so a `match` handing each straight to the door would emit the whole
/// resolver body twice for a choice made once per request. Coercing both to
/// `&dyn FoldSemantics<Score>` costs one virtual call PER ENTITY at the fold and one body; the
/// borrow folds through `FoldSemantics for &F`, so the door beneath is the same statically
/// dispatched door either way.
///
/// The elected fold is bound to a LOCAL first because the `&dyn` borrows it: `fold_by_<field>()`
/// answers by value, and a temporary inside the match arm would not outlive the `await` below.
fn fold_binding(&self, elected: &Elected, engine: &Engine) -> proc_macro2::TokenStream {
let krate = &self.krate;
let seam = framework(krate, &["store"], "VectorEngine");
let semantics = framework(krate, &["retrieve"], "FoldSemantics");
let door = framework(krate, &["graphql"], "FoldDoor");
let lookup = framework(krate, &["graphql"], "installed_fold");
let index = &self.index;
let ty = engine
.resource
.as_ref()
.expect("a plain road names a typed engine");
let marker = elected_marker(self.base(), &elected.field);
let elected_fold = fold_accessor(&elected.field);
let ctx = crate::method::wire_method(&format_ident!("ctx"));
quote! {
let __ingraph_elected_fold = #index::#elected_fold();
let __ingraph_fold: &dyn #semantics<<#ty as #seam>::Score> =
match #lookup::<#ty, #marker>(#ctx) {
::core::option::Option::Some(__ingraph_door) => #door::semantics(__ingraph_door),
::core::option::Option::None => &__ingraph_elected_fold,
};
// THE NAME, read off the resolved fold rather than off either arm — so a refusal names what
// actually folded, and the two arms cannot report differently about themselves.
let __ingraph_fold_name =
<dyn #semantics<<#ty as #seam>::Score>>::name(__ingraph_fold);
}
}
/// **THE BY-EXAMPLE SET ROAD's QUERY FIELD** — one election's EXAMPLE KEY in, the entities whose
/// own set best answers the example's whole set out, without the example.
///
/// ```text
/// shotsSimilarByClipKeys(key: …) → [KeyframeKeyFoldedMatch!]!
/// score the FOLD's answer over m streams
/// streams { score ordinal } one nullable slot per member of the example's own set
/// node { … }
/// ```
///
/// # It is [`similar_leg`](Self::similar_leg) at the OTHER LABEL, and the name does not move
///
/// Same field, same argument, same engine arm, same `first`/`depth` rows, same rename seat. What
/// differs is the door — `retrieve_similar_by_<field>_with` — and therefore the ANSWER, which
/// carries `m` per-stream sightings where the unit road carries one rank. See
/// [`answer_road`](Self::answer_road) for why the label picks the door and for the runtime refusal
/// this ends.
///
/// # The `m` IS THE DEPLOYMENT'S OWN DATA, and there is no guard on it
///
/// The streams a set road walks come from the example's stored set, so their number is whatever
/// the pipeline wrote for that entity rather than anything a request stated. A protective word
/// over it would be a bound on a deployment's own corpus, which is not a thing a request can
/// inflate. The road where that protection HAS a question to answer is the one asked with `m`
/// vectors a CLIENT sends, and it is minted there: `streams = N` is spent in
/// [`points_binding`](Self::points_binding), which only the question legs bind, and no leg on this
/// road emits a count at all.
///
/// # THE FLOOR IS THE ELEMENT'S, unchanged, and there is none in the folded currency
///
/// The engine arm's `floor` row cuts each of the `m` per-vector walks, exactly as it cuts the one
/// walk of the unit road. There is no floor on the folded score and there is no seat for one: a
/// sum of `m` cosines is in a third currency that no engine reports and no author could calibrate.
///
/// # AN EMPTY EXAMPLE SET IS REFUSED BY NAME
///
/// `set.rs`'s own law surfacing — *a set query with no query vectors asks nothing*, which is what
/// `FoldedQuery::of` answers `None` for. The door reaches it as `Unindexed` from the group read, and
/// this leg is where it becomes a sentence naming the field, the argument and the election, rather
/// than the store-shaped refusal a client cannot act on.
fn similar_set_leg(
&self,
tier: &crate::fuse::Tier<'_>,
elected: &Elected,
engine: &Engine,
) -> proc_macro2::TokenStream {
let IndexModel { krate, index, .. } = self;
let ag = framework(krate, &[], "async_graphql");
let seam = framework(krate, &["store"], "VectorEngine");
let hit = framework(krate, &["graphql"], "FoldedMatch");
let crossed = framework(krate, &["graphql"], "folded_matches");
let crossing = framework(krate, &["graphql"], "ToGraphqlInput");
let refused_address = framework(krate, &["graphql"], "refused_address");
let folded = framework(krate, &["retrieve"], "Folded");
let own_refusal = framework(krate, &["retrieve"], "OwnReadError");
let connected = framework(krate, &["store"], "Connected");
let field = &elected.field;
let ty = engine
.resource
.as_ref()
.expect("a plain road names a typed engine");
let selector = tier
.slot_selector(elected)
.expect("a typed election mints its engine selector");
let variant = format_ident!("{}", {
use heck::ToUpperCamelCase as _;
engine.word.to_string().to_upper_camel_case()
});
let key = wire_key_name();
let example = example_key_name();
let sdl = self.field_name(elected, Field::Similar);
let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
let door = Door::SimilarSet.name(field);
let arity = wide_signature();
let numbers = self.answer_numbers(&elected.field);
let fold = self.fold_binding(elected, engine);
// TWO of them, because the door takes two and a `Connected` is not `Clone`. Both carry the
// MOUNT's own manager, which the mint below hands back beside the corpus.
let handle = self.wire_handle(ty);
let mint = self.wire_corpus(
field,
Some(&elected.ty),
engine,
ty,
&format_ident!("__ingraph_slot"),
&format_ident!("__ingraph_connection"),
);
let own = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
let scope = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
let (floor, options) = (
format_ident!("__ingraph_floor"),
format_ident!("__ingraph_options"),
);
let floorless = format!(
"`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
`engine: {{ {engine_word}: {{ floor: … }} }}`. The floor cuts each of the query set's own \
walks, at the grain one pair of vectors is scored in; there is no floor on the folded score, \
which is in a currency no engine reports.",
engine_word = engine.word,
);
let empty = format!(
"`{sdl}` was asked with `key`, and that entity's `{field}` set is empty — a set query with no \
query vectors asks nothing, so there is no question here to answer. Index the entity's \
`{field}` and ask again.",
);
let doc = leading(&format!(
"The addresses [`{index}`]'s `{field}` SET ranks nearest ONE ENTITY's own `{field}` SET, in \
`{engine_word}` — the example itself excluded.\n\nEach of the example's own vectors is asked \
as its own query, and a FOLD is what turns those `m` answers into one score. Every hit \
carries what each of those streams said, under `streams`, in the order the example holds its \
vectors.\n\n{fold}",
engine_word = engine.word,
fold = fold_note(&elected.field, Asked::Example),
));
let ctx = crate::method::wire_method(&format_ident!("ctx"));
let (asked, chosen, first, depth) = (
crate::method::wire_method(&format_ident!("key")),
crate::method::wire_method(&format_ident!("engine")),
crate::method::wire_method(&format_ident!("first")),
crate::method::wire_method(&format_ident!("depth")),
);
let default = self
.wire_first(GraphqlKind::AsyncGraphql, Some(field))
.get();
let default = syn::LitInt::new(&default.to_string(), field.span());
quote! {
#[doc = #doc]
#[graphql(name = #sdl)]
#arity
async fn #method(
&self,
#ctx: &#ag::Context<'_>,
#[graphql(name = "key")] #asked: <#example as #crossing>::Input,
#[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
#[graphql(name = "first", default = #default)] #first: u32,
#[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
) -> #ag::Result<::std::vec::Vec<#hit<#key, <#ty as #seam>::Score>>> {
#numbers
let __ingraph_example = <#example as #crossing>::cross(#asked)
.map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?;
let (#floor, #options) = match #chosen {
::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
__ingraph_named.options(),
),
::core::option::Option::None => (
::core::option::Option::None,
::core::option::Option::None,
),
};
let ::core::option::Option::Some(#floor) = #floor else {
return ::core::result::Result::Err(#ag::Error::new(#floorless));
};
#mint
#fold
let mut __ingraph_folded: ::std::vec::Vec<#folded<_, _>> = #index::#door::<#handle, _>(
&mut __ingraph_slot,
#own,
#scope,
&__ingraph_example,
#floor,
__ingraph_fold,
__ingraph_fetch,
// THE PER-STREAM DEPTH IS THE DOOR'S OWN DEFAULT, which is the fetch above: `depth` is
// the FETCH on this family's wire and there is one such row, so passing it twice would be
// one number wearing two names. The door resolves `None` to its own `limit`, so this is
// byte-for-byte what a second spelling would compute.
::core::option::Option::None,
#options,
)
.await
.map_err(|__ingraph_refusal| match __ingraph_refusal {
// THE EMPTY SET, named: the group read answers `Unindexed` for a column holding nothing,
// and at THIS road that is a question with no query vectors rather than a missing row.
#own_refusal::Unindexed => #ag::Error::new(#empty),
__ingraph_refusal => #ag::Error::new(::std::format!(
"`{}` folded under `{}` and the road refused: {}",
#sdl,
__ingraph_fold_name,
__ingraph_refusal,
)),
})?;
// THE PAGE, cut after the fold — `depth` bought the FETCH and `first` is what a client asked
// to read. The fold's own budget counts ENTITIES, so the two numbers differ wherever the
// floor pruned a stream or the example consumed one of its own hits.
::std::vec::Vec::truncate(
&mut __ingraph_folded,
::core::num::NonZeroUsize::get(__ingraph_page),
);
::core::result::Result::Ok(#crossed(
::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_folded),
|__ingraph_hit| {
let __ingraph_key = ::core::clone::Clone::clone(#folded::node_ref(&__ingraph_hit));
#folded::map_node(
__ingraph_hit,
<#key as ::core::convert::From<_>>::from(__ingraph_key),
)
},
),
))
}
}
}
/// **THE BY-EXAMPLE SET ROAD, HYDRATED** — one entity's address in, its set-neighbours' whole rows
/// out, the example itself excluded.
///
/// [`similar_set_leg`](Self::similar_set_leg)'s every measurement holds, and
/// [`hydrated_leg`](Self::hydrated_leg)'s: the row is the fork point, the pool is the surface
/// `Send` admits, the page is cut at the fill loop, and the three refusals cross under their three
/// words. What is new is the CARRY — `folded_filled` is `filled` at this answer's arity, and it
/// moves the folded score and every per-stream sighting onto the entity found under the key.
///
/// A neighbour whose row the system of record no longer holds drops out, and the ordinals its
/// slots carried stay holes in the streams they came from — which is the same shape tier B already
/// leaves in a `rank`.
fn similar_set_hydrated_leg(
&self,
tier: &crate::fuse::Tier<'_>,
elected: &Elected,
engine: &Engine,
) -> proc_macro2::TokenStream {
let IndexModel { krate, index, .. } = self;
let ag = framework(krate, &[], "async_graphql");
let seam = framework(krate, &["store"], "VectorEngine");
let hit = framework(krate, &["graphql"], "FoldedMatch");
let sql_door = framework(krate, &["graphql"], "SqlDoor");
let crossing = framework(krate, &["graphql"], "ToGraphqlInput");
let refused = framework(krate, &["graphql"], "refused");
let refused_row = framework(krate, &["graphql"], "refused_row");
let refused_address = framework(krate, &["graphql"], "refused_address");
let gather = framework(krate, &["retrieve"], "SqlPooledGather");
let fill = framework(krate, &["retrieve"], "folded_filled");
let folded = framework(krate, &["retrieve"], "Folded");
let own_refusal = framework(krate, &["retrieve"], "OwnReadError");
let connected = framework(krate, &["store"], "Connected");
let field = &elected.field;
let ty = engine
.resource
.as_ref()
.expect("a plain road names a typed engine");
let selector = tier
.slot_selector(elected)
.expect("a typed election mints its engine selector");
let variant = format_ident!("{}", {
use heck::ToUpperCamelCase as _;
engine.word.to_string().to_upper_camel_case()
});
let example = example_key_name();
let (db, row, entity) = hydration_names();
let sdl = self.field_name(elected, Field::SimilarHydrated);
let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
let door = Door::SimilarSet.name(field);
let arity = wide_signature();
let numbers = self.answer_numbers(&elected.field);
let fold = self.fold_binding(elected, engine);
// TWO of them, because the door takes two and a `Connected` is not `Clone`. Both carry the
// MOUNT's own manager, which the mint below hands back beside the corpus.
let handle = self.wire_handle(ty);
let mint = self.wire_corpus(
field,
Some(&elected.ty),
engine,
ty,
&format_ident!("__ingraph_slot"),
&format_ident!("__ingraph_connection"),
);
let own = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
let scope = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
let (floor, options) = (
format_ident!("__ingraph_floor"),
format_ident!("__ingraph_options"),
);
let floorless = format!(
"`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
`engine: {{ {engine_word}: {{ floor: … }} }}`. The floor cuts each of the query set's own \
walks, at the grain one pair of vectors is scored in; there is no floor on the folded score, \
which is in a currency no engine reports.",
engine_word = engine.word,
);
let empty = format!(
"`{sdl}` was asked with `key`, and that entity's `{field}` set is empty — a set query with no \
query vectors asks nothing, so there is no question here to answer. Index the entity's \
`{field}` and ask again.",
);
let doc = leading(&format!(
"The WHOLE UPSTREAM ENTITIES [`{index}`]'s `{field}` SET ranks nearest ONE ENTITY's own \
`{field}` SET, in `{engine_word}` — the example itself excluded, and each neighbour wearing \
the folded score and the per-stream sightings its address carried.\n\nA neighbour whose row \
the system of record no longer holds is absent, and the ordinals it held stay \
holes.\n\n{fold}",
engine_word = engine.word,
fold = fold_note(&elected.field, Asked::Example),
));
let ctx = crate::method::wire_method(&format_ident!("ctx"));
let (asked, chosen, first, depth) = (
crate::method::wire_method(&format_ident!("key")),
crate::method::wire_method(&format_ident!("engine")),
crate::method::wire_method(&format_ident!("first")),
crate::method::wire_method(&format_ident!("depth")),
);
let default = self
.wire_first(GraphqlKind::AsyncGraphql, Some(field))
.get();
let default = syn::LitInt::new(&default.to_string(), field.span());
quote! {
#[doc = #doc]
#[graphql(name = #sdl)]
#arity
async fn #method(
&self,
#ctx: &#ag::Context<'_>,
#[graphql(name = "key")] #asked: <#example as #crossing>::Input,
#[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
#[graphql(name = "first", default = #default)] #first: u32,
#[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
) -> #ag::Result<::std::vec::Vec<#hit<#entity, <#ty as #seam>::Score>>> {
#numbers
let __ingraph_example = <#example as #crossing>::cross(#asked)
.map_err(|__ingraph_refusal| #refused_address(&__ingraph_refusal))?;
let (#floor, #options) = match #chosen {
::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
__ingraph_named.options(),
),
::core::option::Option::None => (
::core::option::Option::None,
::core::option::Option::None,
),
};
let ::core::option::Option::Some(#floor) = #floor else {
return ::core::result::Result::Err(#ag::Error::new(#floorless));
};
#mint
let __ingraph_door = #ag::Context::data::<#sql_door<#db>>(#ctx)?;
#fold
let __ingraph_folded: ::std::vec::Vec<#folded<_, _>> = #index::#door::<#handle, _>(
&mut __ingraph_slot,
#own,
#scope,
&__ingraph_example,
#floor,
__ingraph_fold,
__ingraph_fetch,
::core::option::Option::None,
#options,
)
.await
.map_err(|__ingraph_refusal| match __ingraph_refusal {
#own_refusal::Unindexed => #ag::Error::new(#empty),
__ingraph_refusal => #ag::Error::new(::std::format!(
"`{}` folded under `{}` and the road refused: {}",
#sdl,
__ingraph_fold_name,
__ingraph_refusal,
)),
})?;
let mut __ingraph_gather = #gather::<#row, #db>::new(#sql_door::pool(__ingraph_door));
let __ingraph_filled = #fill(
__ingraph_folded,
&mut __ingraph_gather,
::core::option::Option::None,
::core::num::NonZeroUsize::get(__ingraph_page),
)
.await
.map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
// THE ONE CROSSING, and it is the record resolver's own: the row raises onto the wire
// through the conversion its declaration wrote. The folded score and every slot are read off
// the hit they belong to and never assembled by hand — `map_node` is the one move.
::core::iter::Iterator::collect(::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_filled),
|__ingraph_hit| {
let (__ingraph_score, __ingraph_streams, __ingraph_row) =
#folded::into_components(__ingraph_hit);
::core::result::Result::map_err(
::core::result::Result::map(
<#entity as ::core::convert::TryFrom<#row>>::try_from(__ingraph_row),
|__ingraph_entity| <#hit<_, _> as ::core::convert::From<_>>::from(
#folded::new(__ingraph_score, __ingraph_streams, __ingraph_entity),
),
),
|__ingraph_refusal| #refused_row(&__ingraph_refusal),
)
},
))
}
}
}
/// **THE SET ROAD'S QUESTION FIELD** — `m` POINTS a client sent, walked as `m` streams and folded
/// into one ranking of addresses.
///
/// ```text
/// shotsByClipsKeys(question: { coordinates: [[…], […]] }) → [KeyframeKeyFoldedMatch!]!
/// score the FOLD's answer over m streams
/// streams { score ordinal } one nullable slot per point the request sent
/// node { … }
/// ```
///
/// # It is [`keys_leg`](Self::keys_leg) at the OTHER LABEL, and the name does not move
///
/// Same field, same `question:` argument, same engine arm, same `first`/`depth` rows, same rename
/// seat. What differs is the DOOR — `retrieve_keys_by_<field>_with` — and therefore the shape of
/// what is asked and what comes back: a list of points in, `m` per-stream sightings out. The label
/// picks it, exactly as it already picks the by-example door; see
/// [`answer_road`](Self::answer_road) for the routing.
///
/// This is the road whose absence [`similar_set_leg`](Self::similar_set_leg)'s note used to point
/// at — *the `_with` road asked with `m` vectors a CLIENT sends* — and it is where the protection
/// that note deferred now lives.
///
/// # The `m` IS THE REQUEST'S, which is the whole difference from the by-example twin
///
/// The by-example road reads its streams out of an example's stored set, so its `m` is the
/// deployment's own data and carries no guard. Here a client states `m`, so the declaration may
/// bound it: [`points_binding`](Self::points_binding) emits `streams = N`'s refusal, and a request
/// past the guard is refused naming the count rather than cut down to fit.
///
/// # NOTHING IS EXCLUDED, because there is no example to exclude
///
/// The by-example road drops the example from its own answer per stream. A question road has no
/// address in hand at all, so every owner the engine reports is a legitimate answer — the door
/// spends `owner_best` where its twin spends `owner_best_excluding`, and this leg states the
/// difference rather than compensating for it.
///
/// # THE FLOOR IS THE ELEMENT'S, and AN EMPTY LIST IS REFUSED BY NAME
///
/// Both are [`similar_set_leg`](Self::similar_set_leg)'s word for word: the engine arm's `floor`
/// row cuts each of the `m` per-vector walks and there is none in the folded currency, and
/// `FoldedQuery::new` answers [`None`] for an empty list — *a set query with no query vectors asks
/// nothing* — which this leg turns into a sentence naming the field and the argument.
fn set_keys_leg(
&self,
tier: &crate::fuse::Tier<'_>,
elected: &Elected,
engine: &Engine,
) -> proc_macro2::TokenStream {
let IndexModel { krate, index, .. } = self;
let ag = framework(krate, &[], "async_graphql");
let seam = framework(krate, &["store"], "VectorEngine");
let hit = framework(krate, &["graphql"], "FoldedMatch");
let crossed = framework(krate, &["graphql"], "folded_matches");
let folded = framework(krate, &["retrieve"], "Folded");
let set_query = framework(krate, &["retrieve"], "FoldedQuery");
let connected = framework(krate, &["store"], "Connected");
let field = &elected.field;
let ty = engine
.resource
.as_ref()
.expect("a plain road names a typed engine");
let selector = tier
.slot_selector(elected)
.expect("a typed election mints its engine selector");
let variant = format_ident!("{}", {
use heck::ToUpperCamelCase as _;
engine.word.to_string().to_upper_camel_case()
});
let key = wire_key_name();
let question = self.question_name(tier, elected);
let sdl = self.field_name(elected, Field::Keys);
let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
let door = Door::Set.name(field);
let arity = wide_signature();
let numbers = self.answer_numbers(&elected.field);
let points = self.points_binding(&question, elected, &sdl);
let fold = self.fold_binding(elected, engine);
let handle = self.wire_handle(ty);
let mint = self.wire_corpus(
field,
Some(&elected.ty),
engine,
ty,
&format_ident!("__ingraph_slot"),
&format_ident!("__ingraph_connection"),
);
let scope = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
let (floor, options) = (
format_ident!("__ingraph_floor"),
format_ident!("__ingraph_options"),
);
let floorless = format!(
"`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
`engine: {{ {engine_word}: {{ floor: … }} }}`. The floor cuts each of the question's own \
walks, at the grain one pair of vectors is scored in; there is no floor on the folded score, \
which is in a currency no engine reports.",
engine_word = engine.word,
);
let empty = format!(
"`{sdl}` was asked with no query vectors — a set query with no query vectors asks nothing, so \
there is no question here to answer. Name at least one point under \
`question: {{ coordinates: [[…]] }}`.",
);
let doc = leading(&format!(
"The addresses [`{index}`]'s `{field}` SET ranks nearest a whole QUESTION SET, in \
`{engine_word}`.\n\nEach point the request sent is asked as its own query, and a FOLD is what \
turns those `m` answers into one score. Every hit carries what each of those streams said, \
under `streams`, in the order the request wrote its points.\n\n{fold}",
engine_word = engine.word,
fold = fold_note(
&elected.field,
Asked::Points(self.declared_streams(Some(&elected.field))),
),
));
let ctx = crate::method::wire_method(&format_ident!("ctx"));
let (asked, chosen, first, depth) = (
crate::method::wire_method(&format_ident!("question")),
crate::method::wire_method(&format_ident!("engine")),
crate::method::wire_method(&format_ident!("first")),
crate::method::wire_method(&format_ident!("depth")),
);
let default = self
.wire_first(GraphqlKind::AsyncGraphql, Some(field))
.get();
let default = syn::LitInt::new(&default.to_string(), field.span());
quote! {
#[doc = #doc]
#[graphql(name = #sdl)]
#arity
async fn #method(
&self,
#ctx: &#ag::Context<'_>,
#[graphql(name = "question")] #asked: #question,
#[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
#[graphql(name = "first", default = #default)] #first: u32,
#[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
) -> #ag::Result<::std::vec::Vec<#hit<#key, <#ty as #seam>::Score>>> {
#numbers
#points
let (#floor, #options) = match #chosen {
::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
__ingraph_named.options(),
),
::core::option::Option::None => (
::core::option::Option::None,
::core::option::Option::None,
),
};
let ::core::option::Option::Some(#floor) = #floor else {
return ::core::result::Result::Err(#ag::Error::new(#floorless));
};
// THE EMPTY QUESTION, named — and the CONSTRUCTOR is what names it: `FoldedQuery::new` answers
// `None` for an empty list, so the law lives at the type and this leg spends it rather than
// restating it as a length test of its own.
let ::core::option::Option::Some(__ingraph_query) =
#set_query::new(__ingraph_points, #floor)
else {
return ::core::result::Result::Err(#ag::Error::new(#empty));
};
#mint
#fold
let mut __ingraph_folded: ::std::vec::Vec<#folded<_, _>> = #index::#door::<#handle, _>(
&mut __ingraph_slot,
#scope,
&__ingraph_query,
__ingraph_fold,
__ingraph_fetch,
// THE PER-STREAM DEPTH IS THE DOOR'S OWN DEFAULT, which is the fetch above — the
// by-example twin's line, and its reason unchanged: `depth` is the FETCH on this family's
// wire and there is one such row, so passing it twice would be one number wearing two
// names.
::core::option::Option::None,
#options,
)
.await
.map_err(|__ingraph_refusal| #ag::Error::new(::std::format!(
"`{}` folded under `{}` and the road refused: {}",
#sdl,
__ingraph_fold_name,
__ingraph_refusal,
)))?;
// THE PAGE, cut after the fold — `depth` bought the FETCH and `first` is what a client asked
// to read. The fold's own budget counts ENTITIES, so the two numbers differ wherever the
// floor pruned a stream.
::std::vec::Vec::truncate(
&mut __ingraph_folded,
::core::num::NonZeroUsize::get(__ingraph_page),
);
::core::result::Result::Ok(#crossed(
::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_folded),
|__ingraph_hit| {
let __ingraph_key = ::core::clone::Clone::clone(#folded::node_ref(&__ingraph_hit));
#folded::map_node(
__ingraph_hit,
<#key as ::core::convert::From<_>>::from(__ingraph_key),
)
},
),
))
}
}
}
/// **THE SET ROAD'S QUESTION FIELD, HYDRATED** — `m` points in, the neighbours' whole rows out,
/// each wearing the folded score and every per-stream sighting.
///
/// [`set_keys_leg`](Self::set_keys_leg)'s every measurement holds, and
/// [`similar_set_hydrated_leg`](Self::similar_set_hydrated_leg)'s: the row is the fork point, the
/// pool is the surface `Send` admits, the page is cut at the fill loop, and `folded_filled` is what
/// moves the folded score and every slot onto the entity found under the key.
///
/// It is mounted for its twin's reason and unmounted for the same one: a declaration wearing the
/// head's `keys` word has an ENTITY upstream and no store for this tier to read rows out of.
fn set_hydrated_leg(
&self,
tier: &crate::fuse::Tier<'_>,
elected: &Elected,
engine: &Engine,
) -> proc_macro2::TokenStream {
let IndexModel { krate, index, .. } = self;
let ag = framework(krate, &[], "async_graphql");
let seam = framework(krate, &["store"], "VectorEngine");
let hit = framework(krate, &["graphql"], "FoldedMatch");
let sql_door = framework(krate, &["graphql"], "SqlDoor");
let refused = framework(krate, &["graphql"], "refused");
let refused_row = framework(krate, &["graphql"], "refused_row");
let gather = framework(krate, &["retrieve"], "SqlPooledGather");
let fill = framework(krate, &["retrieve"], "folded_filled");
let folded = framework(krate, &["retrieve"], "Folded");
let set_query = framework(krate, &["retrieve"], "FoldedQuery");
let connected = framework(krate, &["store"], "Connected");
let field = &elected.field;
let ty = engine
.resource
.as_ref()
.expect("a plain road names a typed engine");
let selector = tier
.slot_selector(elected)
.expect("a typed election mints its engine selector");
let variant = format_ident!("{}", {
use heck::ToUpperCamelCase as _;
engine.word.to_string().to_upper_camel_case()
});
let (db, row, entity) = hydration_names();
let question = self.question_name(tier, elected);
let sdl = self.field_name(elected, Field::Hydrated);
let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
let door = Door::Set.name(field);
let arity = wide_signature();
let numbers = self.answer_numbers(&elected.field);
let points = self.points_binding(&question, elected, &sdl);
let fold = self.fold_binding(elected, engine);
let handle = self.wire_handle(ty);
let mint = self.wire_corpus(
field,
Some(&elected.ty),
engine,
ty,
&format_ident!("__ingraph_slot"),
&format_ident!("__ingraph_connection"),
);
let scope = quote_spanned! {ty.span()=> #connected::new(__ingraph_connection, ())};
let (floor, options) = (
format_ident!("__ingraph_floor"),
format_ident!("__ingraph_options"),
);
let floorless = format!(
"`{sdl}` needs a floor in `{engine_word}`'s own score currency — write \
`engine: {{ {engine_word}: {{ floor: … }} }}`. The floor cuts each of the question's own \
walks, at the grain one pair of vectors is scored in; there is no floor on the folded score, \
which is in a currency no engine reports.",
engine_word = engine.word,
);
let empty = format!(
"`{sdl}` was asked with no query vectors — a set query with no query vectors asks nothing, so \
there is no question here to answer. Name at least one point under \
`question: {{ coordinates: [[…]] }}`.",
);
let doc = leading(&format!(
"The WHOLE UPSTREAM ENTITIES [`{index}`]'s `{field}` SET ranks nearest a whole QUESTION SET, \
in `{engine_word}` — each neighbour wearing the folded score and the per-stream sightings its \
address carried.\n\nA neighbour whose row the system of record no longer holds is absent, and \
the ordinals it held stay holes.\n\n{fold}",
engine_word = engine.word,
fold = fold_note(
&elected.field,
Asked::Points(self.declared_streams(Some(&elected.field))),
),
));
let ctx = crate::method::wire_method(&format_ident!("ctx"));
let (asked, chosen, first, depth) = (
crate::method::wire_method(&format_ident!("question")),
crate::method::wire_method(&format_ident!("engine")),
crate::method::wire_method(&format_ident!("first")),
crate::method::wire_method(&format_ident!("depth")),
);
let default = self
.wire_first(GraphqlKind::AsyncGraphql, Some(field))
.get();
let default = syn::LitInt::new(&default.to_string(), field.span());
quote! {
#[doc = #doc]
#[graphql(name = #sdl)]
#arity
async fn #method(
&self,
#ctx: &#ag::Context<'_>,
#[graphql(name = "question")] #asked: #question,
#[graphql(name = "engine")] #chosen: ::core::option::Option<#selector>,
#[graphql(name = "first", default = #default)] #first: u32,
#[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
) -> #ag::Result<::std::vec::Vec<#hit<#entity, <#ty as #seam>::Score>>> {
#numbers
#points
let (#floor, #options) = match #chosen {
::core::option::Option::Some(#selector::#variant(ref __ingraph_named)) => (
::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
__ingraph_named.options(),
),
::core::option::Option::None => (
::core::option::Option::None,
::core::option::Option::None,
),
};
let ::core::option::Option::Some(#floor) = #floor else {
return ::core::result::Result::Err(#ag::Error::new(#floorless));
};
let ::core::option::Option::Some(__ingraph_query) =
#set_query::new(__ingraph_points, #floor)
else {
return ::core::result::Result::Err(#ag::Error::new(#empty));
};
#mint
let __ingraph_door = #ag::Context::data::<#sql_door<#db>>(#ctx)?;
#fold
let __ingraph_folded: ::std::vec::Vec<#folded<_, _>> = #index::#door::<#handle, _>(
&mut __ingraph_slot,
#scope,
&__ingraph_query,
__ingraph_fold,
__ingraph_fetch,
::core::option::Option::None,
#options,
)
.await
.map_err(|__ingraph_refusal| #ag::Error::new(::std::format!(
"`{}` folded under `{}` and the road refused: {}",
#sdl,
__ingraph_fold_name,
__ingraph_refusal,
)))?;
let mut __ingraph_gather = #gather::<#row, #db>::new(#sql_door::pool(__ingraph_door));
let __ingraph_filled = #fill(
__ingraph_folded,
&mut __ingraph_gather,
::core::option::Option::None,
::core::num::NonZeroUsize::get(__ingraph_page),
)
.await
.map_err(|__ingraph_refusal| #refused(&__ingraph_refusal))?;
::core::iter::Iterator::collect(::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_filled),
|__ingraph_hit| {
let (__ingraph_score, __ingraph_streams, __ingraph_row) =
#folded::into_components(__ingraph_hit);
::core::result::Result::map_err(
::core::result::Result::map(
<#entity as ::core::convert::TryFrom<#row>>::try_from(__ingraph_row),
|__ingraph_entity| <#hit<_, _> as ::core::convert::From<_>>::from(
#folded::new(__ingraph_score, __ingraph_streams, __ingraph_entity),
),
),
|__ingraph_refusal| #refused_row(&__ingraph_refusal),
)
},
))
}
}
}
/// The TWO NUMBERS every answer leg resolves before it touches a door — the fetch depth and the
/// page — with the edge-zero law as the one early return.
///
/// Written once because both roads spend it identically and a chain written twice is a chain that
/// can drift at one of them.
fn answer_numbers(&self, field: &syn::Ident) -> proc_macro2::TokenStream {
let depth = framework(&self.krate, &["retrieve"], "route_depth");
// TWO COPIES OF ONE WALL, and it is the borrow rather than two facts: the token is
// `Option::as_ref(&NonZeroU32::new(N))`, whose temporary lives to the end of the statement it
// sits in, so the two `let`s below cannot share one.
let (wall, again) = (self.wall(Some(field)), self.wall(Some(field)));
let first = crate::method::wire_method(&format_ident!("first"));
let written = crate::method::wire_method(&format_ident!("depth"));
quote! {
// THE EDGE-ZERO LAW, and it is the same line as the widening: the door's currency admits no
// zero, so `first: 0` is not a smaller question but no question at all — answered here,
// before any door, any slot lookup and any engine call.
let ::core::option::Option::Some(__ingraph_budget) = ::core::num::NonZeroU32::new(#first)
else {
return ::core::result::Result::Ok(::std::vec::Vec::new());
};
let __ingraph_budget = ::core::result::Result::unwrap_or(
<::core::num::NonZeroUsize as ::core::convert::TryFrom<::core::num::NonZeroU32>>::try_from(
__ingraph_budget,
),
::core::num::NonZeroUsize::MAX,
);
let __ingraph_fetch = #depth(
::core::option::Option::map(
::core::option::Option::and_then(#written, ::core::num::NonZeroU32::new),
|__ingraph_asked| ::core::result::Result::unwrap_or(
<::core::num::NonZeroUsize as ::core::convert::TryFrom<
::core::num::NonZeroU32,
>>::try_from(__ingraph_asked),
::core::num::NonZeroUsize::MAX,
),
),
#wall,
__ingraph_budget,
);
// THE PAGE is the ask with NO edge — `min(first, wall)` — which is the same law read with
// nothing written at the request: what a client may read is what it asked for, inside the
// wall it may never ask past.
let __ingraph_page = #depth(::core::option::Option::None, #again, __ingraph_budget);
}
}
/// THE POINT a request named, width-checked against the election's own projection.
///
/// The refusal names the FIELD and BOTH numbers, which is the whole reason the check is here
/// rather than in the input's `parse`: a GraphQL list carries no width, so nothing below this can
/// know that four coordinates were asked of a 768-wide column.
///
/// A SET election's question road binds [`points_binding`](Self::points_binding) instead — the
/// same check per point, with the offending index named — and the two are exclusive, the label
/// having already chosen which door the leg calls.
fn point_binding(&self, asked: &syn::Ident, elected: &Elected) -> proc_macro2::TokenStream {
let embedding = framework(&self.krate, &["storage"], "Embedding");
let ag = framework(&self.krate, &[], "async_graphql");
let question = crate::method::wire_method(&format_ident!("question"));
let field = elected.field.to_string();
let (width, space, element) = answer_geometry(elected);
quote! {
let #question = match #question {
#asked::Coordinates(__ingraph_written) => __ingraph_written,
};
let __ingraph_given = ::std::vec::Vec::len(&#question);
let ::core::option::Option::Some(__ingraph_point) =
<#embedding<#element, { #width }, #space>>::new(::std::sync::Arc::from(#question))
else {
return ::core::result::Result::Err(#ag::Error::new(::std::format!(
"`{field}` embeds at {width} coordinates and this question carries {given}",
field = #field,
width = #width,
given = __ingraph_given,
)));
};
}
}
/// THE `m` POINTS a request named, each width-checked, bound to `__ingraph_points` — and the
/// declared stream guard, where one was written.
///
/// [`point_binding`](Self::point_binding)'s twin one list deeper, and every word of that one's
/// note holds per point: a GraphQL list carries no width, so nothing below this can know that four
/// coordinates were asked of a 768-wide column.
///
/// # The refusal names WHICH point, which is the whole reason the loop is written out
///
/// A request carrying `m` lists has `m` chances to get the width wrong, and a sentence naming the
/// field and both numbers would leave the author to find the offender by bisection. The index is
/// the position in the list the client itself wrote, so it is a number they can act on.
///
/// # The GUARD is emitted only where a declaration wrote one, and it REFUSES
///
/// `streams = N` — see [`Numbers::streams`] for the protection-tier reading and
/// [`declared_streams`](Self::declared_streams) for the two-tier chain. Past the guard the request
/// is refused whole and never cut down to fit: dropping query vectors answers a different question
/// under the same name, which is the ruled refuse-don't-chunk law read at `m`. Where no tier wrote
/// a guard nothing at all is emitted, so an unguarded road is byte-for-byte what it was before the
/// word existed.
///
/// The EMPTINESS is deliberately NOT checked here: `FoldedQuery::new` answers [`None`] for an empty
/// list and the leg spends that, so *a set query with no query vectors asks nothing* keeps ONE
/// authority.
fn points_binding(
&self,
asked: &syn::Ident,
elected: &Elected,
sdl: &str,
) -> proc_macro2::TokenStream {
let embedding = framework(&self.krate, &["storage"], "Embedding");
let ag = framework(&self.krate, &[], "async_graphql");
let question = crate::method::wire_method(&format_ident!("question"));
let field = elected.field.to_string();
let (width, space, element) = answer_geometry(elected);
let guard = match self.declared_streams(Some(&elected.field)) {
Some(cap) => {
let past = format!(
"`{sdl}` admits at most {cap} query vectors and this question carries {{asked}} — \
`streams = {cap}` is what this declaration lets ONE request spend. The question is not \
cut down to fit: dropping query vectors answers a different question under the same \
name, so one past the guard is refused whole. Ask it in batches of {cap}.",
cap = cap.get(),
);
let cap = syn::LitInt::new(&cap.get().to_string(), elected.field.span());
quote! {
if __ingraph_asked > #cap {
return ::core::result::Result::Err(#ag::Error::new(::std::format!(
#past,
asked = __ingraph_asked,
)));
}
}
}
None => proc_macro2::TokenStream::new(),
};
quote! {
let #question = match #question {
#asked::Coordinates(__ingraph_written) => __ingraph_written,
};
let __ingraph_asked = ::std::vec::Vec::len(&#question);
#guard
let mut __ingraph_points = ::std::vec::Vec::with_capacity(__ingraph_asked);
for (__ingraph_at, __ingraph_written) in
::core::iter::Iterator::enumerate(::std::vec::Vec::into_iter(#question))
{
let __ingraph_given = ::std::vec::Vec::len(&__ingraph_written);
let ::core::option::Option::Some(__ingraph_point) =
<#embedding<#element, { #width }, #space>>::new(::std::sync::Arc::from(__ingraph_written))
else {
return ::core::result::Result::Err(#ag::Error::new(::std::format!(
"`{field}` embeds at {width} coordinates and query vector {at} of this question \
carries {given}",
field = #field,
width = #width,
at = __ingraph_at,
given = __ingraph_given,
)));
};
::std::vec::Vec::push(&mut __ingraph_points, __ingraph_point);
}
}
}
/// **THE FANNED ROAD's ANSWER FAMILY** — one object per leg, the union over them, and the hit that
/// carries a fused root with its whole provenance.
///
/// # Why a UNION and not one object with a nullable score per leg
///
/// A sighting IS one leg's — the fold produced it by reading that leg's ranking — and each leg
/// scores in its own engine's currency, which crosses AS ITSELF. A product with `deep: Float` beside
/// `shallow: Float` would publish a shape where both could be set, neither could, and the two
/// currencies had been flattened into one; the sum publishes the fact.
///
/// # The FOLD's own numbers are `Float` at every arm, and that is not an inconsistency
///
/// `contribution` is `weight × 1/(k + rank)` and the hit's `score` is their sum — the FRAMEWORK's
/// arithmetic over ordinals rather than any engine's measurement — so they are one type however
/// many currencies met. [`Sighting`](https://docs.rs/ingraph) states the same split one layer down.
fn fused_answer(
&self,
tier: &crate::fuse::Tier<'_>,
elected: &Elected,
legs: &[&Engine],
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
use heck::ToUpperCamelCase as _;
let IndexModel {
vis, krate, index, ..
} = self;
let ag = framework(krate, &[], "async_graphql");
let shelf = crate::emit::vendored(krate, "async_graphql");
let seam = framework(krate, &["store"], "VectorEngine");
let transformer = framework(krate, &["transform"], "Transformer");
let face = framework(krate, &["transform"], "Graphql");
let output = framework(krate, &["transform"], "GraphqlOutput");
let upstream = &self.source.node;
let field = &elected.field;
let stem = tier.stem(elected);
let union = format_ident!("{stem}Sighting");
let hit = format_ident!("{stem}FusedKeyMatch");
let engines = format_ident!("{stem}Engines");
let key = wire_key_name();
let members: Vec<syn::Ident> = legs
.iter()
.map(|engine| {
format_ident!(
"{stem}{}Sighting",
engine.word.to_string().to_upper_camel_case()
)
})
.collect();
let variants: Vec<syn::Ident> = legs
.iter()
.map(|engine| format_ident!("{}", engine.word.to_string().to_upper_camel_case()))
.collect();
let scores: Vec<proc_macro2::TokenStream> = legs
.iter()
.map(|engine| {
let ty = engine
.resource
.as_ref()
.expect("a fanned road types every leg");
quote!(<#ty as #seam>::Score)
})
.collect();
// THE ENGINES PRODUCT — one row per leg, each holding that leg's OWN `{floor, options}` package.
//
// A PRODUCT where the selector beside it is a SUM, and the two shapes say two different things:
// the `@oneOf` selector picks ONE leg to read directly, and this names them ALL because the
// fused road walks them all and every one of them needs a floor in its own currency. Built
// through the tier's own package emitter, so its factory chain, its readers and its input face
// are the ones every other package in this family has.
let engines_package = tier.packages().package(
&engines,
&format!(
"The per-leg knobs a FUSED retrieve over [`{index}`]'s `{field}` runs under — one row per \
store the field is written to, each holding that store's own floor and per-query knobs.\n\n\
Every row is the requester's, and the floor is the one this framework cannot default: a \
score's direction belongs to the engine that measures in it."
),
&legs
.iter()
.map(|engine| {
crate::fuse::Row::new(
&engine.word,
{
let package = tier.engine_input(&stem, engine);
quote!(#package)
},
&format!("`{}` leg", engine.word),
)
})
.collect::<Vec<_>>(),
);
let sighting_docs = members.iter().zip(legs).map(|(member, engine)| {
let doc = leading(&format!(
"What the `{word}` store said about a fused root of [`{index}`]'s `{field}` — its own \
score, its own ordinal, and what that ordinal contributed to the fused score.",
word = engine.word,
));
let ty = engine
.resource
.as_ref()
.expect("a fanned road types every leg");
let score = quote!(<#ty as #seam>::Score);
let members = crate::emit::substrate();
quote! {
#[doc = #doc]
#[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
#vis struct #member {
#members score: #score,
#members ordinal: ::core::primitive::u64,
#members contribution: ::core::primitive::f64,
}
#[automatically_derived]
impl #member {
#[doc = " One sighting, in the order the fold hands its three numbers over."]
#[must_use]
#[inline]
#vis const fn new(
score: #score,
ordinal: ::core::primitive::u64,
contribution: ::core::primitive::f64,
) -> Self {
Self { score, ordinal, contribution }
}
#[doc = " The score this store gave the root, in this store's own currency."]
#[must_use]
#[inline]
#vis const fn score_ref(&self) -> &#score {
&self.score
}
#[doc = " The 1-based ordinal this store gave the root in its own stream."]
#[must_use]
#[inline]
#vis const fn ordinal(&self) -> ::core::primitive::u64 {
self.ordinal
}
#[doc = " The weighted term that ordinal added to the fused score."]
#[must_use]
#[inline]
#vis const fn contribution(&self) -> ::core::primitive::f64 {
self.contribution
}
}
}
});
let union_doc = leading(&format!(
"WHICH of [`{index}`]'s `{field}` stores saw a fused root, and what it said — one arm per leg \
the answer can name."
));
let hit_doc = leading(&format!(
"One fused address of [`{index}`]'s `{field}`: where it landed, what the fold scored it, and \
every store that put it there.\n\nThe evidence is CONTRIBUTION-ORDERED — the biggest mover \
first — which is the order the fold itself produced."
));
let substrate = crate::emit::substrate();
let declared = quote! {
#engines_package
#(#sighting_docs)*
#[doc = #union_doc]
#[derive(::core::fmt::Debug, ::core::clone::Clone, ::core::cmp::PartialEq)]
#vis enum #union {
#(#variants(#members),)*
}
// NO `PartialEq`: the row carries the UPSTREAM's address object, which is a wire projection
// and derives none — and a derive here would make this type's faces depend on a decision
// another declaration's emission made. The two rows that ARE comparable carry their own.
#[doc = #hit_doc]
#[derive(::core::fmt::Debug, ::core::clone::Clone)]
#vis struct #hit {
#substrate key:
<<<#upstream as #transformer>::Graphql as #face>::Output as #output>::Key,
#substrate score: ::core::primitive::f64,
#substrate evidence: ::std::vec::Vec<#union>,
}
#[automatically_derived]
impl #hit {
#[doc = " One fused hit, in the order the fold hands its three parts over."]
#[must_use]
#[inline]
#vis const fn new(
key: <<<#upstream as #transformer>::Graphql as #face>::Output as #output>::Key,
score: ::core::primitive::f64,
evidence: ::std::vec::Vec<#union>,
) -> Self {
Self { key, score, evidence }
}
#[doc = " The address, borrowed."]
#[must_use]
#[inline]
#vis const fn key_ref(
&self,
) -> &<<<#upstream as #transformer>::Graphql as #face>::Output as #output>::Key {
&self.key
}
#[doc = " The FUSED score — comparable against the other rows of this answer and nothing else."]
#[must_use]
#[inline]
#vis const fn score(&self) -> ::core::primitive::f64 {
self.score
}
#[doc = " Every store that saw this root, biggest mover first."]
#[must_use]
#[inline]
#vis fn evidence(&self) -> &[#union] {
&self.evidence
}
}
};
let member_faces = members
.iter()
.zip(&scores)
.zip(legs)
.map(|((member, score), engine)| {
let sdl = tier.packages().sdl(member);
let word = &engine.word;
let doc = format!("What the `{word}` store said about this root.");
let (score_method, ordinal, contribution) = (
crate::method::wire_method(&format_ident!("score")),
crate::method::wire_method(&format_ident!("ordinal")),
crate::method::wire_method(&format_ident!("contribution")),
);
quote! {
#[doc = #doc]
#[#ag::Object(crate = #shelf, name = #sdl)]
impl #member {
#[graphql(name = "score")]
async fn #score_method(&self) -> &#score {
#member::score_ref(self)
}
#[graphql(name = "ordinal")]
async fn #ordinal(&self) -> ::core::primitive::u64 {
#member::ordinal(self)
}
#[graphql(name = "contribution")]
async fn #contribution(&self) -> ::core::primitive::f64 {
#member::contribution(self)
}
}
}
});
let union_sdl = tier.packages().sdl(&union);
let hit_sdl = tier.packages().sdl(&hit);
// THE ROW WORD IS `node`, which is the Match family's across every tier — see
// `ingraph::graphql::Match`, whose Rust field has carried the word since the type was written.
// The METHOD is named for the row it publishes and the FIELD keeps the Rust noun it holds, which
// is the same split the hand-written face draws.
let (node_method, score_method, evidence_method) = (
crate::method::wire_method(&format_ident!("node")),
crate::method::wire_method(&format_ident!("score")),
crate::method::wire_method(&format_ident!("evidence")),
);
let hit_face_doc = "One fused result: the address, the fused score, and every store that put it \
there.";
let face = quote! {
#(#member_faces)*
// THE UNION, written out. `#[derive(Union)]` is unreachable from an emission: a derive is
// written ON the declaration, the declaration is ungated so that a build with no wire binding
// still compiles, and `#[cfg_attr]` cannot bridge the two — that predicate asks whether the
// DECLARING crate has a feature called `async-graphql`, which is a different manifest.
#[automatically_derived]
impl #ag::resolver_utils::ContainerType for #union {
async fn resolve_field(
&self,
_ctx: &#ag::Context<'_>,
) -> #ag::ServerResult<::core::option::Option<#ag::Value>> {
::core::result::Result::Ok(::core::option::Option::None)
}
fn collect_all_fields<'__ingraph_seen>(
&'__ingraph_seen self,
__ingraph_ctx: &#ag::ContextSelectionSet<'__ingraph_seen>,
__ingraph_fields: &mut #ag::resolver_utils::Fields<'__ingraph_seen>,
) -> #ag::ServerResult<()> {
match self {
#(Self::#variants(__ingraph_arm) => #ag::resolver_utils::ContainerType::collect_all_fields(
__ingraph_arm,
__ingraph_ctx,
__ingraph_fields,
),)*
}
}
}
#[automatically_derived]
impl #ag::OutputType for #union {
fn type_name() -> ::std::borrow::Cow<'static, ::core::primitive::str> {
::std::borrow::Cow::Borrowed(#union_sdl)
}
fn introspection_type_name(&self) -> ::std::borrow::Cow<'static, ::core::primitive::str> {
match self {
#(Self::#variants(_) => <#members as #ag::OutputType>::type_name(),)*
}
}
fn create_type_info(
__ingraph_registry: &mut #ag::registry::Registry,
) -> ::std::string::String {
__ingraph_registry.create_output_type::<Self, _>(
#ag::registry::MetaTypeId::Union,
|__ingraph_registry| {
#(<#members as #ag::OutputType>::create_type_info(__ingraph_registry);)*
#ag::registry::MetaType::Union {
name: ::std::string::String::from(#union_sdl),
description: ::core::option::Option::None,
possible_types: {
let mut __ingraph_arms = #ag::indexmap::IndexSet::new();
#(__ingraph_arms.insert(::std::borrow::Cow::into_owned(
<#members as #ag::OutputType>::type_name(),
));)*
__ingraph_arms
},
visible: ::core::option::Option::None,
inaccessible: false,
tags: ::std::vec::Vec::new(),
rust_typename: ::core::option::Option::Some(::core::any::type_name::<Self>()),
directive_invocations: ::std::vec::Vec::new(),
}
},
)
}
async fn resolve(
&self,
__ingraph_ctx: &#ag::ContextSelectionSet<'_>,
_field: &#ag::Positioned<#ag::parser::types::Field>,
) -> #ag::ServerResult<#ag::Value> {
#ag::resolver_utils::resolve_container(__ingraph_ctx, self).await
}
}
#[automatically_derived]
impl #ag::UnionType for #union {}
#[doc = #hit_face_doc]
#[#ag::Object(crate = #shelf, name = #hit_sdl)]
impl #hit {
#[graphql(name = "node")]
async fn #node_method(&self) -> &#key {
#hit::key_ref(self)
}
#[graphql(name = "score")]
async fn #score_method(&self) -> ::core::primitive::f64 {
#hit::score(self)
}
#[graphql(name = "evidence")]
async fn #evidence_method(&self) -> &[#union] {
#hit::evidence(self)
}
}
};
(declared, face)
}
/// **THE FUSED ROAD's QUERY FIELD** — one question, every store the field is written to, one
/// leaderboard.
///
/// The floors are per LEG and per CURRENCY, which is why the argument is a product rather than the
/// `@oneOf` selector: the fused road walks every leg, and two stores holding one field score in
/// two units that do not convert. The selector's road — read ONE named leg directly — is not
/// published here; it is the same door with `options.engine` set, and it belongs to the round that
/// gives this field its fuse options.
fn fused_leg(
&self,
tier: &crate::fuse::Tier<'_>,
elected: &Elected,
legs: &[&Engine],
) -> proc_macro2::TokenStream {
use heck::ToUpperCamelCase as _;
let IndexModel { krate, index, .. } = self;
let ag = framework(krate, &[], "async_graphql");
let marker = framework(krate, &["election"], "EmbeddingMarker");
let connected = framework(krate, &["store"], "Connected");
let fused = framework(krate, &["retrieve"], "Fused");
let fused_score = framework(krate, &["retrieve"], "FusedScore");
let sighting = framework(krate, &["retrieve"], "Sighting");
let field = &elected.field;
let ty = &elected.ty;
let stem = tier.stem(elected);
let question = self.question_name(tier, elected);
let engines_ty = format_ident!("{stem}Engines");
let union = format_ident!("{stem}Sighting");
let hit = format_ident!("{stem}FusedKeyMatch");
let evidence = tier.slot_evidence_name(elected);
let asked_package = tier.route_question(elected);
let key = wire_key_name();
let door = Door::FusedLegs.name(field);
let sdl = self.field_name(elected, Field::Fused);
let method = crate::method::wire_method(&format_ident!("{}", crate::emit::snake(&sdl)));
let arity = wide_signature();
let numbers = self.answer_numbers(&elected.field);
let point = self.point_binding(&question, elected);
let engines: Vec<&syn::Path> = legs
.iter()
.map(|engine| {
engine
.resource
.as_ref()
.expect("a fanned road types every leg")
})
.collect();
// ONE HANDLE PER LEG — what the fused door's engine parameters are. A leg names a MOUNT and the
// door is bounded on a read face, so every parameter is the CORPUS type that mount mints.
let handles: Vec<proc_macro2::TokenStream> =
engines.iter().map(|ty| self.wire_handle(ty)).collect();
let variants: Vec<syn::Ident> = legs
.iter()
.map(|engine| format_ident!("{}", engine.word.to_string().to_upper_camel_case()))
.collect();
let members: Vec<syn::Ident> = legs
.iter()
.map(|engine| {
format_ident!(
"{stem}{}Sighting",
engine.word.to_string().to_upper_camel_case()
)
})
.collect();
let ctx = crate::method::wire_method(&format_ident!("ctx"));
let seats = legs.iter().enumerate().map(|(at, engine)| {
let engine_ty = engines[at];
let reader = &engine.word;
let (floor, options, slot, connection) = (
format_ident!("__ingraph_floor_{}", engine.word),
format_ident!("__ingraph_options_{}", engine.word),
format_ident!("__ingraph_slot_{}", engine.word),
format_ident!("__ingraph_connection_{}", engine.word),
);
let mint = self.wire_corpus(
field,
Some(&elected.ty),
engine,
engine_ty,
&slot,
&connection,
);
let floorless = format!(
"`{sdl}` needs a floor in `{reader}`'s own score currency — write \
`engines: {{ {reader}: {{ floor: … }} }}`. Every leg of a fused read states its own, \
because two stores holding one field score in two units that do not convert, and there is \
no number this framework could put there instead: a score's DIRECTION belongs to the \
engine that measures in it."
);
let seat = crate::method::wire_method(&format_ident!("engines"));
quote! {
let (#floor, #options) = match #seat.#reader() {
::core::option::Option::Some(__ingraph_named) => (
// `Option::map` OVER `Option::cloned`: the latter is inherent on BOTH `Option<&T>` and
// `Option<&mut T>`, so a path call is `E0034` at a span the author cannot edit.
::core::option::Option::map(__ingraph_named.floor(), ::core::clone::Clone::clone),
__ingraph_named.options(),
),
::core::option::Option::None => (
::core::option::Option::None,
::core::option::Option::None,
),
};
let ::core::option::Option::Some(#floor) = #floor else {
return ::core::result::Result::Err(#ag::Error::new(#floorless));
};
#mint
}
});
let arguments = legs.iter().enumerate().map(|(at, engine)| {
let engine_ty = engines[at];
let (floor, options, slot, connection) = (
format_ident!("__ingraph_floor_{}", engine.word),
format_ident!("__ingraph_options_{}", engine.word),
format_ident!("__ingraph_slot_{}", engine.word),
format_ident!("__ingraph_connection_{}", engine.word),
);
// THE SCOPE, per leg — `keys_leg`'s own measurement, and the same span discipline. Each leg
// carries ITS OWN mount's manager, two legs of a fan being two resources, and the READ SCOPE
// is still the unit: an engine whose scope is not the unit is `E0308` on the
// `resource = "…"` path its author wrote.
let scope = quote_spanned! {engine_ty.span()=>
#connected::new(#connection, ())
};
quote! {
&mut #slot,
#scope,
#floor,
#options,
}
});
let default = self
.wire_first(GraphqlKind::AsyncGraphql, Some(field))
.get();
let default = syn::LitInt::new(&default.to_string(), field.span());
let doc = leading(&format!(
"The addresses [`{index}`]'s `{field}` ranks nearest a question, across every store it is \
written to at once — one leaderboard, joined by reciprocal rank fusion."
));
let (asked, seat, first, depth) = (
crate::method::wire_method(&format_ident!("question")),
crate::method::wire_method(&format_ident!("engines")),
crate::method::wire_method(&format_ident!("first")),
crate::method::wire_method(&format_ident!("depth")),
);
quote! {
#[doc = #doc]
#[graphql(name = #sdl)]
#arity
async fn #method(
&self,
#ctx: &#ag::Context<'_>,
#[graphql(name = "question")] #asked: #question,
#[graphql(name = "engines")] #seat: #engines_ty,
#[graphql(name = "first", default = #default)] #first: u32,
#[graphql(name = "depth")] #depth: ::core::option::Option<u32>,
) -> #ag::Result<::std::vec::Vec<#hit>> {
#numbers
#point
#(#seats)*
// THE CARRIER, reached through `Into` rather than by assuming the declaration's own item IS
// an `Embedding`: the framework's row converts reflexively, and a third-party carrier joins
// by writing one `From` — which is the openness the election family is built on.
let __ingraph_carried: <#ty as #marker>::Item =
::core::convert::Into::into(__ingraph_point);
let __ingraph_asked = #asked_package::new().with_coordinates(__ingraph_carried);
let mut __ingraph_fused = #index::#door::<#(#handles),*>(
#(#arguments)*
// NO FUSE OPTIONS: this field publishes the plain leaderboard, so the weights, the flavour
// and the per-leg edges are the declaration's own. The seat exists on the door and is
// filled by the round that gives this field its options package.
::core::option::Option::None,
&__ingraph_asked,
__ingraph_fetch,
)
.await
.map_err(|__ingraph_refusal| {
#ag::Error::new(::std::string::ToString::to_string(&__ingraph_refusal))
})?;
::std::vec::Vec::truncate(
&mut __ingraph_fused,
::core::num::NonZeroUsize::get(__ingraph_page),
);
::core::result::Result::Ok(::core::iter::Iterator::collect(
::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_fused),
|__ingraph_row| {
let (__ingraph_score, __ingraph_root, __ingraph_evidence) =
#fused::into_components(__ingraph_row);
#hit::new(
<#key as ::core::convert::From<_>>::from(__ingraph_root),
#fused_score::get(&__ingraph_score),
::core::iter::Iterator::collect(::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_evidence),
|__ingraph_seen| {
let (__ingraph_contribution, __ingraph_ordinal, __ingraph_leg) =
#sighting::into_components(__ingraph_seen);
match __ingraph_leg {
#(#evidence::#variants(__ingraph_at) => #union::#variants(
#members::new(__ingraph_at, __ingraph_ordinal, __ingraph_contribution),
),)*
}
},
)),
)
},
),
))
}
}
}
/// THE ARTIFACT-FAMILY BRIDGE — this declaration's own facts, written into a TYPE so that an
/// entity's wire face can project them off a path.
///
/// # Why a type and not a token read
///
/// The fields that serve this family live on the OUTPUT OBJECT of the entity its objects are
/// derived from, and that object is written by that entity's expansion. This one cannot reach it
/// — a second `#[Object]` block on one type is `E0119` three times over — and that one cannot read
/// this declaration, two derives being blind to each other. So the crossing is a trait: the
/// entity's `locate(…)` word gives its expansion this family's PATH, and everything it needs is a
/// projection off it.
///
/// # What is emitted, and what is deliberately left for somebody else to write
///
/// | impl | when | why |
/// |---|---|---|
/// | `BlobArtifact` | every artifact family | slot, upstream and the type-level suffix are all this declaration's |
/// | `ArtifactSuffix` | every artifact family | the `extension` word's six forms, resolved |
/// | `ArtifactStore` | the family named a store `ingraph` SHIPS | it is the only store this crate can spell |
/// | `ArtifactData` | that, and the family wrote `data` | reading takes the store, so the capability needs one |
///
/// The last two are absent for a family whose store word is bound at a GRAPH ROOT, and the absence
/// is the openness rather than a gap: a root's `engines(…)` is written where the program is
/// assembled, and no declaration's expansion can see one. `ArtifactStore`'s own
/// `on_unimplemented` names both roads, and the second — implement it for the family — is a
/// two-screen impl that this crate's `artifact_bridge` vantage writes in full.
///
/// # The SLOT is minted from the declaration's name, snake-cased — unless a word said otherwise
///
/// The convention every durable name a declaration mints already takes — `RecordModel::table_name`
/// defaults a table this way and `Slot::name` says so out loud — so an artifact family's directory
/// is `thumbnail` for a `Thumbnail`. It was recorded as a NAMING DECISION with an escape named:
/// *the alternative (a word on the head) is additive the day somebody wants a slot that is not the
/// type's name*. That day came, and the word is [`IndexModel::slot`]. The default is untouched, so
/// nothing already stored moves.
fn artifact_bridge(&self) -> proc_macro2::TokenStream {
if self.kind != NodeKind::Blob {
return proc_macro2::TokenStream::new();
}
use heck::ToSnakeCase as _;
let IndexModel { index, krate, .. } = self;
let artifact = framework(krate, &["record"], "BlobArtifact");
let slot_name = framework(krate, &["slot"], "SlotName");
let source = &self.source.node;
// THE DECLARED NAME OR THE CONVENTION, and the convention is what every family written before
// the word arrived is stored under — which is why the word is additive rather than a migration.
let slot = self
.slot
.as_ref()
.map_or_else(|| index.to_string().to_snake_case(), syn::LitStr::value);
let statik = match self.extension.as_ref().and_then(Extension::statik) {
Some(suffix) => quote!(::core::option::Option::Some(#suffix)),
None => quote!(::core::option::Option::None),
};
let suffix = self.artifact_suffix();
let store = self.artifact_store();
quote! {
#[automatically_derived]
impl #artifact for #index {
type Upstream = #source;
const SLOT: &'static #slot_name = #slot_name::new(#slot);
const SUFFIX: ::core::option::Option<&'static ::core::primitive::str> = #statik;
}
#suffix
#store
}
}
/// THE SIX FORMS, resolved — `ArtifactSuffix`, in whichever of its two shapes this family's
/// `extension` word calls for.
///
/// # Two column-less forms take the BLANKET, and it is their implementation rather than a stub
///
/// `extension = "png"` and the omitted form both answer off the type, so the trait's own default
/// body — `Self::SUFFIX`, mapped — already IS them. The impl is written over EVERY row
/// (`impl<__INGRAPH_ROW__> ArtifactSuffix<__INGRAPH_ROW__>`), which costs nothing and buys the
/// thing that matters: the family binds for a caller's row whatever that row turns out to be, so
/// an upstream with no wire face is never asked for one.
///
/// # Four COLUMN forms take one impl, at the row they actually read
///
/// The row is `<Upstream as Graphql>::Output` — the hydrated object a resolver is holding — and
/// the read is a DIRECT MEMBER read, for the reason this file's projections already are: an
/// accessor is spelled four ways depending on what the declaration asked for, and the member's
/// name is the one spelling that does not vary. A column the upstream does not expose is `E0609`
/// at the emitted read, and an upstream with NO wire face is `E0277` on `Graphql` — both at the
/// declaration, which is where the column form's own law says the value has to be: *`from` names a
/// column the locate-field resolver already holds hydrated.*
///
/// # The order inside the body is the two fences' own
///
/// `variants` is an INPUT fence and `any_of` an OUTPUT one, so the body checks the value, renders,
/// and then checks the rendering — which is exactly what makes a `with` hook compose with both.
/// The hook eats the COLUMN VALUE and never the row, which is what lets ONE function serve the
/// write lane and this face at once.
///
/// The enum road renders through the column type's own `as_str()` — the storage textual form
/// `#[derive(ingraph::Enum)]` emits — and the string road through `AsRef<str>`. A type answering
/// neither is `E0599`/`E0277` at the emitted call, at the span its author wrote.
fn artifact_suffix(&self) -> proc_macro2::TokenStream {
let IndexModel { index, krate, .. } = self;
let face = framework(krate, &["record"], "ArtifactSuffix");
let Some(column) = self.extension.as_ref().and_then(Extension::column) else {
let row = format_ident!("__INGRAPH_ROW__");
return quote! {
#[automatically_derived]
impl<#row> #face<#row> for #index {}
};
};
let unfenced = framework(krate, &["record"], "UnfencedSuffix");
let graphql = framework(krate, &["transform"], "Graphql");
let source = &self.source.node;
let field = column.source.field();
let family = index.to_string();
let named = field.to_string();
// The COLUMN VALUE, read by member and borrowed once — every road below reads this binding, so
// the read happens in one place whichever of the four the declaration took.
let value = quote_spanned!(field.span()=> &__ingraph_row.#field);
let enumerated = column.source.enumerated().is_some();
// WHAT THE ROW HELD, as text, for a refusal. The enum road has to render before it can report,
// which is why this is not simply the value: a vocabulary enum's `Debug` is a Rust spelling and
// its `as_str` is the one a declaration wrote.
let found = if enumerated {
quote!(::std::string::ToString::to_string(__ingraph_value.as_str()))
} else {
quote!(::std::string::ToString::to_string(
::core::convert::AsRef::<::core::primitive::str>::as_ref(__ingraph_value)
))
};
// THE INPUT FENCE — the enum road's subset, as PATTERNS. Emitting the variant as a pattern is
// what makes rustc verify it EXISTS, at the string literal that named it: the expansion
// prefix-checked the path against `from`'s type and can check nothing more, so the other half is
// bought by referring to it.
let input = (!column.variants.is_empty()).then(|| {
let patterns: Vec<proc_macro2::TokenStream> = column
.variants
.iter()
.map(|variant| match variant.parse::<syn::Path>() {
Ok(path) => quote_spanned!(variant.span()=> #path),
// Unreachable through the derive, which parses the same literal to prefix-check it. A
// second front end that did not would get its refusal from rustc rather than a panic here.
Err(refusal) => refusal.to_compile_error(),
})
.collect();
let admitted = column.variants.iter().map(syn::LitStr::value);
quote! {
const __INGRAPH_VARIANTS__: &[&::core::primitive::str] = &[#(#admitted),*];
if !::core::matches!(__ingraph_value, #(#patterns)|*) {
return ::core::result::Result::Err(
#unfenced::new(#family, #named, __INGRAPH_VARIANTS__, #found),
);
}
}
});
// THE RENDER, in the three shapes the roads take.
let render = match &column.with {
Some(hook) => quote_spanned!(hook.span()=> #hook(__ingraph_value)),
None if enumerated => quote!(__ingraph_value.as_str()),
None => quote!(::core::convert::AsRef::<::core::primitive::str>::as_ref(
__ingraph_value
)),
};
// THE OUTPUT FENCE — which SUFFIXES this family says it produces. Required on the string road
// and optional on the enum one, so its absence here is the declaration's own answer.
let output = (!column.any_of.is_empty()).then(|| {
let admitted = column.any_of.iter().map(syn::LitStr::value);
quote! {
const __INGRAPH_ANY_OF__: &[&::core::primitive::str] = &[#(#admitted),*];
if !<[&::core::primitive::str]>::contains(
__INGRAPH_ANY_OF__,
&&*__ingraph_suffix,
) {
return ::core::result::Result::Err(#unfenced::new(
#family,
#named,
__INGRAPH_ANY_OF__,
::std::string::ToString::to_string(&*__ingraph_suffix),
));
}
}
});
let row = quote!(<#source as #graphql>::Output);
quote! {
#[automatically_derived]
impl #face<#row> for #index {
fn suffix(
__ingraph_row: &#row,
) -> ::core::result::Result<
::core::option::Option<::std::borrow::Cow<'_, ::core::primitive::str>>,
#unfenced,
> {
let __ingraph_value = #value;
#input
let __ingraph_suffix: ::std::borrow::Cow<'_, ::core::primitive::str> =
::core::convert::Into::into(#render);
#output
::core::result::Result::Ok(::core::option::Option::Some(__ingraph_suffix))
}
}
}
}
/// WHERE THE OBJECTS LIVE — `ArtifactStore` and, under the `data` word, `ArtifactData`, for a
/// family that named a store this crate can SPELL.
///
/// # `fs` is the only word, and that is a measurement rather than a shape
///
/// `EngineKind` is the SHIPPED table, and `ingraph` ships exactly one artifact store. A word
/// outside it is bound at a graph root, which no expansion can see, so nothing here could name its
/// type — and closing the vocabulary to fix that would be the framework deciding which stores may
/// serve a wire field. The family writes the impl instead, and reaches every field the shipped one
/// does.
///
/// # It goes through the KEY-ONLY door, not through `AsyncLocate`
///
/// `LocalFsBlob::address` and `::fetch` take the key's own walk and the suffix and nothing else.
/// The `AsyncLocate` verb beside them reaches the same funnel through a supertrait that projects
/// `BlobRecord` — a payload face this expansion does not emit, and cannot emit without ruling
/// WHICH of a family's declared fields is the payload. The narrower door is the funnel at the
/// bound it actually has, so the bridge needs no such ruling.
///
/// # THIS BODY IS PURE ADDRESSING, and no layer here goes looking
///
/// `locate` is a RENDER at every grain: the capability's own law says a locate which secretly
/// stats is the *`get` that throws its bytes away* it exists instead of, and this layer keeps it
/// rather than spending a syscall of its own one storey up. The division is **addressing here,
/// PRESENCE AT USE**, and the reason is that a presence answer expires the instant it is produced
/// — a `Some` can 404 by the time a client fetches, a `None` can exist by then — so every consumer
/// handles absence at use ANYWAY, and a per-row `stat` buys an unreliable hint while writing the
/// 404 handling twice.
///
/// The seam's `Option` is untouched and its clause still reads exactly right: *each impl draws its
/// own split, because only the store knows what it is able to know*. A store whose presence IS a
/// row column answers `None` honestly and for free; fs and network stores answer `Some(rendered)`
/// and say so. `required` on a locate position remains the SDL promotion, and its
/// `None`-conversion is reachable on the stores that can produce one.
///
/// Recorded plainly, because it is what a deployment on fs will observe: a bare locate position
/// never nulls here. The placeholder UX rides `onerror` on the client, or the data road, which
/// finds the absence for free and un-expired.
///
/// # `ArtifactData` is emitted UNDER THE WORD, and that is the whole of what the word buys
///
/// Presence at the type layer: a family that wrote `data` has the impl and a family that did not
/// has none, so a field asking for bytes is `E0277` naming the family and the word rather than a
/// null on the wire.
fn artifact_store(&self) -> proc_macro2::TokenStream {
let IndexModel { index, krate, .. } = self;
if !self
.stores
.iter()
.any(|engine| engine.shipped() == Some(EngineKind::Fs))
{
return proc_macro2::TokenStream::new();
}
let artifact = framework(krate, &["record"], "BlobArtifact");
let store_face = framework(krate, &["record"], "ArtifactStore");
let data_face = framework(krate, &["record"], "ArtifactData");
let transformer = framework(krate, &["transform"], "Transformer");
let construction = framework(krate, &["store"], "BlobStore");
let fs_store = framework(krate, &["store"], "LocalFsStore");
let fs_error = framework(krate, &["store"], "LocalFsBlobError");
let address = framework(krate, &["store"], "blob_address");
let location = framework(krate, &["store"], "BlobLocation");
let source = &self.source.node;
let key = quote!(<#source as #transformer>::Key);
// The handle is minted per call and that is what it is FOR: `AsyncBlobStore::blob` is sync and
// infallible on both faces because a per-slot handle is stateless, so minting one costs a
// `Utf8Bytes` clone and reaching for a cached one would be a lifetime for no gain.
let handle = quote! {
let __ingraph_handle = <#fs_store as #construction>::blob(
__ingraph_store,
::core::convert::AsRef::<::core::primitive::str>::as_ref(<Self as #artifact>::SLOT),
);
};
let data = self.data.then(|| {
quote! {
#[automatically_derived]
impl #data_face for #index {
fn read(
__ingraph_store: &Self::Store,
__ingraph_key: &#key,
__ingraph_suffix: ::core::option::Option<&::core::primitive::str>,
) -> impl ::core::future::Future<
Output = ::core::result::Result<
::core::option::Option<Self::Payload>,
Self::Error,
>,
> + ::core::marker::Send {
#handle
// A RESOLVED future, which is what a filesystem honestly hands an async caller: the read
// is a blocking syscall and it has already happened by the time this is awaited. It is
// the shipped `AsyncBlobEngine` face's own shape, reached through the key-only door.
//
// The ABSENCE is the backend's, unwrapped by nothing here: `fetch` already tells a miss
// from a fault, so this body carries the answer through rather than drawing the split a
// second time.
::core::future::ready(__ingraph_handle.fetch(
#fs_store::root(__ingraph_store),
__ingraph_key,
__ingraph_suffix,
))
}
}
}
});
quote! {
#[automatically_derived]
impl #store_face for #index {
type Store = #fs_store;
type Location = #location;
type Payload = ::std::vec::Vec<u8>;
type Error = #fs_error;
fn locate(
__ingraph_store: &Self::Store,
__ingraph_key: &#key,
__ingraph_suffix: ::core::option::Option<&::core::primitive::str>,
) -> ::core::result::Result<::core::option::Option<Self::Location>, Self::Error> {
#handle
let __ingraph_path = __ingraph_handle.address(
#fs_store::root(__ingraph_store),
__ingraph_key,
__ingraph_suffix,
)?;
// THE RENDER IS THE WHOLE BODY. A root this store cannot render an address out of refuses
// here, and it refuses whether or not anything was ever written — a refusal that arrived
// only once something HAD been written would be a deployment fault hiding until the day
// the pipeline succeeds.
let __ingraph_address = #address(&__ingraph_path)?;
// `Some`, ALWAYS, and for this store that is the honest answer rather than a shortcut: a
// filesystem address is presence-blind and a `stat` beside it buys an answer that expires
// the instant it is produced. The seam's `Option` is spent by the backends that CAN
// answer presence for free and un-expiring — a store holding it as a row column — and
// under fs absence is discovered where it cannot expire: the data road finds it in the
// read itself, and a client's own GET finds it at the fetch.
::core::result::Result::Ok(::core::option::Option::Some(
#location::new(__ingraph_address),
))
}
}
#data
}
}
/// **LAYER TWO's DECLARATION HALF** — one `Describe<R>` per TARGET this declaration's legs point
/// at, and the `Habitats` impl a graph root's launch drives it through.
///
/// ```ignore
/// impl Describe<crate::Ft> for Media { // the corpora Media owns in Ft
/// const BLUEPRINT: &'static [SlotSchema] = &[
/// SlotSchema::of(SlotName::new("media__title__lexical"), &[SlotColumn::text("title")], false),
/// SlotSchema::of(SlotName::new("media__body__lexical"), &[SlotColumn::text("body")], true),
/// ];
/// }
/// impl Habitats for Media {
/// const UNBOUND: &'static [UnboundCorpus] = &[…]; // the legs that pointed at nothing
/// const TARGETS: &'static [fn() -> ResourceDemand] = &[ResourceDemand::of::<crate::Ft>];
/// fn make(creation) { creation.habitat::<crate::Ft, Selected<{…SYNC}>, Self>().await }
/// }
/// ```
///
/// # `TARGETS` and `make` are ONE list read twice
///
/// The same grouped-by-path rows: the const says WHICH targets this declaration mounts, so a
/// launch can build them before the walk runs, and the body says what to make in each. They cannot
/// drift because neither is written by hand — a leg that grew a `resource = "…"` adds a row to
/// both, and a leg that lost one moves to `UNBOUND` and leaves both.
///
/// # ONE IMPL PER TARGET, and the grouping is what makes it one
///
/// Two elections pointing at the SAME resource are two corpora in ONE mount, so they are two rows
/// of one blueprint rather than two impls — which they have to be, `Describe<R>` admitting one impl
/// per `(type, target)` pair and a second being `E0119`. The legs are grouped by the resource path
/// as WRITTEN, since that is the only spelling this expansion has: two different paths naming one
/// type would be two impls and the compiler's own refusal, which is the honest place for it.
///
/// # The TARGET is the RESOURCE and never the engine
///
/// `Describe<crate::Ft>` and not `Describe<TantivyFulltext>`. Two deployments' tantivy stores are
/// two resource types, so keying the habitat on the ENGINE would collapse them into one and make a
/// second mount unaddressable — the same grain the mount seam and the slot name are already on.
///
/// # What the blueprint carries, and what it deliberately does not
///
/// The NAME is the slot marker's own, so the corpus a boot creates and the corpus a read opens
/// cannot be given two answers. The COLUMN is the elected field under the column language's own
/// door — text for a searched field, bytes for a coordinate one, which is what those values are at
/// a storage boundary. The `stored` posture is the declaration's word. A per-slot KNOB is none of
/// those and is not here: a tokenizer is a value a DEPLOYMENT decides at boot, and it reaches the
/// visitor's own table instead.
///
/// A VECTOR corpus carries its WIDTH beside them, projected off the elected field's own type —
/// the same projection the geometry bindings make, in const position where it belongs.
///
/// # A BLOB declaration emits the `Habitats` impl and NO blueprint
///
/// It elects nothing, so there is no `(field × label)` slot for a leg to point at and no target
/// for a `resource = "…"` to name. Its family's own home vocabulary exists
/// ([`Layout`](../../ingraph/struct.Layout.html)) and is written by hand until the artifact grammar
/// grows a pointing word — stated rather than half-emitted, which is this crate's standing posture
/// for a word nothing spends.
fn habitats(&self) -> proc_macro2::TokenStream {
let IndexModel { index, krate, .. } = self;
let describe = framework(krate, &["schema"], "Describe");
let habitats = framework(krate, &["drive"], "Habitats");
let unbound = framework(krate, &["drive"], "UnboundCorpus");
let slot_name = framework(krate, &["slot"], "SlotName");
let creation = framework(krate, &["drive"], "Creation");
let launch_error = framework(krate, &["drive"], "LaunchError");
let selected = framework(krate, &["operator"], "Selected");
let declared = framework(krate, &["resource"], "DeclaredResource");
let base = self.base();
// The KIND's own row: what a home looks like here, and which resource facet an unpointed corpus
// needs. A blob has neither, which is what makes its whole emission the empty impl.
let Some(resource_kind) = (match self.kind {
NodeKind::Fulltext => Some(quote!(Documents)),
NodeKind::Vector => Some(quote!(Coordinates)),
_ => None,
}) else {
return quote! {
#[automatically_derived]
impl #habitats for #index {}
};
};
let kind = framework(krate, &["resource"], "ResourceKind");
// ONE ROW PER LEG, grouped by the resource path as written — insertion-ordered, so the emission
// is stable and diffable exactly as the slot markers are.
let mut pointed: Vec<(syn::Path, Vec<proc_macro2::TokenStream>)> = Vec::new();
let mut unpointed: Vec<proc_macro2::TokenStream> = Vec::new();
for declared_field in &self.engines {
let field = &declared_field.field;
let column = self.slot_column(field);
for engine in &declared_field.engines {
let slot = crate::engine::Slot {
field: field.clone(),
engine: engine.word.clone(),
};
let name = slot.name(base);
let Some(resource) = engine.resource.as_ref() else {
unpointed.push(quote! {
#unbound::new(#slot_name::new(#name), #kind::#resource_kind)
});
continue;
};
let row = self.blueprint_row(&slot, &name, engine.stored, &column);
// Grouped by the path AS WRITTEN, which is the only spelling this expansion has: two
// different paths naming one type would be two impls and `E0119`, which is the honest place
// for that refusal — a macro that tried to resolve them would be resolving types.
let written = quote!(#resource).to_string();
match pointed
.iter_mut()
.find(|(path, _)| quote!(#path).to_string() == written)
{
Some((_, rows)) => rows.push(row),
None => pointed.push((resource.clone(), vec![row])),
}
}
}
let blueprint = self.blueprint_type();
// SPANNED AT THE WORD, per the projection law this file already keeps: the impl's own
// obligation is `R: Habitat`, and an unspanned one reports it at the ATTRIBUTE — a caret on
// something the author cannot edit. At the path, `E0276`/`E0277` land on the very token that
// named the target.
let describes = pointed.iter().map(|(resource, rows)| {
quote_spanned! {resource.span()=>
#[automatically_derived]
impl #describe<#resource> for #index {
const BLUEPRINT: #blueprint = &[#(#rows,)*];
}
}
});
let steps = pointed.iter().map(|(resource, _)| {
quote! {
#creation::habitat::<
#resource,
#selected<{ <#resource as #declared>::SYNC }>,
Self,
>(__ingraph_creation).await?;
}
});
// EMITTED ONLY WHERE THERE IS A STEP: a declaration whose legs all pointed at nothing takes the
// trait's own empty default rather than carrying a body whose parameter nothing reads.
let make = (!pointed.is_empty()).then(|| {
quote! {
fn make(
__ingraph_creation: &mut #creation<'_>,
) -> impl ::core::future::Future<
Output = ::core::result::Result<(), #launch_error>,
> {
async move {
#(#steps)*
::core::result::Result::Ok(())
}
}
}
});
let unbound_rows = (!unpointed.is_empty()).then(|| {
quote! {
const UNBOUND: &'static [#unbound] = &[#(#unpointed,)*];
}
});
// THE MOUNTS this declaration asks for. A leg that named a target is what makes the deployment
// mount it, and the launch has no other way to learn it: a search resolver holds the same
// `Shared<R>` a landing node does and appears in no list the launch reads. Spanned at the path
// for the `describes` rows' reason — the obligation here is `R: AsyncResource`, and the caret
// belongs on the token that named it.
let demand = framework(krate, &["resource"], "ResourceDemand");
let mounts = pointed.iter().map(|(resource, _)| {
quote_spanned! {resource.span()=>
#demand::of::<#resource>
}
});
let targets = (!pointed.is_empty()).then(|| {
quote! {
const TARGETS: &'static [fn() -> #demand] = &[#(#mounts,)*];
}
});
quote! {
#(#describes)*
#[automatically_derived]
impl #habitats for #index {
#unbound_rows
#targets
#make
}
}
}
/// ONE BLUEPRINT ROW — the corpus one leg owns, in whichever vocabulary its kind describes homes
/// in.
fn blueprint_row(
&self,
declared: &crate::engine::Slot,
name: &str,
stored: bool,
column: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
let krate = &self.krate;
let slot_name = framework(krate, &["slot"], "SlotName");
let field = &declared.field;
match self.kind {
NodeKind::Vector => {
let spec = framework(krate, &["transform"], "SlotSpec");
let width = self
.embeddings
.iter()
.find(|elected| &elected.field == field)
.map(|elected| {
let ty = &elected.ty;
let shape = framework(krate, &["election"], "EmbeddingShape");
let embedding = framework(krate, &["election"], "EmbeddingMarker");
quote_spanned!(field.span()=> <<#ty as #embedding>::Item as #shape>::WIDTH)
});
quote! {
#spec::new(#slot_name::new(#name), &[#column], #width)
}
}
_ => {
let schema = framework(krate, &["transform"], "SlotSchema");
// THE ROSTER TRAVELS WITH THE ROW, read off the slot's own seam rather than restated. A slot
// maker is handed a blueprint and nothing else — it has no slot TYPE to project a `Lanes`
// impl off — and it has to know how many partitions to shape the home for. Naming the seam
// is what keeps the two one fact: an unfanned slot's `LANES` is the default roster of one,
// which is the value `SlotSchema` already holds without this call.
let lanes = framework(krate, &["lane"], "Lanes");
let marker = declared.marker(self.base());
quote! {
#schema::of(#slot_name::new(#name), &[#column], #stored)
.fanned(<#marker as #lanes>::LANES)
}
}
}
}
/// The BLUEPRINT TYPE this kind's targets answer with — the associated type a `Describe<R>` impl's
/// const is written at, and the one a resource's own `Habitat` states.
fn blueprint_type(&self) -> proc_macro2::TokenStream {
let krate = &self.krate;
match self.kind {
NodeKind::Vector => {
let spec = framework(krate, &["transform"], "SlotSpec");
quote!(&'static [#spec])
}
_ => {
let schema = framework(krate, &["transform"], "SlotSchema");
quote!(&'static [#schema])
}
}
}
/// ONE ELECTED FIELD as a blueprint COLUMN — its own name, under the door of the column language
/// its values cross by.
///
/// TEXT for a searched field, whose road produced text by construction; BYTES for a coordinate
/// one, which is what a vector is at a storage boundary and the language's own floor. The WIDTH is
/// not restated here — it is [`SlotSpec`](../../ingraph/struct.SlotSpec.html)'s own member, and two
/// homes for one fact are free to disagree.
fn slot_column(&self, field: &syn::Ident) -> proc_macro2::TokenStream {
let krate = &self.krate;
let column = framework(krate, &["transform"], "SlotColumn");
let name = field.to_string();
match self.kind {
NodeKind::Vector => {
let door = framework(krate, &["store"], "ColumnDoor");
quote!(#column::new(#name, #door::Bytes))
}
_ => quote!(#column::text(#name)),
}
}
/// EVERY slot this declaration names — one per `(elected field × declared engine)`, in declared
/// order.
///
/// The set the storage plumbing is keyed by, and the answer to *how many corpora does this
/// declaration own*. It is EMPTY for a declaration whose elections named no engine, which is the
/// portable case: the slots exist, and which engines they are opened on is the deployment's.
#[must_use]
pub fn slots(&self) -> Vec<Slot> {
self.engines.iter().flat_map(FieldEngines::slots).collect()
}
/// ONE ZERO-SIZED MARKER PER SLOT, at MODULE SCOPE — the `(field × engine)` pairing carried as a
/// type.
///
/// # Why a type rather than the name alone
///
/// `SlotHandle<E, T>` brands a handle with the slot it was opened for, and the brand is what stops
/// a write landing in another slot's corpus — the class whose repair is a reindex rather than a
/// code change. Before this round `T` was the DECLARATION, because a declaration was a slot. It is
/// `(field × engine)` now, so the brand is these markers: two engines holding one field are two
/// types, and a handle opened on one cannot be passed to the other's door.
///
/// At MODULE SCOPE for [`elections`](Self::elections)' reason, and it is the same reason: a
/// deployment names one when it opens a handle, so the name has to be spellable from the scope the
/// declaration was written in.
///
/// # The impl naming a CONCRETE engine rides that engine's gate; the marker does not
///
/// The MEASURED law of the record side, applied here: only what names a concrete type may be
/// gated, because a shut gate deletes it. The marker itself and its slot name are facts of the
/// DECLARATION and exist in every build — a deployment compiling no engine at all still has the
/// names its declaration minted, and a party that asks for the binding is the one that gets
/// `E0277`.
fn slot_markers(&self) -> proc_macro2::TokenStream {
let IndexModel {
index, vis, krate, ..
} = self;
let slot = framework(krate, &["store"], "Slot");
let slot_name = framework(krate, &["slot"], "SlotName");
// THE MARKER MOVES WITH THE BASE AND THE DURABLE NAME DOES NOT, which is the one asymmetry in
// this file worth reading twice. A `rename` is a RUST word: it moves types a declaring scope
// holds. The durable slot name is a STORAGE identity — the corpus this pairing owns — and
// moving it with a Rust rename would silently repoint a live index. The word for that one is
// the storage side's, and it is not this.
let base = self.base();
let markers = self.slots().into_iter().map(|declared| {
let marker = declared.marker(base);
let name = declared.name(index);
let field = declared.field.to_string();
let engine = declared.engine.to_string();
let doc = leading(&format!(
"The `{field}` × `{engine}` SLOT of [`{index}`] — the corpus that pairing owns, as a type. \
A handle opened on it is branded with this marker and cannot be handed to another slot's \
door.",
));
let lanes = self.lane_bindings(&marker, &declared);
quote! {
#[doc = #doc]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#vis struct #marker;
#[automatically_derived]
impl #slot for #marker {
type Of = #index;
const SLOT: &'static #slot_name = #slot_name::new(#name);
const FIELD: &'static ::core::primitive::str = #field;
const ENGINE: &'static ::core::primitive::str = #engine;
}
#lanes
}
});
quote!(#(#markers)*)
}
/// **THE LANE SEAM ONE FULL-TEXT SLOT PUBLISHES** — its roster, its probe currency, and the
/// per-word assertions that refuse a roster claiming one word twice.
///
/// ```ignore
/// impl Lanes for MediaBodyTantivy {
/// const LANES: &'static [Lane] = &[
/// Lane::of(LaneIdent::new("zh")).accepting(&[LaneIdent::new("cmn")]),
/// Lane::of(LaneIdent::new("rest")).catch_all(),
/// ];
/// }
/// impl LanedStore for MediaBodyTantivy { type Probe = String; }
/// const _: () = assert!(!lane_claim_repeats(<MediaBodyTantivy as Lanes>::LANES, 1), "…");
/// ```
///
/// # FULL-TEXT ONLY, and refused BY NAME elsewhere
///
/// A lane exists because a full-text field has ONE tokenizer and an immutable schema. A knn
/// indexes coordinates, which no analyzer reads, and an artifact store holds bytes — so neither
/// kind has a lane story, and the grammar refuses the word on both by name rather than emitting a
/// roster nothing could spend.
///
/// # An UNFANNED slot STILL PUBLISHES THE SEAM
///
/// The impl is emitted whether or not `lanes(…)` was written, and where it was not the body is
/// EMPTY — the trait's own default, which is one lane keyed `und`. That is presence-is-enablement
/// stated in the emission: an unfanned corpus IS a fanned one whose roster has a single entry, so
/// a reader over `S: Lanes` takes every full-text slot there is and nothing anywhere carries an
/// *is this fanned* fork. Nothing about the CORPUS changes — one lane is one field, named `body`,
/// tokenized by tantivy's `default`, which is the schema this backend has always built.
///
/// # The COLLISION AUDIT is spent HERE, at the declaration
///
/// The ruling asks for a folded collision to be a COMPILE-TIME refusal, and this is that call
/// site: one `const` item per word the roster claims, each asserting the word was not claimed by
/// an EARLIER position, and one more per catch-all. The relation is the framework's own —
/// `lane_claim_repeats` reads this crate's ONE fold — so a declaration, a boot walk and a
/// downstream's test cannot come to disagree about what a collision is.
///
/// One item PER WORD rather than one per roster, because that is what buys the sentence: a
/// constant cannot FORMAT a message, so the message is written HERE where the spelling is known,
/// and the span is the word's own — a roster with `zh_hant` beside `zhHant` puts the caret on the
/// SECOND one, which is the one its author can delete.
fn lane_bindings(
&self,
marker: &syn::Ident,
declared: &crate::engine::Slot,
) -> proc_macro2::TokenStream {
let IndexModel { krate, index, .. } = self;
if self.kind != NodeKind::Fulltext {
return proc_macro2::TokenStream::new();
}
let Some(engine) = self.declared_engine(declared) else {
return proc_macro2::TokenStream::new();
};
let lanes_trait = framework(krate, &["lane"], "Lanes");
let laned = framework(krate, &["lane"], "LanedStore");
let lane = framework(krate, &["lane"], "Lane");
let ident = framework(krate, &["lane"], "LaneIdent");
let repeats = framework(krate, &["lane"], "lane_claim_repeats");
let catches_again = framework(krate, &["lane"], "lane_catch_all_repeats");
let field = &declared.field;
let word = &declared.engine;
let roster = (!engine.lanes.is_empty()).then(|| {
let rows = engine.lanes.iter().map(|row| {
let key = row.key.to_string();
let accepting = (!row.accepts.is_empty()).then(|| {
let accepts = row.accepts.iter().map(ToString::to_string);
quote!(.accepting(&[#(#ident::new(#accepts),)*]))
});
let catches = row.catch_all.as_ref().map(|_| quote!(.catch_all()));
// SPANNED AT THE KEY, per this file's projection law: what a row can earn is reported at the
// word its author wrote rather than at the attribute.
quote_spanned!(row.key.span()=> #lane::of(#ident::new(#key)) #accepting #catches)
});
quote! {
const LANES: &'static [#lane] = &[#(#rows,)*];
}
});
// ONE ASSERTION PER CLAIMED WORD, counted out against the roster's own FLAT claim positions —
// each lane's key, then that lane's aliases, which is exactly the order `lane_claim` addresses.
let mut at = 0usize;
let mut audits = proc_macro2::TokenStream::new();
for (lane_at, row) in engine.lanes.iter().enumerate() {
for claimed in row.claims() {
let word_at = at;
let why = format!(
"the word `{claimed}` is claimed twice in `{index}`'s `{field}` × `{word}` lanes — a \
lane's key and every alias it accepts fold through ONE relation, so `{claimed}`, its \
hyphenated spelling and its cased spellings are ONE word. Rename it or drop the second \
claim: two lanes claiming one tag is a document filed by list order"
);
audits.extend(quote_spanned! {claimed.span()=>
const _: () = ::core::assert!(
!#repeats(<#marker as #lanes_trait>::LANES, #word_at),
#why
);
});
at += 1;
}
if let Some(catches) = row.catch_all.as_ref() {
let key = &row.key;
let why = format!(
"lane `{key}` is declared the catch-all in `{index}`'s `{field}` × `{word}` lanes, and an \
EARLIER lane already is — a roster declares exactly one, because two would make *which \
stranger goes where* depend on the order the lanes happen to be written in"
);
audits.extend(quote_spanned! {catches.span()=>
const _: () = ::core::assert!(
!#catches_again(<#marker as #lanes_trait>::LANES, #lane_at),
#why
);
});
}
}
quote! {
#[automatically_derived]
impl #lanes_trait for #marker {
#roster
}
#[automatically_derived]
impl #laned for #marker {
// A full-text lane is asked with TEXT — the query string that lane's own analyzer parses —
// so this is what a router wired to this slot must answer in, and anything else is `E0271`
// at the seat. OWNED, because a fan hands back a `Vec` of probes that outlive the question
// they were split from.
type Probe = ::std::string::String;
}
#audits
}
}
/// The LEG one slot was minted from — the `(field × engine)` pairing read back off the model.
///
/// A slot is minted from a leg and then carried as a pair of idents, so the leg is FOUND rather
/// than threaded through every caller: the lists are a declaration's own length, the walk happens
/// once at expansion time, and the alternative is a second copy of every leg's facts inside a
/// name.
fn declared_engine(&self, declared: &crate::engine::Slot) -> Option<&crate::engine::Engine> {
self
.engines
.iter()
.find(|elected| elected.field == declared.field)?
.engines
.iter()
.find(|engine| engine.word == declared.engine)
}
/// WHAT THIS INDEX EMITS, stated for the downstream declarations that cannot see it.
///
/// A derived index declares no products — its message is the entry it holds, which is the
/// declared struct — so the row is the sole-product pair every one-product node carries. It is
/// here for the same reason it is on a record: a `subscribe(upstream(node = "…"))` names an index
/// as readily as it names anything else, and the payload it projects is `<Index as Emits>::Out`.
fn emits_binding(&self) -> proc_macro2::TokenStream {
let IndexModel { index, krate, .. } = self;
let emits = framework(krate, &["operator"], "Emits");
let sole = framework(krate, &["operator"], "SoleProduct");
quote! {
#[automatically_derived]
impl #emits for #index {
type Out = Self;
}
#[automatically_derived]
impl #sole for #index {}
}
}
/// The `fanout` WRITE LANE — one door per marked field, writing every engine that field declared.
///
/// # Why the DEFAULT case emits nothing, and that is the mirror rather than a gap
///
/// Single-write needs no door. The record side needs `insert_postgres` beside `insert_sqlite`
/// because the ROW TYPE is what picks the database and a caller cannot name it — *the method NAME
/// is where the database is chosen and the type parameter is where the driver is.* Here the slot
/// is already named by the HANDLE: `SlotHandle<E, TitleTantivy>` is branded, so
/// `handle.upsert_document(…)` writes that slot and no other, and an emitted wrapper would add a
/// second spelling of a choice already made. The mirror is exact and its economy is real.
///
/// A FAN is the case no existing door covers: writing one message to several slots at once, whose
/// engines are different types with different contexts and different errors. So `fanout` emits and
/// the default does not, which is also the honest reading of the marker — it is an increment, and
/// what it increments is visible in the expansion.
///
/// # The legs are SEQUENTIAL and the first refusal stops the fan
///
/// See [`Refused`](crate::engine) for why no leg is rolled back: the engines are independent
/// stores sharing no transaction, and inventing one would be this crate deciding a durability
/// question that is the deployment's. What the caller is told is which leg refused, which says
/// exactly which stores took the write.
///
/// # At MODULE SCOPE rather than in the anonymous `const`
///
/// The door is spelled by a DEPLOYMENT — it is the write lane's own call — so it goes where the
/// retrieve pair goes and for the retrieve pair's reason. Its parameters name the slot markers,
/// which are at module scope too.
fn fanouts(&self) -> proc_macro2::TokenStream {
let IndexModel {
index, vis, krate, ..
} = self;
// TWO PATHS where there used to be one, and the split is the engine cutover in BOTH families:
// the CONNECTION is a base seat and the scope, the entry and the verb are the WRITE FACE's, so a
// qualified path has to name whichever trait actually declares the member.
let (base, face, verb) = match self.kind {
NodeKind::Fulltext => (
framework(krate, &["store"], "FulltextEngine"),
framework(krate, &["store"], "AsyncFulltextWrite"),
format_ident!("upsert_document"),
),
NodeKind::Vector => (
framework(krate, &["store"], "VectorEngine"),
framework(krate, &["store"], "AsyncVectorWrite"),
format_ident!("upsert_vector"),
),
// A `blob` elects nothing, so it declares no engine and has nothing to fan.
_ => return proc_macro2::TokenStream::new(),
};
let brand = framework(krate, &["store"], "SlotHandle");
let connected = framework(krate, &["store"], "Connected");
let refused = framework(krate, &["store"], "Refused");
let doors = self
.engines
.iter()
.filter(|declared| declared.fanout)
.map(|declared| {
let field = &declared.field;
let door = fan_door(field);
let legs: Vec<Leg> = declared
.slots()
.into_iter()
.enumerate()
.map(|(at, slot)| Leg {
engine: format_ident!("__INGRAPH_ENGINE_{at}__"),
handle: format_ident!("__ingraph_slot_{at}"),
scope: format_ident!("__ingraph_scope_{at}"),
doc: format_ident!("__ingraph_doc_{at}"),
marker: slot.marker(self.base()),
word: slot.engine.to_string(),
})
.collect();
let parameters = legs.iter().map(|leg| {
let Leg {
engine,
handle,
scope,
doc,
marker,
..
} = leg;
quote! {
#handle: &mut #brand<#engine, #marker>,
#scope: #connected<
'_,
<#engine as #base>::Connection,
<#engine as #face>::WriteContext<'_>,
>,
#doc: <#engine as #face>::Doc,
}
});
let bounds = legs.iter().map(|Leg { engine, .. }| quote!(#engine: #face));
let names = legs.iter().map(|Leg { engine, .. }| engine);
let error = refusal_type(&legs, &refused, &base);
let writes = legs.iter().enumerate().map(|(at, leg)| {
let Leg {
handle, scope, doc, ..
} = leg;
let wrap = refusal_arm(at, legs.len(), &refused);
quote! {
#handle.#verb(#scope, #doc).await.map_err(#wrap)?;
}
});
let words = legs
.iter()
.map(|Leg { word, .. }| format!("`{word}`"))
.collect::<Vec<_>>()
.join(", ");
let doc = leading(&format!(
"Write one entry to EVERY engine `{field}` declared — {words}.\n\n`{field}` is marked \
`fanout`, so all of its engines are live at once: this writes each in declared order and \
stops at the first refusal, naming the leg that gave it. Without the marker the engines \
are portability and a deployment writes through the one slot it opened.",
));
quote! {
#[doc = #doc]
#[allow(clippy::too_many_arguments)]
#vis async fn #door<#(#names),*>(
#(#parameters)*
) -> ::core::result::Result<(), #error>
where
#(#bounds),*
{
#(#writes)*
::core::result::Result::Ok(())
}
}
})
.collect::<Vec<_>>();
if doors.is_empty() {
return proc_macro2::TokenStream::new();
}
quote! {
#[automatically_derived]
impl #index {
#(#doors)*
}
}
}
/// ONE ZERO-SIZED MARKER PER ELECTION, at MODULE SCOPE — the column carried as a type.
///
/// The markers cannot move inside the anonymous `const` the rest of the expansion lives in, and
/// the reason is what they are FOR: a lane names one — `SlotLane<E, SegmentPair,
/// SegmentPairByImageEmbedding>` — so the name has to be spellable from the scope the declaration was
/// written in. Everything inside that const is reachable only by the expansion itself.
///
/// Each carries the declaration's own visibility, exactly as the retrieve methods do, and for the
/// same reason: a wiring site in another module is where the marker is spent, so a marker less
/// visible than the method it selects would leave that method uncallable through the lane.
///
/// # It is emitted PER ELECTION and not per declaration, which is the whole ruling
///
/// The alternative was one marker for the declaration with the column bound at construction, and
/// that is what does not refuse anything: two lanes of one type, differing in a value, are
/// interchangeable at every wiring site. N markers make the two lanes N TYPES, and a door typed
/// for one rejects the other where the two were joined.
///
/// A `blob` or `fulltext` declaration emits nothing here, and for two different reasons. A `blob`
/// elects nothing at all — it is addressed rather than ranked. A `fulltext` elects, but what a
/// marker would be parameterized BY does not exist: the vector marker carries a `VectorColumn`,
/// and a full-text engine is asked for a slot and a string with no column between them. What a
/// full-text election gets instead is its SLOT markers — see
/// [`slot_markers`](Self::slot_markers), which both kinds get and which is the per-field grain the
/// engine grammar supplies.
fn elections(&self) -> proc_macro2::TokenStream {
let IndexModel {
index, vis, krate, ..
} = self;
let elected = framework(krate, &["store"], "Elected");
let column = framework(krate, &["store"], "VectorColumn");
let base = self.base();
let markers = self.embeddings.iter().map(|Elected { field, .. }| {
let marker = elected_marker(base, field);
let name = field.to_string();
let doc = leading(&format!(
"The `{name}` ELECTION of [`{index}`], as a type — what a lane serving that column is \
parameterized by, and what `retrieve_by_{name}` answers from.",
));
quote! {
#[doc = #doc]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#vis struct #marker;
#[automatically_derived]
impl #elected<#index> for #marker {
const COLUMN: #column = #column::new(#name);
}
}
});
quote!(#(#markers)*)
}
/// `impl VectorRecord` — EVERY elected field, projected under its own column, and every fact read
/// through the election family rather than off a token.
///
/// Emitted for the vector kind and for neither of the others, which is the word's own asymmetry:
/// the other two elect nothing and have no coordinates to hand anybody.
///
/// # What each member is, and where the fact came from
///
/// - **`Element`** is `<<F as EmbeddingMarker>::Item as EmbeddingShape>::Element` for the FIRST
/// election's own field type. The width is NOT restated: it is a fact of the field's type, and
/// [`VectorRecord`] deliberately has no `const DIM` for the same reason two homes for one fact
/// are free to disagree.
/// - **`vectors`** yields one `(column, coordinates)` pair per `embedding`-labelled election, in
/// declared order, and nothing else. This is the whole payload posture made mechanical — a
/// declaration's UNELECTED embedding-typed fields are reachable through their own accessors and
/// are named nowhere on this path, so no knn can see one through ANY column.
/// - **`vector_sets`** yields `(column, ordinal, coordinates)` once per MEMBER of every
/// `list(embedding)` election, ordinals running `0..n` in `members()` order — and it is emitted
/// only where a set election exists, a declaration with none keeping the trait's empty default.
/// The two methods partition the elections: a column reported by one is never reported by the
/// other, so *what is stored under this column* has one answer and the shape is read off which
/// face answered.
/// - **`Filter`** is `()`, the empty product this crate uses for a face a declaration does not
/// have. What a search over this index may be scoped BY is the engine block's to state and that
/// grammar has not arrived; `()` is the no-scope case, which a face lowers to no predicate at
/// all rather than to a filter nobody wrote.
///
/// # ONE WALK for both faces, and the label decides only which one reports it
///
/// Both are written over `EmbeddingMarker::members`, which yields one member for a single election
/// and the whole set for a set one. So there is no unwrap on this path and no partial function to
/// get wrong: a single election is a set of one, mechanically, and the difference between the two
/// faces is exactly whether an ordinal rides beside the coordinates.
///
/// # ONE element across N elections, and rustc is what says so
///
/// A slot is opened at one element, so N columns of one slot are N columns of one element. The
/// front end does not check it, and could not: the elections' types are opaque tokens here, and
/// what they DENOTE is the compiler's. So `Element` is the first election's projection and every
/// pair is spanned at ITS OWN election field: a second election at a disagreeing element is
/// `E0308` on the FIELD the author marked, not somewhere inside an expansion.
fn vector_record(&self) -> proc_macro2::TokenStream {
let Some(first) = self.embeddings.first() else {
return proc_macro2::TokenStream::new();
};
let index = &self.index;
let record = framework(&self.krate, &["record"], "VectorRecord");
let column = framework(&self.krate, &["store"], "VectorColumn");
let marker = framework(&self.krate, &["election"], "EmbeddingMarker");
let shape = framework(&self.krate, &["election"], "EmbeddingShape");
let first = &first.ty;
let element = quote!(<<#first as #marker>::Item as #shape>::Element);
// CHAINED rather than arrayed, on both faces: each election contributes a different opaque
// iterator type, so there is no array of a common item to build. Every chain link is the same
// tuple, which is what keeps the item type one.
let singles = self
.embeddings
.iter()
.filter(|elected| !elected.label.is_set())
.map(|Elected { field, ty, .. }| {
let name = field.to_string();
// SPANNED AT THE ELECTION, which is what puts a disagreeing element's `E0308` and a missing
// impl's `E0277` on the word the author wrote rather than on a token of this emitter's.
quote_spanned!(field.span()=> .chain(
<#ty as #marker>::members(&self.#field)
.map(|__ingraph_member| (
#column::new(#name),
<<#ty as #marker>::Item as #shape>::coordinates(__ingraph_member),
))
))
})
.collect::<Vec<_>>();
let sets = self
.embeddings
.iter()
.filter(|elected| elected.label.is_set())
.map(|Elected { field, ty, .. }| {
let name = field.to_string();
// `(0u32..).zip(…)` rather than `.enumerate()`, so the ORDINAL is minted at its own width
// with no cast: a `usize as u32` in emitted code would be a lint an author never wrote and a
// truncation nobody could reach.
quote_spanned!(field.span()=> .chain(
(0u32..)
.zip(<#ty as #marker>::members(&self.#field))
.map(|(__ingraph_at, __ingraph_member)| (
#column::new(#name),
__ingraph_at,
<<#ty as #marker>::Item as #shape>::coordinates(__ingraph_member),
))
))
})
.collect::<Vec<_>>();
// Emitted only where a set election exists, so a declaration that has none keeps the trait's own
// default — the empty stream, which is what *no set members* means — and its expansion says
// nothing about a face it does not have.
let vector_sets = if sets.is_empty() {
proc_macro2::TokenStream::new()
} else {
quote! {
#[inline]
fn vector_sets(&self)
-> impl ::core::iter::Iterator<Item = (#column, u32, &[Self::Element])>
{
::core::iter::empty() #(#sets)*
}
}
};
quote! {
#[automatically_derived]
impl #record for #index {
type Element = #element;
type Filter = ();
#[inline]
fn vectors(&self) -> impl ::core::iter::Iterator<Item = (#column, &[Self::Element])> {
::core::iter::empty() #(#singles)*
}
#vector_sets
}
}
}
/// THE DECLARED FOLD, one accessor per SET election — what
/// `semantics(fold = "…")` is spent on.
///
/// # A word parsed into a model nothing spends is a promise rather than a rule
///
/// This grammar's own standard, applied to its newest word. The `_with` door takes the fold BY
/// VALUE and dispatches it statically, so what a declaration-level default can be is a way to
/// SPELL it: `Clip::fold_by_frames()` hands back the fold this election declared, or the shipped
/// [`Sum`] where it declared none, and the ruled chain reads as one line at the call —
/// `…_with(…, Clip::fold_by_frames(), 10)` for the declaration's, anything else for the query's.
///
/// # Constructed through [`Default`], which is the bound the word asks for
///
/// The emission holds a PATH and no value, so the only way to build one is a trait every
/// implementation can derive. A type that folds but cannot be defaulted is `E0277` here, naming
/// the path its author wrote — and the shipped citizens carry it for exactly this reason.
///
/// Emitted for a SET election alone: a single embedding has one best per query vector, so there is
/// nothing to fold and no door to fold it at.
fn declared_folds(&self) -> proc_macro2::TokenStream {
let IndexModel { vis, krate, .. } = self;
let shipped = |citizen| framework(krate, &["retrieve"], citizen);
let folds = self
.embeddings
.iter()
.filter(|elected| elected.label.is_set())
.map(|elected| {
let field = &elected.field;
let name = fold_accessor(field);
// The SHORTHAND resolves HERE, which is the one place that knows where the shelf is: a word
// names a framework citizen and a path names the declaring crate's own type, and both arrive
// at the same `Default` construction below.
let fold = match &elected.fold {
None | Some(Fold::Sum) => shipped("Sum"),
Some(Fold::Max) => shipped("Max"),
Some(Fold::Custom(path)) => quote!(#path),
};
let doc = leading(&format!(
"The fold `{field}`'s set door takes when the caller has no other — this election's \
DECLARED default, or the framework's `Sum` where it declared none.",
));
let chain = leading(
"The ruled chain is *query explicit > declaration > shipped*, and this is the middle \
step written out: a caller that wants its own fold passes it, and one that wants this \
election's passes this.",
);
let wire = leading(
"THE WIRE'S CHAIN IS SHORTER BY ITS FIRST STEP: a request never chooses a fold, so the \
emitted set road reads *installed at launch > this accessor*, and this is what it falls \
to. The two chains differ because the callers do — a Rust caller states its own \
question, and a client asks one the deployment decided the meaning of.",
);
quote_spanned! {field.span()=>
#[doc = #doc]
#[doc = ""]
#[doc = #chain]
#[doc = ""]
#[doc = #wire]
#[must_use]
#[inline]
#vis fn #name() -> #fold {
<#fold as ::core::default::Default>::default()
}
}
})
.collect::<Vec<_>>();
if folds.is_empty() {
return proc_macro2::TokenStream::new();
}
let index = &self.index;
quote! {
#[allow(dead_code)]
impl #index {
#(#folds)*
}
}
}
/// THE FROM-ROADS — one `FulltextRoad` impl per full-text SLOT, and one bare demand per elected
/// field that named no engine.
///
/// # This is where `searchable`'s CHECK is, and it is a bound rather than a table
///
/// The marker elects a field and says nothing about its type, because the front end has no type
/// to say anything about — and the one check a parser could make is a spelling allowlist, which
/// false-refuses `SmolStr`, a newtype, an alias and `Vec<String>` alike. So the check is
/// *A FROM-ROAD EXISTS*, and it is asked HERE, where rustc can answer it: the identity road
/// demands `Searchable` (blanket over `AsRef<str>`), the shorthands demand a walk whose items are
/// text, and a declared conversion demands a function of the right shape. A field with no road is
/// `E0277` at its OWN TYPE TOKEN — `quote_spanned` puts it there — carrying `Searchable`'s
/// `on_unimplemented` note, which teaches the three roads by name.
///
/// Neither of the two answers that were on the table: not *no check* (a `searchable` field that
/// cannot be read as text would reach the write lane and fail there, or worse, index nothing),
/// and not a syntactic allowlist (a false refusal, which this crate calls a defect of its own).
///
/// # A field with no ENGINE still gets one
///
/// An election naming no engine is the PORTABLE case — legal, and it means the deployment says
/// which engine. There is no slot to hang an impl on, so the demand is emitted bare. Without it a
/// portable declaration would be the one place the check does not run, and *portable* would
/// quietly mean *unchecked*.
///
/// # UNGATED, because nothing here names a concrete engine
///
/// The record side's law is that only what spells a concrete type may ride a feature gate, since
/// a shut gate DELETES what it wraps. A road names a sink, a trait and the declaration's own
/// field — no engine type appears — so these impls exist in a build that compiled no backend at
/// all, which is also the only way the portable case could be checked.
fn roads(&self) -> proc_macro2::TokenStream {
if self.kind != NodeKind::Fulltext {
return proc_macro2::TokenStream::new();
}
let IndexModel { index, krate, .. } = self;
let writer = framework(krate, &["document"], "BoxWriter");
let road = framework(krate, &["store"], "FulltextRoad");
// `Of` is the SUPERTRAIT's — a road is one more fact about a slot, and the SLOT is what says
// which declaration it belongs to. Spelled `<Self as Slot>::Of` and not `Self::Of`, which is
// `E0576` inside an impl of the subtrait.
let slot = framework(krate, &["store"], "Slot");
let mut emitted = proc_macro2::TokenStream::new();
for declared in &self.engines {
if !self.searchable.contains(&declared.field) {
continue;
}
// THE PORTABLE CASE. `engines` carries one entry per ELECTED field whether or not it named an
// engine, so *named none* is the entry with an EMPTY list rather than a missing entry.
if declared.engines.is_empty() {
let body = self.road_body(&declared.field, &Road::Identity);
emitted.extend(quote! {
const _: () = {
#[allow(dead_code)]
fn road(entry: &#index, into: &mut #writer) {
#body
}
};
});
continue;
}
for engine in &declared.engines {
let marker = Slot {
field: declared.field.clone(),
engine: engine.word.clone(),
}
.marker(self.base());
let stored = engine.stored;
let error = if engine.road.fallible() {
crate::model::boxed_error()
} else {
quote!(::core::convert::Infallible)
};
let body = self.road_body(&declared.field, &engine.road);
emitted.extend(quote! {
#[automatically_derived]
impl #road for #marker {
const STORED: bool = #stored;
type Error = #error;
fn write(
entry: &<Self as #slot>::Of,
into: &mut #writer,
) -> ::core::result::Result<(), <Self as #road>::Error> {
#body
::core::result::Result::Ok(())
}
}
});
}
}
emitted
}
/// ONE ROAD's body — the call the declaration's word picks, spanned at the FIELD'S OWN TYPE so a
/// bound it does not satisfy is reported there.
///
/// [`Conversion::apply`](crate::model::Conversion) is deliberately NOT reused: it builds a
/// one-argument call (`f(value)`), and a full-text converter takes the SINK first —
/// `fn(&mut BoxWriter, &Field)` — because the segmentation has to survive, which a returned
/// `String` destroys. Same family, same two spellings, same escape; a different arity, written
/// out.
fn road_body(&self, field: &syn::Ident, road: &Road) -> proc_macro2::TokenStream {
let IndexModel { krate, .. } = self;
let writer = framework(krate, &["document"], "BoxWriter");
let searchable = framework(krate, &["document"], "Searchable");
// The declared type carries the span every refusal about this road lands at. A field the model
// has no column for cannot arise — `searchable` is read off the same walk that built them — and
// the fallback keeps that impossibility from being a panic.
let at = self
.fields
.iter()
.find(|column| column.name == *field)
.map_or_else(|| field.span(), |column| column.ty.span());
match road {
Road::Identity => {
quote_spanned!(at=> #searchable::write(&entry.#field, into);)
}
Road::Join(separator) => {
quote_spanned!(at=> #writer::push_joined(into, &entry.#field, #separator);)
}
Road::Multi => {
quote_spanned!(at=> #writer::push_each(into, &entry.#field);)
}
Road::Declared(Conversion::Default | Conversion::Infallible(_)) => {
let Road::Declared(Conversion::Infallible(path)) = road else {
// `Conversion::Default` never reaches a `Declared` road — a block that named no function
// took `Road::Identity`, which is a different road rather than a missing one.
return quote_spanned!(at=> #searchable::write(&entry.#field, into););
};
quote_spanned!(at=> #path(into, &entry.#field);)
}
Road::Declared(Conversion::Fallible(fallible)) => {
let path = &fallible.path;
match &fallible.escape {
// A plain `?`, so the slot's boxed refusal absorbs the function's through `From` — and a
// pair that cannot is `E0277` AT THE `?`, naming that function's error.
None => quote_spanned!(at=> #path(into, &entry.#field)?;),
Some(escape) => quote_spanned! {at=>
::core::result::Result::map_err(#path(into, &entry.#field), #escape)?;
},
}
}
}
}
/// THE LABEL AUDITS — one per election, holding the field's own type to what its label claimed.
///
/// # Why the claim is audited at all
///
/// The label is what the EXPANSION reads: it decides which faces are written above and which doors
/// are grown below, and a macro cannot resolve a type to check it. The marker is what RUSTC reads.
/// One fact with two readers is the shape that drifts, so the emission states the label's claim as
/// a bound and lets the compiler settle it.
///
/// A field labelled `embedding` whose type carries a set is `E0277` HERE — at the span of the
/// election word its author wrote — with a sentence naming both sides. The same holds the other
/// way round, and between them the label cannot lie.
///
/// `const _: fn() = elects_one::<TheField>;` is the shape every audit in this crate takes.
fn label_audits(&self) -> proc_macro2::TokenStream {
// EVERY labelled field, elected or not. A label on payload is accepted — see
// [`labelled`](IndexModel::labelled) — and accepted is not unexamined: the claim is the same
// claim, so it meets the same compiler.
let elected = self
.embeddings
.iter()
.map(|elected| (&elected.field, &elected.ty, elected.label));
let payload = self
.labelled
.iter()
.map(|labelled| (&labelled.field, &labelled.ty, labelled.label));
let audits = elected.chain(payload).map(|(field, ty, label)| {
let audit = framework(&self.krate, &["election"], label.audit());
quote_spanned!(field.span()=> const _: fn() = #audit::<#ty>;)
});
quote!(#(#audits)*)
}
/// THE KIND AUDITS — one per POINTING leg, holding the resource it named to the kind of seam this
/// declaration writes.
///
/// # The first of the three binding laws, and the only one a declaration can settle alone
///
/// *Named → kind-verified.* A leg writing `resource = "crate::Ft"` names a type this expansion
/// cannot resolve, so the claim is stated as a BOUND and rustc settles it: a vector election
/// pointed at a full-text store is `E0277` naming `VectorEngine`, and the caret sits on the path
/// its author wrote. The other two laws are the DEPLOYMENT's — a sole default, and the refusal
/// that lists candidates — and both need the resource catalog, which is a graph root away.
///
/// # Why it is emitted where the projections already run
///
/// The `floor` and `options` rows of a leg's query package are `<Ft as FulltextEngine>::Score` and
/// `::SearchOptions`, which refuse a wrong kind on their own. Two things they do not do:
///
/// 1. **they land nowhere useful.** A projection sits inside a package row the author never
/// wrote, so the refusal is reported at the whole attribute. This is `quote_spanned!` at the
/// path, so the caret sits on the word — which is what *at the word* asks for, and the only
/// part of the law a reader ever sees;
/// 2. **they belong to the wire.** The package is the question layer's and the kind law is the
/// resource axis's, so a round that changes what the wire mints must not be able to take the
/// check away with it.
///
/// A COVERAGE argument was drafted for a third reason and WITHDRAWN: every shape measured — set
/// elections, fanned legs, `rrf = false` legs, declarations with no GraphQL skin — mints the seat
/// and therefore projects anyway. The two above are the whole of it.
///
/// # The bound is the BASE, never a face
///
/// Verifying a kind must not drag in a verb obligation — a store that holds documents is a
/// full-text resource whether or not this deployment also writes through it — which is what the
/// verb-free base is for. Faces are the per-slot handle's, one grain down.
///
/// # `blob` points at nothing, and that is the grammar rather than an omission
///
/// An artifact family elects nothing and its store blocks claim no pointing word: an artifact is
/// ADDRESSED rather than ranked, so it mints no package for a floor to sit in and has no kind
/// question to ask. The arm answers nothing rather than guessing a seam for it.
fn resource_audits(&self) -> proc_macro2::TokenStream {
let audit = match self.kind {
NodeKind::Fulltext => framework(&self.krate, &["store"], "holds_documents"),
NodeKind::Vector => framework(&self.krate, &["store"], "holds_coordinates"),
NodeKind::Operator
| NodeKind::Entity
| NodeKind::Record
| NodeKind::Aggregate
| NodeKind::Blob => {
return proc_macro2::TokenStream::new();
}
};
let audits = self
.engines
.iter()
.flat_map(|declared| declared.engines.iter())
.filter_map(|engine| engine.resource.as_ref())
.map(|resource| quote_spanned!(resource.span()=> const _: fn() = #audit::<#resource>;));
quote!(#(#audits)*)
}
/// THE MOUNT SEAM this declaration's kind reads a resource through — `None` on a kind that mounts
/// nothing.
///
/// One function, so the two places that name the seam — the WIRE MINT below and the HANDLE the
/// emitted Rust door is turbofished with — cannot come to name two different traits.
fn mount_seam(&self) -> Option<proc_macro2::TokenStream> {
match self.kind {
NodeKind::Fulltext => Some(framework(&self.krate, &["store"], "FulltextMount")),
NodeKind::Vector => Some(framework(&self.krate, &["store"], "VectorMount")),
NodeKind::Operator
| NodeKind::Entity
| NodeKind::Record
| NodeKind::Aggregate
| NodeKind::Blob => None,
}
}
/// THE PER-SLOT HANDLE a pointed resource mints — what an emitted Rust door's engine parameter is.
///
/// The RESOURCE is the mount and the HANDLE is what wears the read faces, so a door bounded
/// `E: AsyncFulltextRead` is spelled with this and never with the resource itself. Spanned at the
/// path the author wrote, so a resource of the wrong kind — one with no mount seam of this family
/// — is `E0277` on the word rather than inside an expansion.
fn wire_handle(&self, resource: &syn::Path) -> proc_macro2::TokenStream {
let mount = self
.mount_seam()
.expect("a retrieving kind mounts its resources");
quote_spanned!(resource.span()=> <#resource as #mount>::Handle)
}
/// THE WIRE MINT — one election's CORPUS, out of the request's own citizens.
///
/// ```ignore
/// let (mut __ingraph_slot, __ingraph_connection) =
/// search_slot::<app::Ft, Media>(ctx, "title", <MediaTitleLexical as Slot>::SLOT)?;
/// ```
///
/// # Three facts, and each of them moved here from somewhere it did not belong
///
/// The CITIZEN is `Shared<R>` — the resource a launch built — rather than a per-pairing door an
/// application installed, because a leg POINTS at a resource and that is the type this expansion
/// can name. The SLOT NAME is read off the marker this declaration already mints, so the corpus a
/// read opens and the corpus a write lands in have ONE home. And the CONNECTION comes back beside
/// the handle, because a minted handle is stateless and reaches its index back through the mount's
/// own manager — the value an emitted resolver had no way to build while all it held was an
/// engine.
///
/// A VECTOR corpus takes its width beside the name, per the two mount seams' one difference, and
/// the width is projected off the ELECTED FIELD's own type — the same projection the geometry
/// bindings make, spelled inline because this position is an expression rather than a const
/// argument.
fn wire_corpus(
&self,
field: &syn::Ident,
elected: Option<&syn::Type>,
engine: &Engine,
resource: &syn::Path,
slot: &syn::Ident,
connection: &syn::Ident,
) -> proc_macro2::TokenStream {
let IndexModel { krate, index, .. } = self;
let ctx = crate::method::wire_method(&format_ident!("ctx"));
let word = field.to_string();
let brand = crate::engine::Slot {
field: field.clone(),
engine: engine.word.clone(),
}
.marker(self.base());
let marker = framework(krate, &["store"], "Slot");
let (door, width) = match (self.kind, elected) {
(NodeKind::Vector, Some(ty)) => {
let shape = framework(krate, &["election"], "EmbeddingShape");
let embedding = framework(krate, &["election"], "EmbeddingMarker");
(
framework(krate, &["graphql"], "vector_slot"),
Some(quote_spanned! {field.span()=>
, <<#ty as #embedding>::Item as #shape>::WIDTH
}),
)
}
_ => (framework(krate, &["graphql"], "search_slot"), None),
};
quote! {
let (mut #slot, #connection) = #door::<#resource, #index>(
#ctx,
#word,
<#brand as #marker>::SLOT #width,
)?;
}
}
/// The RETRIEVE face, written TWICE — once with a span around each door's body and once without.
///
/// The G6 instrument clause, reaching the query path's own doors. `emit::query`'s three crossing
/// entries and these are ONE mechanism: a door that leaves this process is a door whose duration a
/// trace wants, and the retrieve faces are where an application asks the framework a question. See
/// [`observed`](Self::observed) for why the entry is written twice rather than carrying an
/// attribute, and [`retrieve_half`](Self::retrieve_half) for what the doors are.
///
/// A kind that answers no retrieve emits NEITHER half rather than two empty gates, and the test is
/// the emission itself — `blob` returns nothing from the half below, so one `is_empty` keeps the
/// decision about which kinds retrieve in the ONE place that already makes it.
fn retrieve(&self) -> proc_macro2::TokenStream {
let watched = self.retrieve_half(true);
if watched.is_empty() {
return watched;
}
let plain = self.retrieve_half(false);
let gate = framework(&self.krate, &["gate"], "if_tracing");
let ungated = framework(&self.krate, &["gate"], "if_no_tracing");
quote! {
#gate! { #watched }
#ungated! { #plain }
}
}
/// THE FUSED DOORS — `vector_fuse` and `vector_fuse_similar`, over the tier's own routes.
///
/// Emitted per the ADDITIVE DOOR LAW ([`Doors`](crate::fuse::Doors)), which is decided in exactly
/// one place and read here: a tier with two or more routes of one modality gets that modality's
/// door, a mixed tier also gets `fuse`, and every per-kind door beside them goes on emitting. At
/// the INDEX grain the law resolves to one of the three — a full-text declaration is one route
/// however many fields it elects, and a declaration's KIND is its modality, so `fulltext_fuse` and
/// the mixed `fuse` have no route set to fuse here and their home is the root.
///
/// # Every route is asked through the door it already had
///
/// The fused doors reach `retrieve_keys_by_<field>` and `retrieve_similar_by_<field>` and nothing
/// else — no second query path, no floor of their own, no walk of their own. What they add is the
/// three facts a fold needs and a single route has no use for: WHICH routes to ask (the question
/// chain's participation rule), how much each one's opinion counts (`Route::weight`), and what
/// arithmetic joins them (`FusionOptions`).
///
/// # The question chain is resolved HERE, and only its COORDINATES half can run
///
/// `asked`'s law — 自问 > 层问 > 父问 — is what decides a route's question, and `participates` is
/// what turns *no resolvable question* into a structural absence rather than an empty answer. Both
/// are spent below over the `coordinates` seat, which is the half a door can act on: a route
/// holding its own coordinates needs no tower.
///
/// The TEXT half is resolved and NOT run, and the reason is a measurement rather than a choice: a
/// text question becomes coordinates by walking that election's own `ask` chain, whose hops are
/// types the declaration named — so a door running the text chain would take one type parameter
/// per route, and its arity would be the declaration's rather than the grammar's. That is the
/// tower-fanout design and it is unruled, so this door asks in coordinates and the text chain is
/// carried.
///
/// # A route whose example is UNINDEXED is absent rather than fatal
///
/// In `vector_fuse_similar` the example comes from the entity's own stored vectors, per route. An
/// entity indexed in one column and not another is ordinary — that is what a multi-election
/// declaration is FOR — so `Unindexed` from one route drops that route out of the fold, exactly as
/// a missing question does, and every other refusal propagates.
fn fused_half(&self, observed: bool) -> proc_macro2::TokenStream {
use heck::ToUpperCamelCase as _;
let doors = self.tier().doors();
if !doors.vector {
return proc_macro2::TokenStream::new();
}
let IndexModel {
index, vis, krate, ..
} = self;
let key = self.key();
// The BASE carries the vocabulary and the READ FACE carries the lease, so a projection names
// whichever of the two declares the member it asks for; the bound names the face, which implies
// the base. The row names NEITHER — `Field` is engine-blind, which is what the column language
// bought and what makes this bound one word instead of one per engine.
let face = framework(krate, &["store"], "VectorEngine");
let lease = framework(krate, &["store"], "AsyncVectorRead");
let row = framework(krate, &["store"], "Field");
let brand = framework(krate, &["store"], "SlotHandle");
let connected = framework(krate, &["store"], "Connected");
let embedding = framework(krate, &["storage"], "Embedding");
let marker = framework(krate, &["election"], "EmbeddingMarker");
let vector_query = framework(krate, &["retrieve"], "VectorQuery");
let fused = framework(krate, &["retrieve"], "Fused");
let rooted = framework(krate, &["retrieve"], "Rooted");
let route = framework(krate, &["retrieve"], "Route");
let depth = framework(krate, &["retrieve"], "route_depth");
let flavour = framework(krate, &["retrieve"], "FusionOptions");
let fusion = framework(krate, &["retrieve"], "Fusion");
let participates = framework(krate, &["retrieve"], "participates");
let weighted = framework(krate, &["retrieve"], "fuse_weighted");
let refused = framework(krate, &["retrieve"], "OwnReadError");
let join = framework(krate, &["retrieve"], self.dedup.join());
let admits = self.dedup.admits();
let tier = self.tier();
let evidence = tier.evidence_name();
let refusal = tier.fused_error_name();
let options = tier.options_name().expect("a vector tier retrieves");
let question = tier.question_name().expect("a vector tier retrieves");
let routes: Vec<&Elected> = tier.fused_routes().collect();
// ONE ROUTE'S OWN NAMES — its engine parameter, the three values it is asked with, and the two
// projections off that engine. Every list below is in route order and read in lock-step, which
// is what keeps a route's engine, slot, scope and floor from drifting apart across the four
// places they are spelled.
let engines: Vec<syn::Ident> = routes
.iter()
.map(|elected| crate::fuse::engine_param(&elected.field))
.collect();
let slots: Vec<syn::Ident> = routes
.iter()
.map(|elected| format_ident!("{}_slot", elected.field))
.collect();
let scopes: Vec<syn::Ident> = routes
.iter()
.map(|elected| format_ident!("{}_scope", elected.field))
.collect();
let owns: Vec<syn::Ident> = routes
.iter()
.map(|elected| format_ident!("{}_own", elected.field))
.collect();
let floors: Vec<syn::Ident> = routes
.iter()
.map(|elected| format_ident!("{}_floor", elected.field))
.collect();
// THE KNOB SEAT, one per route and beside that route's own floor — for the FLOOR's exact reason,
// stated one member over. A route's knobs are `<T as VectorEngine>::SearchOptions` where `T` is
// the type the DECLARATION named; this door's are `<__INGRAPH_ENGINE_<F>__ as …>::SearchOptions`,
// and nothing proves the two are one type. So the request package's `engine` seat cannot be read
// into a generic call here, and the knobs travel positionally exactly as the floors do.
let knob_seats: Vec<syn::Ident> = routes
.iter()
.map(|elected| format_ident!("{}_options", elected.field))
.collect();
let knobs: Vec<proc_macro2::TokenStream> = engines
.iter()
.map(|engine| quote!(::core::option::Option<&<#engine as #face>::SearchOptions>))
.collect();
let scores: Vec<proc_macro2::TokenStream> = engines
.iter()
.map(|engine| quote!(<#engine as #face>::Score))
.collect();
let refusals: Vec<proc_macro2::TokenStream> = engines
.iter()
.map(|engine| quote!(<#engine as #face>::Error))
.collect();
let variants: Vec<syn::Ident> = routes
.iter()
.map(|elected| format_ident!("{}", elected.field.to_string().to_upper_camel_case()))
.collect();
// ONE ROUTE's edge facts, read the same way in both doors: the weight a parent believes about
// it, whether the parent walked it at all, and HOW DEEP to ask it — the third fact, resolved
// through the framework's own law, which caps the ask against the DECLARED wall and falls to the
// caller's budget where the request named no depth.
let edges = routes.iter().map(|elected| {
let field = &elected.field;
let package = tier.route_options(elected);
let wall = self.wall(::core::option::Option::Some(field));
quote! {
let __ingraph_route = ::core::option::Option::and_then(options, #options::#field);
let __ingraph_enabled = ::core::option::Option::map_or(
__ingraph_route,
#route::<#package>::DEFAULT_ENABLED,
#route::enabled,
);
let __ingraph_weight = ::core::option::Option::map_or(
__ingraph_route,
#route::<#package>::DEFAULT_WEIGHT,
#route::weight,
);
let __ingraph_ceiling = #depth(
::core::option::Option::and_then(__ingraph_route, #route::depth),
// THE DECLARED CEILING, which is the only ceiling there is: a wall is written in the
// DECLARATION and never on a request, so nothing is read out of the package here. The
// word ARRIVED with the number tiers and this is the argument it fills — `None` still,
// and byte-for-byte the old tokens, where no tier of this declaration wrote one.
#wall,
limit,
);
}
});
let asks = routes
.iter()
.enumerate()
.zip(edges)
.map(|((at, elected), edge)| {
let field = &elected.field;
let (width, space) = self.geometry(elected);
let variant = &variants[at];
let engine = &engines[at];
let slot = &slots[at];
let scope = &scopes[at];
let floor = &floors[at];
let knob = &knob_seats[at];
let asked = tier.route_question(elected);
let keys = Door::Keys.name(field);
let point = quote!(#embedding<<#engine as #face>::Element, #width, #space>);
quote! {
{
#edge
let __ingraph_own = ::core::option::Option::and_then(
#question::#field(question),
#asked::coordinates,
);
if #participates(__ingraph_enabled, __ingraph_own) {
let __ingraph_coordinates: #point = ::core::convert::Into::into(
::core::clone::Clone::clone(
__ingraph_own.expect("a participating route resolved a question"),
),
);
let __ingraph_query = #vector_query::new(
__ingraph_coordinates,
::core::clone::Clone::clone(&#floor),
);
let __ingraph_ranked = Self::#keys::<#engine>(
#slot,
::core::clone::Clone::clone(&#scope),
&__ingraph_query,
__ingraph_ceiling,
#knob,
)
.await
.map_err(#refusal::#variant)?;
__ingraph_members.push((
__ingraph_weight,
::core::iter::Iterator::collect::<::std::vec::Vec<_>>(
::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_ranked),
|__ingraph_hit| {
let (__ingraph_score, __ingraph_rank, __ingraph_key) =
__ingraph_hit.into_components();
#rooted::new(
__ingraph_key,
__ingraph_rank,
#evidence::#variant(__ingraph_score),
)
},
),
),
));
}
}
}
});
let examples = routes.iter().enumerate().map(|(at, elected)| {
let field = &elected.field;
let package = tier.route_options(elected);
let variant = &variants[at];
let engine = &engines[at];
let slot = &slots[at];
let scope = &scopes[at];
let own = &owns[at];
let floor = &floors[at];
let knob = &knob_seats[at];
let similar = Door::Similar.name(field);
let wall = self.wall(::core::option::Option::Some(field));
quote! {
{
let __ingraph_route = ::core::option::Option::and_then(options, #options::#field);
let __ingraph_enabled = ::core::option::Option::map_or(
__ingraph_route,
#route::<#package>::DEFAULT_ENABLED,
#route::enabled,
);
let __ingraph_weight = ::core::option::Option::map_or(
__ingraph_route,
#route::<#package>::DEFAULT_WEIGHT,
#route::weight,
);
let __ingraph_ceiling = #depth(
::core::option::Option::and_then(__ingraph_route, #route::depth),
// THE DECLARED CEILING, which is the only ceiling there is: a wall is written in the
// DECLARATION and never on a request, so nothing is read out of the package here. The
// word ARRIVED with the number tiers and this is the argument it fills — `None` still,
// and byte-for-byte the old tokens, where no tier of this declaration wrote one.
#wall,
limit,
);
if __ingraph_enabled {
// AN UNINDEXED ROUTE IS ABSENT, not fatal: an entity held in one column and not another
// is what a multi-election declaration is for. Every other refusal propagates, and the
// ENGINE arm names the route it came from — the widening's whole point.
match Self::#similar::<#engine>(
#slot,
::core::clone::Clone::clone(&#own),
::core::clone::Clone::clone(&#scope),
key,
::core::clone::Clone::clone(&#floor),
__ingraph_ceiling,
#knob,
)
.await
{
::core::result::Result::Ok(__ingraph_ranked) => {
__ingraph_members.push((
__ingraph_weight,
::core::iter::Iterator::collect::<::std::vec::Vec<_>>(
::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_ranked),
|__ingraph_hit| {
let (__ingraph_score, __ingraph_rank, __ingraph_key) =
__ingraph_hit.into_components();
#rooted::new(
__ingraph_key,
__ingraph_rank,
#evidence::#variant(__ingraph_score),
)
},
),
),
));
}
::core::result::Result::Err(#refused::Unindexed) => {}
::core::result::Result::Err(#refused::Engine(__ingraph_refusal)) => {
return ::core::result::Result::Err(
#refused::Engine(#refusal::#variant(__ingraph_refusal)),
);
}
::core::result::Result::Err(#refused::Several { held }) => {
return ::core::result::Result::Err(#refused::Several { held });
}
::core::result::Result::Err(#refused::Width { declared, stored }) => {
return ::core::result::Result::Err(#refused::Width { declared, stored });
}
}
}
}
}
});
let resolved = quote! {
let __ingraph_fusion = ::core::option::Option::map_or(
::core::option::Option::and_then(options, #options::fusion),
<#fusion as ::core::default::Default>::default(),
#flavour::fusion,
);
};
let fuse_door = format_ident!("vector_fuse");
let similar_door = format_ident!("vector_fuse_similar");
let answer = quote!(::std::vec::Vec<#fused<#key, #evidence<#(#scores,)*>>>);
let coordinate_bounds = routes.iter().enumerate().map(|(at, elected)| {
let (width, space) = self.geometry(elected);
let engine = &engines[at];
let ty = &elected.ty;
quote! {
<#ty as #marker>::Item: ::core::clone::Clone
+ ::core::convert::Into<#embedding<<#engine as #face>::Element, #width, #space>>
}
});
// THE PER-ROUTE OBLIGATIONS, one group per route: the engine is one, the key addresses it, its
// currency clones and its read scope clones. Each is stated against THAT route's engine, which
// is what a single `__INGRAPH_ENGINE__` was quietly collapsing into one obligation.
let seams = engines.iter().map(|engine| {
quote! {
#engine: #lease,
#key: #row + #admits + ::core::clone::Clone,
<#engine as #face>::Score: ::core::clone::Clone,
<#engine as #lease>::ReadContext<'__ingraph_scope>: ::core::clone::Clone,
}
});
let similar_seams = seams.clone();
let fuse_params = routes.iter().enumerate().map(|(at, _)| {
let engine = &engines[at];
let slot = &slots[at];
let scope = &scopes[at];
let floor = &floors[at];
let knob = &knob_seats[at];
let seat = &knobs[at];
quote! {
#slot: &mut #brand<#engine, Self>,
#scope: #connected<'__ingraph_scope, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'__ingraph_scope>>,
#floor: <#engine as #face>::Score,
#knob: #seat,
}
});
let similar_params = routes.iter().enumerate().map(|(at, _)| {
let engine = &engines[at];
let slot = &slots[at];
let scope = &scopes[at];
let own = &owns[at];
let floor = &floors[at];
let knob = &knob_seats[at];
let seat = &knobs[at];
quote! {
#slot: &mut #brand<#engine, Self>,
#own: #connected<'__ingraph_scope, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'__ingraph_scope>>,
#scope: #connected<'__ingraph_scope, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'__ingraph_scope>>,
#floor: <#engine as #face>::Score,
#knob: #seat,
}
});
let fuse_body = self.observed(
observed,
&fuse_door,
quote! {
#resolved
let mut __ingraph_members = ::std::vec::Vec::new();
#(#asks)*
::core::result::Result::Ok(
#weighted::<_, _, #join<#key>>(__ingraph_members, __ingraph_fusion)
)
},
);
let similar_body = self.observed(
observed,
&similar_door,
quote! {
#resolved
let mut __ingraph_members = ::std::vec::Vec::new();
#(#examples)*
::core::result::Result::Ok(
#weighted::<_, _, #join<#key>>(__ingraph_members, __ingraph_fusion)
)
},
);
let fuse_doc = leading(&format!(
"FUSED, VECTOR — every one of [`{index}`]'s vector routes asked at once, their rankings \
joined by reciprocal rank fusion. Answers in THIS tier's own key.",
));
let law = leading(
"Beside the per-election doors and never instead of them: a caller asking one column still \
calls that column's own pair. What this adds is the four facts a fold needs and one route \
has no use for — WHICH routes to ask (a route with no resolvable question is structurally \
absent, and one the parent disabled is not walked), how much each one's opinion counts, HOW \
DEEP to ask each of them, and what arithmetic joins them.",
);
let depths = leading(
"PER-ROUTE DEPTH, spent at each route's own fetch: a route's `Route.depth` is what this door \
hands that route's `knn`, falling back to `limit` where the request named none, and CAPPED \
by the declaration's own ceiling wherever one is declared. Asymmetric engines therefore each \
get their own number — which is the point, since RRF is sum-family and a candidate pool \
deeper than the answer is the ordinary shape. A `depth` below `limit` is legal, and a \
`depth` above the wall is capped rather than refused: the request's number is a preference \
and the declaration's is protection.",
);
let hetero = leading(
"ONE ENGINE PARAMETER PER ROUTE, and one slot, one read scope, one FLOOR and one set of \
KNOBS beside each — because a floor is a number in ONE engine's currency and its knobs are \
written in ONE engine's vocabulary, and two routes held in two stores have two of each. The \
homogeneous tier names the same engine in every position, which is the DEGENERATE case of \
this signature rather than a second door.",
);
let knobs_doc = leading(
"PER-ROUTE KNOBS, spent at each route's own crossing and read by nothing here: \
`<field>_options` is handed to that route's tier-A door verbatim, and a route given none \
runs under its engine's own defaults.",
);
let knobs_wall = leading(
"They are POSITIONAL for the FLOOR's reason, one member over. The request package's `engine` \
seat holds `<T as VectorEngine>::SearchOptions` for the type the DECLARATION named — a \
concrete type — where this door's parameter is that projection off a generic engine, and \
nothing proves the two are one. So a generic door cannot read the seat's knobs into its own \
call, and what a caller holds concretely it hands in positionally.",
);
let knobs_borrow = leading(
"BORROWED, which is what makes a fan free: one request value reaches every route with no \
copy taken, and no route's package is cloned to be spent. No door of this family states a \
`Clone` obligation about the knobs.",
);
let currency = leading(
"No score of any route enters the fusion — only the ORDINAL its engine gave the hit — which \
is what lets routes whose currencies were never compared be fused at all. Each route's own \
score rides out as EVIDENCE instead, in that route's own currency.",
);
let similar_doc = leading(&format!(
"FUSED, VECTOR, BY EXAMPLE — what else is near THIS entity, according to every one of \
[`{index}`]'s vector routes at once. The key is this tier's own at every level, and each \
route reaches its own stored vectors through its own by-example door.",
));
let absence = leading(
"A route holding nothing for this entity drops OUT of the fold rather than refusing the \
whole answer: an entity indexed in one column and not another is what a multi-election \
declaration is for. Every other refusal — a width the declaration does not state, several \
vectors where it elected one, the engine's own — propagates, the engine's own wearing the \
name of the route that spoke it.",
);
quote! {
#[doc = #fuse_doc]
#[doc = ""]
#[doc = #law]
#[doc = ""]
#[doc = #depths]
#[doc = ""]
#[doc = #hetero]
#[doc = ""]
#[doc = #knobs_doc]
#[doc = ""]
#[doc = #knobs_wall]
#[doc = ""]
#[doc = #knobs_borrow]
#[doc = ""]
#[doc = #currency]
#[allow(clippy::too_many_arguments)]
#vis async fn #fuse_door<'__ingraph_scope, #(#engines),*>(
#(#fuse_params)*
options: ::core::option::Option<&#options>,
question: &#question,
limit: ::core::num::NonZeroUsize,
) -> ::core::result::Result<#answer, #refusal<#(#refusals,)*>>
where
#(#seams)*
#(#coordinate_bounds,)*
{
#fuse_body
}
#[doc = #similar_doc]
#[doc = ""]
#[doc = #absence]
#[doc = ""]
#[doc = #depths]
#[doc = ""]
#[doc = #hetero]
#[doc = ""]
#[doc = #knobs_doc]
#[doc = ""]
#[doc = #knobs_wall]
#[doc = ""]
#[doc = #knobs_borrow]
#[doc = ""]
#[doc = #currency]
#[allow(clippy::too_many_arguments)]
#vis async fn #similar_door<'__ingraph_scope, #(#engines),*>(
#(#similar_params)*
key: &#key,
options: ::core::option::Option<&#options>,
limit: ::core::num::NonZeroUsize,
) -> ::core::result::Result<#answer, #refused<#refusal<#(#refusals,)*>>>
where
#(#similar_seams)*
{
#similar_body
}
}
}
/// THE MINI FUSE DOORS — `vector_fuse_by_<field>` and `vector_fuse_similar_by_<field>`, over ONE
/// fanned election's legs.
///
/// # The fractal, one level down
///
/// A fanned field carries the tier's whole fusion kit onto one field: its LEGS are its routes, its
/// slot package is a mini `FuseOptions`, and this is the door that spends them. Everything the
/// tier door does over the fields a declaration elected, this does over the stores ONE field is
/// written to — the same fold, the same ordinals, the same evidence shape.
///
/// # ONE QUESTION, and that is the deliberate asymmetry
///
/// The tier door takes a question package per route, because two elections are two spaces. The
/// legs are ONE field's coordinates in several stores, so there is one question and every leg is
/// asked it — which is why the question package of a fanned slot has no per-leg row, and why this
/// signature takes one `question` where the tier's takes a tree.
///
/// The asymmetry does not reach the KNOBS: a leg's `Route` carries its own weight and its own
/// DEPTH, resolved exactly as a tier route's is, so the legs share a question and disagree about
/// how deep to answer it.
///
/// # The SELECTOR is read here and nowhere else
///
/// `engine` absent picks the FUSED road: every participating leg is walked and their ordinals are
/// folded. `engine` present picks ONE leg and reads it directly, answering the SAME shape — the
/// evidence enum with a single variant filled. There is no second door and no second answer type,
/// which is the whole of what *addressability* costs.
///
/// A leg a `resource =` word made addressable but `rrf = false` took out of the leaderboard is
/// reachable ONLY by the selector, and is skipped on the fused road. A participating leg with no
/// `resource =` word is the reverse: folded, and unnameable.
///
/// # The floors are POSITIONAL, and the seat's own floor is not spent
///
/// The selector's variants each carry a `floor` in their engine's own `Score` — a CONCRETE type,
/// projected off the path the declaration wrote. This door's floor is
/// `<__INGRAPH_ENGINE_<LEG>__ as VectorEngine>::Score`, a generic. Nothing proves the two are one
/// type, so the seat's floor cannot be read into a generic door's call and the positional floor is
/// what is spent. Same posture as the tier door's, and the same posture `options` has carried
/// since β4b.
fn fanned_half(&self, observed: bool) -> proc_macro2::TokenStream {
let tier = self.tier();
let slots: Vec<proc_macro2::TokenStream> = tier
.fanned_slots()
.map(|elected| self.fanned_slot_doors(observed, elected))
.collect();
quote!(#(#slots)*)
}
/// ONE fanned election's pair of mini fuse doors — see [`fanned_half`](Self::fanned_half).
fn fanned_slot_doors(&self, observed: bool, elected: &Elected) -> proc_macro2::TokenStream {
use heck::ToUpperCamelCase as _;
let IndexModel { vis, krate, .. } = self;
let key = self.key();
// The BASE carries the vocabulary and the READ FACE carries the lease, so a projection names
// whichever of the two declares the member it asks for; the bound names the face, which implies
// the base. The row names NEITHER — `Field` is engine-blind, which is what the column language
// bought and what makes this bound one word instead of one per engine.
let face = framework(krate, &["store"], "VectorEngine");
let lease = framework(krate, &["store"], "AsyncVectorRead");
let row = framework(krate, &["store"], "Field");
let brand = framework(krate, &["store"], "SlotHandle");
let connected = framework(krate, &["store"], "Connected");
let embedding = framework(krate, &["storage"], "Embedding");
let marker = framework(krate, &["election"], "EmbeddingMarker");
let vector_query = framework(krate, &["retrieve"], "VectorQuery");
let fused = framework(krate, &["retrieve"], "Fused");
let rooted = framework(krate, &["retrieve"], "Rooted");
let route = framework(krate, &["retrieve"], "Route");
let depth = framework(krate, &["retrieve"], "route_depth");
let flavour = framework(krate, &["retrieve"], "FusionOptions");
let fusion = framework(krate, &["retrieve"], "Fusion");
let participates = framework(krate, &["retrieve"], "participates");
let weighted = framework(krate, &["retrieve"], "fuse_weighted");
let refused = framework(krate, &["retrieve"], "OwnReadError");
let join = framework(krate, &["retrieve"], self.dedup.join());
let admits = self.dedup.admits();
let tier = self.tier();
let field = &elected.field;
let legs = tier.slot_legs(elected);
let options = tier.route_options(elected);
let asked = tier.route_question(elected);
let evidence = tier.slot_evidence_name(elected);
let refusal = tier.slot_error_name(elected);
let selector = tier.slot_selector(elected);
let (width, space) = self.geometry(elected);
let keys = Door::Keys.name(field);
let similar = Door::Similar.name(field);
let fuse_door = Door::FusedLegs.name(field);
let similar_door = Door::FusedLegsSimilar.name(field);
// ONE LEG'S OWN NAMES, in written order and read in lock-step — the same discipline the tier
// door's route lists are under, at the grain where a route is a STORE.
let engines: Vec<syn::Ident> = legs
.iter()
.map(|engine| crate::fuse::engine_param(&engine.word))
.collect();
let variants: Vec<syn::Ident> = legs
.iter()
.map(|engine| format_ident!("{}", engine.word.to_string().to_upper_camel_case()))
.collect();
let handles: Vec<syn::Ident> = legs
.iter()
.map(|engine| format_ident!("{}_slot", engine.word))
.collect();
let scopes: Vec<syn::Ident> = legs
.iter()
.map(|engine| format_ident!("{}_scope", engine.word))
.collect();
let owns: Vec<syn::Ident> = legs
.iter()
.map(|engine| format_ident!("{}_own", engine.word))
.collect();
let floors: Vec<syn::Ident> = legs
.iter()
.map(|engine| format_ident!("{}_floor", engine.word))
.collect();
// ONE LEG'S KNOBS, beside its floor and named after the WORD its declaration wrote — the tier
// door's own seat one grain down, and positional for the same measured reason.
let knob_seats: Vec<syn::Ident> = legs
.iter()
.map(|engine| format_ident!("{}_options", engine.word))
.collect();
let knobs: Vec<proc_macro2::TokenStream> = engines
.iter()
.map(|engine| quote!(::core::option::Option<&<#engine as #face>::SearchOptions>))
.collect();
let scores: Vec<proc_macro2::TokenStream> = engines
.iter()
.map(|engine| quote!(<#engine as #face>::Score))
.collect();
let refusals: Vec<proc_macro2::TokenStream> = engines
.iter()
.map(|engine| quote!(<#engine as #face>::Error))
.collect();
// THE SELECTOR, read ONCE at the head of each body — `None` where the slot typed no leg, in
// which case every gate below collapses to the edge fact alone.
let chosen = selector
.as_ref()
.map_or_else(proc_macro2::TokenStream::new, |_| {
quote! {
let __ingraph_chosen = ::core::option::Option::and_then(options, #options::engine);
}
});
// ONE LEG's gate and edge facts. A PARTICIPANT reads its `Route` seat; a typed non-participant
// has no seat to read and is reachable only by being named.
let edge = |at: usize| {
let engine = legs[at];
let variant = &variants[at];
let named = selector.as_ref().map(|selector| {
quote!(
::core::matches!(__ingraph_chosen, ::core::option::Option::Some(#selector::#variant(_)))
)
});
if engine.rrf {
let leg = tier.slot_leg_options(elected, engine);
let word = &engine.word;
// The FUSED road's gate is the parent's edge fact; the SELECTOR road's is the name. A
// request that named ANOTHER leg does not walk this one even though it participates.
let gate = named.map_or_else(
|| quote!(let __ingraph_walk = __ingraph_enabled;),
|named| {
quote! {
let __ingraph_walk = if ::core::option::Option::is_some(&__ingraph_chosen) {
#named
} else {
__ingraph_enabled
};
}
},
);
let wall = self.wall(::core::option::Option::Some(&elected.field));
quote! {
let __ingraph_route = ::core::option::Option::and_then(options, #options::#word);
let __ingraph_enabled = ::core::option::Option::map_or(
__ingraph_route,
#route::<#leg>::DEFAULT_ENABLED,
#route::enabled,
);
let __ingraph_weight = ::core::option::Option::map_or(
__ingraph_route,
#route::<#leg>::DEFAULT_WEIGHT,
#route::weight,
);
let __ingraph_ceiling = #depth(
::core::option::Option::and_then(__ingraph_route, #route::depth),
// THE DECLARED CEILING, which is the only ceiling there is: a wall is written in the
// DECLARATION and never on a request, so nothing is read out of the package here. The
// word ARRIVED with the number tiers and this is the argument it fills — `None` still,
// and byte-for-byte the old tokens, where no tier of this declaration wrote one.
#wall,
limit,
);
#gate
}
} else {
let named =
named.expect("a leg outside the leaderboard is in the walk only if it is typed");
quote! {
// NO `Route` SEAT: this leg is outside the leaderboard, so its parent holds no edge facts
// about it — no weight, no depth. It is walked only when a request NAMES it, and then it
// is the whole answer: the weight is the neutral one and the depth is the caller's own
// budget, there being no fold to ask it deeper for.
let __ingraph_weight = #route::<()>::DEFAULT_WEIGHT;
let __ingraph_ceiling = limit;
let __ingraph_walk = #named;
}
}
};
let asks = (0..legs.len()).map(|at| {
let edge = edge(at);
let engine = &engines[at];
let variant = &variants[at];
let handle = &handles[at];
let scope = &scopes[at];
let floor = &floors[at];
let knob = &knob_seats[at];
let point = quote!(#embedding<<#engine as #face>::Element, #width, #space>);
quote! {
{
#edge
// THE ONE QUESTION, read per leg because each leg converts it into its OWN engine's
// element type. `participates` is the tier door's own predicate, reached rather than
// restated: no resolvable question is a structural absence at both grains.
let __ingraph_own = #asked::coordinates(question);
if #participates(__ingraph_walk, __ingraph_own) {
let __ingraph_coordinates: #point = ::core::convert::Into::into(
::core::clone::Clone::clone(
__ingraph_own.expect("a walked leg resolved the slot's question"),
),
);
let __ingraph_query = #vector_query::new(
__ingraph_coordinates,
::core::clone::Clone::clone(&#floor),
);
let __ingraph_ranked = Self::#keys::<#engine>(
#handle,
::core::clone::Clone::clone(&#scope),
&__ingraph_query,
__ingraph_ceiling,
#knob,
)
.await
.map_err(#refusal::#variant)?;
__ingraph_members.push((
__ingraph_weight,
::core::iter::Iterator::collect::<::std::vec::Vec<_>>(
::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_ranked),
|__ingraph_hit| {
let (__ingraph_score, __ingraph_rank, __ingraph_key) =
__ingraph_hit.into_components();
#rooted::new(
__ingraph_key,
__ingraph_rank,
#evidence::#variant(__ingraph_score),
)
},
),
),
));
}
}
}
});
let examples = (0..legs.len()).map(|at| {
let edge = edge(at);
let engine = &engines[at];
let variant = &variants[at];
let handle = &handles[at];
let scope = &scopes[at];
let own = &owns[at];
let floor = &floors[at];
let knob = &knob_seats[at];
quote! {
{
#edge
if __ingraph_walk {
// AN UNINDEXED LEG IS ABSENT, not fatal — one store holding this entity and another
// not is exactly what a fan is for. Every other refusal propagates, the engine's own
// wearing the name of the STORE that spoke it.
match Self::#similar::<#engine>(
#handle,
::core::clone::Clone::clone(&#own),
::core::clone::Clone::clone(&#scope),
key,
::core::clone::Clone::clone(&#floor),
__ingraph_ceiling,
#knob,
)
.await
{
::core::result::Result::Ok(__ingraph_ranked) => {
__ingraph_members.push((
__ingraph_weight,
::core::iter::Iterator::collect::<::std::vec::Vec<_>>(
::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_ranked),
|__ingraph_hit| {
let (__ingraph_score, __ingraph_rank, __ingraph_key) =
__ingraph_hit.into_components();
#rooted::new(
__ingraph_key,
__ingraph_rank,
#evidence::#variant(__ingraph_score),
)
},
),
),
));
}
::core::result::Result::Err(#refused::Unindexed) => {}
::core::result::Result::Err(#refused::Engine(__ingraph_refusal)) => {
return ::core::result::Result::Err(
#refused::Engine(#refusal::#variant(__ingraph_refusal)),
);
}
::core::result::Result::Err(#refused::Several { held }) => {
return ::core::result::Result::Err(#refused::Several { held });
}
::core::result::Result::Err(#refused::Width { declared, stored }) => {
return ::core::result::Result::Err(#refused::Width { declared, stored });
}
}
}
}
}
});
let resolved = quote! {
let __ingraph_fusion = ::core::option::Option::map_or(
::core::option::Option::and_then(options, #options::fusion),
<#fusion as ::core::default::Default>::default(),
#flavour::fusion,
);
};
let answer = quote!(::std::vec::Vec<#fused<#key, #evidence<#(#scores,)*>>>);
let seams = engines.iter().map(|engine| {
quote! {
#engine: #lease,
#key: #row + #admits + ::core::clone::Clone,
<#engine as #face>::Score: ::core::clone::Clone,
<#engine as #lease>::ReadContext<'__ingraph_scope>: ::core::clone::Clone,
}
});
let similar_seams = seams.clone();
let ty = &elected.ty;
let coordinate_bounds = engines.iter().map(|engine| {
quote! {
<#ty as #marker>::Item: ::core::clone::Clone
+ ::core::convert::Into<#embedding<<#engine as #face>::Element, #width, #space>>
}
});
let fuse_params = (0..legs.len()).map(|at| {
let engine = &engines[at];
let handle = &handles[at];
let scope = &scopes[at];
let floor = &floors[at];
let knob = &knob_seats[at];
let seat = &knobs[at];
quote! {
#handle: &mut #brand<#engine, Self>,
#scope: #connected<'__ingraph_scope, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'__ingraph_scope>>,
#floor: <#engine as #face>::Score,
#knob: #seat,
}
});
let similar_params = (0..legs.len()).map(|at| {
let engine = &engines[at];
let handle = &handles[at];
let scope = &scopes[at];
let own = &owns[at];
let floor = &floors[at];
let knob = &knob_seats[at];
let seat = &knobs[at];
quote! {
#handle: &mut #brand<#engine, Self>,
#own: #connected<'__ingraph_scope, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'__ingraph_scope>>,
#scope: #connected<'__ingraph_scope, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'__ingraph_scope>>,
#floor: <#engine as #face>::Score,
#knob: #seat,
}
});
let fuse_body = self.observed(
observed,
&fuse_door,
quote! {
#chosen
#resolved
let mut __ingraph_members = ::std::vec::Vec::new();
#(#asks)*
::core::result::Result::Ok(
#weighted::<_, _, #join<#key>>(__ingraph_members, __ingraph_fusion)
)
},
);
let similar_body = self.observed(
observed,
&similar_door,
quote! {
#chosen
#resolved
let mut __ingraph_members = ::std::vec::Vec::new();
#(#examples)*
::core::result::Result::Ok(
#weighted::<_, _, #join<#key>>(__ingraph_members, __ingraph_fusion)
)
},
);
let fuse_doc = leading(&format!(
"FUSED, FANNED SLOT — every store `{field}` is written to asked at once with the SAME \
question, their rankings joined by reciprocal rank fusion.",
));
let fractal = leading(
"The tier's own door one level down: a fanned field's LEGS are its routes, so this is the \
same fold over the stores one field lives in rather than over the fields a declaration \
elected. It stands beside the per-election pair and never instead of it.",
);
let one_question = leading(
"ONE QUESTION for every leg, which is the fan's deliberate asymmetry: the legs are one \
field's coordinates in several stores, so there is nothing per-leg to ask. What IS per-leg \
is the parent's own `Route.depth`, which is what this door hands that leg's `knn`. A leg the \
declaration left out of the leaderboard has no `Route` seat to carry one and takes the \
caller's budget whole.",
);
let per_leg_knobs = leading(
"The ENGINE's own per-query knobs are per-leg too, and `<word>_options` is the seat: two \
stores holding one field speak two vocabularies, so there is no package both could take. \
Each is handed to that leg's tier-A door verbatim and BORROWED — one question, several \
stores, no copy — and a leg given none runs under its engine's defaults. Positional for the \
floor's own reason: the seat's knobs are the concrete type the declaration NAMED, and this \
door's are that projection off a generic engine.",
);
let selector_doc = leading(
"The `engine` seat picks the ROAD. Absent, the fused one: every leg the declaration left in \
the leaderboard is walked. Present, a single-leg direct read of the leg it names — answering \
the SAME shape, with one variant of the evidence filled, so a client that switches roads \
parses the same answer.",
);
let similar_doc = leading(&format!(
"FUSED, FANNED SLOT, BY EXAMPLE — what else is near THIS entity's `{field}`, according to \
every store it is written to at once.",
));
let absence = leading(
"A store holding nothing for this entity drops OUT of the fold rather than refusing the whole \
answer. Every other refusal propagates, the engine's own wearing the name of the store that \
spoke it.",
);
quote! {
#[doc = #fuse_doc]
#[doc = ""]
#[doc = #fractal]
#[doc = ""]
#[doc = #one_question]
#[doc = ""]
#[doc = #per_leg_knobs]
#[doc = ""]
#[doc = #selector_doc]
#[allow(clippy::too_many_arguments)]
#vis async fn #fuse_door<'__ingraph_scope, #(#engines),*>(
#(#fuse_params)*
options: ::core::option::Option<&#options>,
question: &#asked,
limit: ::core::num::NonZeroUsize,
) -> ::core::result::Result<#answer, #refusal<#(#refusals,)*>>
where
#(#seams)*
#(#coordinate_bounds,)*
{
#fuse_body
}
#[doc = #similar_doc]
#[doc = ""]
#[doc = #fractal]
#[doc = ""]
#[doc = #absence]
#[doc = ""]
#[doc = #per_leg_knobs]
#[doc = ""]
#[doc = #selector_doc]
#[allow(clippy::too_many_arguments)]
#vis async fn #similar_door<'__ingraph_scope, #(#engines),*>(
#(#similar_params)*
key: &#key,
options: ::core::option::Option<&#options>,
limit: ::core::num::NonZeroUsize,
) -> ::core::result::Result<#answer, #refused<#refusal<#(#refusals,)*>>>
where
#(#similar_seams)*
{
#similar_body
}
}
}
/// THE FUSED-READ IMPL — the `keys` verb a fused read asks this member through.
///
/// # The MODALITY MARKER that used to ride here is gone
///
/// Until 2026-08-19 this emission also wrote `impl VectorFusable for …` (or the full-text twin),
/// free at the index grain because a declaration's KIND is its modality. What DEMANDED it — a
/// graph root's `fuse(vector)` / `fuse(fulltext)` trim — had already retired with the root's own
/// typed doors, and no round after it wrote the bound: the recipe layer LISTS its members, so
/// there is no typed door for a trim to select. A capability nobody demands is a trait in a
/// prelude, so both markers and this impl went together. The verb below is unaffected — it was
/// always ONE trait for both modalities, which is what lets a mixed door reach every member
/// through one projection.
///
/// # ONE ENGINE PER MEMBER at this seat, and the member's own heterogeneity is still reachable
///
/// The impl is generic over one `E`: a fused read's routes are its MEMBERS, so the currency law at
/// that grain is one engine parameter per member exactly as the index grain's is one per route. A
/// member whose own routes are held by DIFFERENT engines is still asked through its own
/// `vector_fuse`, which takes one engine each; widening this seat would mean a consumer's
/// signature naming a member's route count, which is the wall the projection exists to keep.
///
/// # `Ctx` is one `(slot, scope, floor, options)` seat per ASKING POSITION the member's top door has
///
/// Named inside this impl and nowhere else — a root spells `<M as AsyncFusedRead<E>>::Ctx<'_>` and
/// learns nothing about a slot. The last two ride here for ONE reason, and it is the reason the
/// floor already rode here: both are written in the ENGINE's own vocabulary — `Score` and
/// `SearchOptions` — and a root holds this member's package by PROJECTION, so there is no row it
/// could read either out of. What a caller holds concretely it hands in through the seat; what the
/// root can name it hands in through `options`. The list is the emission's own:
///
/// | this member | its top door | `Ctx` |
/// |---|---|---|
/// | ≥ 2 fused routes | `vector_fuse` | one seat per route |
/// | 1 fused route | that route's `retrieve_keys_by_<field>` | one seat |
/// | a full-text subject | `retrieve_keys` | one seat |
/// | a vector tier whose only election is a SET | — | no impl at all |
///
/// The last row is the presence law reaching this seam: a set election is no route of its own tier
/// (see [`crate::fuse::Tier::doors`]), so a declaration electing nothing else has nothing a
/// parent's fold could read an ordinal from, and it does not implement the capability. A root
/// naming it is `E0277` rather than a member that silently contributes nothing.
///
/// # What `keys` hands up, per route count
///
/// | routes | `Evidence` | the ordinal a parent reads |
/// |---|---|---|
/// | one | `<E as …>::Score` | the ENGINE's raw ordinal, untouched |
/// | several | `Vec<<Index>FusedEvidence<…>>` | this member's own FUSED position, 1-based |
///
/// The second row is the fractal's own sentence — *each child fusing its own routes and entering
/// its parent as one* — and it is the one place in this pipeline where an ordinal is MINTED. It is
/// lawful exactly where a set election's is not: the number comes from an ORDER a fold authored,
/// where a set election's `m` streams have no order between them to author one from. A member's
/// own weights and fusion flavour are spent producing it, which is what makes them reachable from
/// a root at all.
///
/// # A question nobody asked is a STRUCTURAL ABSENCE
///
/// A member whose seat in the root's question package is empty answers the empty list rather than
/// its whole corpus — `participates`' law, read at the member grain, so a root asking two of its
/// three members does not silently ask the third.
fn capability(&self) -> proc_macro2::TokenStream {
let IndexModel { index, krate, .. } = self;
let tier = self.tier();
let (Some(options), Some(question)) = (tier.options_name(), tier.question_name()) else {
return proc_macro2::TokenStream::new();
};
// THREE ROWS, and the third is the engine cutover: `lease` is the trait that declares the read
// scope and `face` the one that declares the vocabulary. The ROW is neither's — `Field` is
// engine-blind, one impl per TYPE, so BOTH families now spell the same one word where each used
// to spell its own engine-keyed trait. A FOURTH row named the modality marker until 2026-08-19.
let (face, lease, row) = match self.kind {
NodeKind::Fulltext => (
framework(krate, &["store"], "FulltextEngine"),
framework(krate, &["store"], "AsyncFulltextRead"),
framework(krate, &["store"], "Field"),
),
NodeKind::Vector => (
framework(krate, &["store"], "VectorEngine"),
framework(krate, &["store"], "AsyncVectorRead"),
framework(krate, &["store"], "Field"),
),
NodeKind::Operator
| NodeKind::Entity
| NodeKind::Record
| NodeKind::Aggregate
| NodeKind::Blob => {
return proc_macro2::TokenStream::new();
}
};
let seam = framework(krate, &["retrieve"], "AsyncFusedRead");
let depth = framework(krate, &["retrieve"], "route_depth");
let engine = format_ident!("__INGRAPH_ENGINE__");
let key = self.key();
let brand = framework(krate, &["store"], "SlotHandle");
let connected = framework(krate, &["store"], "Connected");
let rooted = framework(krate, &["retrieve"], "Rooted");
let admits = self.dedup.admits();
let participates = framework(krate, &["retrieve"], "participates");
let routes: Vec<&Elected> = tier.fused_routes().collect();
if self.kind == NodeKind::Vector && routes.is_empty() {
return proc_macro2::TokenStream::new();
}
let seats = routes.len().max(1);
// ONE ASKING POSITION: the slot, the read scope, the FLOOR and the KNOBS. The last two ride here
// for one reason — both are written in the ENGINE's own vocabulary, and a root holds this
// member's package by PROJECTION and can read no row out of it. So neither can arrive through
// `options`, and both arrive through the seat a root hands down whole without naming its parts.
let seat = quote! {
(
&'__ingraph_ctx mut #brand<#engine, Self>,
#connected<'__ingraph_ctx, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'__ingraph_ctx>>,
<#engine as #face>::Score,
::core::option::Option<&'__ingraph_ctx <#engine as #face>::SearchOptions>,
)
};
// ONE SEAT IS THE TUPLE ITSELF. A one-element tuple is a legal type and an ugly call — `((a, b,
// c, d),)` at every single-route member, which is most of them — so the wrapper appears exactly
// where there is something to wrap.
let seats_list: Vec<proc_macro2::TokenStream> = (0..seats).map(|_| seat.clone()).collect();
let ctx = if seats == 1 {
seat.clone()
} else {
quote!((#(#seats_list,)*))
};
let slots: Vec<syn::Ident> = (0..seats)
.map(|at| format_ident!("__ingraph_slot_{at}"))
.collect();
let scopes: Vec<syn::Ident> = (0..seats)
.map(|at| format_ident!("__ingraph_scope_{at}"))
.collect();
let floors: Vec<syn::Ident> = (0..seats)
.map(|at| format_ident!("__ingraph_floor_{at}"))
.collect();
let knob_seats: Vec<syn::Ident> = (0..seats)
.map(|at| format_ident!("__ingraph_options_{at}"))
.collect();
let destructure = if seats == 1 {
let slot = &slots[0];
let scope = &scopes[0];
let floor = &floors[0];
let knob = &knob_seats[0];
quote!(let (#slot, #scope, #floor, #knob) = ctx;)
} else {
quote!(let (#((#slots, #scopes, #floors, #knob_seats),)*) = ctx;)
};
// The RANKED-TO-ROOTED mapping, written once: the engine's own ordinal rides out untouched and
// the score becomes this member's evidence.
let carried = quote! {
::core::iter::Iterator::collect(::core::iter::Iterator::map(
::std::vec::Vec::into_iter(__ingraph_ranked),
|__ingraph_hit| {
let (__ingraph_score, __ingraph_rank, __ingraph_key) = __ingraph_hit.into_components();
#rooted::new(__ingraph_key, __ingraph_rank, __ingraph_score)
},
))
};
let first_slot = &slots[0];
let first_scope = &scopes[0];
let first_floor = &floors[0];
let first_knobs = &knob_seats[0];
let (evidence, refusal, body) = if routes.len() > 1 {
let fused_evidence = tier.evidence_name();
let fused_error = tier.fused_error_name();
let door = format_ident!("vector_fuse");
let scores = (0..routes.len()).map(|_| quote!(<#engine as #face>::Score));
let errors = (0..routes.len()).map(|_| quote!(<#engine as #face>::Error));
let engines = (0..routes.len()).map(|_| quote!(#engine));
let handed = (0..routes.len()).map(|at| {
let slot = &slots[at];
let scope = &scopes[at];
let floor = &floors[at];
let knob = &knob_seats[at];
quote!(#slot, #scope, #floor, #knob,)
});
// THE NESTED EVIDENCE IS THIS MEMBER'S OWN SIGHTING LIST, WHOLE (Q3b + #296-L2). A parent's
// variant holds what the child's fold answered, and what a fold answers is now a list of
// sightings — the member's evidence beside the term each of them contributed. Unwrapping to
// the bare evidence here would strip the number at exactly the seam the wire union publishes
// it at.
let sighting = framework(krate, &["retrieve"], "Sighting");
(
quote!(::std::vec::Vec<#sighting<#fused_evidence<#(#scores,)*>>>),
quote!(#fused_error<#(#errors,)*>),
quote! {
#destructure
let __ingraph_fused = Self::#door::<#(#engines),*>(
#(#handed)*
options,
question,
limit,
)
.await?;
// THE MINTED ORDINAL, and the one place this pipeline mints one. It is a POSITION in an
// order this member's own fold AUTHORED — which is exactly the condition a set election
// lacks, and why that case is excluded from the walk rather than given a number.
::core::result::Result::Ok(
::core::iter::Iterator::collect(::core::iter::Iterator::map(
::core::iter::Iterator::enumerate(::std::vec::Vec::into_iter(__ingraph_fused)),
|(__ingraph_at, __ingraph_row)| {
let (_, __ingraph_root, __ingraph_seen) = __ingraph_row.into_components();
#rooted::new(__ingraph_root, (__ingraph_at as u64) + 1, __ingraph_seen)
},
)),
)
},
)
} else if self.kind == NodeKind::Fulltext {
let door = format_ident!("retrieve_keys");
let query = framework(krate, &["retrieve"], "FulltextQuery");
// THE UNSUFFIXED SUBJECT has no election to name, so the wall it is capped by is the
// CONTAINER's alone — which is the whole chain at this grain rather than a step of it.
let wall = self.wall(::core::option::Option::None);
(
quote!(<#engine as #face>::Score),
quote!(<#engine as #face>::Error),
quote! {
#destructure
// NO EDGE AT THIS GRAIN, and that is the fractal rather than a gap: the parent already
// spent its `Route`'s depth against its own budget before it called, so what arrives as
// `limit` IS this edge's number. What is left to resolve is this declaration's own.
let __ingraph_ceiling = #depth(
::core::option::Option::None,
// THE DECLARED CEILING, which is the only ceiling there is: a wall is written in the
// DECLARATION and never on a request, so nothing is read out of the package here. The
// word ARRIVED with the number tiers and this is the argument it fills — `None` still,
// and byte-for-byte the old tokens, where no tier of this declaration wrote one.
#wall,
limit,
);
let __ingraph_question = match #question::question(question) {
::core::option::Option::Some(__ingraph_text) => __ingraph_text,
::core::option::Option::None => {
return ::core::result::Result::Ok(::std::vec::Vec::new());
}
};
let __ingraph_query = #query::new(
::std::string::String::clone(__ingraph_question),
#first_floor,
);
let __ingraph_ranked = Self::#door::<#engine>(
#first_slot,
#first_scope,
&__ingraph_query,
__ingraph_ceiling,
#first_knobs,
)
.await?;
::core::result::Result::Ok(#carried)
},
)
} else {
let elected = routes[0];
let field = &elected.field;
let (width, space) = self.geometry(elected);
let embedding = framework(krate, &["storage"], "Embedding");
let vector_query = framework(krate, &["retrieve"], "VectorQuery");
let route = framework(krate, &["retrieve"], "Route");
let door = Door::Keys.name(field);
let package = tier.route_options(elected);
let asked = tier.route_question(elected);
// A FANNED route takes the caller's own budget and does NOT read its edge's depth, where a
// flat leaf does. That asymmetry is INHERITED rather than chosen here: the read used to be one
// `route_depth` call whose middle argument was the leaf package's `ceiling` row, and a mini
// tier has no such row, so the whole call was skipped for a fan and the edge went with it. The
// wall law retired that row, which leaves the skip standing on nothing — whether a fanned
// route's own `Route::depth` should now be spent is a LETTER rather than a guess, and until it
// is answered the behaviour here is unmoved.
let flat = !tier
.fanned_slots()
.any(|fanned| fanned.field == elected.field);
// WHERE THE ROUTE'S OWN PACKAGE IS. A tier electing ONE field IS its route — the binding table
// hands the leaf up, and `options` already IS it. A tier electing several hands up its own
// fuse package, so the route is one seat inside it and is reached through the same `Route`
// edge the tier door reads. Both are possible with a single FUSED route: a set election is no
// route of its tier, so a two-election tier may have exactly one.
let nested = self.embeddings.len() > 1;
let read = if nested {
let ceiling = flat.then(|| {
let wall = self.wall(::core::option::Option::Some(field));
quote! {
let __ingraph_ceiling = #depth(
::core::option::Option::and_then(__ingraph_route, #route::depth),
// THE DECLARED CEILING, which is the only ceiling there is: a wall is written in the
// DECLARATION and never on a request, so nothing is read out of the package here. The
// word ARRIVED with the number tiers and this is the argument it fills — `None` still,
// and byte-for-byte the old tokens, where no tier of this declaration wrote one.
#wall,
limit,
);
}
});
let budget = ceiling
.is_none()
.then(|| quote!(let __ingraph_ceiling = limit;));
quote! {
let __ingraph_route = ::core::option::Option::and_then(options, #options::#field);
let __ingraph_enabled = ::core::option::Option::map_or(
__ingraph_route,
#route::<#package>::DEFAULT_ENABLED,
#route::enabled,
);
#ceiling
#budget
let __ingraph_own = ::core::option::Option::and_then(
#question::#field(question),
#asked::coordinates,
);
if !#participates(__ingraph_enabled, __ingraph_own) {
return ::core::result::Result::Ok(::std::vec::Vec::new());
}
let __ingraph_own = __ingraph_own.expect("a participating route resolved a question");
}
} else {
let ceiling = if flat {
let wall = self.wall(::core::option::Option::Some(field));
quote! {
let __ingraph_ceiling = #depth(
::core::option::Option::None,
// THE DECLARED CEILING, which is the only ceiling there is: a wall is written in the
// DECLARATION and never on a request, so nothing is read out of the package here. The
// word ARRIVED with the number tiers and this is the argument it fills — `None` still,
// and byte-for-byte the old tokens, where no tier of this declaration wrote one.
#wall,
limit,
);
}
} else {
quote!(let __ingraph_ceiling = limit;)
};
quote! {
#ceiling
let __ingraph_own = match #question::coordinates(question) {
::core::option::Option::Some(__ingraph_at) => __ingraph_at,
::core::option::Option::None => {
return ::core::result::Result::Ok(::std::vec::Vec::new());
}
};
}
};
(
quote!(<#engine as #face>::Score),
quote!(<#engine as #face>::Error),
quote! {
#destructure
#read
let __ingraph_coordinates: #embedding<
<#engine as #face>::Element, #width, #space
> = ::core::convert::Into::into(::core::clone::Clone::clone(__ingraph_own));
let __ingraph_query = #vector_query::new(__ingraph_coordinates, #first_floor);
let __ingraph_ranked = Self::#door::<#engine>(
#first_slot,
#first_scope,
&__ingraph_query,
__ingraph_ceiling,
#first_knobs,
)
.await?;
::core::result::Result::Ok(#carried)
},
)
};
// THE OBLIGATIONS, which are the member's own doors' restated once — a root that names this
// member inherits them at its own call rather than learning them.
let coordinates = routes.iter().map(|elected| {
let (width, space) = self.geometry(elected);
let ty = &elected.ty;
let marker = framework(krate, &["election"], "EmbeddingMarker");
let embedding = framework(krate, &["storage"], "Embedding");
quote! {
<#ty as #marker>::Item: ::core::clone::Clone
+ ::core::convert::Into<#embedding<<#engine as #face>::Element, #width, #space>>
}
});
let coordinates: Vec<proc_macro2::TokenStream> = match self.kind {
NodeKind::Vector => coordinates.collect(),
_ => Vec::new(),
};
// THE CLONE IS THE FUSED DOOR'S OWN, and it is asked for only where that door is reached: the
// tier door clones one read scope per route, and a member with one route never does. Stating it
// unconditionally would keep an engine whose scope is a lease out of every root, for a call it
// does not make.
let scoped = (routes.len() > 1).then(|| {
quote! {
for<'__ingraph_scope> <#engine as #lease>::ReadContext<'__ingraph_scope>:
::core::clone::Clone,
}
});
let doc = leading(&format!(
"[`{index}`] answers this modality's fused query — the capability this declaration's KIND \
states, and the verb a fused read asks it through.",
));
quote! {
const _: () = {
#[doc = #doc]
#[automatically_derived]
impl<#engine> #seam<#engine> for #index
where
#engine: #lease,
#key: #row + #admits + ::core::clone::Clone,
<#engine as #face>::Score: ::core::clone::Clone,
#scoped
#(#coordinates,)*
{
// The GAT's own outlives clauses, RESTATED — the trait owns them and an impl may not add
// one, so the impl repeats exactly what the trait declared.
// The GAT's own outlives clause, RESTATED — the trait owns it and an impl may not add
// one, so the impl repeats exactly what the trait declared. The two PROJECTIONS a borrowed
// scope needs follow from it by rustc's own projection-outlives rule, which is why the
// trait names one clause rather than three it could not spell over an unbounded engine.
type Ctx<'__ingraph_ctx>
= #ctx
where
#engine: '__ingraph_ctx;
type Error = #refusal;
type Evidence = #evidence;
type Root = #key;
fn keys<'__ingraph_ctx>(
ctx: Self::Ctx<'__ingraph_ctx>,
options: ::core::option::Option<&#options>,
question: &#question,
limit: ::core::num::NonZeroUsize,
) -> impl ::core::future::Future<
Output = ::core::result::Result<
::std::vec::Vec<#rooted<Self::Root, Self::Evidence>>,
Self::Error,
>,
>
where
#engine: '__ingraph_ctx,
{
async move { #body }
}
}
};
}
}
/// ONE ELECTION's width and space, as PROJECTIONS off the field's own type.
///
/// Both used to be tokens this crate read out of the field's spelling. They are now
/// `<<F as EmbeddingMarker>::Item as EmbeddingShape>::WIDTH` and `::Space`, which is the same two
/// facts arriving from the only party that can know them.
///
/// Three things come free with the move. An ALIAS works, because a bound resolves what a peel
/// could not. The SPACE stops being an [`Option`]: the parameter defaults to `Anon`, so a field
/// that named no space projects `Anon` and the emission no longer decides whether to spell a
/// third argument. And a ZERO WIDTH is `E0080` wherever the const is reached, because the
/// projection reads `Embedding::DIM` rather than `N`.
///
/// The width is BRACED because it is a const argument built from a path: a bare qualified path is
/// not one, and the braces are what put it in const-expression position. Nothing generic enters
/// it — the field's type is the declaration's own, concrete — so no unstable const machinery is
/// involved.
fn geometry(&self, elected: &Elected) -> (syn::Ident, syn::Ident) {
geometry(elected)
}
/// THE GEOMETRY BINDINGS — one `const` and one `type` per election, projecting the field's width
/// and its space out of the election family ONCE.
///
/// # Why the projections are bound to a name rather than written where they are spent
///
/// The width lands in CONST-ARGUMENT position, where a qualified path is not a legal const
/// argument and a braced block is. Two braced blocks of identical text are two ANONYMOUS
/// CONSTANTS, and rustc will not match a `where` clause carrying one against an obligation
/// carrying the other — the ask road, whose bound and whose call both name the elected width, is
/// where that shows up as *the trait bound is not satisfied* on the road's own hop. Measured, then
/// bound: one const, named, and every position refers to the SAME one.
///
/// The space has no such rule and is bound beside it anyway: the pair reads as one fact, and a
/// signature naming two short idents is a signature a person can read.
///
/// They live inside the expansion's anonymous `const`, so nothing of this is nameable from the
/// declaring scope.
fn geometry_bindings(&self) -> proc_macro2::TokenStream {
let marker = framework(&self.krate, &["election"], "EmbeddingMarker");
let shape = framework(&self.krate, &["election"], "EmbeddingShape");
let bound = self.embeddings.iter().map(|elected| {
let (width, space) = geometry(elected);
let ty = &elected.ty;
let at = elected.field.span();
// SPANNED AT THE ELECTION, which is what puts a missing impl's `E0277` on the word the author
// wrote rather than on a token of this emitter's.
quote_spanned! {at=>
#[allow(non_upper_case_globals)]
const #width: usize = <<#ty as #marker>::Item as #shape>::WIDTH;
#[allow(dead_code, non_camel_case_types)]
type #space = <<#ty as #marker>::Item as #shape>::Space;
}
});
quote!(#(#bound)*)
}
/// ONE HALF of the retrieve face: two inherent methods PER SUBJECT, and no trait over any of them.
///
/// # A full-text index has ONE subject and an embedding index has one PER ELECTION
///
/// The full-text kind emits `retrieve_keys` / `retrieve` — the WHOLE-SUBJECT pair, asking `All` —
/// and one `retrieve_keys_by_<field>` / `retrieve_by_<field>` pair per elected field beside it,
/// each minting a one-column `FulltextSubset`. The unsuffixed pair used to be the whole family
/// because there was nowhere to put a suffixed one's answer; the seam takes the subset now, so
/// there is. It STAYS because `All` and `These([field])` are two questions: `All` is whatever the
/// SLOT holds, and a slot may hold columns the declaration never elected. The vector pair is
/// `retrieve_keys_by_<field>` / `retrieve_by_<field>`, UNIFORMLY — one pair per election,
/// including where a declaration elects exactly one. There is no unsuffixed alias for the
/// single-election case: a name whose spelling depended on the CARDINALITY of the declaration
/// would move the day a second `knn` arrived, breaking every caller of a method nobody edited,
/// which is the same silent-shift argument that makes the marker mandatory.
///
/// # Why inherent and not a `Retrieve<Q>`
///
/// Everything that differs between two retrieve-capable nodes is EMITTED — the upstream entity a
/// tier-B answer holds, the filter type its store takes, the dedup mechanism its key admits — so a
/// unifying trait would be generic over all of it and would name nothing shared. What IS shared is
/// the framework's own core, which both methods delegate to. A trait minted OVER these methods, if
/// the fused cross-index query ever needs one, is a pure widening.
///
/// # What each method is generic over, and why none of it could be a concrete name
///
/// - **The ENGINE.** A declaration names its engines by WORD, and a word is bound to a type by
/// the deployment rather than here — shipped words under their own feature, everyone else's at
/// the graph root. So the seam is the parameter and the caller passes its handle, which is the
/// record side's own division read onto this axis: the SLOT is where the engine is chosen and the
/// type parameter is where the handle is. It also has to be: a build may have no engine compiled
/// at all.
/// - **The STORE.** Tier B gathers the UPSTREAM's rows, and the upstream's row types belong to
/// another expansion this one cannot see. Naming a dialect would be worse than impossible: a
/// derived index declares no database, so an emission reaching `sqlx` would make this
/// declaration fail to compile in a build with no SQL family at all. The seam is `AsyncGather`,
/// which is ungated, and the framework's `SqlGather` is what a SQL caller passes.
///
/// # THE TYPED READ IS HERE, because A′ took it off the engine
///
/// Neither engine face names a record: each answers with its OWN addresses, in its own vocabulary,
/// and the read back into `<Upstream as Transformer>::Key` is this emission's act — which is the
/// whole content of *the emission owns the typing*. Two lines carry it, one pair per family:
///
/// - `#key: Field` on the `where` clause, which is the KEY's structure impl — one `write`/`read`
/// pair per column, in the key's own order, and ENGINE-BLIND on both arms;
/// - `retrieve::keyed::<E, #key>(hits)?` / `retrieve::vector_keyed::<E, #key>(hits)?`, the
/// framework's shared walk over it.
///
/// A key column whose type has no row at all is `E0277` naming it — *`f64: Field` is not
/// satisfied* — at the retrieve call. It names ONE thing where the retired per-engine rows named
/// two, and that is the language having one fewer axis rather than a weaker refusal: a row is
/// written once per TYPE and reaches every engine, so *this type does not cross* is now the whole
/// of what can be wrong.
///
/// # It is emitted for BOTH RETRIEVING KINDS, and what was in the way was a WORD
///
/// The wall went first, and it was never the last thing standing: `VectorDb::knn` carried
/// `where R: VectorRecord + Transformer`, and requiring an absent impl on an inherent method of a
/// CONCRETE type is `E0277` — *add `#![feature(trivial_bounds)]`* — at a span inside an expansion
/// its author cannot edit. A′'s R-free `VectorEngine` has no such `where` at all. What remained
/// was not a bound but a FACT the declaration had no way to state: WHICH field of it is the
/// embedding. `#[ingraph(knn)]` states it, so the vector arm below reads the marked field and
/// nothing is picked on anybody's behalf.
///
/// `blob` still answers no retrieve, and that absence is permanent rather than pending: an
/// artifact family is ADDRESSED, not ranked, so there is no hit stream for a tier A to collapse.
///
/// # The two flavours differ in three lines, and share the rest
///
/// The engine face, the query type and the engine CALL — a string against coordinates. Everything
/// after the hits exist is the same code reached through the same core, which is what
/// *the pipeline is flavour-blind* means stated as an emission rather than as prose. Tier B is
/// identical on both: it takes keys and gathers rows, and by then a knn and a search have produced
/// the same thing.
///
/// The vector query carries the declaration's WIDTH — `VectorQuery<E::Element, E::Score, #N>`,
/// with `N` read off THIS election's field type — so asking a 768-wide column with a 384-wide
/// embedding is `E0308` at the call, and two elections of different widths take their own. Its
/// element and score are the ENGINE's, since it is the engine's `knn` that consumes the one and
/// reports the other.
///
/// It carries the SPACE the same way and from the same place: a field declared
/// `Embedding<f32, 768, Clip>` emits `VectorQuery<…, 768, Clip>`, so a query built in another
/// space is `E0308` at the call for the mismatch a width cannot see, and a field that named no
/// space emits the three-argument form its default already means.
///
/// The ELECTION SELECTOR rides beside it and is not a parameter: `knn` is asked for THIS method's
/// own `VectorColumn`, minted `const` from the field its `knn` marker elected. So which column
/// answers is a fact of the METHOD rather than an argument a caller could get wrong, and the pair
/// of suffixed names is the whole of the choice a caller makes.
///
/// # An election LABELLED `list(embedding)` grows a THIRD door
///
/// `retrieve_keys_by_<field>_with`, beside the pair and never instead of it: `m` query vectors and
/// a `FoldSemantics` in, one score per ENTITY out. It differs from the pair in three ways and each
/// is forced:
///
/// - it answers in `Folded` rather than `Ranked`, because the FOLD authors the answer's order —
/// there are `m` engine streams and no order between them, so no ordinal is minted ACROSS them
/// and each stream's own rides in that stream's slot;
/// - it names the SCOPE's lifetime, because the scope is CLONED once per query vector and the
/// `Clone` bound has to be written about a lifetime the signature can spell;
/// - it is TIER A only. The pair's tier B is unchanged and still answers the single-vector
/// question with whole entities.
///
/// The pair itself needs nothing: at one query vector the set road IS the pair's road, the
/// per-owner collapse being the dedup stage the pair already runs. And the door is gated on the
/// LABEL rather than on a bound, so a single election has no `_with` door at all — a true absence
/// rather than a seat nobody can sit in.
///
/// # The DEDUP word is spent here and nowhere else
///
/// It picks the membership type the delegation names, which picks the bound the method's `where`
/// clause carries. A key that cannot satisfy it is `E0277` at the CALL — which is where the
/// mismatch actually is, the key being the upstream's rather than this declaration's. The set door
/// spends it TWICE — once for the collapse's membership and once for the fold's accumulator — and
/// the two are the same word's two rows.
///
/// # `#[allow(dead_code)]`
///
/// The methods sit in the anonymous `const` with the rest of the expansion, so a declaration that
/// never retrieves would otherwise warn in its own `-D warnings` build about code its author did
/// not write.
///
/// # THE BY-KEY DOORS: `get_<field>` is the read, and the similar door is sugar over it
///
/// `get_<field>(slot, own, &key)` answers *what did you store for THIS entity in this column* —
/// the entity's own embedding, CHECKED against the elected field's own type. It is the by-key
/// read raised to door grade, and it is where every judgment about a stored vector is spent:
/// the seam answers a SET, this election declared ONE, so none is `Unindexed`, several is
/// `Several { held }` rather than a pick nobody made, and a width the declaration does not state
/// is `Width { declared, stored }` rather than a value the type is lying about. ONE engine call,
/// so ONE read scope, and NO `Admits` bound: nothing here builds a dedup membership.
///
/// `retrieve_similar_by_<field>` answers *what else is near THIS entity*, given the entity's key
/// rather than coordinates. Its whole body is the ruled recipe — **fetch own set → query with it
/// → exclude self** — and every step of it is a call to something already here: `get_<field>`
/// above, the same `knn` the raw pair calls, the same address read, the same walk. The one thing
/// it does that no existing line did is start that walk's dedup membership with the example
/// ALREADY SEEN, which is what makes the exclusion leave the example's raw-stream ordinal as a
/// HOLE and makes `limit` count neighbours. **The arity and the width are not restated here**:
/// the example arrives through the door above, so the three judgments have ONE authority and the
/// refusal rides `?` undecorated.
///
/// Both are emitted per ELECTION, like the pair, and conditional on nothing a declaration writes:
/// the by-key read is a capability of the seam, so any elected column can be asked. There is no
/// tier-B twin — the ruling names two doors and both are `retrieve_keys_*` — and no FOLD either:
/// a fold is what turns `m` per-query numbers into one, and both of these ask with a single
/// vector. The set door beside them is where a fold is spent.
///
/// # ALL SIX DOORS ARE INSTRUMENTED, and the `entry` field is what tells them apart
///
/// `observed` decides whether each body wears a span. Every method here crosses to an engine —
/// tier A directly, tier B through tier A, an `ask` road through the hops before either, the get
/// door in one crossing of its own, and the similar door through that one plus a `knn` — so
/// instrumenting some of them would need a rule nobody has written, which is the query face's own
/// answer one family over. The nesting a trace then shows is the composition it IS: a road inside
/// a tier B inside a tier A, a get inside a similar, each door named by its own `entry`.
fn retrieve_half(&self, observed: bool) -> proc_macro2::TokenStream {
let IndexModel {
index, vis, krate, ..
} = self;
let upstream = &self.source.node;
let key = self.key();
let engine = format_ident!("__INGRAPH_ENGINE__");
let store = format_ident!("__INGRAPH_STORE__");
// THE THREE LINES THE FLAVOURS DIFFER IN, decided once: which seam the methods project through,
// what a query IS, and how the engine is asked. `blob` decides nothing and answers nothing —
// an artifact family is addressed rather than ranked, which is why its arm is an early return
// and not a third row here.
//
// The BRAND is not among them: `SlotHandle` is a struct rather than a trait and is engine-kind
// agnostic, so the door each flavour goes through is branded by the same path.
let (face, lease, row, keyed) = match self.kind {
NodeKind::Fulltext => (
framework(krate, &["store"], "FulltextEngine"),
framework(krate, &["store"], "AsyncFulltextRead"),
framework(krate, &["store"], "Field"),
framework(krate, &["retrieve"], "keyed"),
),
NodeKind::Vector => (
framework(krate, &["store"], "VectorEngine"),
framework(krate, &["store"], "AsyncVectorRead"),
framework(krate, &["store"], "Field"),
framework(krate, &["retrieve"], "vector_keyed"),
),
_ => return proc_macro2::TokenStream::new(),
};
// A FOURTH LINE the flavours differ in, and it is the engine cutover rather than a new idea:
// the LEASE is declared by the read face now and the VOCABULARY by the base, so a projection
// names whichever of the two owns the member.
//
// The ROW is the one line that stopped differing. Both families' engine-keyed row traits are
// deleted, so `#key: Field` is what both arms emit — one impl per TYPE, reaching every engine
// there is.
let brand = framework(krate, &["store"], "SlotHandle");
let connected = framework(krate, &["store"], "Connected");
let gather = framework(krate, &["retrieve"], "AsyncGather");
let ranked = framework(krate, &["retrieve"], "Ranked");
let refusal = framework(krate, &["retrieve"], "RetrieveError");
let membership = framework(krate, &["retrieve"], self.dedup.membership());
let ranked_keys = framework(krate, &["retrieve"], "ranked_keys");
let filled = framework(krate, &["retrieve"], "filled");
let admits = self.dedup.admits();
// THE KNOB SEAT, spelled once for every searching door of this half — the engine's own
// per-query vocabulary, BORROWED, so a fan hands one request value to every leg with no copy.
// It is the LAST positional because the seam's own verbs put it last: what precedes it are the
// universal facts (subject, query, k) and what it holds is the backend's business alone.
let knobs = quote!(::core::option::Option<&<#engine as #face>::SearchOptions>);
let knobs_doc = leading(
"`options` is the request's OWN per-query knobs, handed to the engine verb verbatim — this \
door reads none of it, defaults none of it and substitutes nothing for it. `None` runs under \
the engine's own defaults, which is what every caller got before the seat existed.",
);
let knobs_borrow = leading(
"It is BORROWED rather than owned, which is what lets one request value reach every route of \
a fold with no copy: a fused door holds one package and hands the same reference down each \
leg. No door of this family states a `Clone` obligation about it.",
);
let forwarded_doc = leading(
"It FORWARDS them to its tier A unchanged, which is what makes the seat reach a hydrated \
answer at all: this door is one hop above the crossing rather than a second caller with \
defaults of its own, and a wire resolver rides THIS door for the whole entities it \
publishes. `None` is still the engine's own defaults — the difference is that a request \
naming knobs now has somewhere to put them.",
);
let own_read_note = leading(
"The knobs reach the SEARCH and not the by-key read: a door making both crossings spends \
`options` on the one the seam takes them for, and the address read has no such seat to \
spend them into.",
);
let streams_knobs = leading(
"ONE package for all `m` streams, and the borrow is what makes that free: the `m` calls are \
one question asked in `m` places, so there is one set of knobs to run them under and no \
copy of it is taken. A per-stream package would be a knob per DATA-BORN vector, which is \
not a thing a request can name.",
);
let pairs = self.subjects().into_iter().map(|subject| {
let Subject {
keys,
whole,
about,
grain,
} = &subject;
let election = match grain {
Grain::Election(elected) => Some(*elected),
Grain::Whole | Grain::Column(_) => None,
};
let (query, ask) = match grain {
// The WHOLE full-text subject: the query is a string against whatever grammar the engine
// has, and the subset is the word that asks over everything the slot holds.
Grain::Whole => {
let query = framework(krate, &["retrieve"], "FulltextQuery");
let subset = framework(krate, &["store"], "FulltextSubset");
(
quote!(#query<<#engine as #face>::Score>),
quote!(search(
slot,
scope,
#subset::All,
query.text(),
limit,
options,
)),
)
}
// ONE SEARCHABLE FIELD: the same query type, narrowed by a subset this method MINTS. The
// list is a `const` item rather than a `&[…]` temporary so the slice is `'static` and the
// future holds no array across its await.
Grain::Column(field) => {
let name = field.to_string();
let query = framework(krate, &["retrieve"], "FulltextQuery");
let subset = framework(krate, &["store"], "FulltextSubset");
let column = framework(krate, &["store"], "FulltextColumn");
(
quote!(#query<<#engine as #face>::Score>),
quote! {
search(
slot,
scope,
#subset::These({
const __INGRAPH_COLUMNS: &[#column] = &[#column::new(#name)];
__INGRAPH_COLUMNS
}),
query.text(),
limit,
options,
)
},
)
}
// An ELECTION's subject: the query carries THIS column's width, and the engine is told which
// column answers by a `VectorColumn` this method mints rather than takes.
Grain::Election(elected) => {
let (width, space) = self.geometry(elected);
let name = elected.field.to_string();
let query = framework(krate, &["retrieve"], "VectorQuery");
let column = framework(krate, &["store"], "VectorColumn");
(
quote!(#query<<#engine as #face>::Element, <#engine as #face>::Score, #width, #space>),
quote!(knn(
slot,
scope,
#column::new(#name),
query.coordinates(),
limit,
options,
)),
)
}
};
// THE TWO BY-KEY DOORS, emitted for every election and conditional on nothing — a declaration
// that elected a column can always be asked *what did you store for this entity* and *what
// else is near it*, the by-key read being a capability of the SEAM rather than of a declared
// word. They sit beside the raw pair rather than replacing anything: a caller holding
// coordinates still calls the pair, and these two are for the caller holding a KEY.
//
// The GET door is emitted FIRST because the similar door is written in terms of it, and every
// judgment about what an engine stored for a key is spent inside it exactly once.
let by_key = election.map_or_else(proc_macro2::TokenStream::new, |elected| {
let (width, space) = self.geometry(elected);
let name = elected.field.to_string();
let column = framework(krate, &["store"], "VectorColumn");
let embedding = framework(krate, &["storage"], "Embedding");
let vector_query = framework(krate, &["retrieve"], "VectorQuery");
let addressed = framework(krate, &["retrieve"], "vector_addressed");
let excluding = framework(krate, &["retrieve"], "ranked_keys_excluding");
let refused = framework(krate, &["retrieve"], "OwnReadError");
let own_door = Door::Own.name(&elected.field);
let door = Door::Similar.name(&elected.field);
let input = quote!(#embedding::<<#engine as #face>::Element, #width, #space>);
// THE ANSWER SHAPE IS THE ELECTION'S LABEL, decided HERE and nowhere else. A unit election
// declared ONE embedding, so the door answers one and several is a refusal; a `list`
// election declared a SET, so the door answers the whole group with its ordinals and
// several is the point. One door, two answer shapes, and ZERO runtime judgment about which
// — the label is read at expansion.
let grouped = elected.label.is_set();
let held = framework(krate, &["retrieve"], "Held");
let answers = if grouped {
quote!(#held<#input>)
} else {
quote!(#input)
};
let own_doc = leading(&format!(
"BY KEY — this entity's OWN `{field}` {noun}, CHECKED against what the declaration says \
it is. A READ, and not a search: nothing is ranked, scored or compared here.",
field = elected.field,
noun = if grouped {
"set, whole"
} else {
"embedding"
},
));
let own_scope = leading(
"ONE engine call and ONE read scope, which is the whole of what separates it from the \
similar door below: this is the by-key read alone, so `own` is the only crossing there \
is. No dedup membership is built either, so the declaration's own `dedup` word buys \
this door no bound.",
);
let own_judgment = leading(if grouped {
"IT IS WHERE THE WIDTH IS JUDGED, per member and against the elected field's own type. \
The seam answers with a SET and this election DECLARED one, so the arity is not a \
judgment here at all — what would be `Several` on a unit election is this door's \
ordinary answer, and it comes back whole in `Held`, each member under the ordinal a set \
query asked with it is attributed by. An empty column is `Unindexed`, which is a fact \
about the caller's own argument rather than a set of zero."
} else {
"IT IS WHERE THE ARITY AND THE WIDTH ARE JUDGED, and the only place either is. The seam \
answers with a SET, because one entity may hold several vectors in one column, and what \
this election declared is a single embedding — so none is a named refusal, several is a \
named refusal rather than one of them picked on the caller's behalf, and a stored \
vector that is not the declared width is named rather than trusted. Every other door \
needing this entity's own embedding comes through here, so all three are written ONCE."
});
let own_errors = leading(if grouped {
"The engine's own refusal from the by-key read, or the KEY itself: a column holding \
nothing for it, or a stored vector of the wrong width. `Several` cannot arise — a set \
of several is what this election declared."
} else {
"The engine's own refusal from the by-key read, or the KEY itself: a column holding \
nothing for it, one holding several vectors for it where this election declared one, or \
a stored vector of the wrong width."
});
let doc = leading(&format!(
"TIER A, BY EXAMPLE — the ranked, deduped KEYS nearest to `key`'s OWN `{field}`, WITHOUT \
`key` itself.",
field = elected.field,
));
let recipe = leading(&format!(
"Sugar over the pair above and not a second query path: it reads the example's own \
embedding back through [`{own_door}`](Self::{own_door}), hands it to the same `knn`, \
and excludes the example — which the pipeline does by starting its dedup membership \
with `key` ALREADY SEEN, so the example consumes its own raw-stream ordinal (the rank \
hole stays) and `limit` counts NEIGHBOURS rather than counting the example as one of \
them.",
));
let budget = leading(
"`limit` is ALSO the `k` the engine is handed, and a BUDGET at both ends: an answer \
one short of it is ordinary, because the example occupies one of the fetched hits \
whenever it is among them — the same class of shortening a floor drop causes from the \
other end, and never a silent widening.",
);
let scopes = leading(
"TWO read scopes, because the door makes TWO engine calls and a `Connected` is \
deliberately not `Clone` — a scope may be a lease. `own` is the by-key read's and \
`scope` is the `knn`'s; both borrow the same connection-manager, which is where an \
engine's searcher actually lives.",
);
let errors = leading(&format!(
"Everything [`{own_door}`](Self::{own_door}) refuses about the EXAMPLE, carried through \
undecorated, plus the engine's own refusal from the `knn` and from the address read \
after it.",
));
// THE ARITY WALK, one per answer shape and picked at EMISSION. Both spend the SAME width
// crossing against the elected field's own type — nothing an engine hands back has been
// through that constructor, so this is where the drift is catchable at all — and they differ
// in exactly what the LABEL says they differ in: how many values the declaration promised.
let arity = if grouped {
quote! {
if ::std::vec::Vec::is_empty(&__ingraph_held) {
return ::core::result::Result::Err(#refused::Unindexed);
}
let mut __ingraph_members = ::std::vec::Vec::with_capacity(__ingraph_held.len());
for __ingraph_stored in __ingraph_held {
let __ingraph_width = __ingraph_stored.len();
match #input::new(::std::sync::Arc::from(__ingraph_stored)) {
::core::option::Option::Some(__ingraph_point) => {
__ingraph_members.push(__ingraph_point);
}
::core::option::Option::None => {
return ::core::result::Result::Err(#refused::Width {
declared: #input::DIM,
stored: __ingraph_width,
});
}
}
}
// THE ORDER IS THE ENGINE'S, unreordered — which is what makes the ordinal a `Held`
// carries the same number a `Folded` asked with this set is subscripted by.
::core::result::Result::Ok(#held::new(
::std::vec::Vec::into_boxed_slice(__ingraph_members),
))
}
} else {
quote! {
let mut __ingraph_held = __ingraph_held;
// The ARITY is spent HERE and only here: the seam answers with a SET because one entity
// may hold several vectors in one column, and what this declaration elected is a single
// `Embedding` — so one is taken, none is named, and several is named rather than having
// one of them picked on the caller's behalf.
let __ingraph_stored = match __ingraph_held.len() {
0 => return ::core::result::Result::Err(#refused::Unindexed),
1 => ::std::vec::Vec::remove(&mut __ingraph_held, 0),
count => return ::core::result::Result::Err(#refused::Several { held: count }),
};
let __ingraph_width = __ingraph_stored.len();
match #input::new(::std::sync::Arc::from(__ingraph_stored)) {
::core::option::Option::Some(__ingraph_point) => {
::core::result::Result::Ok(__ingraph_point)
}
::core::option::Option::None => ::core::result::Result::Err(#refused::Width {
declared: #input::DIM,
stored: __ingraph_width,
}),
}
}
};
// HOW THE SINGLE-VECTOR BY-EXAMPLE DOOR TAKES ITS EXAMPLE, which is the ARITY question the
// group read handed back. A unit election's `get_` already answers one. A SET election's
// answers the whole group — and this door asks with ONE vector by construction, so the
// arity judgment lives HERE for the set case rather than in a door whose declaration says
// several are ordinary. What was `Several` before the split is `Several` still; it is
// simply refused where the arity is actually needed.
//
// The `_with` twin beside it is the door a set election is FOR, and it asks with all `m`.
let example = if grouped {
quote! {
let __ingraph_group = Self::#own_door::<#engine>(slot, own, key).await?;
let mut __ingraph_members =
::std::vec::Vec::from(#held::into_members(__ingraph_group));
let example = match __ingraph_members.len() {
1 => ::std::vec::Vec::remove(&mut __ingraph_members, 0),
count => return ::core::result::Result::Err(#refused::Several { held: count }),
};
}
} else {
quote!(let example = Self::#own_door::<#engine>(slot, own, key).await?;)
};
let own_body = self.observed(
observed,
&own_door,
quote! {
let address = #addressed::<#engine, #key>(key);
let __ingraph_held = #brand::get_vectors(slot, own, #column::new(#name), &address)
.await
.map_err(#refused::Engine)?;
#arity
},
);
let body = self.observed(
observed,
&door,
quote! {
// THE EXAMPLE COMES THROUGH THE DOOR ABOVE, which is what makes this one sugar: the
// WIDTH is judged there, so nothing here restates it and the refusal rides `?`
// unchanged.
#example
let query = #vector_query::new(example, floor);
let hits = #brand::knn(
slot,
scope,
#column::new(#name),
query.coordinates(),
limit,
options,
)
.await
.map_err(#refused::Engine)?;
let hits = #keyed::<#engine, #key>(hits).map_err(#refused::Engine)?;
::core::result::Result::Ok(#excluding::<_, _, #membership<#key>>(
hits,
query.floor(),
::core::num::NonZeroUsize::get(limit),
key,
))
},
);
quote! {
#[doc = #own_doc]
#[doc = ""]
#[doc = #own_scope]
#[doc = ""]
#[doc = #own_judgment]
#[doc = ""]
#[doc = " # Errors"]
#[doc = ""]
#[doc = #own_errors]
#vis async fn #own_door<#engine>(
slot: &mut #brand<#engine, Self>,
own: #connected<'_, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'_>>,
key: &#key,
) -> ::core::result::Result<#answers, #refused<<#engine as #face>::Error>>
where
#engine: #lease,
#key: #row,
{
#own_body
}
#[doc = #doc]
#[doc = ""]
#[doc = #recipe]
#[doc = ""]
#[doc = #budget]
#[doc = ""]
#[doc = #scopes]
#[doc = ""]
#[doc = " # Errors"]
#[doc = ""]
#[doc = #errors]
#[doc = ""]
#[doc = #knobs_doc]
#[doc = ""]
#[doc = #knobs_borrow]
#[doc = ""]
#[doc = #own_read_note]
#[allow(clippy::too_many_arguments)]
#vis async fn #door<#engine>(
slot: &mut #brand<#engine, Self>,
own: #connected<'_, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'_>>,
scope: #connected<'_, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'_>>,
key: &#key,
floor: <#engine as #face>::Score,
limit: ::core::num::NonZeroUsize,
options: #knobs,
) -> ::core::result::Result<
::std::vec::Vec<#ranked<#key, <#engine as #face>::Score>>,
#refused<<#engine as #face>::Error>,
>
where
#engine: #lease,
#key: #row + #admits,
{
#body
}
}
});
// THE SET DOOR, beside the pair above and never instead of it — emitted only for an election
// whose LABEL states a set. Everything it needs is in scope here for the ask road's reason:
// the three roads answer about one column and differ in what they are given.
let set_door = election.map_or_else(proc_macro2::TokenStream::new, |elected| {
// THE LABEL is the gate, and it is the whole gate: a declaration that wrote `embedding` has
// no `_with` door at all, which is a TRUE ABSENCE rather than a door standing behind a bound
// nobody can satisfy.
if !elected.label.is_set() {
return proc_macro2::TokenStream::new();
}
let (width, space) = self.geometry(elected);
let name = elected.field.to_string();
let with = Door::Set.name(&elected.field);
let column = framework(krate, &["store"], "VectorColumn");
let folded = framework(krate, &["retrieve"], "Folded");
let set_query = framework(krate, &["retrieve"], "FoldedQuery");
let fold_semantics = framework(krate, &["retrieve"], "FoldSemantics");
let sightings = framework(krate, &["retrieve"], "Sightings");
let owner_best = framework(krate, &["retrieve"], "owner_best");
let set_scored = framework(krate, &["retrieve"], "set_scored");
let accumulator = framework(krate, &["retrieve"], self.dedup.accumulator());
let fold = format_ident!("__INGRAPH_FOLD__");
let doc = leading(&format!(
"TIER A, SET-SIMILARITY — the entities whose `{field}` SET best answers `m` query \
vectors at once. Each vector's own best match in an entity's set is found first, and \
`fold` is how those `m` bests become ONE score.",
field = elected.field,
));
let shape_note = leading(
"It answers in `Folded` rather than in `Ranked`, and `limit` counts ENTITIES. The FOLD \
authors this answer's order — there are `m` engine streams and no order between them — \
so no ordinal is minted ACROSS them, and each stream's own ordinal is carried in that \
stream's slot instead. The pair above stays the door for the single-vector question, and \
asking this one with a single vector is that same question: every fold agrees at \
`m = 1`, down to the one rank the slots then carry.",
);
let fold_note = leading(
"The fold is a TYPE rather than a word — `Sum`, `Max` and `Weighted` are the three this \
framework ships, and a fourth is one impl. It is taken by value and dispatched \
statically, so a fold nobody here has heard of costs this door nothing.",
);
let raw_depth = leading(
"`depth` is HOW DEEP EACH OF THE `m` STREAMS FETCHES, and `limit` still counts the \
ENTITIES the fold answers with — two bounds at two grains, neither able to widen the \
other. Absent, each stream fetches `limit`, which is byte-for-byte what this door did \
before the knob existed.\n\nIt is a DOOR PARAMETER rather than an edge fact for the \
by-example twin's reason, which covers this door word for word: the streams are \
DATA-BORN — `m` vectors a caller brought, where the twin's `m` come out of an example's \
stored set — so there is no declared route for a `Route` seat to hang on either way. A \
`depth` BELOW `limit` is legal and is not refused: every number here is a ceiling rather \
than a promise.\n\nWHY it is worth a number of its own: the fold reads `m` per-entity \
bests, and a sum-family fold depends on positions no single stream's top slice \
determines — so fetching deeper than the answer is wide is the pattern, and the VALUE is \
the caller's rather than one this door could invent. Inflating `limit` and truncating \
afterwards is not the same request: it distorts the answer contract to smuggle in a pool \
size.",
);
// THE BY-EXAMPLE TWIN, the fourth door a set election gets and the one the spec's §6
// measurement found missing. It stands to `retrieve_similar_by_<field>` exactly as the door
// above stands to `retrieve_keys_by_<field>`: the same question, asked with `m` vectors.
// THE DEPTH LAW, bound once for BOTH `_with` doors: the raw twin and the by-example one
// resolve the same chain at the same grain, so a second binding would be a second place for
// the path to drift.
let stream_depth = framework(krate, &["retrieve"], "route_depth");
let by_example = Door::SimilarSet.name(&elected.field);
let similar = Door::Similar.name(&elected.field);
let own_door = Door::Own.name(&elected.field);
let embedding = framework(krate, &["storage"], "Embedding");
let held = framework(krate, &["retrieve"], "Held");
let refused = framework(krate, &["retrieve"], "OwnReadError");
let best_excluding = framework(krate, &["retrieve"], "owner_best_excluding");
let by_example_doc = leading(&format!(
"TIER A, SET-SIMILARITY BY EXAMPLE — the entities whose `{field}` SET best answers \
`key`'s OWN set, WITHOUT `key` itself.",
field = elected.field,
));
let by_example_recipe = leading(&format!(
"The by-example recipe asked with `m` vectors instead of one — fetch own set, query with \
EACH of them, exclude self, fold. The exclusion runs per stream rather than on the fused \
answer, which is what keeps the example from contributing to its own neighbours' \
sightings; filtering afterwards would answer a different ranking under the same name. \
[`{similar}`](Self::{similar}) is the single-vector spelling of the same question.",
));
let by_example_read = leading(&format!(
"It reads the example's set through [`{own}`](Self::{own}), which on a SET election \
answers the GROUP — the `m` vectors under the ordinals this door then asks them in. That \
is one authority for the emptiness and one for the width, where the two used to be \
written twice and could drift.",
own = Door::Own.name(&elected.field),
));
let by_example_depth = leading(
"`depth` is HOW DEEP EACH OF THE `m` STREAMS FETCHES, and `limit` still counts the \
ENTITIES the fold answers with — two bounds at two grains, neither able to widen the \
other. Absent, each stream fetches `limit`, which is byte-for-byte what this door did \
before the knob existed.\n\nIt is a DOOR PARAMETER rather than an edge fact because \
these streams are DATA-BORN: the `m` of them come from the example's own stored set, so \
there is no declared route to hang a `Route` seat on. A `depth` BELOW `limit` is legal \
and is not refused — every number here is a ceiling rather than a promise, and a fold \
handed shallower streams answers from what it was given.\n\nWHY it is worth a number \
of its own: the fold is over `m` per-entity bests, and a sum-family fold reads positions \
no single stream's top slice determines — so fetching deeper than the answer is wide is \
the pattern, and the VALUE is the caller's rather than one this door could invent.",
);
let by_example_errors = leading(
"The engine's own refusal from the by-key read, from any of the `m` knn calls or from \
the address reads after them; `Unindexed` where the column holds nothing for `key`; and \
`Width` where one of the stored vectors is not the declared width. `Several` cannot \
arise — a set of several is what this door is for.",
);
// THE FOLD NAMES ITSELF ON THE SPAN, which is the first of the three places the
// `FoldSemantics::name` row is spent: a trace of a set retrieve says WHICH arithmetic
// authored the order it answered in, and that fork is otherwise invisible from outside —
// two deployments running `sum` and `max` over one corpus produce two rankings and one
// indistinguishable span. FULLY QUALIFIED because the fold is a type parameter and the
// method call would be resolved against a bound rather than against a spelling.
let fold_field = quote! {
fold = <#fold as #fold_semantics<<#engine as #face>::Score>>::name(&fold),
};
let by_example_body = self.observed_with(
observed,
&by_example,
fold_field,
quote! {
// THE EXAMPLE COMES THROUGH THE GROUP READ, which is what the set door's `get_` IS. The
// walk that used to stand here — empty check, width crossing, per-member collect — was
// that door's body written a second time, and the two could drift; now the emptiness
// and the width have ONE authority and the refusal rides `?` undecorated.
let __ingraph_example = Self::#own_door::<#engine>(slot, own, key).await?;
// THE PER-STREAM DEPTH, resolved once for all `m` — the same law a `Route`'s own
// depth resolves by, with no middle tier: a stream is DATA-BORN and has no declaration
// to carry a ceiling. Absent, it is the fold's own budget, which is byte-for-byte what
// every stream fetched before the seat existed.
let __ingraph_depth = #stream_depth(depth, ::core::option::Option::None, limit);
let mut __ingraph_bests =
::std::vec::Vec::with_capacity(#held::len(&__ingraph_example));
for __ingraph_point in #held::members(&__ingraph_example) {
let __ingraph_hits = #brand::knn(
slot,
::core::clone::Clone::clone(&scope),
#column::new(#name),
#embedding::coordinates(__ingraph_point),
__ingraph_depth,
options,
)
.await
.map_err(#refused::Engine)?;
let __ingraph_hits =
#keyed::<#engine, #key>(__ingraph_hits).map_err(#refused::Engine)?;
__ingraph_bests.push(
#best_excluding::<_, _, #membership<#key>>(__ingraph_hits, &floor, key)
);
}
::core::result::Result::Ok(#set_scored::<
_, _, #accumulator<#key, #sightings<<#engine as #face>::Score>>, _
>(__ingraph_bests, &fold, ::core::num::NonZeroUsize::get(limit)))
},
);
quote! {
#[doc = #doc]
#[doc = ""]
#[doc = #shape_note]
#[doc = ""]
#[doc = #fold_note]
#[doc = ""]
#[doc = #raw_depth]
#[doc = ""]
#[doc = #knobs_doc]
#[doc = ""]
#[doc = #streams_knobs]
#[allow(clippy::too_many_arguments)]
#vis async fn #with<'__ingraph_scope, #engine, #fold>(
slot: &mut #brand<#engine, Self>,
scope: #connected<'__ingraph_scope, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'__ingraph_scope>>,
query: &#set_query<
<#engine as #face>::Element, <#engine as #face>::Score, #width, #space
>,
fold: #fold,
limit: ::core::num::NonZeroUsize,
depth: ::core::option::Option<::core::num::NonZeroUsize>,
options: #knobs,
) -> ::core::result::Result<
::std::vec::Vec<#folded<#key, <#engine as #face>::Score>>,
<#engine as #face>::Error,
>
where
#engine: #lease,
#key: #row + #admits,
#fold: #fold_semantics<<#engine as #face>::Score>,
<#engine as #lease>::ReadContext<'__ingraph_scope>: ::core::clone::Clone,
{
// THE PER-STREAM DEPTH, resolved once for all `m` — the by-example twin's own line, at
// the door that asks the same question with vectors a caller brought instead of vectors
// an example held. There is no middle tier for the same reason there: a stream here is
// DATA-BORN and has no declaration to carry a ceiling. Absent, it is the fold's own
// budget, which is byte-for-byte what every stream fetched before the seat existed.
let __ingraph_depth = #stream_depth(depth, ::core::option::Option::None, limit);
let mut __ingraph_bests =
::std::vec::Vec::with_capacity(query.inputs().len());
for __ingraph_coordinates in query.coordinates() {
// The scope is CLONED per query vector: `knn` takes it by value, and `m` calls need
// `m` of them. Read knobs are per-call by nature, and an engine whose read scope must
// not be duplicated is absent from this door at compile time.
//
// `k` is EACH STREAM's ceiling, and the fold's `limit` counts ENTITIES: two bounds at
// two grains, neither able to widen the other.
let __ingraph_hits = #brand::knn(
slot,
::core::clone::Clone::clone(&scope),
#column::new(#name),
__ingraph_coordinates,
__ingraph_depth,
options,
).await?;
let __ingraph_hits = #keyed::<#engine, #key>(__ingraph_hits)?;
__ingraph_bests.push(
#owner_best::<_, _, #membership<#key>>(__ingraph_hits, query.floor())
);
}
::core::result::Result::Ok(#set_scored::<
_, _, #accumulator<#key, #sightings<<#engine as #face>::Score>>, _
>(__ingraph_bests, &fold, ::core::num::NonZeroUsize::get(limit)))
}
#[doc = #by_example_doc]
#[doc = ""]
#[doc = #by_example_recipe]
#[doc = ""]
#[doc = #by_example_read]
#[doc = ""]
#[doc = #by_example_depth]
#[doc = ""]
#[doc = " # Errors"]
#[doc = ""]
#[doc = #by_example_errors]
#[doc = ""]
#[doc = #knobs_doc]
#[doc = ""]
#[doc = #streams_knobs]
#[doc = ""]
#[doc = #own_read_note]
#[allow(clippy::too_many_arguments)]
#vis async fn #by_example<'__ingraph_scope, #engine, #fold>(
slot: &mut #brand<#engine, Self>,
own: #connected<'_, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'_>>,
scope: #connected<'__ingraph_scope, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'__ingraph_scope>>,
key: &#key,
floor: <#engine as #face>::Score,
fold: #fold,
limit: ::core::num::NonZeroUsize,
depth: ::core::option::Option<::core::num::NonZeroUsize>,
options: #knobs,
) -> ::core::result::Result<
::std::vec::Vec<#folded<#key, <#engine as #face>::Score>>,
#refused<<#engine as #face>::Error>,
>
where
#engine: #lease,
#key: #row + #admits,
#fold: #fold_semantics<<#engine as #face>::Score>,
<#engine as #lease>::ReadContext<'__ingraph_scope>: ::core::clone::Clone,
{
#by_example_body
}
}
});
let keys_doc = leading(&format!(
"TIER A — the ranked, deduped KEYS this {noun} matched{about}: the engine alone, no store \
hop and no filter. `limit` is a BUDGET, and a short answer is legal.",
noun = self.kind.noun(),
));
let whole_doc = leading(&format!(
"TIER B — the WHOLE upstream entities this {noun} matched{about}, in the ENGINE's order, \
each wearing the score and the raw-stream rank of its key.",
noun = self.kind.noun(),
));
let keys_body = self.observed(
observed,
keys,
quote! {
let hits = #brand::#ask.await?;
let hits = #keyed::<#engine, #key>(hits)?;
// The walk's OWN truncation stays, and it is not a second ceiling: `k` bounds what the
// engine FETCHES and this bounds what survives the floor and the dedup, which can only be
// shorter. The walk counts SURVIVORS and takes a plain `usize` for it — a walk asked for
// nothing is a legal call with an empty answer, where an ENGINE asked for nothing is not a
// question at all — so the door's non-zero number is spent at this boundary.
::core::result::Result::Ok(#ranked_keys::<_, _, #membership<#key>>(
hits,
query.floor(),
::core::num::NonZeroUsize::get(limit),
))
},
);
let whole_body = self.observed(
observed,
whole,
quote! {
// UNBOUNDED at tier A: the fill loop's own filter is what decides how many of the
// above-floor keys become results, so a budget here would starve it. `NonZeroUsize::MAX` is
// the honest spelling of *as many as exist* in the door family's own currency, and what an
// engine does with a huge ceiling is that engine's business in its own storage — the seam
// says so, and tantivy's `min(k, num_docs)` clamp is the reference.
let ranked = match Self::#keys::<#engine>(
slot,
scope,
query,
::core::num::NonZeroUsize::MAX,
// FORWARDED VERBATIM: the knobs are the REQUEST's, and a hydrating door is one hop
// above the seat rather than a second caller with defaults of its own. Reading,
// defaulting or substituting anything here would be this door having an opinion about
// an engine's own vocabulary.
options,
)
.await
{
::core::result::Result::Ok(ranked) => ranked,
::core::result::Result::Err(error) => {
return ::core::result::Result::Err(#refusal::Engine(error));
}
};
#filled(ranked, store, filter, ::core::num::NonZeroUsize::get(limit))
.await
.map_err(#refusal::Gather)
},
);
quote! {
#[doc = #keys_doc]
#[doc = ""]
#[doc = #knobs_doc]
#[doc = ""]
#[doc = #knobs_borrow]
#vis async fn #keys<#engine>(
slot: &mut #brand<#engine, Self>,
scope: #connected<'_, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'_>>,
query: &#query,
limit: ::core::num::NonZeroUsize,
options: #knobs,
) -> ::core::result::Result<
::std::vec::Vec<#ranked<#key, <#engine as #face>::Score>>,
<#engine as #face>::Error,
>
where
#engine: #lease,
#key: #row + #admits,
{
#keys_body
}
#[doc = #whole_doc]
#[doc = ""]
#[doc = #knobs_doc]
#[doc = ""]
#[doc = #forwarded_doc]
#[allow(clippy::too_many_arguments)]
#vis async fn #whole<#engine, #store>(
slot: &mut #brand<#engine, Self>,
scope: #connected<'_, <#engine as #face>::Connection,
<#engine as #lease>::ReadContext<'_>>,
store: &mut #store,
query: &#query,
filter: ::core::option::Option<&<#store as #gather<#key, #upstream>>::Filter>,
limit: ::core::num::NonZeroUsize,
options: #knobs,
) -> ::core::result::Result<
::std::vec::Vec<#ranked<#upstream, <#engine as #face>::Score>>,
#refusal<
<#engine as #face>::Error,
<#store as #gather<#key, #upstream>>::Error,
>,
>
where
#engine: #lease,
#store: #gather<#key, #upstream>,
#key: #row + #admits,
{
#whole_body
}
#by_key
#set_door
}
});
// THE FUSED DOORS ride the same impl and the same observation gate as the doors they call: a
// trace of a fused retrieve is one span per route inside one span for the fold, which is the
// composition it IS.
let fused = self.fused_half(observed);
// THE MINI FUSE DOORS ride beside them, for the same reason and one grain down: a fanned slot
// is a tier whose routes are STORES, so its fold is one span per leg inside one for the fold.
let fanned = self.fanned_half(observed);
quote! {
#[allow(dead_code)]
impl #index {
#(#pairs)*
#fused
#fanned
}
}
}
/// ONE DOOR'S BODY, with a span around it or without — the G6 instrument clause, applied to the
/// retrieve faces.
///
/// The query face's own clause is `emit::query`'s `observed`, and everything that one states holds
/// here word for word: `#[instrument]` cannot be reached from an expansion at all —
/// `tracing-attributes` 0.1 declares no crate-path key and writes `::tracing::…`
/// absolutely, and those paths resolve in the DECLARING crate, which names no tracing — so the
/// span is opened by hand through the `macro_rules!` family, whose `$crate` follows the definition
/// and lands on the shelf whatever path reached it. A `#[cfg_attr]` cannot stand in either: that
/// predicate asks whether the declaring crate has a feature by that name. So the body is written
/// twice and `if_tracing!`/`if_no_tracing!` keep exactly one.
///
/// # It wraps the WHOLE body, and that is what the query face wraps too
///
/// There the entry's body IS the crossing call, so the two readings coincide; here a door walks a
/// road, reads an address, dedupes and gathers, and what a reader of `ingraph.query` is asking is
/// how long the DOOR took. An `async move` block is what carries a multi-statement body into that
/// position — its output is the method's own, so `?` and an early `return` mean inside it exactly
/// what they meant before.
///
/// # The LEVEL is `Info`, and it is the framework's default rather than a choice made here
///
/// `span!` builds its metadata in a `static`, so the level has to be const-evaluable — which is
/// why the query face reads the declaration's word at expansion time. A DERIVED INDEX writes no
/// such word: `tracing(level = …)` is not in the vocabulary the derive's index front end admits —
/// `upstream(…)`, `dedup(…)`, `embedding(…)` and `crate = "…"` are the whole of it — so there is
/// nothing to read, and what these doors open at is the default a declaration that wrote no word
/// gets. The day the word reaches this grammar, this line reads the model instead of the constant
/// and nothing else moves.
///
/// # The third field is `engine` where the query face's is `db`
///
/// Both name what the door crossed to, and a full-text index is not a database. `record` and
/// `entry` are the query face's own, unchanged, so one `ingraph.query` pane holds every emitted
/// door and the `entry` field is what tells them apart.
fn observed(
&self,
observed: bool,
entry: &syn::Ident,
body: proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
if !observed {
return body;
}
let instrument = framework(&self.krate, &["tracing"], "Instrument");
let span = framework(&self.krate, &["tracing"], "span");
let level = framework(&self.krate, &["tracing"], "Level");
let constant = TracingLevel::Info.constant();
let record = self.index.to_string();
let entry = entry.to_string();
let engine = self.kind.as_str();
quote! {
{
use #instrument as _;
async move { #body }
.instrument(#span!(
#level::#constant,
"ingraph.query",
record = #record,
entry = #entry,
engine = #engine,
))
.await
}
}
}
/// [`observed`](Self::observed) WITH ONE MORE FIELD, whose value is a RUNTIME expression rather
/// than a constant — the set door's `fold`, and today nothing else.
///
/// # It is a second function rather than a parameter on the first, and the SPAN IS HOISTED
///
/// Two reasons, and the second is a measurement. The span above is built INSIDE `.instrument(…)`,
/// which is evaluated after the `async move` block has already captured everything it moves — so a
/// field reading the door's own `fold` parameter there is `E0382`, a use of a moved value. Binding
/// the span first ends the borrow at the `let`, because `span!` records a `&str` field eagerly
/// rather than holding it.
///
/// The other reason is that the shape above must not move: every other door's expansion is pinned
/// byte-for-byte by this module's tracing suite, and a hoist applied to all of them would be an
/// unrelated diff in eleven emissions to buy a field one of them needs.
fn observed_with(
&self,
observed: bool,
entry: &syn::Ident,
fields: proc_macro2::TokenStream,
body: proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
if !observed {
return body;
}
let instrument = framework(&self.krate, &["tracing"], "Instrument");
let span = framework(&self.krate, &["tracing"], "span");
let level = framework(&self.krate, &["tracing"], "Level");
let constant = TracingLevel::Info.constant();
let record = self.index.to_string();
let entry = entry.to_string();
let engine = self.kind.as_str();
quote! {
{
use #instrument as _;
let __ingraph_span = #span!(
#level::#constant,
"ingraph.query",
record = #record,
entry = #entry,
engine = #engine,
#fields
);
async move { #body }.instrument(__ingraph_span).await
}
}
}
/// The SUBJECTS this declaration answers under — one per pair of emitted retrieve methods.
///
/// A full-text index has ONE unsuffixed pair plus one per searchable field; an embedding index has
/// one per election, each named by the field its `knn` marker elected. The third kind reaches this
/// nowhere: `blob` returns before it, an artifact family being addressed rather than ranked.
///
/// # The full-text pairs, and why there are now N + 1 of them
///
/// The unsuffixed pair used to be the whole family, and the reason was the seam: a per-field door
/// would have to tell the engine which field answered, and `FulltextRead::search` took a slot, a
/// scope and a string with nowhere to put the answer. That is the argument the grain ruling
/// dissolved — the seam takes a [`FulltextSubset`] now — so the door family arrives, at VECTOR
/// PARITY: `retrieve_keys_by_<field>` / `retrieve_by_<field>`, one pair per searchable field,
/// minting a one-column subset the way the vector pair mints its own `VectorColumn`.
///
/// The unsuffixed pair STAYS, and is not an alias for the single-field case. It asks
/// `FulltextSubset::All`, which is a different question from *this field*: `All` is whatever the
/// SLOT holds, and a slot may hold columns the declaration never elected. So one declaration
/// electing one field emits both, and the two mean two things.
///
/// The unsuffixed pair is emitted FIRST, which is what makes the vector kind's rule — a name whose
/// spelling depends on the CARDINALITY of the declaration would move the day a second election
/// arrived — hold on this side too: no full-text name moves when a field is elected, because the
/// whole-subject pair was never one of the per-field ones.
///
/// # WHAT THE FAN STILL WAITS ON, and why it did not hold the doors up
///
/// A `fanout` field writes every declared engine at once, so a read that answered from ALL of its
/// legs has to fan and FUSE them, and that is not built on either side of this face. What the
/// per-field doors do instead is what the unsuffixed pair has always done: the ENGINE is a type
/// parameter and the handle is the caller's, so which leg answers is the caller's own choice at
/// the call rather than a winner this emission picked. The fan is the fused round's, it arrives
/// for both pairs together, and it was never an argument about suffixes.
fn subjects(&self) -> Vec<Subject<'_>> {
if self.kind != NodeKind::Vector {
let (keys, whole) = Door::pair(None);
let mut subjects = vec![Subject {
keys,
whole,
about: searched(&self.searchable),
grain: Grain::Whole,
}];
subjects.extend(self.searchable.iter().map(|field| {
let (keys, whole) = Door::pair(Some(field));
Subject {
keys,
whole,
about: format!(" in `{field}`"),
grain: Grain::Column(field),
}
}));
return subjects;
}
self
.embeddings
.iter()
.map(|elected| {
let field = &elected.field;
let (keys, whole) = Door::pair(Some(field));
Subject {
keys,
whole,
about: format!(" in `{field}`"),
grain: Grain::Election(elected),
}
})
.collect()
}
/// The index's OWN API: the constructor, the borrow of the key it carries, and one accessor
/// family per declared field.
///
/// A CONSTRUCTOR, which a record deliberately has none of, and the reason is the injection rather
/// than a change of taste: this macro adds a field to the item its author wrote, so the struct
/// literal an author would otherwise write no longer names every field and cannot be written at
/// all. `new` is what replaces it, and the key comes first because it is the argument the
/// declaration did not declare.
///
/// `key_ref` and NO `key`. The by-value half is `Transformer::key`, emitted below; an inherent
/// method of the same name would shadow it with a second spelling of one answer. The BORROW has no
/// such twin — the trait hands a key back by value — and a document read to learn its key would
/// otherwise clone one.
///
/// Every field takes the MUTATORS, [`FieldsModel`](crate::fields::FieldsModel)'s rule for
/// [`FieldsModel`](crate::fields::FieldsModel)'s reason: a record withholds them from the fields
/// that bear identity, and no field here bears any. The key field takes none — it is the
/// upstream's answer about which message this document is, and a document that could be re-keyed
/// in place would be a document that could lie about where it came from.
fn carrier(&self) -> proc_macro2::TokenStream {
let IndexModel {
index, vis, krate, ..
} = self;
let field = borrowed_key(&self.prefix);
let key = self.key();
let (names, types): (Vec<&syn::Ident>, Vec<&syn::Type>) = self
.fields
.iter()
.map(|column| (&column.name, &column.ty))
.unzip();
let families = self.fields.iter().map(|column| {
// A DERIVED INDEX's own fields carry no condition seat — the word is the record family's.
column.methods(
vis,
krate,
&format!("`{}` field of this [`{index}`]", column.name),
true,
&proc_macro2::TokenStream::new(),
)
});
let new_doc = leading(&format!(
"Construct {article} {noun} from the upstream key it carries and its own fields.",
article = self.kind.article(),
noun = self.kind.noun(),
));
let key_doc = leading("The upstream key this document is addressed by, by reference.");
let arity = wide_signature();
quote! {
impl #index {
#[doc = #new_doc]
#arity
#[inline]
#vis const fn new(#field: #key, #(#names: #types,)*) -> Self {
Self { #field, #(#names,)* }
}
#[doc = #key_doc]
#[inline]
#vis const fn key_ref(&self) -> &#key {
&self.#field
}
#(#families)*
}
}
}
/// The ENTITY BINDING, every member of it a projection of the upstream's own.
///
/// `Key` and `Lineage` are the upstream's verbatim, which is what *one document per upstream
/// message* means: the document is that message, indexed, so it is addressed by that message's
/// address and descends from that message's ancestors. Naming them through the upstream rather
/// than copying its columns is also what keeps them true — re-keying the upstream re-keys every
/// index over it, and a drift is a compile error rather than a convention.
///
/// `Id` is read off the KEY rather than off the upstream, and the difference is which impl has to
/// exist: `Identifiable::id_ref` is answered here by borrowing through the carried key, so what
/// this expansion needs is that the key answers it. Every key a node macro emits does — the record
/// emission writes `impl Identifiable for <Record>Key` beside the record's own — and an upstream
/// whose key does not is `E0277` naming that key.
///
/// `Record` and `Graphql` are both `()`, the empty product this crate uses for a face a
/// declaration does not have. A derived index becomes no SQL row: its documents live in an engine
/// of its own. Its wire face is a RANKING rather than a predicate — a different surface from the
/// one `Graphql` describes — and binding `Self` for a face with no types behind it would be a
/// claim nothing answers.
///
/// The SUBSCRIPTION is not audited separately here, and needs no second item: `<Upstream as
/// Transformer>::Key` is itself the bound, so a path naming nothing is `E0412` and a path naming
/// something that is not a node is `E0277`, both at the string the author wrote. A record spells
/// the audit out because its `subscribe = "…"` reaches no other emitted position.
fn binding(&self) -> proc_macro2::TokenStream {
let index = &self.index;
let upstream = &self.source.node;
let field = borrowed_key(&self.prefix);
let key = self.key();
let transformer = framework(&self.krate, &["transform"], "Transformer");
let identifiable = framework(&self.krate, &["transform"], "Identifiable");
quote! {
#[automatically_derived]
impl #identifiable for #index {
type Id = <#key as #identifiable>::Id;
#[inline]
fn id_ref(&self) -> &Self::Id {
#identifiable::id_ref(&self.#field)
}
}
#[automatically_derived]
impl #transformer for #index {
type Key = #key;
type Lineage = <#upstream as #transformer>::Lineage;
type Record = ();
type Graphql = ();
#[inline]
fn key(&self) -> Self::Key {
::core::clone::Clone::clone(&self.#field)
}
}
}
}
/// **THE SUBSCRIBER** — the `subscribe` word's whole emission: a launchable node beside the
/// declaration, which receives the upstream's messages over a real edge, projects them into this
/// declaration's documents, lands those documents in this declaration's own corpora, and publishes
/// them onward.
///
/// EMPTY without the word, which is what makes subscription additive: the hand road's expansion is
/// unchanged to the byte, and a deployment that fills its corpora itself keeps doing so.
///
/// # WHY A SECOND TYPE — [`default_indexer_name`] carries the argument
///
/// The declaration's value is a DOCUMENT and a node's value holds its `Shared<R>` mounts; one type
/// cannot honestly be both. So the node is minted beside the document, and everything below is
/// written on it.
///
/// # THE BATCH IS THE DELIVERY, because the delivery is the only boundary there is
///
/// A subscriber opens ONE batch per `accept`, queues every document of that delivery into it, and
/// publishes before it answers. That is not a policy choice among several: `Payload` carries `One`
/// and `Batch` and NOTHING ELSE — there is no end-of-stream punctuation in this layer's vocabulary
/// — so a batch spanning more than one delivery would have no event that closes it, and a batch
/// per ITEM would commit N times for a delivery the sender framed as one. The delivery is the
/// frame the sender chose, and it is the frame the corpus takes.
///
/// What a caller gets from this is the property the whole road exists for: when `accept` returns
/// `Ok`, every document of that delivery is durable AND FINDABLE — see
/// [`FulltextLane::publish`](https://docs.rs/ingraph), where the two are one act.
///
/// # THE FATE OF A REFUSED WRITE IS THE DELIVERY'S, and the batch is rolled back under it
///
/// A refusal anywhere in a batch discards that batch and returns `Err`, which
/// [`Operator`](https://docs.rs/ingraph)'s own failure contract turns into a `DeadLettered` fate at
/// this node. Nothing half-written survives the failure and no document is ever dropped in
/// silence, which is the one outcome a write must not have — and the documents are NOT emitted
/// either, so a refused delivery reaches no downstream.
///
/// ACROSS corpora the guarantee stops at *whole or not at all*, and that is the topology's own
/// answer rather than this emission's shortcoming: a declaration electing two fields writes two
/// INDEPENDENT stores that share no transaction, so a refusal in the second leaves the first
/// published. Inventing a rollback across them would be this expansion deciding a durability
/// question that belongs to the deployment — the same statement the `fanout` door's own
/// [`Refused`](crate::engine) note makes one seam over — and what the redelivery of a
/// dead-lettered item costs is a repeat of an idempotent keyed replace.
///
/// # THE DOCUMENTS ARE EMITTED AFTER THEY LAND, and the order is observable
///
/// `emitter.emit` runs below the publish, so a downstream consumer of this node sees a document
/// only once the corpus can answer for it. The reverse order would publish a document downstream
/// that a search cannot find, which is the *read sees a partial entity* hazard moved one node
/// earlier and made invisible.
///
/// # THE RETRACTION SEAM, LEFT OPEN ON PURPOSE
///
/// Every delivered item is an UPSERT here, and that is a statement about today's vocabulary rather
/// than a claim about the world: `Payload` has no retraction variant, so a deletion cannot arrive
/// and this body does not pretend to route one.
///
/// What that leaves for the round which brings one is a SEAM rather than a rewrite. The walk is
/// written over ITEMS — `into_items`, which is shape-agnostic — and matches no framework enum at
/// all, so nothing here is an exhaustive match a new variant would have to break, and nothing here
/// silently absorbs a variant it has never seen. The arm that carries a retraction lands in the
/// document loop beside the upsert, and the engine act it needs is one more member on the write
/// lane beside [`entry`](https://docs.rs/ingraph). Neither is written now, because a seam that is
/// filled by guessing is worse than one that is empty and says so.
fn subscriber(&self) -> proc_macro2::TokenStream {
if !self.subscribe || self.kind != NodeKind::Fulltext {
return proc_macro2::TokenStream::new();
}
let IndexModel {
index, vis, krate, ..
} = self;
let node = crate::model::default_indexer_name(self.base());
let upstream = &self.source.node;
// THE MOUNTS, grouped by the resource path AS WRITTEN — `habitats`' own grouping, for its own
// reason: two spellings of one type would be two fields holding one `Shared`, and the emission
// has no way to resolve them into one. One field per written path, in declaration order.
let mut pointed: Vec<syn::Path> = Vec::new();
let mut lanes: Vec<(usize, syn::Ident, &syn::Ident)> = Vec::new();
for declared in &self.engines {
if !self.searchable.contains(&declared.field) {
continue;
}
for engine in &declared.engines {
let Some(resource) = engine.resource.as_ref() else {
continue;
};
let written = quote!(#resource).to_string();
let at = pointed
.iter()
.position(|path| quote!(#path).to_string() == written)
.unwrap_or_else(|| {
pointed.push(resource.clone());
pointed.len() - 1
});
let marker = crate::engine::Slot {
field: declared.field.clone(),
engine: engine.word.clone(),
}
.marker(self.base());
lanes.push((at, marker, &declared.field));
}
}
// A DECLARATION WHOSE LEGS POINT AT NOTHING has no node to mint: there is no store to open and
// no mount to demand, so a subscriber would be a running node that lands nowhere. The word is
// not refused for it — an unpointed leg is legal and means the deployment says instead — and
// what it gets is the hand road it already had.
if pointed.is_empty() {
return proc_macro2::TokenStream::new();
}
let mounts: Vec<syn::Ident> = (0..pointed.len())
.map(|at| format_ident!("__ingraph_mount_{at}"))
.collect();
let shared = framework(krate, &["resource"], "Shared");
let demand = framework(krate, &["resource"], "ResourceDemand");
let resources = framework(krate, &["drive"], "Resources");
let missing = framework(krate, &["drive"], "MissingResourceError");
let constructor = framework(krate, &["drive"], "AsyncConstructor");
let declared = framework(krate, &["drive"], "Declared");
let effect = framework(krate, &["drive"], "Effect");
let upstream_row = framework(krate, &["drive"], "Upstream");
let unchanneled = framework(krate, &["drive"], "Unchanneled");
let buffered = framework(krate, &["drive"], "Buffered");
let downstream = framework(krate, &["drive"], "Downstream");
let awaited = framework(krate, &["operator"], "Async");
let context = framework(krate, &["drive"], "Context");
let delivery = framework(krate, &["drive"], "Delivery");
let item = framework(krate, &["drive"], "Item");
let emitter = framework(krate, &["operator"], "Emitter");
let operator = framework(krate, &["operator"], "AsyncOperator");
let transformer = framework(krate, &["transform"], "Transformer");
let identifiable = framework(krate, &["transform"], "Identifiable");
let handle = framework(krate, &["store"], "SlotHandle");
let mount = framework(krate, &["store"], "FulltextMount");
let lane = framework(krate, &["store"], "FulltextLane");
let road = framework(krate, &["store"], "FulltextRoad");
let slot = framework(krate, &["store"], "Slot");
let box_writer = framework(krate, &["document"], "BoxWriter");
let connected = framework(krate, &["store"], "Connected");
let refusal = framework(krate, &["store"], "IndexRefusal");
let named = quote!(#upstream).to_string();
let node_doc = leading(&format!(
"**THE SUBSCRIBER** [`{index}`] mints by wearing `subscribe` — the node a deployment mounts to \
have this declaration's corpora filled for it.\n\nIt holds one mount per resource this \
declaration's legs point at, receives [`{named}`]'s messages over the edge \
`upstream(…)` named, and lands one document per message in each of this declaration's \
corpora before publishing that document onward."
));
let fields = mounts.iter().zip(&pointed).map(|(field, resource)| {
let doc = leading(&format!(
"The `{}` this node's corpora live in, built by the launch and reached at construction.",
quote!(#resource)
));
quote_spanned! {resource.span()=>
#[doc = #doc]
#field: #shared<#resource>
}
});
let reaches = mounts.iter().zip(&pointed).map(|(field, resource)| {
quote_spanned! {resource.span()=>
#field: #resources::shared::<#resource>(__ingraph_resources)?
}
});
let demands = pointed.iter().map(|resource| {
quote_spanned! {resource.span()=>
#demand::of::<#resource>
}
});
// ONE PROJECTION PER FIELD, in the DECLARATION's own order, which is the order `new` takes them
// in. Read off `fields` rather than off the projection list so the two cannot drift: a field
// whose entry is missing has already been refused, and the fallback keeps that refusal from
// becoming a panic here.
let projected = self.fields.iter().map(|column| {
let name = &column.name;
let from = self
.source
.projections
.iter()
.find(|projected| projected.field == *name)
.map_or(name, |projected| &projected.from);
quote_spanned!(from.span()=> ::core::clone::Clone::clone(&__ingraph_message.#from))
});
let blocks = lanes.iter().map(|(at, marker, _)| {
let held = &mounts[*at];
let resource = &pointed[*at];
// THE ENGINE, NAMED. Every lane call spells it rather than leaning on inference: `scope` and
// `open` are answered through associated types alone, so a bare `_` leaves the solver with
// `<_ as FulltextLane>::Batch == …` and nothing to unify it against. Spanned at the resource
// path, so an engine with no lane is `E0277` on the word that chose it.
let engine = quote_spanned!(resource.span()=> <#resource as #mount>::Handle);
quote_spanned! {resource.span()=>
{
let __ingraph_mount = #shared::get(&self.#held);
let __ingraph_connection = <#resource as #mount>::connection(__ingraph_mount);
let __ingraph_slot = <#resource as #mount>::corpus(
__ingraph_mount,
<#marker as #slot>::SLOT.as_ref(),
);
let mut __ingraph_batch =
<#engine as #lane>::open::<#marker>(&__ingraph_slot, __ingraph_connection)
.map_err(#refusal::of)?;
let mut __ingraph_corpus = #handle::<#engine, #index>::mint(__ingraph_slot);
// THE QUEUE, and every refusal in it is the BATCH's: the loop stops at the first, the
// batch is discarded whole below, and the delivery is dead-lettered rather than
// half-landed.
let __ingraph_queued: ::core::result::Result<(), Self::Error> = async {
for __ingraph_document in &__ingraph_documents {
let mut __ingraph_segments = #box_writer::new();
<#marker as #road>::write(__ingraph_document, &mut __ingraph_segments)
.map_err(#refusal::of)?;
let __ingraph_entry = <#engine as #lane>::entry(
#handle::engine(&__ingraph_corpus),
#identifiable::id_ref(__ingraph_document),
#index::key_ref(__ingraph_document),
&__ingraph_segments,
)
.map_err(#refusal::of)?;
#handle::upsert_document(
&mut __ingraph_corpus,
#connected::new(
__ingraph_connection,
<#engine as #lane>::scope(&mut __ingraph_batch),
),
__ingraph_entry,
)
.await
.map_err(#refusal::of)?;
}
::core::result::Result::Ok(())
}
.await;
match __ingraph_queued {
::core::result::Result::Ok(()) => <#engine as #lane>::publish(
#handle::engine(&__ingraph_corpus),
__ingraph_connection,
__ingraph_batch,
)
.map_err(#refusal::of)?,
::core::result::Result::Err(__ingraph_refusal) => {
<#engine as #lane>::discard(
#handle::engine(&__ingraph_corpus),
__ingraph_connection,
__ingraph_batch,
);
return ::core::result::Result::Err(__ingraph_refusal);
}
}
}
}
});
quote! {
#[doc = #node_doc]
#vis struct #node {
#(#fields,)*
}
#[automatically_derived]
impl #constructor for #node {
type Error = #missing;
type Options = ();
fn with_options(
__ingraph_resources: &#resources,
(): (),
) -> impl ::core::future::Future<
Output = ::core::result::Result<Self, <Self as #constructor>::Error>,
> {
async move {
::core::result::Result::Ok(Self {
#(#reaches,)*
})
}
}
}
#[automatically_derived]
impl #declared for #node {
const EFFECT: #effect = #effect::Lands;
const HOLDS_LANE: bool = true;
const UPSTREAMS: &'static [#upstream_row] = &[#upstream_row::of::<#upstream>(#named)];
const DEMANDS: &'static [fn() -> #demand] = &[#(#demands,)*];
type Channels = #unchanneled;
type Options = ();
type Mode = #awaited;
type Pair = #buffered;
type Wires<__INGRAPH_OUT__> = #downstream<__INGRAPH_OUT__>;
// NO ATTRIBUTION, and there is no word here to write one with. This node is INJECTED rather
// than declared — the `subscribe` word on a corpus mints it — and what it emits is the
// DERIVED index document, which carries no `Attributes` impl for a projection to resolve
// through. Its observations stay counter-grade, exactly as they were before the seat
// existed.
type Attribution<__INGRAPH_OUT__> = ();
}
#[automatically_derived]
impl #operator for #node {
type In = #upstream;
type Out = #index;
type Error = #refusal;
fn accept(
&mut self,
_: &#context,
__ingraph_delivery: #delivery<Self::In>,
__ingraph_emitter: &mut #emitter<Self::Out>,
) -> impl ::core::future::Future<
Output = ::core::result::Result<(), <Self as #operator>::Error>,
> {
async move {
// EVERY DOCUMENT FIRST, before a single store is opened: a declaration with several
// corpora writes each of them from the same set, and building per corpus would project
// the same message once per engine.
let mut __ingraph_documents = ::std::vec::Vec::new();
for __ingraph_item in #delivery::into_items(__ingraph_delivery) {
let __ingraph_message = #item::into_value(__ingraph_item);
__ingraph_documents.push(#index::new(
#transformer::key(&__ingraph_message),
#(#projected,)*
));
}
// AN EMPTY DELIVERY OPENS NOTHING. A writer costs a lock and a thread, and a batch of
// no documents publishes nothing — so the honest answer to one is to have done nothing.
if !::std::vec::Vec::is_empty(&__ingraph_documents) {
#(#blocks)*
}
// BELOW THE PUBLISH, which is the ordering this node's whole contract rests on: what
// leaves here is findable in every corpus this declaration named.
for __ingraph_document in __ingraph_documents {
#emitter::emit(__ingraph_emitter, __ingraph_document);
}
::core::result::Result::Ok(())
}
}
}
}
}
/// One PROJECTION AUDIT per declared field: a function whose body reads the upstream field the
/// declaration named, and whose return type is the index field's own.
///
/// It is the whole mechanism by which `title = "speaker"` is checked. The body is spanned at the
/// STRING the author wrote, so a field the upstream does not have is `E0609` there, one it will
/// not show from this module is `E0616` there, and one whose type does not match is `E0308` there
/// — each naming the upstream, none of them landing inside an expansion.
///
/// DEAD BY CONSTRUCTION, and the `allow` says so: nothing calls these and nothing is meant to.
/// They exist to be type-checked, which is what a macro that cannot see the upstream can do about
/// the upstream. Calling one would make the audit a code path, and a code path is a thing that has
/// to stay correct rather than a thing that has to compile.
///
/// One function per FIELD, so the errors arrive one per mistake rather than collapsing into the
/// first. Two sources projecting one field would collide on the name, which is exactly the
/// position the frame law on [`borrowed_key`](crate::model::borrowed_key) reserves an index for.
fn projections(&self) -> proc_macro2::TokenStream {
let upstream = &self.source.node;
let audits = self.source.projections.iter().map(|projected| {
let Projected { field, from, ty } = projected;
let name = format_ident!("__ig_project_{field}");
let read = quote_spanned!(from.span()=> &value.#from);
quote! {
#[allow(dead_code)]
fn #name(value: &#upstream) -> &#ty {
#read
}
}
});
quote!(#(#audits)*)
}
/// `<Upstream as Transformer>::Key` — the type of the carried field, and of everything read out of
/// it.
///
/// Written once here because four emitted positions spell it — the constructor's first parameter,
/// `key_ref`'s return, `Transformer::Key` and the `Identifiable` it is projected through — and
/// four hand-written copies is four places for the projection to drift.
fn key(&self) -> proc_macro2::TokenStream {
let upstream = &self.source.node;
let transformer = framework(&self.krate, &["transform"], "Transformer");
quote!(<#upstream as #transformer>::Key)
}
/// γ′ — the ONE field this expansion adds to the item its author wrote.
///
/// Minted here rather than at the front end that injects it, so that the name, the type and the
/// visibility are decided by the code that also reads them back: `new` takes it, `key_ref` borrows
/// it, the entity binding answers through it, and all four are above.
///
/// `pub(crate)`, which is the stamp every other field of the declaration wears — see
/// `ingraph-derive`'s `host` module — and no exception is carved for this one. The visibility
/// convention is about a declaration's fields being read by the code emitted around them, and this
/// field is the case that statement was written for.
///
/// # Panics
/// Never in practice: the tokens are this function's own, and the only way they fail to parse as a
/// named field is a change to this line.
#[must_use]
pub fn carried_key(&self) -> syn::Field {
use syn::parse::Parser as _;
let name = borrowed_key(&self.prefix);
let key = self.key();
syn::Field::parse_named
.parse2(quote!(pub(crate) #name: #key))
.expect("a named field")
}
/// Every method this emission declares, in EMISSION ORDER, for the front end that has to refuse a
/// collision before an expansion lands two of one name in a scope its author cannot edit.
///
/// The FIXED names are here for the reason a declaration's derived ones are: a field called `key`
/// reaches `key_ref`, and a `copy` field called `new` reaches `new`. Neither is a near miss — both
/// are the emitted name exactly — so both are refused at the declaration rather than left to be a
/// duplicate definition inside the expansion.
///
/// # EVERY name, and the ones this used to miss are the reason it says so
///
/// The list once held the constructor, the borrowed key and the accessor families, and the whole
/// read-and-write surface below them was absent. Each absence was the same defect: a `copy` field
/// called `fan_title` beside a `fanout`-marked `title` gives the index two `fan_title`, a field
/// called `retrieve_keys` gives it two of those, and `E0592` reports each of them at
/// `#[ingraph::fulltext(…)]` — a span the author cannot edit, in a message that never names the
/// field. A table that knows about the accessors alone refuses the collisions it happens to have
/// heard of and is silent about the rest, which reads as a rule that has been applied.
///
/// # ONE OWNER, and an impl written inside the anonymous const is not a smaller scope
///
/// Every method here lands on the DECLARATION's own type, which is why they all carry
/// [`Owner::Record`]. The retrieve face is emitted inside the expansion's anonymous `const` and the
/// fan door at module scope, and that difference buys nothing: an inherent impl is global whatever
/// block it was written in, so the two impls' names share one namespace and collide with each other
/// exactly as they collide with the carrier's.
///
/// The order is the EMITTER's own walk — see [`emit`](Self::emit) — so a front end reporting a
/// collision can name the earlier of the two as the one already there. It is pinned against the
/// emission itself by `tests::the_enumeration_names_exactly_the_methods_the_emission_declares`,
/// rather than maintained by hand.
#[must_use]
pub fn emitted_methods(&self) -> Vec<Emitted> {
let mint = |name: syn::Ident, origin: Origin| Emitted {
owner: Owner::Record,
owner_name: self.index.clone(),
name,
origin,
};
// The FANS lead, because the emission writes them before the const the rest of it lives in.
let mut emitted: Vec<Emitted> = self
.fans()
.map(|field| mint(fan_door(field), Origin::Fan(field.clone())))
.collect();
// The FUSE FAMILY next — the packages, questions and the column vocabulary the tier writes
// between the fans and the carrier, rostered by the tier itself so the names and their
// predicates live beside the emission.
emitted.extend(
self
.tier()
.emitted_methods()
.into_iter()
.map(|(on, name)| Emitted {
owner: Owner::Fuse,
owner_name: on.clone(),
name: name.clone(),
origin: Origin::Fuse(crate::method::FuseOrigin { on, member: name }),
}),
);
emitted.push(mint(format_ident!("new"), Origin::Constructor));
emitted.push(mint(format_ident!("key_ref"), Origin::BorrowedKey));
emitted.extend(
self
.fields
.iter()
.flat_map(|column| column.emitted(Owner::Record, &self.index, true)),
);
// The DECLARED FOLDS, between the carrier and the retrieve face because that is where they are
// written — one per SET election, which is the predicate `declared_folds` asks rather than a
// second reading of it.
emitted.extend(
self
.embeddings
.iter()
.filter(|elected| elected.label.is_set())
.map(|elected| {
mint(
fold_accessor(&elected.field),
Origin::Fold(elected.field.clone()),
)
}),
);
emitted.extend(
self
.retrieve_methods()
.into_iter()
.map(|(name, origin)| mint(name, origin)),
);
emitted
}
/// The RETRIEVE face's names, in the order [`retrieve_half`](Self::retrieve_half) writes them —
/// the doors of every subject, each subject's whole family before the next subject's.
///
/// Split out for the reason the record's order-by methods are: the conditions differ from every
/// other family's, and a walk this long inside one function would hide which of them is answered
/// where. Each condition is asked HERE in the same form the emission asks it — a kind that answers
/// no retrieve has no subjects at all, a by-key pair rides an election, the set door rides the
/// LABEL and the asked pair rides a declared road.
fn retrieve_methods(&self) -> Vec<(syn::Ident, Origin)> {
let mut emitted = Vec::new();
// The `blob` kind reaches no retrieve at all — an artifact family is addressed rather than
// ranked — and `subjects` cannot say so on its own: it answers the unelected pair for every kind
// that is not `vector`, which is what makes the full-text pair unsuffixed.
if !self.seamed() {
return emitted;
}
// THE FUSED DOORS lead the per-subject walk, because the emission writes them after it — the
// roster's order is the emitter's own, and `retrieve_half` appends them to the impl.
let mut fused = Vec::new();
if self.tier().doors().vector {
fused.push((
format_ident!("vector_fuse"),
Origin::Door(DoorOrigin {
door: Door::Fused,
election: None,
}),
));
fused.push((
format_ident!("vector_fuse_similar"),
Origin::Door(DoorOrigin {
door: Door::FusedSimilar,
election: None,
}),
));
}
for subject in self.subjects() {
// The audit's ELECTION is the door's SUFFIX: `None` reconstructs the unsuffixed pair and
// `Some` a `_by_<field>` one, so a per-field full-text door answers its column exactly as a
// vector door answers its election.
let suffix = match subject.grain {
Grain::Whole => None,
Grain::Column(field) => Some(field.clone()),
Grain::Election(elected) => Some(elected.field.clone()),
};
let door = |door: Door| {
Origin::Door(DoorOrigin {
door,
election: suffix.clone(),
})
};
emitted.push((subject.keys.clone(), door(Door::Keys)));
emitted.push((subject.whole.clone(), door(Door::Whole)));
let Grain::Election(elected) = subject.grain else {
continue;
};
// The BY-KEY pair, conditional on nothing but the election itself — a declaration that elected
// a column can always be asked what it stored for an entity and what else is near it.
emitted.push((Door::Own.name(&elected.field), door(Door::Own)));
emitted.push((Door::Similar.name(&elected.field), door(Door::Similar)));
if elected.label.is_set() {
emitted.push((Door::Set.name(&elected.field), door(Door::Set)));
emitted.push((
Door::SimilarSet.name(&elected.field),
door(Door::SimilarSet),
));
}
}
emitted.extend(fused);
// THE MINI FUSE DOORS, last for the emitter's own reason — `retrieve_half` appends them after
// the tier's, and the roster's order is the emission's. The condition is asked in the same form
// the emission asks it: `fanned_slots`, which is two or more PARTICIPATING legs and not a set
// election, read from the one place that decides it.
for elected in self.tier().fanned_slots() {
let field = elected.field.clone();
let door = |door: Door| {
Origin::Door(DoorOrigin {
door,
election: Some(field.clone()),
})
};
emitted.push((Door::FusedLegs.name(&field), door(Door::FusedLegs)));
emitted.push((
Door::FusedLegsSimilar.name(&field),
door(Door::FusedLegsSimilar),
));
}
emitted
}
/// The fields that GET A FAN DOOR — every `fanout`-marked one, on a kind that has a write verb to
/// fan.
///
/// An enumeration naming a door the expansion does not write would refuse a declaration for a
/// collision it could not have, which is why the kind is asked here at all.
fn fans(&self) -> impl Iterator<Item = &syn::Ident> {
self
.engines
.iter()
.filter(|_| self.seamed())
.filter(|declared| declared.fanout)
.map(|declared| &declared.field)
}
/// Whether this kind HAS AN ENGINE SEAM — the one predicate the fan door and the retrieve face are
/// both conditional on.
///
/// [`fanouts`](Self::fanouts) and [`retrieve_half`](Self::retrieve_half) each ask it as the `_`
/// arm of a match that also picks the seam's trait paths and its write verb, so what is shared is
/// the QUESTION and not the answer — a `blob` elects nothing, holds no corpus and therefore has
/// neither door. Written once here so the two enumerations above ask it in one spelling, and
/// pinned against the emitters by this module's `audits` suite: a kind that grew a seam and did
/// not reach this predicate fails there.
const fn seamed(&self) -> bool {
matches!(self.kind, NodeKind::Fulltext | NodeKind::Vector)
}
/// Every TYPE this emission declares into the DECLARING SCOPE, in EMISSION ORDER — the markers,
/// which are the whole of what a derived index puts in the type namespace beside the item its
/// author wrote.
///
/// [`RecordModel::emitted_types`](crate::model::RecordModel::emitted_types)' argument, one family
/// over: the front end refuses a declaration whose emitted types collide, and it asks HERE which
/// those are rather than keeping a list of its own.
///
/// # WHY a derived index needs this at all, when its markers are minted rather than named
///
/// No word renames either of these, so the collisions are not a rename landing on a neighbour —
/// they are the JOIN. A marker is `<Index><Field><Engine>` in upper camel case, and camel case has
/// no separator: field `a` × engine `b_c` and field `a_b` × engine `c` both mint `<Index>ABC`.
/// The election markers are `<Index>By<Field>` and stand in the same scope, so field `by` × engine
/// `image` mints exactly the marker of an election on `image`.
///
/// The durable slot NAME has the same three parts and does NOT have the problem — see
/// [`Slot::name`](crate::engine::Slot::name), which joins with `__` for precisely this reason and
/// is test-pinned.
///
/// # The boundary-preserving JOIN was measured against the refusal, and lost on two counts
///
/// **A TYPE cannot take that separator.** `<Index>__a__b_c` is not upper camel case, so every
/// marker would arrive under `non_camel_case_types` in a crate that never wrote it — the cost
/// [`one_storage_marker`](crate::model::one_storage_marker) already spends `allow`s on, paid here
/// on names the WIRING spells rather than on a hidden one. And spell them it does:
/// `SlotHandle<E, SearchDocumentTitleTantivy>` and the lanes over it are some eighty sites across
/// this workspace, several of them `compile_fail` goldens whose text IS the assertion.
///
/// **And it would not close the class.** The election markers camel-join too, so elections on
/// `image_1` and `image1` mint one `<Index>ByImage1` whatever the slot markers do. A respelling
/// buys one of the three collisions and leaves the other two live — under an error code that would
/// then look handled, which is the failure the whole-fix constraint was written against.
///
/// So the name stays and the collision is REFUSED at the declaration, which is the road that leaves
/// the author's own tokens the thing that moves.
///
/// # The INDEX's own name is not here, and cannot collide with one of these
///
/// A record adds its own name to this list because a rename can land on it. Nothing here can:
/// every marker is the index's name followed by at least one more camel-case segment, so
/// `<Index>` itself is not in the set — and a name this enumeration invented would refuse a
/// declaration for a clash that could not happen.
///
/// The order is the emitter's own walk — elections, then slots — and it is pinned against the
/// emission by `tests::the_enumeration_names_exactly_the_types_the_emission_declares`.
#[must_use]
pub fn emitted_types(&self) -> Vec<Declared> {
let index = self.base();
self
.embeddings
.iter()
.map(|elected| Declared {
name: elected_marker(index, &elected.field),
role: Role::Election(elected.field.clone()),
})
.chain(self.slots().into_iter().map(|slot| Declared {
name: slot.marker(index),
role: Role::Slot(slot),
}))
.chain(
self
.tier()
.emitted_types()
.into_iter()
.map(|name| Declared {
name,
role: Role::Fuse,
}),
)
// THE QUERY UNIT, last and only where the declaration is dressed — a name in the declaring
// scope is a name the collision refusals are measured against, whatever tier minted it.
.chain(self.mounts().then(|| Declared {
name: self.queries_name(),
role: Role::Queries,
}))
// THE ANSWER FAMILY, after it and in the emitter's own walk — one question per road, and the
// hit shapes a fanned road adds. Every one of them is a module-scope declaration OUTSIDE the
// binding gate, which is what makes this enumeration able to name them at all: a type minted
// inside a gate would be invisible here and visible to a declaring author.
.chain(self.answer_names())
.collect()
}
/// EVERY TYPE the answer family lands, in the emitter's own walk — see
/// [`answers`](Self::answers).
fn answer_names(&self) -> Vec<Declared> {
use heck::ToUpperCamelCase as _;
let tier = self.tier();
let mut names = Vec::new();
for (elected, road) in self.answer_roads() {
let stem = tier.stem(elected);
let role = Role::Answer(elected.field.clone());
names.push(Declared {
name: format_ident!("{stem}Question"),
role: role.clone(),
});
if let AnswerRoad::Fanned(legs) = road {
names.push(Declared {
name: format_ident!("{stem}Engines"),
role: role.clone(),
});
for engine in &legs {
names.push(Declared {
name: format_ident!(
"{stem}{}Sighting",
engine.word.to_string().to_upper_camel_case()
),
role: role.clone(),
});
}
names.push(Declared {
name: format_ident!("{stem}Sighting"),
role: role.clone(),
});
names.push(Declared {
name: format_ident!("{stem}FusedKeyMatch"),
role,
});
}
}
names
}
/// What the field wrote, or [`None`] where it wrote nothing — the ELECTION tier's lookup.
#[must_use]
pub fn numbers_of(&self, field: &syn::Ident) -> Option<&FieldNumbers> {
self
.field_numbers
.iter()
.find(|written| &written.field == field)
}
/// **THE WALL FOR ONE ROUTE** — the declared ceiling `route_depth` caps every fetch against.
///
/// Two tiers and no third: the ELECTION's word where it wrote one, else the CONTAINER's. There is
/// no framework default and there never will be one — an absent wall is the AUTHOR'S INFORMED
/// OPENNESS (#293-B), and a number invented on their behalf would be the framework deciding what a
/// deployment may afford.
///
/// `field` is [`None`] at the grains that are not one election's — the full-text tier's unsuffixed
/// subject — where the container's word is the whole chain.
#[must_use]
pub fn declared_ceiling(&self, field: Option<&syn::Ident>) -> Option<core::num::NonZeroU32> {
field
.and_then(|field| self.numbers_of(field))
.and_then(|written| written.numbers.ceiling)
.or(self.numbers.ceiling)
}
/// **THE STREAM GUARD FOR ONE ELECTION** — how many query vectors one request may ask its `_with`
/// road with, or [`None`] where no tier wrote a guard.
///
/// [`declared_ceiling`](Self::declared_ceiling)'s twin on the other protective axis, resolved the
/// same way and for the same reason: the ELECTION's word where it wrote one, else the CONTAINER's,
/// and no third step — a word written closer to the door is the more specific statement of the same
/// rule, and an unwritten guard is NO guard rather than a number this crate invented.
///
/// It is spent in [`points_binding`](Self::points_binding) and nowhere else, which is the ruled
/// scope: the guard is over an `m` a REQUEST states, and the only road asked with one is the
/// `_with` question road.
#[must_use]
pub fn declared_streams(&self, field: Option<&syn::Ident>) -> Option<core::num::NonZeroU32> {
field
.and_then(|field| self.numbers_of(field))
.and_then(|written| written.numbers.streams)
.or(self.numbers.streams)
}
/// **THE WALL, AS AN EMITTED `route_depth` READS IT** — the token that fills the second argument
/// every fetch resolves through.
///
/// `Option::as_ref` over a fresh `Option<NonZeroU32>` rather than a hoisted `const`, and the shape
/// is the borrow's: the callee takes `Option<&NonZeroU32>`, the temporary lives to the end of the
/// `let` statement the call sits in, and `route_depth` hands back an owned number — so nothing
/// outlives the statement and no item has to be minted in the emitted body's scope.
///
/// [`None`] where no tier declared one, which is the `::core::option::Option::None` every site
/// spelled while the word did not exist — so a declaration that writes nothing expands to exactly
/// the tokens it expanded to before, and the word is purely additive.
#[must_use]
pub fn wall(&self, field: Option<&syn::Ident>) -> proc_macro2::TokenStream {
match self.declared_ceiling(field) {
Some(wall) => {
let wall = wall.get();
quote! {
::core::option::Option::as_ref(&::core::num::NonZeroU32::new(#wall))
}
}
None => quote!(::core::option::Option::None),
}
}
/// **THE WIRE DEFAULT** — the literal one election's `first:` argument publishes, resolved through
/// the ruled chain and capped by the wall.
///
/// ```text
/// field-skin `first` → field `limit` → container-skin `first` → container `limit` → 20
/// ```
///
/// The order is Q6a's verbatim, and each step is the more specific statement of the same number:
/// a skin's word beats the bones at its own tier because it is written closer to the schema, and a
/// field's tier beats the container's because it is written closer to the door. [`FRAMEWORK_LIMIT`]
/// is the floor of the chain rather than a default anybody writes.
///
/// The WALL caps the answer, and that is not decoration: a default published above the ceiling
/// would be a schema promising a page size the fetch silently cuts, which is the one thing an SDL
/// literal must not be able to do.
#[must_use]
pub fn wire_first(&self, kind: GraphqlKind, field: Option<&syn::Ident>) -> core::num::NonZeroU32 {
let at = field.and_then(|field| self.numbers_of(field));
let asked = at
.and_then(|written| written.skin(kind))
.and_then(|skin| skin.first)
.or_else(|| at.and_then(|written| written.numbers.limit))
.or_else(|| {
self
.graphql
.as_ref()
.and_then(|block| block.skin(kind))
.and_then(|skin| skin.first)
})
.or(self.numbers.limit)
.unwrap_or(FRAMEWORK_LIMIT);
match self.declared_ceiling(field) {
Some(wall) => asked.min(wall),
None => asked,
}
}
/// **THE POOL DEPTH** a fold's streams are fetched at when a request names none — the declared
/// half of Q6b's chain.
///
/// ```text
/// (request depth) → field `depth` → container `depth` → the whole limit chain
/// ```
///
/// The first step is the REQUEST's and is therefore the resolver's, not a declaration's: what this
/// answers is everything below it, which is what a resolver falls to when the request deferred.
/// Falling to the limit chain rather than to a depth of its own is the same statement
/// `Route::depth`'s `None` makes one grain up — *as deep as the answer is wide* — and it keeps an
/// undepthed world byte-identical to the one before the knob existed.
#[must_use]
pub fn pool_depth(&self, kind: GraphqlKind, field: Option<&syn::Ident>) -> core::num::NonZeroU32 {
let asked = field
.and_then(|field| self.numbers_of(field))
.and_then(|written| written.numbers.depth)
.or(self.numbers.depth);
match asked {
Some(depth) => match self.declared_ceiling(field) {
Some(wall) => depth.min(wall),
None => depth,
},
// NO `min` REPEATED HERE: the limit chain has already been through the wall, and capping a
// capped number twice is the same number.
None => self.wire_first(kind, field),
}
}
}
/// WHICH of an election's QUERY FIELDS a name is being asked for — a closed vocabulary of five, one
/// per road an election can mount and no more.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Field {
/// `<index>By<Field>Keys` — one typed store, a QUESTION, ranked addresses.
Keys,
/// `<index>By<Field>` — the same question, HYDRATED: the upstream's whole entities.
Hydrated,
/// `<index>FusedBy<Field>Keys` — every store the field is written to, one leaderboard.
Fused,
/// `<index>SimilarBy<Field>Keys` — one typed store, an EXAMPLE KEY, ranked addresses without the
/// example.
Similar,
/// `<index>SimilarBy<Field>` — the same example, HYDRATED: the neighbours' whole entities.
SimilarHydrated,
}
impl Field {
/// Every road, in the order a refusal lists them — which is also the order the near-miss line
/// measures a typo against, and the TIER ORDER of each pair: the keys rung first, its hydrated
/// twin under it.
///
/// [`RenamePiece::ALL`]'s twin one axis over, and the same law: the vocabulary and the reader are
/// ONE list, so a word offered by a suggestion is a word the next compile reads.
pub const ALL: [Self; 5] = [
Self::Keys,
Self::Hydrated,
Self::Fused,
Self::Similar,
Self::SimilarHydrated,
];
/// The word a declaration writes to name this road's query field.
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Keys => "keys",
Self::Hydrated => "hydrated",
Self::Fused => "fused",
Self::Similar => "similar",
Self::SimilarHydrated => "similar_hydrated",
}
}
/// What a refusal calls the field this word is about — the half an author reading a sentence about
/// their own typo needs, five roads being four more than anybody holds in their head.
#[must_use]
pub const fn what(self) -> &'static str {
match self {
Self::Keys => "the ranked addresses one typed store answers a question with",
Self::Hydrated => "the same question answered with the upstream's whole entities",
Self::Fused => "the one leaderboard every store this field is written to agrees on",
Self::Similar => "the ranked addresses one typed store answers an EXAMPLE KEY with",
Self::SimilarHydrated => "the same example answered with the neighbours' whole entities",
}
}
/// The road a path names, if it names one.
#[must_use]
pub fn of(path: &syn::Path) -> Option<Self> {
Self::ALL
.into_iter()
.find(|road| path.is_ident(road.as_str()))
}
/// The DERIVED name, before any declared word replaces it.
///
/// Built from the declaration's rename-aware base rather than from its own ident, so
/// `rename = "ShotSearch"` moves the field with the family — the same law every minted type name
/// is under, at the one name that is a schema's rather than Rust's.
///
/// # The shape is `{subject}{road?}By{election}{tier?}`, and the TIER NOUN is the law
///
/// The user's ruling of 2026-08-16, uniform across all three families: **a keys-tier field wears
/// the `Keys` noun, and the bare name is the hydrated twin's.** So the two slots are filled by two
/// independent facts — the road word (`Fused`, `Similar`, or nothing for the question road) says
/// WHICH road, and the tier noun says which TIER of it — and every road's pair of names differs by
/// the noun alone.
///
/// The fused road is the one that had to move: it published the bare name while no fused tier B
/// existed to want it, which is a name that would have had to be renamed on the day one arrived.
/// One rule over three families is what keeps that day from being a naming deadlock, and
/// `{subject}FusedBy{election}` is now RESERVED rather than emitted.
fn derived(self, base: &syn::Ident, field: &syn::Ident) -> String {
use heck::{ToLowerCamelCase as _, ToUpperCamelCase as _};
let subject = base.to_string().to_lower_camel_case();
let election = field.to_string().to_upper_camel_case();
match self {
Self::Keys => format!("{subject}By{election}Keys"),
Self::Hydrated => format!("{subject}By{election}"),
Self::Fused => format!("{subject}FusedBy{election}Keys"),
Self::Similar => format!("{subject}SimilarBy{election}Keys"),
Self::SimilarHydrated => format!("{subject}SimilarBy{election}"),
}
}
}
/// The THREE PROJECTIONS one election's answer face binds — the width, the space and the element.
///
/// The `__…__` fence and the field spelled inside it, this crate's standing answer for every emitted
/// ident: two elections cannot mint one name and no declaration can collide with either. Distinct
/// from [`geometry`]'s pair on purpose — those live inside the expansion's OTHER anonymous const and
/// a name in one const is a name in one const.
fn answer_geometry(elected: &Elected) -> (syn::Ident, syn::Ident, syn::Ident) {
let at = elected.field.span();
let field = elected.field.to_string().to_uppercase();
(
format_ident!("__INGRAPH_ANSWER_WIDTH_{field}__", span = at),
format_ident!("__INGRAPH_ANSWER_SPACE_{field}__", span = at),
format_ident!("__INGRAPH_ANSWER_ELEMENT_{field}__", span = at),
)
}
/// **WHAT A CLIENT IS TOLD ABOUT THE FOLD** — the sentence both set legs publish, and the third of
/// the three places [`FoldSemantics::name`] is spent.
///
/// # The sentence cannot say WHICH fold ran, and it says so
///
/// SDL descriptions are built when the schema is compiled and the installed fold is a LAUNCH-time
/// fact, so a row naming the running fold would be a string the schema cannot know. What the
/// description can carry is the CHAIN — the deployment's seat, the election's word, and the citizen
/// both fall back to — plus where the running fold's own name is readable, which is the `fold` field
/// on this door's trace span. A dynamic wire row for it waits for an introspection home that does
/// not exist yet.
///
/// # And it says the request is not in the chain
///
/// A fold changes what the answer MEANS, so a client that read this sentence and looked for an
/// argument would be looking for a seat the ruling deliberately does not mint. Naming the absence is
/// cheaper for a schema reader than leaving it to be inferred from a field list.
///
/// [`FoldSemantics::name`]: ../../ingraph/retrieve/trait.FoldSemantics.html#tymethod.name
fn fold_note(field: &syn::Ident, asked: Asked) -> String {
let m = match asked {
Asked::Example => format!(
"The `{field}` set is asked WHOLE: `m` is however many vectors the example holds, which is \
this deployment's own data rather than anything a request states — so no number here bounds \
it."
),
Asked::Points(None) => format!(
"`m` is however many points this request sent under `coordinates`, and this declaration wrote \
no `streams` guard — so nothing here bounds it but the engine's own corpus. `{field}`'s \
streams are walked one per point and folded once."
),
Asked::Points(Some(guard)) => format!(
"`m` is however many points this request sent under `coordinates`, and this declaration \
admits at most {guard} of them: a question past that is REFUSED naming the count rather than \
cut down to fit, because dropping query vectors answers a different question. `{field}`'s \
streams are walked one per point and folded once.",
guard = guard.get(),
),
};
format!(
"WHICH FOLD runs is the DEPLOYMENT's and never the request's: it installs any `FoldSemantics` \
for this pairing at launch, else this election's own `semantics(fold = …)` word answers, else \
the framework's `Sum` — every query vector contributing its own \
best. There is no argument for it here, because two answers of one corpus folded differently \
cannot be compared against each other. The fold that actually ran names itself on this door's \
`ingraph.query` span, under `fold`.\n\n{m}"
)
}
/// WHERE ONE SET ROAD'S `m` COMES FROM — which is what decides whether anything may bound it.
///
/// A vocabulary of two rather than a bool, because the second arm CARRIES the guard: the two facts a
/// reader of the published description needs are *who states `m`* and *what caps it*, and only one
/// of the two roads has an answer to the second.
#[derive(Debug, Clone, Copy)]
enum Asked {
/// The example's own stored set — this deployment's data, which no request can inflate and no
/// declared word bounds.
Example,
/// The points a REQUEST sent, with the declared `streams` guard over them where a tier wrote one.
Points(Option<core::num::NonZeroU32>),
}
/// The name the UPSTREAM's wire address is bound to inside an answer face's `const`.
///
/// One per declaration rather than one per election: every hit of every road carries the same
/// address, the upstream being the one thing a derived index draws from.
fn wire_key_name() -> syn::Ident {
format_ident!("__INGRAPH_ANSWER_KEY__")
}
/// The name the UPSTREAM's OWN key type is bound to inside an answer face's `const`.
///
/// [`wire_key_name`]'s twin at the other end of one address: that one is what a hit RENDERS into,
/// this one is what a by-example door TAKES — and the two are different types joined by a `From`,
/// which the plain road's crossing already spends. One per declaration for that one's reason.
fn example_key_name() -> syn::Ident {
format_ident!("__INGRAPH_ANSWER_EXAMPLE__")
}
/// The three names a HYDRATED road's projections are bound to — the upstream's database, its row in
/// that database, and the wire object that row raises into.
///
/// One per declaration, [`wire_key_name`]'s reason unchanged: every hydrated road of every election
/// reads the same upstream out of the same store. They are bound inside the `if_sqlx!` half alone —
/// see [`IndexModel::hydration_bindings`] — so a build without the SQL family has neither the names
/// nor anything that could resolve them.
fn hydration_names() -> (syn::Ident, syn::Ident, syn::Ident) {
(
format_ident!("__INGRAPH_ANSWER_DB__"),
format_ident!("__INGRAPH_ANSWER_ROW__"),
format_ident!("__INGRAPH_ANSWER_ENTITY__"),
)
}
/// ONE ELECTION's width and space, as the NAMES the expansion binds its projections to — see
/// [`IndexModel::geometry`], whose doc states the whole of it.
///
/// Free rather than a method because more than one emitter needs the same two tokens, so one home
/// keeps the spellings from drifting.
fn geometry(elected: &Elected) -> (syn::Ident, syn::Ident) {
let at = elected.field.span();
let field = elected.field.to_string().to_uppercase();
(
format_ident!("__INGRAPH_WIDTH_{field}__", span = at),
format_ident!("__INGRAPH_SPACE_{field}__", span = at),
)
}
/// WHICH fields a full-text subject is about, as its doc line names them.
///
/// EMPTY for an empty set, which is the one case that never reaches a live emission — a full-text
/// declaration marking nothing is refused by name at the front end — and is reachable from a model
/// built by hand. An emission that read *every projection* here would be the dissolved posture
/// restated in the docs, so the sentence is built from the elections rather than from the fields.
fn searched(fields: &[syn::Ident]) -> String {
if fields.is_empty() {
return String::new();
}
format!(
" in {}",
fields
.iter()
.map(|field| format!("`{field}`"))
.collect::<Vec<_>>()
.join(", "),
)
}
/// ONE LEG of a `fanout` write — the names its parameters take, and the slot it writes.
///
/// A struct rather than a tuple, because six parallel `Vec`s over one index is exactly the shape
/// that drifts: the engine parameter, the three bindings and the marker have to describe ONE slot,
/// and here they are one value that cannot be zipped wrongly.
struct Leg {
/// The engine TYPE PARAMETER this leg introduces.
///
/// One per leg and never shared, which is the whole reason the fan is emitted rather than written
/// generically: two engines are two types, and a signature that named one parameter twice would
/// refuse the case the marker exists for.
engine: syn::Ident,
/// The branded handle's parameter name.
handle: syn::Ident,
/// The connection-and-write-context parameter's name.
scope: syn::Ident,
/// The entry's parameter name.
doc: syn::Ident,
/// The slot MARKER this leg's handle is branded with.
marker: syn::Ident,
/// The engine WORD, for the door's own doc line.
word: String,
}
/// The fan's error type: the legs' own errors, summed by right-nesting.
///
/// `Refused<A, Refused<B, C>>` for three legs, `A`'s own error for one. The nesting is the arity
/// mechanism — see [`Refused`](crate::engine) for why a wider enum per arity is refused — and this
/// is the one place its shape is decided, so the type a door returns and the arms
/// [`refusal_arm`] builds cannot disagree.
fn refusal_type(
legs: &[Leg],
refused: &proc_macro2::TokenStream,
face: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
let Some((first, rest)) = legs.split_first() else {
// A fan with no leg is refused at the front end — `fanout` needs two engines to fan between —
// so this is the shape of an unreachable model rather than a case.
return quote!(::core::convert::Infallible);
};
let engine = &first.engine;
let mine = quote!(<#engine as #face>::Error);
if rest.is_empty() {
return mine;
}
let theirs = refusal_type(rest, refused, face);
quote!(#refused<#mine, #theirs>)
}
/// The wrapper leg `at` of `legs` maps its error through, to reach [`refusal_type`]'s nesting.
///
/// `First` at its own depth, `Second` for every leg above it, and the LAST leg skips the `First`
/// because it is what the innermost `Second` already holds.
fn refusal_arm(
at: usize,
legs: usize,
refused: &proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
let binding = format_ident!("__ingraph_refused");
let mut wrapped = if at + 1 == legs {
quote!(#binding)
} else {
quote!(#refused::First(#binding))
};
for _ in 0..at {
wrapped = quote!(#refused::Second(#wrapped));
}
quote!(|#binding| #wrapped)
}