ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
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
//! The emitter's acceptance, over models built BY HAND.
//!
//! Not one of these tests parses a declaration, and that is the point: if the emitter could only
//! be driven from a `DeriveInput`, the split that lets `ingraph-compiler` reach it from a manifest
//! would not exist. `syn::parse2` appears only to read the emitter's OUTPUT back for inspection.

use quote::ToTokens;

use crate::{
  construct::{Build, Construction},
  model::{
    Column, Condition, Derived, FallibleConversion, FanIn, Field, Fusion, Key, Kind, Lineage,
    Mirror, NodeKind, Product, Products, Projection, RecordModel, Reference, Shape, Subscription,
    Through, Upstream, Upstreams, default_downstream_name, default_in_name, default_key_name,
    default_lineage_name, default_out_kind_name, default_out_name, fanned_lineage,
    fanned_lineage_column, one_storage_marker,
  },
  prefix::EmissionPrefix,
};

/// The three fixtures' shapes, as models: a root, a child, and a grandchild whose lineage is the
/// full path rather than only its parent — and which, like the fixture, renames both of its
/// emitted types and marks ONE of its columns `copy`, so a mixed shape is always under test.
fn video_track() -> RecordModel {
  let mut model = model("VideoTrack", &["media_id", "video_id"], "id");
  model.key.name = ident("TrackAddress");
  model.key.path[0].project = Projection::Copied;
  let lineage = model.lineage.as_mut().expect("a grandchild has a path");
  lineage.name = ident("TrackScope");
  lineage.path_mut()[0].project = Projection::Copied;
  mark(&mut model, "media_id");
  model
}

/// Mark one of the record's own fields `copy`, as the declaration's marker would have.
fn mark(model: &mut RecordModel, name: &str) {
  model
    .fields
    .iter_mut()
    .find(|field| field.column.name == name)
    .expect("a field of the record")
    .column
    .project = Projection::Copied;
}

/// Give a field the INTERPRETATION a declaration's label would have given it — the field's own,
/// which is where a label lives.
fn label(model: &mut RecordModel, source: &str, marker: Marker) {
  let source = ident(source);
  model
    .fields
    .iter_mut()
    .find(|field| field.column.source == source)
    .expect("a field of the record")
    .marker = Some(marker);
}

fn video() -> RecordModel {
  model("Video", &["media_id"], "id")
}

/// The root, whose id is `copy` — as the fixture's is.
fn media() -> RecordModel {
  let mut model = model("Media", &[], "id");
  model.key.id.project = Projection::Copied;
  mark(&mut model, "id");
  model
}

/// [`video`] FUSING: two upstreams, the first designated, and its one lineage column mapped onto a
/// parent field of another name — so the equation's two halves are both under test.
fn fused() -> RecordModel {
  let mut model = video();
  model.upstreams = Some(Upstreams::Fused(Fusion {
    parent: syn::parse_quote!(media::Frame),
    others: vec![syn::parse_quote!(asr::Segment)],
    mirrors: vec![Mirror {
      column: ident("media_id"),
      from: ident("frame"),
    }],
  }));
  model
}

/// [`video`] FANNED: two independent upstreams, no designation — so its lineage is a CHOICE, and
/// the key's leading column is that choice rather than a path step.
fn fanned() -> RecordModel {
  fanned_under(EmissionPrefix::default())
}

/// [`fanned`] under a stated emission prefix, so the injected field and the model's own seat cannot
/// be flipped one without the other — the fixture writes the injected column's source itself, so a
/// caller that moved only the seat would be asserting against a model no front end could build.
fn fanned_under(prefix: EmissionPrefix) -> RecordModel {
  let mut model = video();
  model.prefix = prefix;
  let kinds = vec![
    Kind {
      node: syn::parse_quote!(media::Frame),
      variant: ident("Frame"),
    },
    Kind {
      node: syn::parse_quote!(asr::Segment),
      variant: ident("Segment"),
    },
  ];
  model.upstreams = Some(Upstreams::Fanned(FanIn {
    kinds: kinds.clone(),
  }));
  let lineage = model.lineage.as_mut().expect("a child has a lineage");
  lineage.shape = Shape::Kinds(kinds);
  let column = &mut model.key.path[0];
  column.name = fanned_lineage_column();
  column.source = fanned_lineage(&model.prefix);
  column.ty = syn::parse_quote!(VideoLineage);
  model
}

/// A model carrying the CONVENTIONAL names and no `copy` marker, so a rename or a marker can be
/// shown to displace what it replaces.
///
/// Its record carries the key columns first, then one DATA field of each projection shape — a
/// scalar, a `Vec<_>` and an `Option<_>` — so the record's own impl is always under test.
pub(crate) fn model(record: &str, lineage: &[&str], id: &str) -> RecordModel {
  let record = ident(record);
  let identity: Vec<Column> = lineage
    .iter()
    .map(|name| column(name))
    .chain([column(id)])
    .collect();
  let mut chapters = column_of("chapters", generic("Vec", "Uuid7"));
  chapters.project = Projection::Repeated;
  let mut cover = column_of("cover_id", generic("Option", "Uuid7"));
  cover.project = Projection::Optional;
  let data = [column_of("checksum", ty("u64")), chapters, cover];
  RecordModel {
    prefix: EmissionPrefix::default(),
    kind: NodeKind::Record,
    options: None,
    receipt: None,
    remote: None,
    construction: Construction::default(),
    key: Key {
      name: default_key_name(&record),
      path: lineage.iter().map(|name| column(name)).collect(),
      id: column(id),
    },
    krate: ingraph_path(),
    vis: syn::Visibility::Public(syn::token::Pub::default()),
    fields: identity
      .into_iter()
      .map(|column| Field {
        column,
        identity: true,
        marker: None,
        sortable: false,
        indexed: false,
        reference: None,
        skip: None,
        docs: Vec::new(),
        condition: Condition::always(),
        build: Build::default(),
      })
      .chain(data.into_iter().map(|column| Field {
        column,
        identity: false,
        marker: None,
        sortable: false,
        indexed: false,
        reference: None,
        skip: None,
        docs: Vec::new(),
        condition: Condition::always(),
        build: Build::default(),
      }))
      .collect(),
    lineage: (!lineage.is_empty()).then(|| Lineage {
      name: default_lineage_name(&record),
      shape: Shape::Path(lineage.iter().map(|name| column(name)).collect()),
    }),
    // The persist projection is its own roster below — every model here is a pure-compute record, so
    // the key/lineage assertions stay about the key and the lineage.
    persist: None,
    errors: Vec::new(),
    order_by: RustSafeName::from_ident(&default_order_by_name(&record)),
    progress: None,
    graphql: None,
    derived: Vec::new(),
    artifacts: Vec::new(),
    implements: Vec::new(),
    // Driven by nothing inside the graph, which is what the key/lineage roster is about; the
    // subscription's and the fusion's own emissions have their own models below.
    subscribe: None,
    // Torn down by `Drop`, which is what a declaration that writes no `teardown` says.
    teardown: false,
    asynchronous: None,
    streaming: None,
    autonomous: None,
    attributed: false,
    upstreams: None,
    // The fan-in container and the product list are the TOPOLOGY declarations, and a model built
    // for the key/lineage roster writes neither: one upstream and one product is today's world, and
    // the emissions that need the words carry their own models below.
    subscriptions: None,
    products: None,
    // No clock of its own either, for the same reason: the poll word's emission carries its own
    // models, beside the topology ones.
    polls: None,
    // Observed at the framework's own default, which is what a declaration writing no `tracing(…)`
    // word says — and what makes the emitted facts trait state nothing about it.
    tracing: None,
    record,
  }
}

/// A one-argument generic type path, assembled rather than parsed.
fn generic(outer: &str, item: &str) -> syn::Type {
  let mut segment = syn::PathSegment::from(ident(outer));
  let mut args = syn::punctuated::Punctuated::new();
  args.push(syn::GenericArgument::Type(ty(item)));
  segment.arguments = syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
    colon2_token: None,
    lt_token: syn::token::Lt::default(),
    args,
    gt_token: syn::token::Gt::default(),
  });
  syn::Type::Path(syn::TypePath {
    attrs: Vec::new(),
    qself: None,
    path: syn::Path {
      leading_colon: None,
      segments: core::iter::once(segment).collect(),
    },
  })
}

fn column_of(name: &str, ty: syn::Type) -> Column {
  Column {
    name: ident(name),
    source: ident(name),
    ty,
    project: Projection::Borrowed,
  }
}

fn column(name: &str) -> Column {
  column_of(name, ty("Uuid7"))
}

/// The same model as the source struct would have had without a `pub`.
fn private(mut model: RecordModel) -> RecordModel {
  model.vis = syn::Visibility::Inherited;
  model
}

fn ident(name: &str) -> syn::Ident {
  syn::Ident::new(name, proc_macro2::Span::call_site())
}

/// A one-segment type path, assembled rather than parsed.
fn ty(name: &str) -> syn::Type {
  syn::Type::Path(syn::TypePath {
    attrs: Vec::new(),
    qself: None,
    path: ident(name).into(),
  })
}

/// `::ingraph`, assembled rather than parsed.
fn ingraph_path() -> syn::Path {
  syn::Path {
    leading_colon: Some(syn::token::PathSep::default()),
    segments: core::iter::once(syn::PathSegment::from(ident("ingraph"))).collect(),
  }
}

/// The emission, read back as a file so its items can be inspected one by one — with every
/// CONDITIONAL-EXPANSION GATE opened, as a build carrying that backend would open it.
///
/// A gate is a macro invocation, so `syn` parses one as `Item::Macro` and every walk below would
/// step straight over what it holds. That would not merely lose coverage: it would make the gate a
/// place an unauthorised impl could be written and pass the era rule vacuously. Opening them here is
/// what keeps ONE entry point answering for the whole emission, whatever it is wrapped in.
///
/// [`gated`] is the other half, and the two are not redundant: this reads the emission as though
/// every feature were on, and that one reads it as written and states which items a gate holds.
pub(crate) fn emission(model: &RecordModel) -> syn::File {
  let file: syn::File = syn::parse2(model.emit()).expect("the emission is a parsable file");
  syn::File {
    items: ungate(file.items),
    ..file
  }
}

/// Whether a macro path is one of the framework's feature GATES — `#krate::__private::gate::if_*`.
///
/// Matched on the shelf segment rather than on the leaf's spelling, so a macro the emitter reached
/// through some other shelf module is not silently opened by this walk.
fn is_gate(path: &syn::Path) -> bool {
  path
    .segments
    .iter()
    .skip_while(|segment| segment.ident != "__private")
    .nth(1)
    .is_some_and(|segment| segment.ident == "gate")
}

/// Whether a gate is a COMPLEMENT — `if_no_*`, the half that survives when the feature is OFF.
///
/// A complement's tokens are DISCARDED by the walk below, and that is the walk's own definition
/// rather than a convenience: [`emission`] is what a build with every feature on sees, and in such a
/// build a complement expands to nothing. Opening both halves would report each entry twice — which
/// is exactly what a complementary pair means and exactly what no build ever has.
///
/// The pair shape is the ruled answer to *an attribute cannot be added by a macro that expands to
/// nothing*: the item is written twice, once inside each half. The options spine's `Deserialize`
/// was the first (it never reaches this walk, being emitted from `OptionsSpine`), and the query
/// face's instrumented entries are the first inside a record's own emission.
fn is_complement(path: &syn::Path) -> bool {
  path
    .segments
    .last()
    .is_some_and(|segment| segment.ident.to_string().starts_with("if_no_"))
}

/// Replace every gate invocation with the items it holds, at top level and inside the anonymous
/// const the impls live in — and DROP a complement's, for the reason [`is_complement`] states.
///
/// `pub(crate)` because a derived index's emission now rides a gate pair too, and its own suite
/// reads that emission through the same walk — one opener for every emitter, so a gate cannot become
/// a place an unasserted item hides in whichever suite happens not to open it.
pub(crate) fn ungate(items: Vec<syn::Item>) -> Vec<syn::Item> {
  let mut opened = Vec::with_capacity(items.len());
  for item in items {
    match item {
      syn::Item::Macro(gate) if is_gate(&gate.mac.path) && is_complement(&gate.mac.path) => {}
      syn::Item::Macro(gate) if is_gate(&gate.mac.path) => {
        let held: syn::File = syn::parse2(gate.mac.tokens).expect("a gate holds parsable items");
        opened.extend(ungate(held.items));
      }
      syn::Item::Const(mut anonymous) => {
        if let syn::Expr::Block(block) = &mut *anonymous.expr {
          let statements = core::mem::take(&mut block.block.stmts);
          block.block.stmts = ungate_statements(statements);
        }
        opened.push(syn::Item::Const(anonymous));
      }
      other => opened.push(other),
    }
  }
  opened
}

/// The same walk one level down. A brace-delimited macro inside a block is a `Stmt::Macro` rather
/// than a `Stmt::Item`, which is the whole reason this is written out instead of being the item
/// walk applied twice.
fn ungate_statements(statements: Vec<syn::Stmt>) -> Vec<syn::Stmt> {
  let mut opened = Vec::with_capacity(statements.len());
  for statement in statements {
    match statement {
      syn::Stmt::Macro(gate) if is_gate(&gate.mac.path) && is_complement(&gate.mac.path) => {}
      syn::Stmt::Macro(gate) if is_gate(&gate.mac.path) => {
        let held: syn::File = syn::parse2(gate.mac.tokens).expect("a gate holds parsable items");
        opened.extend(ungate(held.items).into_iter().map(syn::Stmt::Item));
      }
      syn::Stmt::Item(item) => opened.extend(ungate(vec![item]).into_iter().map(syn::Stmt::Item)),
      other => opened.push(other),
    }
  }
  opened
}

/// Every GATED group in the emission AS WRITTEN: which gate, and the trait impls it holds.
///
/// Read off the raw tokens rather than off [`emission`], which has already opened them — the
/// question here is what a build WITHOUT a backend sees, and that is decided by the wrapper and not
/// by its contents.
fn gated(model: &RecordModel) -> Vec<(String, Vec<String>)> {
  fn walk(items: &[syn::Item], into: &mut Vec<(String, Vec<String>)>) {
    for item in items {
      match item {
        syn::Item::Macro(gate) if is_gate(&gate.mac.path) => {
          let held: syn::File =
            syn::parse2(gate.mac.tokens.clone()).expect("a gate holds parsable items");
          let leaf = gate
            .mac
            .path
            .segments
            .last()
            .expect("a path has a last segment")
            .ident
            .to_string();
          let traits = held
            .items
            .iter()
            .filter_map(|item| match item {
              syn::Item::Impl(item) => item
                .trait_
                .as_ref()
                .map(|(path, _)| format!("{} for {}", tight(path), impl_of(item))),
              _ => None,
            })
            .collect();
          into.push((leaf, traits));
        }
        syn::Item::Const(anonymous) => {
          if let syn::Expr::Block(block) = &*anonymous.expr {
            for statement in &block.block.stmts {
              match statement {
                syn::Stmt::Macro(gate) if is_gate(&gate.mac.path) => walk(
                  &[syn::Item::Macro(syn::ItemMacro {
                    attrs: gate.attrs.clone(),
                    ident: None,
                    mac: gate.mac.clone(),
                    semi_token: gate.semi_token,
                  })],
                  into,
                ),
                syn::Stmt::Item(item) => walk(core::slice::from_ref(item), into),
                _ => {}
              }
            }
          }
        }
        _ => {}
      }
    }
  }
  let file: syn::File = syn::parse2(model.emit()).expect("the emission is a parsable file");
  let mut found = Vec::new();
  walk(&file.items, &mut found);
  found
}

fn structs(file: &syn::File) -> Vec<&syn::ItemStruct> {
  file
    .items
    .iter()
    .filter_map(|item| match item {
      syn::Item::Struct(item) => Some(item),
      _ => None,
    })
    .collect()
}

fn names(file: &syn::File) -> Vec<String> {
  structs(file).iter().map(|s| s.ident.to_string()).collect()
}

/// Every TYPE the emission declares, in declaration order.
///
/// Enums as well as structs, because the order-by is one — a walk over [`structs`] alone would pass
/// the enumeration's last entry vacuously. Descending into the const wrapper for the reason
/// [`all_items`] states.
fn declared_types(file: &syn::File) -> Vec<String> {
  all_items(file)
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Struct(item) => Some(item.ident.to_string()),
      syn::Item::Enum(item) => Some(item.ident.to_string()),
      _ => None,
    })
    .collect()
}

/// The types an emission lands in the DECLARING SCOPE — the top-level structs and enums, in order.
///
/// Not [`declared_types`], which descends into the const as well. The difference is the one the
/// COLLISION RULE turns on: a type minted inside the anonymous const is in no scope an author's own
/// name could clash with, so the relation artifacts and the wire face's two carriers are outside
/// this list and outside [`RecordModel::emitted_types`] alike.
fn scoped_types(file: &syn::File) -> Vec<String> {
  file
    .items
    .iter()
    .filter_map(|item| match item {
      syn::Item::Struct(item) => Some(item.ident.to_string()),
      syn::Item::Enum(item) => Some(item.ident.to_string()),
      _ => None,
    })
    .collect()
}

fn fields(item: &syn::ItemStruct) -> Vec<String> {
  named(item)
    .iter()
    .map(|f| f.ident.as_ref().expect("named").to_string())
    .collect()
}

fn named(item: &syn::ItemStruct) -> &syn::punctuated::Punctuated<syn::Field, syn::Token![,]> {
  match &item.fields {
    syn::Fields::Named(named) => &named.named,
    syn::Fields::Unnamed(_) | syn::Fields::Unit => panic!("an emitted type has named fields"),
  }
}

fn documented(attrs: &[syn::Attribute]) -> bool {
  attrs.iter().any(|attr| attr.path().is_ident("doc"))
}

/// Every item the emission declares, DESCENDING into the anonymous const the impls live in.
///
/// A check that walked only `syn::File::items` would find no impl at all now and pass every rule
/// about them vacuously — see `the_impl_walk_descends_into_the_const_wrapper`.
fn all_items(file: &syn::File) -> Vec<&syn::Item> {
  fn walk<'a>(item: &'a syn::Item, into: &mut Vec<&'a syn::Item>) {
    into.push(item);
    if let syn::Item::Const(anonymous) = item
      && let syn::Expr::Block(block) = &*anonymous.expr
    {
      for statement in &block.block.stmts {
        if let syn::Stmt::Item(inner) = statement {
          walk(inner, into);
        }
      }
    }
  }
  let mut items = Vec::new();
  for item in &file.items {
    walk(item, &mut items);
  }
  items
}

fn impls(file: &syn::File) -> Vec<&syn::ItemImpl> {
  all_items(file)
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Impl(item) => Some(item),
      _ => None,
    })
    .collect()
}

/// The INHERENT impls — the ones carrying `new`, the accessors and the mutators.
fn inherent(file: &syn::File) -> Vec<&syn::ItemImpl> {
  impls(file)
    .into_iter()
    .filter(|item| item.trait_.is_none())
    .collect()
}

/// The TRAIT impls, each with the trait it implements.
fn trait_impls(file: &syn::File) -> Vec<(&syn::ItemImpl, &syn::Path)> {
  impls(file)
    .into_iter()
    .filter_map(|item| item.trait_.as_ref().map(|(path, _)| (item, path)))
    .collect()
}

/// Whether a trait path is one of the FRAMEWORK's OWN — `#krate::…`, or `crate::…` from inside it.
///
/// This is the distinction the era rule turns on, and it is decidable: the model carries the
/// framework's own path, so "starts with it" is an exact comparison rather than a guess. `From`
/// and the other `core` traits are not rooted there; `ingraph::Unique` is.
///
/// A path through the shelf's VENDORED segment is rooted at the framework crate and is NOT the
/// framework's own trait: `#krate::__private::sqlx::FromRow` IS `::sqlx::FromRow`, a third-party
/// trait on a third-party release cadence, and the era rule is about this crate's own still-moving
/// trait layer owing consumers a revision. The list is this predicate's one exception — the shelf
/// walk beside it has none at all — and every other name under the crate's root still counts as
/// the framework's.
fn framework_rooted(path: &syn::Path, krate: &syn::Path) -> bool {
  const VENDORED: &[&str] = &["async_graphql", "serde", "sqlx"];
  // `async_graphql` joined the list with the WIRE FACE, and on exactly the stated ground:
  // `#krate::__private::async_graphql::InputType` IS `::async_graphql::InputType`, a third-party
  // trait on a third-party release cadence, where the era rule is about this crate's own still-moving
  // layer owing consumers a revision.
  let segments: Vec<String> = path.segments.iter().map(|s| s.ident.to_string()).collect();
  let root: Vec<String> = krate.segments.iter().map(|s| s.ident.to_string()).collect();
  let rooted =
    segments.first().is_some_and(|first| first == "crate") || segments.starts_with(&root);
  let vendored = segments
    .iter()
    .skip_while(|segment| *segment != "__private")
    .nth(1)
    .is_some_and(|segment| VENDORED.contains(&segment.as_str()));
  rooted && !vendored
}

/// Every FRAMEWORK trait impl an emission declares that this round did not authorise.
///
/// The era rule lifted PER ITEM rather than wholesale, so the check is an ALLOWLIST rather than an
/// emptiness: one trait, on one self type, with one shape of argument. Anything else — another
/// framework trait, the authorised trait on the wrong type, or the right pair carrying a storage
/// type no declared database names — is still refused, and refused by this one predicate wherever
/// the walk runs.
fn unauthorised_framework_impls(model: &RecordModel, file: &syn::File) -> Vec<String> {
  trait_impls(file)
    .into_iter()
    .filter(|(_, path)| framework_rooted(path, &model.krate))
    .filter(|(item, path)| !authorised(model, item, path))
    .map(|(item, path)| format!("{} for {}", tight(path), impl_of(item)))
    .collect()
}

/// The TWENTY-FOUR framework trait impls this round emits: `ToDatabaseComparison<Row, Db>` on the
/// record's own filter, keyed on a row a declared database really stores; `ComplexComparison<Db>`
/// on a comparison that same model names; `Transformer` on the RECORD; `Record<Db>` on the
/// record, once per declared database, naming that database's own comparison; `Related<Target>` on
/// the record, for a target one of the model's OWN `ref` fields names; `Reference` on an
/// artifact the emitter mints for one of those fields; `Identifiable` TWICE, on the record and on
/// the `*Key` the model names; `KeySegments` on that same `*Key`; `Graphql` on the
/// record; and `GraphqlInput`/`GraphqlOutput`, each on the carrier the emitter mints for that half.
///
/// The first two are one allowlist rather than two rules because they are one obligation. The map's
/// associated type carries an item bound — `Comparison: ComplexComparison<Db>` — so an expansion
/// that writes the map must write the lowering or the map is not well formed. Authorising the first
/// and refusing the second would refuse the emission its own bound demands.
///
/// The third is admitted on a different ground: what it binds is the emission's own output — the
/// `*Key`, the `*Lineage` and the id column's declared type — so it names nothing that could settle
/// differently later. It takes no argument, which is why it is matched on the shelf path and the
/// self type alone.
///
/// The fourth stands on the SAME ground as the third, one step on: `Record` is the settled
/// vocabulary the entity binding's row-form member answers, and what an impl of it binds is the
/// `<Row>Comparison` this emission also declares. Its argument is the CONCRETE backend, which is
/// the declaration's own choice of database rather than a consumer type — and the one place the
/// emission names one, which is why the check reads the backend as well as the comparison.
///
/// The fifth and sixth are one obligation for the first two's reason: the pairing is the evidence a
/// reverse declaration reads, and its `Fields` names the artifacts — so an expansion writing the
/// pairing must write their marker impls or the pairing names types that answer nothing.
///
/// The seventh and eighth are ONE TRAIT on two self types, and they are two entries because this
/// list is pairs rather than traits. `Identifiable` is the third's supertrait, so an expansion that
/// writes the entity binding must write it or the binding is not well formed; what it binds is one
/// member of what the third already binds. The RECORD's impl and the `*KEY`'s are both authorised
/// and nothing else is — the `*Lineage` in particular is refused here, as a chain of ancestors has
/// no one id.
///
/// The ninth is the `*Key`'s SECOND impl: `KeySegments`, the filesystem blob store's key
/// requirement, whose walk is the key's own columns in the key's own order. It stands on the
/// third's ground — the self type is the emission's, the sink is the framework's, and nothing else
/// is named — and it is keyed on the `*Key` alone: the record answers no address of its own and the
/// `*Lineage` is refused here for the reason it is refused above.
///
/// The ORDER used to be a tenth entry — `Orderable` on the record, a second impl under a second
/// condition. It is retired: the order is a MEMBER of `Record<Db>` now, so the fourth entry
/// authorises it along with the row and the comparison, and there is no separate pair for this list
/// to carry. One storability fact, stated once.
///
/// The tenth, eleventh and twelfth are the WIRE FACE, and they are one obligation for the
/// fifth and sixth's reason: `Graphql`'s two members are CARRIERS this emission mints, so an
/// expansion writing the face must write their impls or the face names types that answer nothing.
/// Two of the three are keyed on those carriers rather than on the record, and the names come from
/// the EMITTER for the reason [`database_parameter`] does.
///
/// The fourteenth is `Implements<Interface>`, on the RECORD, and it stands on the fifth and sixth's
/// ground alone: a membership is declared in TWO derives that cannot see each other, so this impl
/// is the only way an interface's expansion can know its member agreed. What it binds is a path the
/// declaration itself wrote, and it carries nothing — a relation needs the referring fields crossing
/// that boundary, and a membership needs only the fact.
///
/// The fifteenth is `ToSubjectPath`, on the ORDER-BY, and it is the first entry whose self type is
/// neither the record, its key, nor a carrier the wire face mints. It stands on the third's ground:
/// what it binds is the emission's own output — one path per variant, built from the RECORD FIELD's
/// name, which is the identity `identity` already answers with and which no `<db>(rename)`
/// moves — so it names nothing that could settle differently later. The trait takes no argument,
/// which is why this arm reads the shelf path and the self type alone; the ORDER-BY's name is a
/// `graphql(…)` block's to rename, so it comes from the model like every other name here.
///
/// The sixteenth through twentieth are the TOPOLOGY family, and they stand on the third's ground
/// with one addition of its own: `Emits<N>` and `SoleProduct` are how a node states what it puts on
/// an edge, which is the ONE fact a downstream declaration cannot read for itself — the fifth and
/// sixth's argument, at the other end of the edge. `Emits` is admitted at ANY index, because the
/// index is the product's position in the declaration's own `emits` list; `SoleProduct` carries
/// no argument at all. `Products` and `ProductKind` are on the product sum and its vocabulary, both
/// of which this emission declares, and `Sink<Out>` is on the DOWNSTREAM it declares beside them —
/// checked at that `Out` as well as at the self type, so routing bound to another node's products
/// is refused exactly as a twenty-first trait would be.
///
/// The TWENTY-FIRST is `Declared`, on the RECORD, and it is the one entry whose ground is neither
/// the third's nor the fifth's: what it binds is nothing at all — an effect, a lane, a table of
/// upstreams and an options path — but the party that READS it is outside this declaration. A graph
/// root sees a field's type and nothing else, so a node's own facts have to reach it as an impl or
/// the root's entry can name none of them. It carries no argument, so the check is the shelf path
/// and the self type.
///
/// The TWENTY-THIRD is `Describe<Db>`, on the RECORD, and it stands on the FOURTH's ground with the
/// fourth's own argument: the SCHEMA is what the row's `SqlQuery::ADDRESS` and `COLUMNS` already
/// state, read through the emission's own row type with a `StoredAs` word beside each field, at the
/// CONCRETE backend this declaration named. Nothing in it is a consumer type and nothing is a name
/// this expansion invents — an edge table's is derived by the renderer and a companion column's is
/// the one mint the write plan beside it reads. So the check is the vocabulary's: the record as the
/// self type, and a backend a declared database really is.
///
/// The TWENTY-SECOND is `ToGraphqlInput`, on the `*KEY`, and it stands on the ninth's ground: the
/// self type is the emission's own, what it binds is either the ID COLUMN's declared type (a root's
/// address IS its id, so its wire form is that type's own) or the argument object this same
/// expansion declares beside it. Nothing else is named, and the record and the `*Lineage` are
/// refused here exactly as they are one arm up — a record is not an address and a chain of
/// ancestors is not one either.
///
/// The TWENTY-FOURTH is `Attributes<Record>`, on the FRAMEWORK's own `RootProjection<Record>` — the
/// one entry in this list whose self type is neither the record, its key, nor a carrier the wire
/// face mints, but a zero-sized seat the framework itself declares for exactly this. Its ground is
/// the twenty-first's: what it binds is read by a party OUTSIDE this declaration, the root-key
/// registry, and every record gets one unconditionally the moment it has a key — so there is no
/// word to check the model for, only the two places the emission writes the record itself: the
/// trait's own argument, and `RootProjection`'s.
///
/// Every self type is checked against the MODEL rather than against a spelling, so an impl that
/// named some other type — a row belonging to another record, a lowering on the row instead of on
/// its comparison, a binding on the key instead of on the record, an identity or a path walk on the
/// lineage, or a pairing at a target this declaration never named — is refused rather than passing
/// on a name that merely looks right.
fn authorised(model: &RecordModel, item: &syn::ItemImpl, path: &syn::Path) -> bool {
  let shelved: Vec<String> = path
    .segments
    .iter()
    .skip_while(|segment| segment.ident != "__private")
    .skip(1)
    .map(|segment| segment.ident.to_string())
    .collect();
  let filter = model
    .graphql
    .as_ref()
    .map(|graphql| graphql.filter.safe().to_string());
  let databases = || model.persist.iter().flat_map(|persist| &persist.backends);
  let rows: Vec<String> = databases()
    .map(|database| database.name().to_string())
    .collect();
  // The lowering's self type carries the database parameter, so it is matched on the comparison's
  // NAME with the parameter written after it — a bare name would admit a lowering on some other
  // generic type of the same stem.
  let comparisons: Vec<String> = databases()
    .map(|database| format!("{}<{}>", database.comparison_name(), database_parameter()))
    .collect();
  // The vocabulary's argument is the CONCRETE backend, and each declared database's spelling of one
  // is read from the EMITTER rather than restated here — the reason [`database_parameter`] gives.
  let backends: Vec<String> = databases()
    .map(|database| tight(database.backend_type(model)))
    .collect();
  let map = shelved == ["comparison", "ToDatabaseComparison"]
    && filter.is_some_and(|filter| impl_of(item) == filter)
    && storage_argument(path).is_some_and(|storage| rows.contains(&storage));
  let lowering =
    shelved == ["comparison", "ComplexComparison"] && comparisons.contains(&impl_of(item));
  let binding = shelved == ["transform", "Transformer"] && model.record == impl_of(item);
  // The wire face and its two halves. The OBJECT names come from the MODEL, as every other name
  // here does: they are renameable, and a list kept in this file would agree with a name the
  // emission no longer writes.
  let wire = shelved == ["transform", "Graphql"] && model.record == impl_of(item);
  let half = |member: &str, name: Option<&RustSafeName>| {
    shelved == ["transform", member] && name.is_some_and(|name| *name.safe() == impl_of(item))
  };
  let wire_input = half("GraphqlInput", model.graphql.as_ref().map(|g| &g.input));
  let wire_output = half("GraphqlOutput", model.graphql.as_ref().map(|g| &g.output));
  // The id capability's two self types, read off the MODEL like every other arm: the record it is
  // declared on, and the key name the model carries — which is the convention's or an author's
  // rename, already settled there.
  let identity = shelved == ["transform", "Identifiable"]
    && (model.record == impl_of(item) || model.key.name == impl_of(item));
  // The path walk's ONE self type, read off the model the same way: the key, and never the record
  // or the lineage — a record has no address of its own and a chain of ancestors is not one.
  let address = shelved == ["store", "KeySegments"] && model.key.name == impl_of(item);
  // The address's INWARD crossing, on the `*Key` alone — read off the model like the two arms above
  // it, and refused on the record and on the lineage for their reason: a record is not an address
  // and a chain of ancestors is not one either.
  let sent_address = shelved == ["graphql", "ToGraphqlInput"] && model.key.name == impl_of(item);
  let vocabulary = shelved == ["transform", "Record"]
    && model.record == impl_of(item)
    && storage_argument(path).is_some_and(|backend| backends.contains(&backend));
  let referred = || {
    model
      .fields
      .iter()
      .filter_map(|field| field.reference.as_ref())
  };
  let pairing = shelved == ["transform", "Related"]
    && model.record == impl_of(item)
    && storage_argument(path)
      .is_some_and(|target| referred().any(|reference| tight(&reference.target) == target));
  // The artifact NAMES come from the emitter, for the reason `database_parameter` does: a list kept
  // here would agree with a name the emission no longer writes.
  // The MEMBERSHIP evidence, keyed on an interface the model's own `implements(…)` really names —
  // so an impl at an interface this declaration never agreed to is refused exactly as a fourteenth
  // trait would be.
  let membership = shelved == ["transform", "Implements"]
    && model.record == impl_of(item)
    && storage_argument(path).is_some_and(|interface| {
      model
        .implements
        .iter()
        .any(|declared| tight(declared) == interface)
    });
  let artifact = shelved == ["transform", "Reference"]
    && model
      .fields
      .iter()
      .filter(|field| field.reference.is_some())
      .any(|field| model.artifact(&field.column.source) == impl_of(item));
  // The WIRE's reading of the identity, keyed on the ORDER-BY — the one self type in this list that
  // is neither the record, nor its key, nor a carrier the wire face mints. The name is the MODEL's,
  // as every other name here is, because the `graphql(…)` block may rename it.
  let subject = shelved == ["graphql", "ToSubjectPath"] && *model.order_by.safe() == impl_of(item);
  // The TOPOLOGY family, each keyed on a self type this emission also declares — the record for
  // what it emits, the product sum and its vocabulary for the link a body reads the connection
  // state through, and the downstream for the routing itself. The names come from the MODEL, as
  // every other name here does.
  let emits = shelved.first().is_some_and(|module| module == "operator")
    && shelved.get(1).is_some_and(|name| name == "Emits")
    && model.record == impl_of(item);
  let sole = shelved == ["operator", "SoleProduct"] && model.record == impl_of(item);
  let products =
    shelved == ["operator", "Products"] && default_out_name(&model.record) == impl_of(item);
  let vocabulary_of_products =
    shelved == ["operator", "ProductKind"] && default_out_kind_name(&model.record) == impl_of(item);
  let routing = shelved == ["drive", "Sink"]
    && default_downstream_name(&model.record) == impl_of(item)
    && storage_argument(path).is_some_and(|out| default_out_name(&model.record) == out);
  // The FACTS, on the record — the twenty-first, and the only one whose reason is a party OUTSIDE
  // this declaration. It takes no argument, so the shelf path and the self type are the whole check.
  let facts = shelved == ["drive", "Declared"] && model.record == impl_of(item);
  // The SCHEMA, on the record — read at the backend exactly as the vocabulary one arm up is, since
  // the argument is the same concrete dialect and a blueprint at a database this declaration never
  // named would be as wrong as a vocabulary row at one.
  let blueprint = shelved == ["schema", "Describe"]
    && model.record == impl_of(item)
    && storage_argument(path).is_some_and(|backend| backends.contains(&backend));
  // The ROOT PROJECTION, on the FRAMEWORK's own `RootProjection<Record>` rather than on the record
  // — the one entry in this list whose self type is not the emission's own. The record still names
  // it, twice over: once as the trait's own argument, checked like every other argument here, and
  // once as `RootProjection`'s, read off the same path builder the emitter's own `root_projection`
  // calls so this file never restates a shelf name the emitter could move.
  let projection = crate::emit::framework(&model.krate, &["drive"], "RootProjection");
  let record = &model.record;
  let attribution = shelved == ["drive", "Attributes"]
    && storage_argument(path).is_some_and(|root| model.record == root)
    && impl_of(item) == tight(quote::quote!(#projection<#record>));
  map
    || blueprint
    || lowering
    || binding
    || wire
    || wire_input
    || wire_output
    || identity
    || address
    || sent_address
    || vocabulary
    || pairing
    || artifact
    || membership
    || subject
    || emits
    || sole
    || products
    || vocabulary_of_products
    || routing
    || facts
    || attribution
}

/// The database parameter's emitted NAME, taken from the emitter rather than restated.
///
/// Restating it would make this file agree with a name the emitter no longer writes, which is the
/// one failure a shape check cannot survive: the assertions below would pass against a parameter
/// spelled anything at all.
fn database_parameter() -> String {
  crate::emit::parameter("DB").to_string()
}

/// The first generic argument of a trait path — `V` in `ToDatabaseComparison<V, Db>`.
fn storage_argument(path: &syn::Path) -> Option<String> {
  let syn::PathArguments::AngleBracketed(arguments) = &path.segments.last()?.arguments else {
    return None;
  };
  arguments.args.iter().find_map(|argument| match argument {
    syn::GenericArgument::Type(ty) => Some(tight(ty)),
    _ => None,
  })
}

fn methods(item: &syn::ItemImpl) -> Vec<&syn::ImplItemFn> {
  item
    .items
    .iter()
    .filter_map(|item| match item {
      syn::ImplItem::Fn(item) => Some(item),
      _ => None,
    })
    .collect()
}

/// Every INHERENT method name an emission declares, in declaration order.
fn method_names(file: &syn::File) -> Vec<String> {
  inherent(file)
    .iter()
    .flat_map(|item| methods(item))
    .map(|method| method.sig.ident.to_string())
    .collect()
}

/// The methods of the KEY's own impl — the first one emitted.
fn key_methods(file: &syn::File) -> Vec<&syn::ImplItemFn> {
  methods(inherent(file)[0])
}

/// The name of the type an impl is FOR.
fn impl_of(item: &syn::ItemImpl) -> String {
  tight(&item.self_ty)
}

/// The type an impl is for, by NAME alone — a comparison's self type carries the database
/// parameter, and [`RecordModel::emitted_methods`] names types rather than spelling them.
fn owner_of(item: &syn::ItemImpl) -> String {
  match &*item.self_ty {
    syn::Type::Path(path) => path
      .path
      .segments
      .last()
      .expect("a path has a last segment")
      .ident
      .to_string(),
    other => panic!("an inherent impl is for a named type: {}", tight(other)),
  }
}

/// The methods of the impl on a named type, in declaration order.
fn methods_of(file: &syn::File, name: &str) -> Vec<String> {
  inherent(file)
    .into_iter()
    .filter(|item| impl_of(item) == name)
    .flat_map(methods)
    .map(|method| method.sig.ident.to_string())
    .collect()
}

fn method_of<'a>(file: &'a syn::File, type_name: &str, name: &str) -> &'a syn::ImplItemFn {
  inherent(file)
    .into_iter()
    .filter(|item| impl_of(item) == type_name)
    .flat_map(methods)
    .find(|method| method.sig.ident == name)
    .unwrap_or_else(|| panic!("`{type_name}::{name}` is emitted"))
}

fn returns(method: &syn::ImplItemFn) -> String {
  match &method.sig.output {
    syn::ReturnType::Type(_, ty) => tight(ty),
    syn::ReturnType::Default => "()".to_owned(),
  }
}

fn key_method<'a>(file: &'a syn::File, name: &str) -> &'a syn::ImplItemFn {
  key_methods(file)
    .into_iter()
    .find(|method| method.sig.ident == name)
    .unwrap_or_else(|| panic!("`{name}` is emitted"))
}

fn is_const(method: &syn::ImplItemFn) -> bool {
  method.sig.constness.is_some()
}

fn returns_reference(method: &syn::ImplItemFn) -> bool {
  matches!(&method.sig.output, syn::ReturnType::Type(_, ty) if matches!(**ty, syn::Type::Reference(_)))
}

fn must_use(method: &syn::ImplItemFn) -> bool {
  method
    .attrs
    .iter()
    .any(|attr| attr.path().is_ident("must_use"))
}

/// Tokens with their spacing removed, so a comparison is about content rather than layout.
fn tight(tokens: impl ToTokens) -> String {
  tokens.to_token_stream().to_string().replace(' ', "")
}

/// The text of an item's `#[doc]` attributes, joined.
fn docs(attrs: &[syn::Attribute]) -> String {
  attrs
    .iter()
    .filter(|attr| attr.path().is_ident("doc"))
    .map(|attr| tight(&attr.meta))
    .collect()
}

#[test]
fn a_grandchild_emits_a_key_and_a_lineage() {
  assert_eq!(
    names(&emission(&video_track())),
    ["TrackAddress", "TrackScope"],
    "the fixture renames both, so this doubles as the proof that a rename reaches emission"
  );
}

/// Names come from the MODEL, never from the emitter's own idea of the convention — one model,
/// renamed and not, emitting both ways.
#[test]
fn the_emitter_uses_the_models_names_not_the_convention() {
  let conventional = model("VideoTrack", &["media_id", "video_id"], "id");
  assert_eq!(
    names(&emission(&conventional)),
    ["VideoTrackKey", "VideoTrackLineage"]
  );
  assert_eq!(
    names(&emission(&video_track())),
    ["TrackAddress", "TrackScope"]
  );
}

#[test]
fn the_key_lays_out_lineage_root_first_then_the_id() {
  let file = emission(&video_track());
  assert_eq!(
    fields(structs(&file)[0]),
    ["media_id", "video_id", "id"],
    "flat, and in exactly that order — root attribution reads the leading column and prefix \
     deletes range-scan it"
  );
  assert_eq!(
    fields(structs(&file)[1]),
    ["media_id", "video_id"],
    "the lineage type is the path without the id"
  );
}

#[test]
fn a_root_emits_a_key_and_no_lineage_type_at_all() {
  let file = emission(&media());
  assert_eq!(names(&file), ["MediaKey"], "absence by omission");
  assert_eq!(fields(structs(&file)[0]), ["id"]);
}

#[test]
fn a_child_carries_its_one_parent() {
  let file = emission(&video());
  assert_eq!(names(&file), ["VideoKey", "VideoLineage"]);
  assert_eq!(fields(structs(&file)[0]), ["media_id", "id"]);
  assert_eq!(fields(structs(&file)[1]), ["media_id"]);
}

/// The ONE-STORAGE MARKER: minted by the kind that stores, at MODULE SCOPE, under the name the
/// naming authority computes.
///
/// All three facts are the mechanism rather than decoration. The SCOPE is what makes a second
/// storage derive's marker collide at all — two of them inside two anonymous consts would be two
/// items in two scopes and no collision — and the NAME is what two derives that cannot see each
/// other have to agree on, which is why it is asserted against [`one_storage_marker`] rather than
/// against a spelling written out here.
#[test]
fn a_storage_node_mints_the_one_storage_marker_at_module_scope() {
  let file = emission(&media());
  let minted: Vec<String> = file
    .items
    .iter()
    .filter_map(|item| match item {
      syn::Item::Const(named) => Some(named.ident.to_string()),
      _ => None,
    })
    .filter(|name| name != "_")
    .collect();
  assert_eq!(
    minted,
    [one_storage_marker(&EmissionPrefix::default(), &ident("Media")).to_string()],
    "one marker, named by the authority both derives read"
  );
}

/// **THE SEAT MOVES A WHOLE EXPANSION**: a model built under a platform's own mark wears it on
/// every name this emission puts in the declarer's scope, and wears `ingraph`'s on none of them.
///
/// The negative half is the assertion that matters. A test that only checked the new spelling would
/// pass on a mint that had been threaded and a mint that had not, since both would be present.
#[test]
fn a_platform_mark_moves_every_name_the_record_mints() {
  let mut model = media();
  model.prefix = EmissionPrefix::new("__mg");
  let rendered = prettyplease::unparse(&emission(&model));

  assert!(
    rendered.contains(&one_storage_marker(&model.prefix, &ident("Media")).to_string()),
    "the storage marker is minted under the model's own mark",
  );
  assert!(
    !rendered.contains("__ig_Media_holds_one_storage"),
    "and `ingraph`'s spelling of it is nowhere in the expansion",
  );
}

/// The injected LINEAGE field, moved the same way — the second of the two names a framework writes
/// into a declaration's own struct.
#[test]
fn a_platform_mark_moves_the_injected_lineage_field() {
  let rendered = prettyplease::unparse(&emission(&fanned_under(EmissionPrefix::new("__mg"))));
  assert!(
    rendered.contains("__mg_lineage__"),
    "the injected field wears the platform's mark"
  );
  assert!(
    !rendered.contains("__ig_lineage__"),
    "and nothing in the expansion still spells `ingraph`'s",
  );
}

/// **MIXED GRAPHS**: two declarations under two marks, expanded in one build, keep their own names.
///
/// Emitted SEPARATELY and read together, which is what a deployment holding both frameworks'
/// records actually is — nothing in either expansion is entitled to assume a single mark, and the
/// proof is that neither expansion holds the other's spelling of a SEATED name.
///
/// SEATED is the word doing the work, and the negative assertions name their strings rather than
/// scanning for a bare `__ig_`. The hygienic-local mints — `__ig_says_goodbye` and the rest — are
/// deliberately outside the seat (see [`crate::prefix`]), so a blanket scan would be asserting the
/// opposite of the ruling and would fail the day one of these fixtures grew a `teardown`.
#[test]
fn two_frameworks_declarations_stand_beside_each_other() {
  let ingraph = prettyplease::unparse(&emission(&fanned()));

  let mut platform = media();
  platform.prefix = EmissionPrefix::new("__mg");
  let platform = prettyplease::unparse(&emission(&platform));

  assert!(ingraph.contains("__ig_lineage__"), "{ingraph}");
  assert!(!ingraph.contains("__mg_lineage__"), "{ingraph}");

  assert!(
    platform.contains("__mg_Media_holds_one_storage"),
    "{platform}"
  );
  assert!(
    !platform.contains("__ig_Media_holds_one_storage"),
    "{platform}"
  );
}

/// The DEFAULT is unmoved, and this is the assertion that says so directly rather than by the
/// absence of a diff: a model that names no mark expands under `ingraph`'s, whatever the seat is
/// capable of.
#[test]
fn a_model_that_names_no_mark_expands_exactly_as_before() {
  assert!(
    prettyplease::unparse(&emission(&fanned())).contains("__ig_lineage__"),
    "the injected lineage field is where it always was",
  );
  assert!(
    prettyplease::unparse(&emission(&media())).contains("__ig_Media_holds_one_storage"),
    "and so is the storage marker",
  );
}

/// The SUBSCRIPTION audit: the declared path, emitted under a bound, inside an anonymous const.
///
/// The path is asserted VERBATIM because the whole mechanism is that the derive resolves nothing —
/// it hands the string's path to rustc, which resolves it where it lands. An emission that
/// normalised or re-rooted it would be answering a question this layer cannot see.
#[test]
fn a_subscriber_emits_its_upstream_under_a_node_bound() {
  let mut model = media();
  model.subscribe = Some(syn::parse_quote!(asr::TranscriptSegment));
  let rendered = prettyplease::unparse(&emission(&model));
  // The bound is read off the AUDIT'S OWN function and not off the emission at large: every record
  // names `Transformer` anyway, in the entity binding, so a substring test for the trait alone
  // passes with the bound deleted. Measured — that mutation is one of this round's, and this
  // assertion is what it moved.
  assert!(
    rendered.contains(
      "fn __ig_subscribes_to<\n            __INGRAPH_UPSTREAM__: ::ingraph::__private::transform::Transformer,\n        >()"
    ),
    "the bound says what a subscribe target has to BE: {rendered}"
  );
  assert!(
    rendered.contains("__ig_subscribes_to::<asr::TranscriptSegment>"),
    "and the path is handed over exactly as written: {rendered}"
  );
}

/// A node driven by nothing emits no audit at all — absence by omission, which is the shape every
/// optional member of this model uses.
#[test]
fn a_node_that_subscribes_to_nothing_emits_no_audit() {
  assert!(
    !prettyplease::unparse(&emission(&media())).contains("__ig_subscribes_to"),
    "no upstream, no audit"
  );
}

/// The GOODBYE audit: the word said the value has something to await, and this is what makes the
/// word cost something at the declaration rather than at the first shutdown.
#[test]
fn a_node_that_opted_into_the_goodbye_emits_it_under_a_teardown_bound() {
  let mut model = media();
  model.teardown = true;
  let rendered = prettyplease::unparse(&emission(&model));
  // Read WHITESPACE-STRIPPED, which is how every other token assertion in this tree reads: the
  // bound's own path crossed prettyplease' line budget when the trait gained its `Async` prefix, so
  // the one-line spelling became `fn __ig_says_goodbye<\n    __INGRAPH_NODE__: …,\n>()`. What is
  // pinned is the BOUND, and a formatter's wrap column is no part of it.
  let compact: String = rendered.chars().filter(|c| !c.is_whitespace()).collect();
  assert!(
    compact
      .contains("fn__ig_says_goodbye<__INGRAPH_NODE__:::ingraph::__private::drive::AsyncTeardown"),
    "the bound is what the word buys: {rendered}"
  );
  assert!(
    rendered.contains("__ig_says_goodbye::<Media>"),
    "and it is demanded of the declared type itself: {rendered}"
  );
}

/// A declaration that wrote no `teardown` emits no audit — absence by omission, and `Drop` is what
/// tears such a value down.
#[test]
fn a_node_torn_down_by_drop_emits_no_goodbye_audit() {
  assert!(
    !prettyplease::unparse(&emission(&media())).contains("__ig_says_goodbye"),
    "no word, no audit"
  );
}

/// A FUSING node reaches the same audit, once per upstream — the claim *this path names a node* is
/// the same claim however many upstreams a declaration writes, so one spelling of it serves both.
#[test]
fn every_upstream_of_a_fusion_reaches_the_subscription_audit() {
  let rendered = prettyplease::unparse(&emission(&fused()));
  for upstream in ["media::Frame", "asr::Segment"] {
    assert!(
      rendered.contains(&format!("__ig_subscribes_to::<{upstream}>")),
      "the upstream that is not the parent is still an upstream: {rendered}"
    );
  }
}

/// The KEY-PARENT EQUATION: the parent's key in, this node's lineage out, written as a struct
/// literal so each half of the claim fails separately and by name.
///
/// The parent's path is asserted VERBATIM for the subscription audit's reason — this layer resolves
/// nothing — and the MAPPING is asserted per column, because a same-name mirror and a diverging one
/// are the two shapes the ruled grammar has.
#[test]
fn a_fusion_emits_the_equation_its_lineage_is_checked_by() {
  let rendered = prettyplease::unparse(&emission(&fused()));
  assert!(
    rendered.contains(
      "fn(\n        <media::Frame as ::ingraph::__private::transform::Transformer>::Key,\n    ) -> VideoLineage"
    ),
    "the parent's key in, this node's lineage out: {rendered}"
  );
  assert!(
    rendered.contains("media_id: __ingraph_key.frame"),
    "a diverging mirror reads the parent field it was mapped onto: {rendered}"
  );
}

/// **A FAN-IN's LINEAGE IS AN ENUM**, one variant per upstream, each carrying that upstream's WHOLE
/// key — so a row's ancestry is exactly the address of the message it came from.
///
/// The payload is a PROJECTION for the subscription audit's reason: this layer resolves nothing, so
/// the compiler reads `<asr::Segment as Transformer>::Key` where the declaration wrote the string.
#[test]
fn a_fan_ins_lineage_is_a_choice_among_its_upstreams() {
  let rendered = prettyplease::unparse(&emission(&fanned()));
  assert!(
    rendered.contains("pub enum VideoLineage"),
    "the ancestry is a choice, not a path: {rendered}"
  );
  for (variant, node) in [("Frame", "media::Frame"), ("Segment", "asr::Segment")] {
    assert!(
      rendered.contains(&format!(
        "{variant}(<{node} as ::ingraph::__private::transform::Transformer>::Key)"
      )),
      "each variant carries that upstream's whole key: {rendered}"
    );
  }
  assert!(
    !rendered.contains("impl VideoLineage"),
    "an enum is built by naming a variant and read by matching on one — no constructor, no \
     accessors: {rendered}"
  );
}

/// The KEY's leading column is that choice, and the conversion reads it out of the INJECTED field —
/// which is the one place the mint and its reader have to agree.
#[test]
fn a_fan_ins_key_leads_with_the_choice_it_was_injected_with() {
  let model = fanned();
  let rendered = prettyplease::unparse(&emission(&model));
  assert!(
    rendered.contains("pub(crate) lineage: VideoLineage"),
    "the key column takes a name an address can be spelled with: {rendered}"
  );
  assert!(
    rendered.contains("lineage: record.__ig_lineage__"),
    "and it is read out of the field the echo appended: {rendered}"
  );
  assert_eq!(
    model
      .fanned_lineage()
      .map(|field| quote::ToTokens::to_token_stream(&field).to_string()),
    Some("pub (crate) __ig_lineage__ : VideoLineage".to_owned()),
    "the mint the echo appends, spelled where it is read back"
  );
}

/// **THE ADDRESS GROWS A VARIANT LEVEL.** A choice is not a column the id vocabulary can render, so
/// the key WALKS into it rather than pushing it, and the choice pushes the upstream's own WORD
/// before that upstream's key walks itself.
///
/// The word rather than a tag: one vocabulary across every place a discriminant is spelled, so a
/// stored artifact is findable from the declaration a reader has in front of them.
#[test]
fn a_fan_ins_address_grows_a_variant_level() {
  let rendered = prettyplease::unparse(&emission(&fanned()));
  assert!(
    rendered.contains("impl ::ingraph::__private::store::KeySegments for VideoLineage"),
    "the choice walks itself: {rendered}"
  );
  assert!(
    rendered.contains("out.push_word(\"Frame\");"),
    "the variant's own word is a segment: {rendered}"
  );
  assert!(
    rendered.contains(
      "::ingraph::__private::store::KeySegments::segments(&self.lineage, out);\n            out.push(&self.id);"
    ),
    "and the key walks the choice, then pushes its own id: {rendered}"
  );
}

/// And a node that designates no parent emits no equation — the same absence by omission the audit
/// above uses.
#[test]
fn a_node_that_designates_no_parent_emits_no_equation() {
  assert!(
    !prettyplease::unparse(&emission(&video())).contains("__ingraph_key"),
    "no designation, no equation"
  );
}

/// And a node holding no storage mints none: with nothing to hold, it has no second storage to make
/// unspellable.
#[test]
fn a_node_with_no_storage_mints_no_marker() {
  let mut model = media();
  model.kind = NodeKind::Operator;
  let file = emission(&model);
  assert!(
    !all_items(&file)
      .iter()
      .any(|item| matches!(item, syn::Item::Const(named) if named.ident != "_")),
    "an operator's emission carries no named const at all"
  );
}

/// The entity binding names the emission's OWN types, and a root binds `()` where it has no
/// lineage type to name — the same absence [`a_root_emits_a_key_and_no_lineage_type_at_all`]
/// asserts, seen from the binding's side.
///
/// The renamed model is on the roster because a binding that reached for the convention rather than
/// the model would still pass on the other two.
#[test]
fn the_address_binding_names_the_emitted_types() {
  for (model, lineage) in [
    (video_track(), "TrackScope"),
    (video(), "VideoLineage"),
    (media(), "()"),
  ] {
    let file = emission(&model);
    let bound = binding(&file);
    assert_eq!(impl_of(bound), model.record.to_string(), "on the RECORD");
    assert_eq!(associated(bound, "Key"), model.key.name.to_string());
    assert_eq!(associated(bound, "Lineage"), lineage);
  }
}

/// The ID CAPABILITY is bound TWICE and on exactly two types: the record, and the key that addresses
/// it. Both name the id column's declared type.
///
/// The `*Lineage` is the absence asserted here, and it is a claim rather than an oversight — a path
/// from the root is a chain of ancestors' ids, and no single one of them addresses the row — so a
/// third impl appearing would be caught by the count, not merely by the era rule that would also
/// admit it.
///
/// The renamed model is on the roster for [`the_address_binding_names_the_emitted_types`]' reason:
/// a walk reaching for the convention's `VideoTrackKey` rather than for the model's `TrackAddress`
/// would still pass on the other two.
#[test]
fn the_id_capability_is_bound_on_the_record_and_on_its_key() {
  for model in [video_track(), video(), media()] {
    let file = emission(&model);
    let identities: Vec<(String, String)> = trait_impls(&file)
      .into_iter()
      .filter(|(_, path)| {
        path
          .segments
          .last()
          .is_some_and(|segment| segment.ident == "Identifiable")
      })
      .map(|(item, _)| (impl_of(item), associated(item, "Id")))
      .collect();
    let id = tight(&model.key.id.ty);
    assert_eq!(
      identities,
      [
        (model.record.to_string(), id.clone()),
        (model.key.name.to_string(), id)
      ],
      "the record and its key, each binding the id column's declared type verbatim — an alias \
       stays an alias — and nothing else identified"
    );
  }
}

/// The KEY's PATH WALK: one push per column, in the key's own order — the lineage root-first and
/// the id last, because that order IS the directory tree the filesystem blob store nests. The
/// parents are the directories and the id is the file.
///
/// A ROOT pushes ONE segment, and no branch here says so: a root's whole key is its id, so the same
/// walk over the same iterator produces a one-segment address.
///
/// Every push is BY REFERENCE and by the KEY's field name, which is why the roster carries a model
/// whose key renames a lineage step: a walk reading the record's source names instead would emit a
/// field the `*Key` does not have, and one reading them in declaration order off the record would
/// put the id wherever the declaration happened to write it.
///
/// The mutation this exists for is an id-first walk. Nothing else in the emission would notice —
/// the impl would still be authorised, still be on the right type, and still compile — and every
/// blob a declaration ever wrote would live one level from the lineage that was supposed to nest
/// it.
#[test]
fn the_key_walks_its_columns_root_first() {
  let mut renamed = video_track();
  renamed.key.path[1].name = ident("video");
  for (model, pushes) in [
    (video_track(), ["media_id", "video_id", "id"].as_slice()),
    (renamed, ["media_id", "video", "id"].as_slice()),
    (video(), ["media_id", "id"].as_slice()),
    (media(), ["id"].as_slice()),
  ] {
    let file = emission(&model);
    let walk = path_walk(&file);
    assert_eq!(impl_of(walk), model.key.name.to_string(), "on the KEY");
    let expected: Vec<String> = pushes
      .iter()
      .map(|column| format!("out.push(&self.{column});"))
      .collect();
    assert_eq!(statements(walk), expected);
  }
}

/// The key's path walk — the trait impl whose shelf path ends at `KeySegments`.
fn path_walk(file: &syn::File) -> &syn::ItemImpl {
  trait_impls(file)
    .into_iter()
    .find_map(|(item, path)| {
      path
        .segments
        .last()
        .is_some_and(|segment| segment.ident == "KeySegments")
        .then_some(item)
    })
    .expect("the key's path walk is emitted")
}

/// Every statement of every method an impl declares, in order and with the spacing removed.
fn statements(item: &syn::ItemImpl) -> Vec<String> {
  methods(item)
    .into_iter()
    .flat_map(|method| &method.block.stmts)
    .map(tight)
    .collect()
}

/// The ROW FORM the binding names: the record where the declaration persists, and `()` where it
/// persists nowhere.
///
/// The three address models above store nothing, so each of them is the absent half already; this
/// is the pair, over one model with a `persist(…)` block and one without. `Self` rather than the
/// record's name, because the impl is ON the record and the two are one type — a binding that
/// reached for a row type instead would name one database's spelling of a form every database
/// projects.
#[test]
fn a_record_binds_its_row_form_only_where_it_persists() {
  assert_eq!(
    associated(binding(&emission(&persisted())), "Record"),
    "Self",
    "three databases, one row form: the record they are all projections of"
  );
  assert_eq!(
    associated(binding(&emission(&video_track())), "Record"),
    "()",
    "and a record no database stores becomes no row"
  );
}

/// **The two conditions' square**, walked whole: STORED against EXPOSED, and what each of the four
/// declarations that makes gets.
///
/// The diagonal is what carries it, and it is the reason the two faces are not one question. A
/// persist-only declaration has every column an order could name and nothing to send a filter
/// through; a wire-only one is the mirror, exposed with no column to order by — so a binding
/// reading either predicate for both would still pass on the corners.
///
/// The wire face is a SLOT, so its absence is `()` a reader finds in the impl block; the order is a
/// capability, so its absence is the missing impl, which is the assertion a `()` could not make.
#[test]
fn the_two_query_conditions_cut_a_declaration_four_ways() {
  for (model, wire, order, why) in [
    (
      wired(),
      "Self",
      Some("VideoTrackOrderBy"),
      "stored and exposed: both",
    ),
    (
      persisted(),
      "()",
      Some("VideoTrackOrderBy"),
      "stored only: an order over the columns, and no face to reach it through",
    ),
    (
      wire_only(),
      "Self",
      None,
      "exposed only: a face, and no column an order could name",
    ),
    (video_track(), "()", None, "neither"),
  ] {
    let file = emission(&model);
    assert_eq!(associated(binding(&file), "Graphql"), wire, "{why}");
    assert_eq!(
      order_capability(&file).map(|item| associated(item, "OrderBy")),
      order.map(str::to_owned),
      "{why}"
    );
  }
}

/// The names each side of the square reads off the MODEL rather than off a convention.
///
/// Both knobs at once, and on the model that has both to displace: `order_by(rename = "…")` moves
/// the term type and `filter(rename = "…")` moves the filter, so an emission reaching for either
/// naming convention reds here while passing every row above.
#[test]
fn the_query_faces_name_the_models_types_and_not_the_conventions() {
  let mut model = wired();
  model.order_by = RustSafeName::from_ident(&ident("TrackSort"));
  model
    .graphql
    .as_mut()
    .expect("`wired` declares a face")
    .filter = RustSafeName::from_ident(&ident("TrackWhere"));

  let file = emission(&model);
  assert_eq!(
    associated(
      wire_half(&file, "GraphqlInput").expect("the input half is emitted"),
      "Filter"
    ),
    "TrackWhere"
  );
  assert_eq!(
    associated(
      order_capability(&file).expect("a stored record carries its order"),
      "OrderBy"
    ),
    "TrackSort"
  );
}

/// The WIRE FACE's own three impls: the record's, and one per half on the CARRIER that half is.
///
/// The carriers are why this is not read off an existing wire type. A half is a BUNDLE — the input
/// names a filter and an order today — so a half bound to the filter would make the filter the
/// namespace for its own siblings. What the assertions pin is that each half names the emitted type
/// beside it and holds nothing else.
///
/// The last row is the square's wire-only corner read from this side: a face with no stored column
/// behind it binds `()` for its order, and the two predicates part exactly there.
#[test]
fn a_wire_face_binds_a_carrier_per_half_and_each_half_names_its_types() {
  let file = emission(&wired());
  let face = wire_face(&file).expect("`wired` declares a face");
  assert_eq!(associated(face, "Input"), "VideoTrackGraphqlInput");
  assert_eq!(associated(face, "Output"), "VideoTrackGraphqlOutput");

  let input = wire_half(&file, "GraphqlInput").expect("the input half is emitted");
  assert_eq!(associated(input, "Filter"), "VideoTrackFilter");
  assert_eq!(associated(input, "OrderBy"), "VideoTrackOrderBy");
  assert_eq!(
    associated(
      wire_half(&file, "GraphqlOutput").expect("the output half is emitted"),
      "Key"
    ),
    "VideoTrackKeyOutput"
  );

  assert!(
    wire_face(&emission(&persisted())).is_none(),
    "a declaration with no `graphql(…)` block gets no face impl at all"
  );

  let unstored = emission(&wire_only());
  assert_eq!(
    associated(
      wire_half(&unstored, "GraphqlInput").expect("the input half is emitted"),
      "OrderBy"
    ),
    "()",
    "a face over a record stored nowhere has no term type to name"
  );
}

/// The address binding's impl — the trait impl whose shelf path ends at `Transformer`.
fn binding(file: &syn::File) -> &syn::ItemImpl {
  trait_impls(file)
    .into_iter()
    .find_map(|(item, path)| {
      path
        .segments
        .last()
        .is_some_and(|segment| segment.ident == "Transformer")
        .then_some(item)
    })
    .expect("the address binding is emitted")
}

/// The impl the ORDER is a member of, IF the emission wrote one.
///
/// It is `Record<Db>` since the capability trait was retired: a record's storability is one fact, so
/// the row, the comparison and the order are three members of one impl rather than two impls under
/// two predicates. The absence is still an answer — a record stored nowhere gets no impl at all.
fn order_capability(file: &syn::File) -> Option<&syn::ItemImpl> {
  wrote(file, "Record")
}

/// The wire face's impl, IF the emission wrote one.
fn wire_face(file: &syn::File) -> Option<&syn::ItemImpl> {
  wrote(file, "Graphql")
}

/// One HALF of the wire face, by the vocabulary it answers.
fn wire_half<'a>(file: &'a syn::File, half: &str) -> Option<&'a syn::ItemImpl> {
  wrote(file, half)
}

/// The impl of one framework trait, by the last segment of its shelf path, or `None` where the
/// emission wrote none.
fn wrote<'a>(file: &'a syn::File, name: &str) -> Option<&'a syn::ItemImpl> {
  trait_impls(file).into_iter().find_map(|(item, path)| {
    path
      .segments
      .last()
      .is_some_and(|segment| segment.ident == name)
      .then_some(item)
  })
}

/// What one associated type of an impl is bound to.
fn associated(item: &syn::ItemImpl, name: &str) -> String {
  item
    .items
    .iter()
    .find_map(|entry| match entry {
      syn::ImplItem::Type(bound) if bound.ident == name => Some(tight(&bound.ty)),
      _ => None,
    })
    .unwrap_or_else(|| panic!("`type {name}` is bound"))
}

/// The identity kit and nothing else. `Ord` is absent because no consumer sorts a key yet, and
/// `Copy` because a macro cannot know whether the field types are `Copy` — both deliberate, both
/// recorded at the emitter.
#[test]
fn every_emitted_type_carries_exactly_the_five_derives_and_no_other_attribute() {
  for model in [video_track(), video(), media()] {
    let file = emission(&model);
    for item in structs(&file) {
      let attrs: Vec<String> = item
        .attrs
        .iter()
        .filter(|attr| !attr.path().is_ident("doc"))
        .map(tight)
        .collect();
      assert_eq!(
        attrs,
        [
          "#[derive(::core::fmt::Debug,::core::clone::Clone,::core::cmp::PartialEq,::core::cmp::Eq,::core::hash::Hash)]"
        ],
        "`{}` carries that and its docs, and nothing else — `non_exhaustive` in particular \
         would stop anything outside from calling `new`",
        item.ident
      );
    }
  }
}

/// ONLY THE AUTHORISED TRAIT IMPLEMENTATIONS, mechanical rather than remembered.
///
/// The rule was *no framework trait impl at all*, because the framework's trait layer was moving
/// and an expansion that named a half-settled trait would owe every consumer a revision the day it
/// settled. That layer has settled for `ToDatabaseComparison` — the type-level map from a filter to
/// the comparison it crosses into — and for `Transformer` with the `Identifiable` supertrait it
/// cannot be written without, whose faces are the emission's own output, so the rule lifts for those
/// and holds for every other.
/// [`unauthorised_framework_impls`] is where the line is drawn, and it checks the self type and the
/// storage argument against the MODEL, so an authorised trait on the wrong type is refused exactly
/// as an unauthorised one would be.
///
/// An INHERENT impl still binds nothing and is allowed — `new`, the accessors and the mutators live
/// in one.
#[test]
fn the_emission_declares_only_the_authorised_trait_impl() {
  for model in [video_track(), video(), media()] {
    let file = emission(&model);
    let framework = unauthorised_framework_impls(&model, &file);
    assert!(
      framework.is_empty(),
      "`{}` implemented {framework:?}; the framework's trait layer must settle before an \
       expansion names it",
      model.record
    );
    let stray: Vec<&syn::Item> = all_items(&file)
      .into_iter()
      .filter(|item| {
        !matches!(
          item,
          syn::Item::Struct(_) | syn::Item::Impl(_) | syn::Item::Const(_)
        )
      })
      .collect();
    assert!(
      stray.is_empty(),
      "only structs, their inherent impls, and the const those sit in"
    );
  }
}

/// Every emitted impl sits inside ONE anonymous const per record, and the structs stay outside it.
///
/// The const is a scope: the `use` statements impl-era emission will need can live beside the
/// impls without leaking a name into the caller's namespace. The structs are the API, so they stay
/// where a caller can see them.
#[test]
fn the_impls_live_in_one_anonymous_const_and_the_structs_stay_outside() {
  for (model, types) in [(video_track(), 2), (video(), 2), (media(), 1)] {
    // The record's own impl joins the emitted types' — one more impl, no more structs — and its
    // address binding is one more again, with the id capability on the record and on the key beside
    // it, and the key's path walk after that. Each emitted type also gets its two conversions from
    // the record. The last two are what every node states about its EDGES: the one product it
    // emits, and the marker that makes an unselected subscription to it well formed.
    // …and the FACTS the node states about itself, which is the row a graph root reads it through
    // — and the root projection beside it, which is the row the root-key registry reads instead.
    let impl_count = types + 1 + 1 + 2 + 1 + types * 2 + 2 + 1 + 1;
    let file = emission(&model);
    let consts: Vec<&syn::ItemConst> = file
      .items
      .iter()
      .filter_map(|item| match item {
        syn::Item::Const(item) => Some(item),
        _ => None,
      })
      .collect();
    // Two consts at top level and they are different things: the one-storage MARKER, which is
    // named and whose whole job is to be here where a second storage derive's would land, and the
    // anonymous WRAPPER the impls live in.
    assert_eq!(consts.len(), 2, "the marker, then one wrapper per record");
    assert_eq!(
      consts[0].ident,
      one_storage_marker(&EmissionPrefix::default(), &model.record)
    );
    assert_eq!(consts[1].ident, "_", "and the wrapper is anonymous");

    let top: Vec<&syn::Item> = file.items.iter().collect();
    assert_eq!(
      top.len(),
      types + 2,
      "the structs, the marker, then the const"
    );
    assert!(
      top
        .iter()
        .all(|item| matches!(item, syn::Item::Struct(_) | syn::Item::Const(_))),
      "no impl at top level"
    );
    assert_eq!(structs(&file).len(), types, "the structs are outside");
    assert_eq!(impls(&file).len(), impl_count, "the impls are inside");
  }
}

/// The impl walk descends. If it looked only at `syn::File::items` it would find nothing now, and
/// every rule about impls — the era rule above included — would pass while checking nothing.
#[test]
fn the_impl_walk_descends_into_the_const_wrapper() {
  let file = emission(&video_track());
  assert!(
    !file
      .items
      .iter()
      .any(|item| matches!(item, syn::Item::Impl(_))),
    "there is no impl at top level to find"
  );
  assert_eq!(
    inherent(&file).len(),
    3,
    "the key's, the lineage type's and the record's, all found inside the wrapper"
  );
  assert_eq!(
    trait_impls(&file).len(),
    12,
    "and the four conversions beside the address binding, its two id impls, the key's path walk, \
     the two rows every node states about what it emits, the FACTS a graph root reads it \
     through, and the root projection the root-key registry reads instead"
  );
  assert!(
    !method_names(&file).is_empty(),
    "and their methods with them"
  );
}

/// `#[automatically_derived]` is valid on TRAIT impls only — on an inherent impl this toolchain
/// warns that it will become a hard error. So every emitted trait impl carries it — the conversions,
/// the SQL rows' `FromRow`, and the filter's map into each comparison — and no inherent impl does.
///
/// `wired()` is on the roster because it is the only fixture that emits the map at all; without it
/// the newest trait impl would be the one this rule did not cover.
#[test]
fn automatically_derived_marks_the_trait_impls_and_only_those() {
  for model in [
    video_track(),
    video(),
    media(),
    persisted(),
    wired(),
    referring(),
  ] {
    let file = emission(&model);
    let derived = |attrs: &[syn::Attribute]| {
      attrs
        .iter()
        .any(|attr| attr.path().is_ident("automatically_derived"))
    };
    for (item, path) in trait_impls(&file) {
      assert!(
        derived(&item.attrs),
        "`impl {} for {}` is generated and says so",
        tight(path),
        tight(&item.self_ty)
      );
    }
    for item in inherent(&file) {
      assert!(
        !derived(&item.attrs),
        "`impl {}` is INHERENT — rustc warns on the attribute there and will make it an error",
        tight(&item.self_ty)
      );
    }
    for item in structs(&file) {
      assert!(!derived(&item.attrs), "`{}`", item.ident);
    }
  }
}

/// An emitted type is exactly as visible as the record it addresses — no more. A private record
/// whose key were `pub` would have leaked into its crate's public API without anyone writing it.
#[test]
fn the_emitted_visibility_mirrors_the_source_struct() {
  for model in [video_track(), video(), media()] {
    for (emission, expected) in [
      (emission(&model.clone()), "pub"),
      (emission(&private(model)), ""),
    ] {
      for item in structs(&emission) {
        assert_eq!(tight(&item.vis), expected, "`{}`", item.ident);
      }
      for method in inherent(&emission).iter().flat_map(|item| methods(item)) {
        assert_eq!(
          tight(&method.vis),
          expected,
          "`{}` is reached exactly as widely as the type it belongs to",
          method.sig.ident
        );
      }
    }
  }
}

/// A field is never wider than the CRATE, whatever the record's visibility — the accessors are the
/// way in from outside, so no caller in another crate can name a column directly.
///
/// The two ADDRESS types carry `pub(crate)` on theirs and every other emitted struct keeps them
/// private, which is the split the key-parent equation needs: a fusing node reads its parent's key
/// column by name, and a private field would make that read `E0616` at a span the author cannot act
/// on. Nothing reads a row's or a wire face's columns across a module, so nothing widens them.
#[test]
fn a_field_is_never_wider_than_the_crate() {
  for model in [video_track(), video(), media()] {
    let addresses = [
      model.key.name.to_string(),
      model
        .lineage
        .as_ref()
        .map_or_else(String::new, |lineage| lineage.name.to_string()),
    ];
    let file = emission(&model);
    for item in structs(&file) {
      let expected = if addresses.contains(&item.ident.to_string()) {
        "pub(crate)"
      } else {
        ""
      };
      for field in named(item) {
        assert_eq!(
          tight(&field.vis),
          expected,
          "`{}::{}`",
          item.ident,
          field.ident.as_ref().expect("named")
        );
      }
    }
  }
}

/// A consumer that denies `missing_docs` cannot edit a generated type to satisfy the lint, so
/// every emitted item the lint covers carries its own documentation.
///
/// This is asserted STRUCTURALLY rather than by compiling a fixture under
/// `#![deny(missing_docs)]`: that lint fires only on items reachable from OUTSIDE the crate, and a
/// test target is a binary from which nothing is reachable — measured, a `deny(missing_docs)`
/// fixture module compiles undocumented items without complaint. Requiring the attribute directly
/// is the same guarantee without the vacuum.
///
/// The lint covers inherent methods too, so `new`, every accessor and every mutator are checked.
/// It does NOT cover private fields, which are therefore left to the accessor that projects them
/// rather than documented twice.
#[test]
fn every_emitted_item_the_lint_covers_is_documented() {
  for model in [video_track(), video(), media()] {
    let file = emission(&model);
    for item in structs(&file) {
      assert!(documented(&item.attrs), "`{}` is undocumented", item.ident);
    }
    for method in inherent(&file).iter().flat_map(|item| methods(item)) {
      assert!(
        documented(&method.attrs),
        "`{}` is undocumented",
        method.sig.ident
      );
    }
  }
}

/// The documentation says what the item IS. A key's doc names the record it addresses, an
/// accessor's doc names the column it projects, and a mutator's says what it changes.
#[test]
fn the_documentation_describes_the_type_not_the_macro() {
  let file = emission(&video_track());
  let key = structs(&file)[0];
  assert!(
    docs(&key.attrs).contains("[`VideoTrack`]"),
    "the key names the record it addresses: {:?}",
    docs(&key.attrs)
  );
  for (method, expected) in [
    ("media_id", "The`media_id`stepofthelineagepath."),
    (
      "media_id_ref",
      "The`media_id`stepofthelineagepath,byreference.",
    ),
    ("set_media_id", "Setthe`media_id`stepofthelineagepath."),
    ("with_media_id", "Thesamevaluewithadifferent`media_id`."),
    ("id_ref", "Therow'sownid,byreference."),
  ] {
    let doc = docs(&key_method(&file, method).attrs);
    assert!(doc.contains(expected), "`{method}`: {doc:?}");
  }
}

/// One construction path, positional, in KEY ORDER — lineage root-first, then the id. `new` is
/// `const` for every column shape, marked or not: moving a value into a struct drops nothing.
#[test]
fn a_key_is_constructed_by_one_positional_const_new_in_key_order() {
  for model in [video_track(), video(), media()] {
    let file = emission(&model);
    let new = key_method(&file, "new");
    assert!(is_const(new), "`new` is const whatever the columns are");
    let parameters: Vec<String> = new
      .sig
      .inputs
      .iter()
      .map(|input| match input {
        syn::FnArg::Typed(typed) => tight(&typed.pat),
        syn::FnArg::Receiver(_) => panic!("`new` takes no self"),
      })
      .collect();
    let expected: Vec<String> = model
      .key
      .columns()
      .map(|column| column.name.to_string())
      .collect();
    assert_eq!(parameters, expected);
  }
}

/// A `copy` column gets a value accessor as well as the borrow, and its mutators are `const`:
/// assigning over a `Copy` value drops nothing, so no destructor has to run at compile time.
#[test]
fn a_copy_column_gets_a_value_accessor_and_const_mutators() {
  let file = emission(&video_track());
  let value = key_method(&file, "media_id");
  assert!(is_const(value) && !returns_reference(value), "`media_id`");
  let borrow = key_method(&file, "media_id_ref");
  assert!(
    is_const(borrow) && returns_reference(borrow),
    "`media_id_ref`"
  );
  assert!(is_const(key_method(&file, "set_media_id")));
  assert!(is_const(key_method(&file, "with_media_id")));
}

/// A plain column gets ONLY the borrow, and its mutators are not `const`: the assignment drops the
/// value it replaced, and a `const` destructor is unstable.
#[test]
fn a_plain_column_gets_only_a_ref_accessor_and_non_const_mutators() {
  let file = emission(&video_track());
  let borrow = key_method(&file, "video_id_ref");
  assert!(
    is_const(borrow) && returns_reference(borrow),
    "`video_id_ref`"
  );
  assert!(
    !key_methods(&file)
      .iter()
      .any(|method| method.sig.ident == "video_id"),
    "an unmarked column has no by-value accessor"
  );
  assert!(!is_const(key_method(&file, "set_video_id")));
  assert!(!is_const(key_method(&file, "with_video_id")));
}

/// The marker is ADDITIVE: it adds `x()` and takes nothing away. `x_ref()` is emitted either way,
/// so toggling `copy` on a column never breaks a caller that was already borrowing it.
#[test]
fn the_marker_only_adds_the_value_accessor() {
  let plain = emission(&video());
  let mut marked = video();
  // The marker describes the record FIELD, so the parser sets it on that field's column in every
  // scope. Both are set here for the same reason.
  marked
    .lineage
    .as_mut()
    .expect("a child has a path")
    .path_mut()[0]
    .project = Projection::Copied;
  marked.key.path[0].project = Projection::Copied;
  let marked = emission(&marked);

  assert!(method_names(&plain).contains(&"media_id_ref".to_owned()));
  assert!(method_names(&marked).contains(&"media_id_ref".to_owned()));
  assert!(!method_names(&plain).contains(&"media_id".to_owned()));
  assert!(method_names(&marked).contains(&"media_id".to_owned()));

  let gained: Vec<String> = method_names(&marked)
    .into_iter()
    .filter(|name| !method_names(&plain).contains(name))
    .collect();
  assert_eq!(
    gained,
    ["media_id", "media_id"],
    "nothing is renamed or removed — and the marker describes the COLUMN, so it reaches both the \
     key and the lineage type, which `media_id` is a column of"
  );
}

/// `with_*` returns the changed value, so dropping it is always a mistake. Nothing else is
/// `#[must_use]`: an accessor's result may legitimately be ignored, and `set_*` mutates in place.
#[test]
fn every_with_carries_must_use_and_nothing_else_does() {
  for model in [video_track(), video(), media()] {
    let file = emission(&model);
    for method in inherent(&file).iter().flat_map(|item| methods(item)) {
      let name = method.sig.ident.to_string();
      assert_eq!(
        must_use(method),
        name.starts_with("with_"),
        "`{name}` and `#[must_use]`"
      );
    }
  }
}

/// The exact method set, per column shape and in order: `new`, then each column's family in key
/// order. A key has no invariants and nothing to build up, so there is no builder and no
/// `Default`; and no `clear_*` or `*_mut`, because a method family per field is what a generator
/// must not produce.
#[test]
fn the_method_set_is_new_then_each_columns_family() {
  let file = emission(&video_track());
  assert_eq!(
    methods_of(&file, "TrackAddress"),
    [
      // media_id is `copy`, video_id and id are not.
      "new",
      "media_id",
      "media_id_ref",
      "set_media_id",
      "with_media_id",
      "video_id_ref",
      "set_video_id",
      "with_video_id",
      "id_ref",
      "set_id",
      "with_id",
    ]
  );
  assert_eq!(
    methods_of(&file, "TrackScope"),
    [
      "new",
      "media_id",
      "media_id_ref",
      "set_media_id",
      "with_media_id",
      "video_id_ref",
      "set_video_id",
      "with_video_id",
    ],
    "the same path without the id"
  );
  assert_eq!(
    methods_of(&emission(&media()), "MediaKey"),
    ["new", "id", "id_ref", "set_id", "with_id"],
    "a root with a marked id"
  );
}

/// The anti-drift half of the collision rule, and the half worth more than the refusal.
///
/// A front end refuses a declaration whose emitted method names collide, and it asks
/// [`RecordModel::emitted_methods`] what those names are. That enumeration is a SECOND reading of
/// the emitter's walk — the shapes are shared, through `method::Member::name`, but which of them a
/// given type declares is not — so it is asserted against the emission itself rather than
/// maintained by hand.
///
/// Both directions matter. A name the emitter GROWS and the enumeration does not know about is a
/// collision that goes back to being reported inside the expansion; a name the enumeration invents
/// is a declaration refused for a clash that would never have happened, which is the worse failure
/// of the two, since these are ordinary field names.
///
/// In ORDER, because the order is what lets a refusal name the earlier method as the one already
/// there.
#[test]
fn the_enumeration_names_exactly_the_methods_the_emission_declares() {
  for model in [
    video_track(),
    video(),
    media(),
    persisted(),
    whole_row(),
    wired(),
    ordered(),
  ] {
    let file = emission(&model);
    let declared: Vec<(String, String)> = inherent(&file)
      .into_iter()
      .flat_map(|item| {
        let owner = owner_of(item);
        methods(item)
          .into_iter()
          .map(move |method| (owner.clone(), method.sig.ident.to_string()))
      })
      .collect();
    let named: Vec<(String, String)> = model
      .emitted_methods()
      .iter()
      .map(|method| (method.owner_name.to_string(), method.name.to_string()))
      .collect();
    assert_eq!(named, declared, "`{}`", model.record);
  }
}

/// The same anti-drift half one level UP: the TYPES a declaration emits into one scope.
///
/// A front end refuses a declaration whose emitted type names collide, and it asks
/// [`RecordModel::emitted_types`] what those names are. Every one of them lands in a single scope,
/// so which types there ARE has to be read off the emitter rather than restated beside it.
///
/// Both directions matter, and the second is the worse one. A type the emitter GROWS and the
/// enumeration does not know about is a collision that goes back to being reported inside the
/// expansion; a type the enumeration INVENTS is a declaration refused for a clash that would never
/// have happened — over a name its author chose.
///
/// In ORDER, because the order is what lets a refusal name the earlier type as the one already
/// there. The record's own name is on neither side: no emission declares it, and
/// [`RecordModel::emitted_types`] says why the front end is what adds it.
///
/// Over [`scoped_types`] rather than the whole emission, which is the rule's own scope: a type
/// minted inside the anonymous const collides with nothing an author wrote, so the relation
/// artifacts and the wire face's carriers belong to neither side of this comparison.
#[test]
fn the_enumeration_names_exactly_the_types_the_emission_declares() {
  for model in [
    video_track(),
    video(),
    media(),
    persisted(),
    whole_row(),
    wired(),
    wire_only(),
    ordered(),
  ] {
    let declared = scoped_types(&emission(&model));
    // Every one of these six emits at least its key, so an empty comparison is a broken walk rather
    // than a record that declares nothing.
    assert!(!declared.is_empty(), "`{}` emits types", model.record);
    let named: Vec<String> = model
      .emitted_types()
      .iter()
      .map(|declared| declared.name.to_string())
      .collect();
    assert_eq!(named, declared, "`{}`", model.record);
  }
}

/// The RECORD gets an impl of its own — and no constructor in it. A real aggregate has twenty-odd
/// fields, so a positional `new` would be unusable, and the application hand-writes a validating
/// one the macro cannot replicate.
#[test]
fn the_record_gets_an_impl_with_no_constructor() {
  for model in [video_track(), video(), media()] {
    let file = emission(&model);
    let record = model.record.to_string();
    let names = methods_of(&file, &record);
    assert!(!names.is_empty(), "`{record}` has an impl");
    assert!(
      !names.contains(&"new".to_owned()),
      "`{record}` has no generated constructor: {names:?}"
    );
  }
}

/// On the RECORD, an identity-bearing field is set at construction — getters only. Every other
/// field gets the mutator pair. The rule is the product schema's own (`video/facet.rs:98`).
#[test]
fn identity_fields_get_getters_only_on_the_record() {
  let file = emission(&video_track());
  assert_eq!(
    methods_of(&file, "VideoTrack"),
    [
      // media_id — a lineage step, marked `copy`: both getters, no mutators.
      "media_id",
      "media_id_ref",
      // video_id — a lineage step: the borrow alone.
      "video_id_ref",
      // id — identity: the borrow alone.
      "id_ref",
      // and the data fields, each with its projection and its mutators.
      "checksum_ref",
      "set_checksum",
      "with_checksum",
      "chapters_slice",
      "set_chapters",
      "with_chapters",
      "cover_id_ref",
      "set_cover_id",
      "with_cover_id",
    ]
  );
}

/// A marked field is projected through the framework's trait, with its DECLARED type written
/// verbatim into the qualification.
#[test]
fn marked_fields_get_the_projected_shapes() {
  let file = emission(&video());
  let record = "Video";
  assert_eq!(
    returns(method_of(&file, record, "chapters_slice")),
    "&[<Vec<Uuid7>as::ingraph::__private::project::Repeated>::Item]"
  );
  assert_eq!(
    returns(method_of(&file, record, "cover_id_ref")),
    "::core::option::Option<&<Option<Uuid7>as::ingraph::__private::project::Optional>::Item>"
  );
  assert_eq!(
    returns(method_of(&file, record, "checksum_ref")),
    "&u64",
    "and an unmarked field takes the plain borrow — nothing is inferred"
  );
}

/// A projected accessor calls a trait method, and const trait methods are unstable — so it is not
/// `const`. The accessors that touch no trait still are.
#[test]
fn a_projected_accessor_is_not_const_but_a_plain_one_is() {
  let file = emission(&video());
  assert!(!is_const(method_of(&file, "Video", "chapters_slice")));
  assert!(!is_const(method_of(&file, "Video", "cover_id_ref")));
  assert!(is_const(method_of(&file, "Video", "checksum_ref")));
  assert!(is_const(method_of(&file, "Video", "media_id_ref")));
}

/// A field whose type is written through an ALIAS projects exactly as the same type spelled out
/// would: the marker says WHICH projection, and the declared type is written verbatim into the
/// trait qualification, so no pattern-match on the type's spelling is involved.
///
/// This is the bug this design fixes. Syntactic matching on `Vec<…>` silently handed an aliased
/// field back as `&Ids`, and nothing caught it.
#[test]
fn an_aliased_collection_type_still_projects() {
  let mut model = video();
  model.fields[3].column.ty = ty("Chapters");
  model.fields[4].column.ty = ty("MaybeCover");
  let file = emission(&model);
  assert_eq!(
    returns(method_of(&file, "Video", "chapters_slice")),
    "&[<Chaptersas::ingraph::__private::project::Repeated>::Item]"
  );
  assert_eq!(
    returns(method_of(&file, "Video", "cover_id_ref")),
    "::core::option::Option<&<MaybeCoveras::ingraph::__private::project::Optional>::Item>"
  );
}

/// The framework path the projections are qualified through is the MODEL's, so a declaration that
/// reaches `ingraph` under another name gets accessors that compile there — `__private` included.
#[test]
fn the_projection_traits_are_reached_through_the_models_crate_path() {
  let mut model = video();
  model.krate = syn::parse_quote!(shim::vendored::ingraph);
  let file = emission(&model);
  assert_eq!(
    returns(method_of(&file, "Video", "chapters_slice")),
    "&[<Vec<Uuid7>asshim::vendored::ingraph::__private::project::Repeated>::Item]"
  );
}

/// The shelf is addressable at whatever depth it mirrors, because mirroring is recursive: a family
/// that is a module inside a module is reached through both segments.
///
/// One segment and two are the same call with a longer slice — there is no second helper for the
/// nested case and no `::` parsed out of a string, so a segment is an identifier by construction.
#[test]
fn a_shelf_path_names_as_many_modules_as_the_item_lives_under() {
  let model = video();
  assert_eq!(
    tight(model.framework(&["graphql"], "ToGraphqlFilter")),
    "::ingraph::__private::graphql::ToGraphqlFilter"
  );
  assert_eq!(
    tight(model.framework(&["comparison", "sql"], "SqlScalarComparison")),
    "::ingraph::__private::comparison::sql::SqlScalarComparison"
  );
}

/// EVERY framework path in an emission is `#krate::__private::<module…>::<item>`. Emitted code
/// depends on that shelf rather than on where the framework keeps an item, so the framework can
/// move or rename one without regenerating anyone's expansion.
///
/// EVERY is literal — there is no exception list here, and adding one would give up the property
/// for whatever it exempts. The filter map used to be exempt on the argument that a declarer must
/// WRITE its impl by hand and would read the path back out of the compiler's "trait bound not
/// satisfied" message, which a `__private` spelling would make unactionable. Measurement refuted
/// it: rustc prints the trait's DEFINITION path, never the path written in the bound, so a bound
/// written through the shelf still reports `lower::ToGraphqlFilter` and the public spelling bought
/// nothing. The same measurement is why moving the projection onto markers moved no `.stderr`
/// fixture — a trait-bound message names the RESOLVED type, not the projection. Reachability for a
/// human is the separate question, with its own separate answer — a name a declarer must write
/// stays publicly exported as well, and a re-export is the same trait, so
/// `impl ingraph::ScalarFilterMarker for MyType` satisfies a bound the macro wrote through
/// `__private`.
///
/// The MODULE segment is load-bearing, not decoration: `__private` mirrors the crate's modules
/// with a glob apiece, so it needs no maintenance as the crate grows and two modules that each
/// define a `Column` stay apart. An item named directly beneath `__private` would be the flattened
/// shape that gives up both, so this fails on it exactly as it fails on a missing `__private`.
///
/// The module part is a PATH and not one segment, because mirroring is recursive: `comparison::sql`
/// is a module inside a module and is shelved at that depth, so `__private::comparison::sql::<item>`
/// is well formed here. What the check asks is unchanged in strength — `__private`, then AT LEAST
/// one module segment, then the item — and [`shelf_refusals`] is the negative half, feeding this
/// same scan the two shapes it exists to reject.
///
/// Mechanical rather than a habit: it walks the emitted TOKENS, so the next framework reference
/// added anywhere in the emitter is checked without anyone remembering to check it.
///
/// A walk sees only what the MODEL makes the emitter write, so the roster is what gives the check
/// its reach. The three fixtures are pure-compute — they declare no database and no wire face, so
/// their emissions name the framework in the projection accessors and nowhere else, and for as long
/// as they were the whole roster the sql, mongo and graphql emitters were unwalked. `wired()` is
/// here to close that: it carries three databases and a wire face, so one pass covers every
/// emitter that writes a framework path.
#[test]
fn every_framework_path_goes_through_a_private_module() {
  for mut model in [video_track(), video(), media(), wired()] {
    for krate in [
      syn::parse_quote!(::ingraph),
      syn::parse_quote!(shim::vendored::ingraph),
    ] {
      model.krate = krate;
      let ill_formed = framework_paths_not_through_a_private_module(&model);
      assert!(
        ill_formed.is_empty(),
        "`{}` reaches the framework outside `__private::<module…>`: {ill_formed:?}",
        model.record
      );
    }
  }
}

/// The same rule over the GRAPH ROOT's emission, which no record model reaches.
///
/// A root is not a record — it has a model of its own and an emitter of its own — so the roster
/// above cannot walk it, and the shelf rule is the framework's and not one emitter's. The gate is
/// the reason this cannot be folded into the walk above: `if_sqlx!` is a macro INVOCATION, so the
/// tokens inside it are a group the scan sees exactly as it sees the rest.
#[test]
fn the_ingraph_roots_emission_goes_through_the_shelf_too() {
  for krate in [
    syn::parse_quote!(::ingraph),
    syn::parse_quote!(shim::vendored::ingraph),
  ] {
    let model = crate::graph::GraphModel {
      krate,
      vis: syn::parse_quote!(pub),
      name: syn::parse_quote!(App),
      nodes: vec![syn::parse_quote!(media::Video), syn::parse_quote!(Scene)],
      mounts: vec![syn::parse_quote!(videos), syn::parse_quote!(scenes)],
      // Both walked sources, so the scan covers the resource block, the catalog walk and the
      // create walk's first step — every one of which names framework items of its own.
      queried: Vec::new(),
      interfaces: Vec::new(),
      fused: Vec::new(),
      resources: vec![
        crate::catalog::ResourceField {
          mount: syn::parse_quote!(egemma),
          ty: syn::parse_quote!(models::Egemma),
          source: crate::catalog::ResourceSource::Section,
          teardown: false,
        },
        crate::catalog::ResourceField {
          mount: syn::parse_quote!(cache),
          ty: syn::parse_quote!(Cache),
          source: crate::catalog::ResourceSource::Initializer(syn::parse_quote!(boot::cache)),
          teardown: true,
        },
        crate::catalog::ResourceField {
          mount: syn::parse_quote!(pool),
          ty: syn::parse_quote!(Pool),
          source: crate::catalog::ResourceSource::Prepare,
          teardown: false,
        },
      ],
      origins: Vec::new(),
      // The scan is over framework paths; a bound engine word adds one and is covered by
      // `graph::tests`.
      engines: Vec::new(),
      retired: None,
      generations: None,
    };
    let root = model
      .krate
      .segments
      .last()
      .expect("a crate path has a last segment")
      .ident
      .clone();
    let ill_formed = ill_formed_shelf_paths(model.emit(), &root);
    assert!(
      ill_formed.is_empty(),
      "the graph root reaches the framework outside `__private::<module…>`: {ill_formed:?}"
    );
  }
}

/// The scan's REFUSAL half, on streams written to be refused.
///
/// [`every_framework_path_goes_through_a_private_module`] asserts an emptiness, and an emptiness is
/// also what a scan that had stopped looking would report. These four streams are the control: the
/// two shapes the shelf rule exists to reject, and the two depths it admits.
///
/// The admitted pair is what changed when the module part became a path — one segment and two are
/// both well formed now — and the rejected pair is what did not.
#[test]
fn shelf_refusals() {
  let root = ident("ingraph");
  let scan = |stream: proc_macro2::TokenStream| ill_formed_shelf_paths(stream, &root);

  assert_eq!(
    scan(quote::quote!(::ingraph::ToGraphqlFilter)).len(),
    1,
    "a path that skips `__private` entirely"
  );
  assert_eq!(
    scan(quote::quote!(::ingraph::__private::ToGraphqlFilter)).len(),
    1,
    "and one that names an item directly beneath it — the flattened shape, which is what the \
     module segment exists to prevent"
  );
  assert_eq!(
    scan(quote::quote!(::ingraph::graphql::lower::ToGraphqlFilter)).len(),
    1,
    "a path of the right DEPTH through the wrong module is still refused — depth is not what is \
     being checked, `__private` is, and reaching an item where it really lives is exactly what the \
     shelf exists to stop an expansion doing"
  );
  assert!(
    scan(quote::quote!(
      ::ingraph::__private::graphql::ToGraphqlFilter
    ))
    .is_empty(),
    "one module segment is well formed"
  );
  assert!(
    scan(quote::quote!(
      ::ingraph::__private::comparison::sql::SqlScalarComparison
    ))
    .is_empty(),
    "and so is a family nested one deeper, which is how the shelf mirrors a module inside a module"
  );
}

/// Every place the emission names the framework crate and does NOT continue
/// `::__private::<module…>::<item>`.
fn framework_paths_not_through_a_private_module(model: &RecordModel) -> Vec<String> {
  let root = &model
    .krate
    .segments
    .last()
    .expect("a crate path has a last segment")
    .ident;
  ill_formed_shelf_paths(model.emit(), root)
}

/// Every place `stream` names `root` and does NOT continue `::__private::<module…>::<item>`.
///
/// Taking the stream rather than a model is what lets [`shelf_refusals`] drive it: the property is
/// about a token sequence, and a model is only one way to obtain one.
fn ill_formed_shelf_paths(stream: proc_macro2::TokenStream, root: &syn::Ident) -> Vec<String> {
  let tokens = flat_tokens(stream);

  let colon = |at: usize| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == ':');
  let named = |at: usize, name: &str| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Ident(id)) if id == name);
  let any_ident = |at: usize| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Ident(_)));
  // `#root :: __private` and then `:: <ident>` as many times as the shelf is deep — at least TWICE,
  // since the last of them is the ITEM and everything before it is the module path it lives in.
  let well_formed = |at: usize| {
    if !(colon(at + 1) && colon(at + 2) && named(at + 3, "__private")) {
      return false;
    }
    let mut segments = 0;
    let mut cursor = at + 3;
    while colon(cursor + 1) && colon(cursor + 2) && any_ident(cursor + 3) {
      segments += 1;
      cursor += 3;
    }
    segments >= 2
  };

  (0..tokens.len())
    .filter(|at| named(*at, &root.to_string()))
    .filter(|at| !well_formed(*at))
    .map(|at| {
      tokens[at..(at + 10).min(tokens.len())]
        .iter()
        .map(ToString::to_string)
        .collect()
    })
    .collect()
}

/// GENERATED CODE NAMES NO PER-DIALECT ALIAS MODULE.
///
/// `comparison::sql::{sqlite, postgres, mysql}` hold the family's types with the dialect fixed, and
/// they are for what a PERSON writes. An expansion writes the full form, and the reasons are not
/// style:
///
/// - The shelf is what emitted code is allowed to depend on, and an alias is a second indirection
///   the shelf does not control — one the framework could retarget without the shelf's promise
///   covering it.
/// - The emitter already holds the `Db` type, so the full form is what it naturally writes. Routing
///   through an alias would make it carry a dialect-to-module-name map for no gain.
/// - An error inside generated code that named an alias would send its reader to the alias rather
///   than to the type. Generated code is what a declarer cannot edit, so the path in its diagnostics
///   has to be the real one.
///
/// The shelf could not resolve one in any case — `__private::comparison::sql` declares its own empty
/// `sqlite`, `postgres` and `mysql` segments, and an explicitly declared module shadows the glob
/// re-export that would otherwise carry the real ones — so this test is what states the RULE, ahead
/// of the resolution failure that would state it as an accident.
#[test]
fn no_emitted_path_names_a_per_dialect_alias_module() {
  for mut model in [video_track(), video(), media(), wired()] {
    for krate in [
      syn::parse_quote!(::ingraph),
      syn::parse_quote!(shim::vendored::ingraph),
    ] {
      model.krate = krate;
      let named = per_dialect_alias_paths(model.emit());
      assert!(
        named.is_empty(),
        "`{}` reaches a per-dialect alias module: {named:?}; an expansion writes the full form",
        model.record
      );
    }
  }
}

/// The scan's REFUSAL half, on streams written to be refused.
///
/// [`no_emitted_path_names_a_per_dialect_alias_module`] asserts an emptiness, which is also what a
/// scan that had stopped looking would report. `sqlx::Postgres` is the control that matters most: an
/// emission may name the dialect TYPE, and the module segment is one character and one case away
/// from it.
#[test]
fn per_dialect_alias_refusals() {
  assert_eq!(
    per_dialect_alias_paths(quote::quote!(
      ::ingraph::__private::comparison::sql::postgres::ScalarComparison
    ))
    .len(),
    1,
    "the shelf spelling"
  );
  assert_eq!(
    per_dialect_alias_paths(quote::quote!(
      ::ingraph::comparison::sql::sqlite::TextComparison
    ))
    .len(),
    1,
    "and the public one, which the shelf rule would let through with its own error"
  );
  assert!(
    per_dialect_alias_paths(quote::quote!(
      ::ingraph::__private::comparison::sql::SqlScalarComparison
    ))
    .is_empty(),
    "the full form is what an expansion writes"
  );
  assert!(
    per_dialect_alias_paths(quote::quote!(::ingraph::__private::sqlx::Postgres)).is_empty(),
    "naming the dialect TYPE is not naming its alias module, and `sqlx` is not `sql`"
  );
}

/// Every place `stream` steps from the `sql` family module into one of its per-dialect alias
/// modules.
///
/// It keys on the SEGMENT PAIR rather than on a whole path, so the shelf spelling and the public one
/// are caught alike — and `sqlx::sqlite`, which is a different module of a different crate, is not.
fn per_dialect_alias_paths(stream: proc_macro2::TokenStream) -> Vec<String> {
  const DIALECTS: [&str; 3] = ["sqlite", "postgres", "mysql"];

  let tokens = flat_tokens(stream);
  let colon = |at: usize| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == ':');
  let named = |at: usize, name: &str| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Ident(id)) if id == name);

  (0..tokens.len())
    .filter(|at| named(*at, "sql"))
    .filter(|at| {
      colon(at + 1) && colon(at + 2) && DIALECTS.iter().any(|dialect| named(at + 3, dialect))
    })
    .map(|at| {
      tokens[at..(at + 7).min(tokens.len())]
        .iter()
        .map(ToString::to_string)
        .collect()
    })
    .collect()
}

/// `stream`'s tokens with every group flattened into the sequence, so a path can be recognised by
/// walking a window regardless of the brackets it was nested in.
fn flat_tokens(stream: proc_macro2::TokenStream) -> Vec<proc_macro2::TokenTree> {
  fn flatten(stream: proc_macro2::TokenStream, into: &mut Vec<proc_macro2::TokenTree>) {
    for tree in stream {
      match tree {
        proc_macro2::TokenTree::Group(group) => flatten(group.stream(), into),
        other => into.push(other),
      }
    }
  }
  let mut tokens = Vec::new();
  flatten(stream, &mut tokens);
  tokens
}

/// Every emitted method is `#[inline]` — they are one-line cross-crate wrappers. NOT
/// `#[inline(always)]`, which the repository's type-conventions reference declines to make a house
/// default even though the product schema writes it by hand; the divergence is recorded at the
/// emitter with both citations.
#[test]
fn every_emitted_method_is_inline_but_not_inline_always() {
  for model in [video_track(), video(), media()] {
    let file = emission(&model);
    for method in impls(&file).iter().flat_map(|item| methods(item)) {
      let attrs: Vec<String> = method
        .attrs
        .iter()
        .filter(|attr| !attr.path().is_ident("doc"))
        .map(tight)
        .collect();
      assert!(
        attrs.contains(&"#[inline]".to_owned()),
        "`{}`: {attrs:?}",
        method.sig.ident
      );
      assert!(
        !attrs.iter().any(|attr| attr.contains("always")),
        "`{}`: {attrs:?}",
        method.sig.ident
      );
    }
  }
}

/// The argument-count allow rides every POSITIONAL CONSTRUCTOR and nothing wider.
///
/// `new` is the one emitted signature whose parameter count is a declaration's rather than this
/// emitter's — an address type's columns, or one predicate per stored column — so it is the only
/// one that can trip `clippy::too_many_arguments` in a crate that cannot edit the expansion. The
/// same attribute on an impl, on a struct or on the anonymous const would reach hand-written code
/// the declaration also holds, which is the failure mode a blanket allow has and the reason the
/// attribute is placed per method.
#[test]
fn the_argument_count_allow_rides_every_constructor_and_nothing_wider() {
  const ALLOW: &str = "#[allow(clippy::too_many_arguments)]";
  let carries = |attrs: &[syn::Attribute]| attrs.iter().any(|attr| tight(attr) == ALLOW);
  for model in [video_track(), video(), media(), persisted()] {
    let file = emission(&model);
    for item in all_items(&file) {
      let (attrs, what) = match item {
        syn::Item::Impl(item) => (&item.attrs, format!("`impl {}`", impl_of(item))),
        syn::Item::Struct(item) => (&item.attrs, format!("`{}`", item.ident)),
        syn::Item::Const(item) => (&item.attrs, "the anonymous const".to_owned()),
        _ => continue,
      };
      assert!(!carries(attrs), "{what} carries the allow");
    }
    let mut constructors = 0;
    for method in impls(&file).iter().flat_map(|item| methods(item)) {
      let constructor = method.sig.ident == "new";
      constructors += usize::from(constructor);
      assert_eq!(
        carries(&method.attrs),
        constructor,
        "`{}` and the argument-count allow",
        method.sig.ident
      );
    }
    assert!(
      constructors > 0,
      "an emission declares a constructor at all"
    );
  }
}

#[test]
fn a_fields_type_is_the_models_own_type_verbatim() {
  let mut model = video();
  model.key.id.ty = ty("MediaFileId");
  let file = emission(&model);
  let key = structs(&file)[0];
  let types: Vec<String> = named(key).iter().map(|f| tight(&f.ty)).collect();
  assert_eq!(types, ["Uuid7", "MediaFileId"]);
}

/// The whole rendered text of two fixture shapes, so the emission's face is pinned rather than
/// described: every doc comment, the visibility, the private fields, the derive list, the
/// one-storage marker with the `allow`s that keep it from failing a declarer's own `-D warnings`
/// build, the anonymous const the impls sit in, `#[inline]` on every method, `#[must_use]` on
/// every `with_*`,
/// each field's exact family with its projection — trait-qualified through `__private` — the id's
/// FIVE-BOUND obligation, the address binding with the id capability on either side of it, the
/// key's path walk after that, and both conversions, with `#[automatically_derived]` on each.
///
/// Both goldens were RE-BLESSED by the batching round for that obligation —
/// `const _: fn() = …::ids_are_keys::<Uuid7>;`, one line, immediately above the record's own
/// `Identifiable` impl. The position is part of the claim: it sits beside the impl that NAMES the
/// id. So is the presence, in BOTH shapes — neither fixture stores anywhere or publishes a wire
/// face, and the mandate is unconditional, so neither is exempt.
///
/// Between them the two shapes pin BOTH forms of the walk: `MEDIA`'s is a root's one push, and
/// `VIDEO_PRIVATE`'s is a lineage step followed by the id.
///
/// `MEDIA` is a root whose id is marked `copy`, with an unmarked scalar, a `repeated` field and an
/// `optional` one. `VIDEO_PRIVATE` is the child shape with nothing copied and no `pub` on its
/// source struct, so it covers the unmarked families and the mirrored visibility together — and,
/// between them, both forms the binding's `Lineage` takes.
/// `VideoTrack`'s distinctive content — the renames, two lineage steps, a mixed marked/unmarked
/// pair — is structural, and is asserted as structure above rather than pinned as text a third
/// time.
#[test]
fn the_fixture_shapes_render_exactly() {
  assert_eq!(prettyplease::unparse(&emission(&media())), MEDIA);
  assert_eq!(
    prettyplease::unparse(&emission(&private(video()))),
    VIDEO_PRIVATE,
    "the same shape without a `pub` on its source struct"
  );
}

const MEDIA: &str = "\
/// The address of a [`Media`] row: its own id.
#[derive(
    ::core::fmt::Debug,
    ::core::clone::Clone,
    ::core::cmp::PartialEq,
    ::core::cmp::Eq,
    ::core::hash::Hash
)]
pub struct MediaKey {
    pub(crate) id: Uuid7,
}
#[doc(hidden)]
#[allow(dead_code, non_upper_case_globals)]
const __ig_Media_holds_one_storage: () = ();
const _: () = {
    impl MediaKey {
        /// Construct an address from the row's own id.
        #[allow(clippy::too_many_arguments)]
        #[inline]
        pub const fn new(id: Uuid7) -> Self {
            Self { id }
        }
        /// The row's own id.
        #[inline]
        pub const fn id(&self) -> Uuid7 {
            self.id
        }
        /// The row's own id, by reference.
        #[inline]
        pub const fn id_ref(&self) -> &Uuid7 {
            &self.id
        }
        /// Set the row's own id.
        #[inline]
        pub const fn set_id(&mut self, value: Uuid7) -> &mut Self {
            self.id = value;
            self
        }
        /// The same value with a different `id`.
        #[must_use]
        #[inline]
        pub const fn with_id(mut self, value: Uuid7) -> Self {
            self.id = value;
            self
        }
    }
    impl Media {
        /// The `id` field of this [`Media`].
        #[inline]
        pub const fn id(&self) -> Uuid7 {
            self.id
        }
        /// The `id` field of this [`Media`], by reference.
        #[inline]
        pub const fn id_ref(&self) -> &Uuid7 {
            &self.id
        }
        /// The `checksum` field of this [`Media`], by reference.
        #[inline]
        pub const fn checksum_ref(&self) -> &u64 {
            &self.checksum
        }
        /// Set the `checksum` field of this [`Media`].
        #[inline]
        pub fn set_checksum(&mut self, value: u64) -> &mut Self {
            self.checksum = value;
            self
        }
        /// The same value with a different `checksum`.
        #[must_use]
        #[inline]
        pub fn with_checksum(mut self, value: u64) -> Self {
            self.checksum = value;
            self
        }
        /// The `chapters` field of this [`Media`], as a slice.
        #[inline]
        pub fn chapters_slice(
            &self,
        ) -> &[<Vec<Uuid7> as ::ingraph::__private::project::Repeated>::Item] {
            ::ingraph::__private::project::Repeated::as_slice(&self.chapters)
        }
        /// Set the `chapters` field of this [`Media`].
        #[inline]
        pub fn set_chapters(&mut self, value: Vec<Uuid7>) -> &mut Self {
            self.chapters = value;
            self
        }
        /// The same value with a different `chapters`.
        #[must_use]
        #[inline]
        pub fn with_chapters(mut self, value: Vec<Uuid7>) -> Self {
            self.chapters = value;
            self
        }
        /// The `cover_id` field of this [`Media`], by reference.
        #[inline]
        pub fn cover_id_ref(
            &self,
        ) -> ::core::option::Option<
            &<Option<Uuid7> as ::ingraph::__private::project::Optional>::Item,
        > {
            ::ingraph::__private::project::Optional::as_option(&self.cover_id)
        }
        /// Set the `cover_id` field of this [`Media`].
        #[inline]
        pub fn set_cover_id(&mut self, value: Option<Uuid7>) -> &mut Self {
            self.cover_id = value;
            self
        }
        /// The same value with a different `cover_id`.
        #[must_use]
        #[inline]
        pub fn with_cover_id(mut self, value: Option<Uuid7>) -> Self {
            self.cover_id = value;
            self
        }
    }
    const _: fn() = ::ingraph::__private::transform::ids_are_keys::<Uuid7>;
    #[automatically_derived]
    impl ::ingraph::__private::transform::Identifiable for Media {
        type Id = Uuid7;
        #[inline]
        fn id_ref(&self) -> &Uuid7 {
            &self.id
        }
    }
    #[automatically_derived]
    impl ::ingraph::__private::transform::Transformer for Media {
        type Key = MediaKey;
        type Lineage = ();
        type Record = ();
        type Graphql = ();
        #[inline]
        fn key(&self) -> MediaKey {
            <MediaKey as ::core::convert::From<&Media>>::from(self)
        }
    }
    #[automatically_derived]
    impl ::ingraph::__private::transform::Identifiable for MediaKey {
        type Id = Uuid7;
        #[inline]
        fn id_ref(&self) -> &Uuid7 {
            &self.id
        }
    }
    #[automatically_derived]
    impl ::ingraph::__private::store::KeySegments for MediaKey {
        #[inline]
        fn segments(&self, out: &mut ::ingraph::__private::store::Segments) {
            out.push(&self.id);
        }
    }
    #[automatically_derived]
    impl ::core::convert::From<Media> for MediaKey {
        #[inline]
        fn from(record: Media) -> Self {
            Self { id: record.id }
        }
    }
    #[automatically_derived]
    impl<'a> ::core::convert::From<&'a Media> for MediaKey {
        #[inline]
        fn from(record: &'a Media) -> Self {
            Self {
                id: ::core::clone::Clone::clone(&record.id),
            }
        }
    }
    #[automatically_derived]
    impl ::ingraph::__private::operator::Emits for Media {
        type Out = Self;
    }
    #[automatically_derived]
    impl ::ingraph::__private::operator::SoleProduct for Media {}
    #[automatically_derived]
    impl ::ingraph::__private::drive::Declared for Media {
        /// What a [`Media`]'s outputs become — read off the kind it was declared under.
        const EFFECT: ::ingraph::__private::drive::Effect = ::ingraph::__private::drive::Effect::Lands;
        /// Whether a [`Media`] holds a write lane of its own — read off the same kind.
        const HOLDS_LANE: bool = true;
        /// Every upstream a [`Media`] draws from, in declaration order.
        const UPSTREAMS: &'static [::ingraph::__private::drive::Upstream] = &[];
        /// Every store a [`Media`] granted itself the right to write, in declaration order.
        const GRANTS: &'static [::ingraph::__private::drive::Grant] = &[];
        type Channels = ::ingraph::__private::drive::Unchanneled;
        type Options = ();
        /// A [`Media`] wrote no `stream`, so its body wears the BUFFERED pair — an `accept` per delivery, mounted at `Blueprint::node`.
        type Pair = ::ingraph::__private::drive::Buffered;
        /// A [`Media`] emits ONE thing, so it publishes through the framework's own fan-out set — N edges of that one product, the copy taken at the set rather than asked of any driver.
        type Wires<__INGRAPH_OUT__> = ::ingraph::__private::drive::Downstream<
            __INGRAPH_OUT__,
        >;
        /// A [`Media`] wrote no `attributed`, so it attributes its outputs to nothing — the unit projection, whose `Attributes` impl is the empty program and whose value is zero-sized. Its observations stay counter-grade, which is the shipped posture for every node that emits a payload with no declared root. The product parameter is the attributed road's and is unread here.
        type Attribution<__INGRAPH_OUT__> = ();
        /// A [`Media`] wrote no mode word, so its `accept` is the blocking face's — an `Operator` body, called by either engine and answering without a future.
        type Mode = ::ingraph::__private::operator::Block;
    }
    #[automatically_derived]
    impl ::ingraph::__private::drive::Attributes<Media>
    for ::ingraph::__private::drive::RootProjection<Media> {
        /// This root family's own name, read off the root type rather than off a column name so that every record sharing a root agrees on it without saying so.
        const FAMILY: &'static str = \"uuid7\";
        /// Which root key a [`Media`] descends from — its key's FIRST column, which is the `id` field. The root-key registry tables one machine per family, and this is what tells it which family a record of this type belongs to.
        type Root = Uuid7;
        #[inline]
        fn root(&self, record: &Media) -> Self::Root {
            ::core::clone::Clone::clone(&record.id)
        }
        #[inline]
        fn observe(
            &self,
            _root: &Self::Root,
            _worker: &::ingraph::__private::drive::NodeName,
            _arrival: &::ingraph::__private::drive::Arrival,
        ) {}
    }
};
";

const VIDEO_PRIVATE: &str = "\
/// The address of a [`Video`] row: its lineage path followed by its own id.
#[derive(
    ::core::fmt::Debug,
    ::core::clone::Clone,
    ::core::cmp::PartialEq,
    ::core::cmp::Eq,
    ::core::hash::Hash
)]
struct VideoKey {
    pub(crate) media_id: Uuid7,
    pub(crate) id: Uuid7,
}
/// The path from the root to a [`Video`] row, root-first.
#[derive(
    ::core::fmt::Debug,
    ::core::clone::Clone,
    ::core::cmp::PartialEq,
    ::core::cmp::Eq,
    ::core::hash::Hash
)]
struct VideoLineage {
    pub(crate) media_id: Uuid7,
}
#[doc(hidden)]
#[allow(dead_code, non_upper_case_globals)]
const __ig_Video_holds_one_storage: () = ();
const _: () = {
    impl VideoKey {
        /// Construct an address from its lineage path and the row's own id.
        #[allow(clippy::too_many_arguments)]
        #[inline]
        const fn new(media_id: Uuid7, id: Uuid7) -> Self {
            Self { media_id, id }
        }
        /// The `media_id` step of the lineage path, by reference.
        #[inline]
        const fn media_id_ref(&self) -> &Uuid7 {
            &self.media_id
        }
        /// Set the `media_id` step of the lineage path.
        #[inline]
        fn set_media_id(&mut self, value: Uuid7) -> &mut Self {
            self.media_id = value;
            self
        }
        /// The same value with a different `media_id`.
        #[must_use]
        #[inline]
        fn with_media_id(mut self, value: Uuid7) -> Self {
            self.media_id = value;
            self
        }
        /// The row's own id, by reference.
        #[inline]
        const fn id_ref(&self) -> &Uuid7 {
            &self.id
        }
        /// Set the row's own id.
        #[inline]
        fn set_id(&mut self, value: Uuid7) -> &mut Self {
            self.id = value;
            self
        }
        /// The same value with a different `id`.
        #[must_use]
        #[inline]
        fn with_id(mut self, value: Uuid7) -> Self {
            self.id = value;
            self
        }
    }
    impl VideoLineage {
        /// Construct a path from its steps, root-first.
        #[allow(clippy::too_many_arguments)]
        #[inline]
        const fn new(media_id: Uuid7) -> Self {
            Self { media_id }
        }
        /// The `media_id` step of the lineage path, by reference.
        #[inline]
        const fn media_id_ref(&self) -> &Uuid7 {
            &self.media_id
        }
        /// Set the `media_id` step of the lineage path.
        #[inline]
        fn set_media_id(&mut self, value: Uuid7) -> &mut Self {
            self.media_id = value;
            self
        }
        /// The same value with a different `media_id`.
        #[must_use]
        #[inline]
        fn with_media_id(mut self, value: Uuid7) -> Self {
            self.media_id = value;
            self
        }
    }
    impl Video {
        /// The `media_id` field of this [`Video`], by reference.
        #[inline]
        const fn media_id_ref(&self) -> &Uuid7 {
            &self.media_id
        }
        /// The `id` field of this [`Video`], by reference.
        #[inline]
        const fn id_ref(&self) -> &Uuid7 {
            &self.id
        }
        /// The `checksum` field of this [`Video`], by reference.
        #[inline]
        const fn checksum_ref(&self) -> &u64 {
            &self.checksum
        }
        /// Set the `checksum` field of this [`Video`].
        #[inline]
        fn set_checksum(&mut self, value: u64) -> &mut Self {
            self.checksum = value;
            self
        }
        /// The same value with a different `checksum`.
        #[must_use]
        #[inline]
        fn with_checksum(mut self, value: u64) -> Self {
            self.checksum = value;
            self
        }
        /// The `chapters` field of this [`Video`], as a slice.
        #[inline]
        fn chapters_slice(
            &self,
        ) -> &[<Vec<Uuid7> as ::ingraph::__private::project::Repeated>::Item] {
            ::ingraph::__private::project::Repeated::as_slice(&self.chapters)
        }
        /// Set the `chapters` field of this [`Video`].
        #[inline]
        fn set_chapters(&mut self, value: Vec<Uuid7>) -> &mut Self {
            self.chapters = value;
            self
        }
        /// The same value with a different `chapters`.
        #[must_use]
        #[inline]
        fn with_chapters(mut self, value: Vec<Uuid7>) -> Self {
            self.chapters = value;
            self
        }
        /// The `cover_id` field of this [`Video`], by reference.
        #[inline]
        fn cover_id_ref(
            &self,
        ) -> ::core::option::Option<
            &<Option<Uuid7> as ::ingraph::__private::project::Optional>::Item,
        > {
            ::ingraph::__private::project::Optional::as_option(&self.cover_id)
        }
        /// Set the `cover_id` field of this [`Video`].
        #[inline]
        fn set_cover_id(&mut self, value: Option<Uuid7>) -> &mut Self {
            self.cover_id = value;
            self
        }
        /// The same value with a different `cover_id`.
        #[must_use]
        #[inline]
        fn with_cover_id(mut self, value: Option<Uuid7>) -> Self {
            self.cover_id = value;
            self
        }
    }
    const _: fn() = ::ingraph::__private::transform::ids_are_keys::<Uuid7>;
    #[automatically_derived]
    impl ::ingraph::__private::transform::Identifiable for Video {
        type Id = Uuid7;
        #[inline]
        fn id_ref(&self) -> &Uuid7 {
            &self.id
        }
    }
    #[automatically_derived]
    impl ::ingraph::__private::transform::Transformer for Video {
        type Key = VideoKey;
        type Lineage = VideoLineage;
        type Record = ();
        type Graphql = ();
        #[inline]
        fn key(&self) -> VideoKey {
            <VideoKey as ::core::convert::From<&Video>>::from(self)
        }
    }
    #[automatically_derived]
    impl ::ingraph::__private::transform::Identifiable for VideoKey {
        type Id = Uuid7;
        #[inline]
        fn id_ref(&self) -> &Uuid7 {
            &self.id
        }
    }
    #[automatically_derived]
    impl ::ingraph::__private::store::KeySegments for VideoKey {
        #[inline]
        fn segments(&self, out: &mut ::ingraph::__private::store::Segments) {
            out.push(&self.media_id);
            out.push(&self.id);
        }
    }
    #[automatically_derived]
    impl ::core::convert::From<Video> for VideoKey {
        #[inline]
        fn from(record: Video) -> Self {
            Self {
                media_id: record.media_id,
                id: record.id,
            }
        }
    }
    #[automatically_derived]
    impl<'a> ::core::convert::From<&'a Video> for VideoKey {
        #[inline]
        fn from(record: &'a Video) -> Self {
            Self {
                media_id: ::core::clone::Clone::clone(&record.media_id),
                id: ::core::clone::Clone::clone(&record.id),
            }
        }
    }
    #[automatically_derived]
    impl ::core::convert::From<Video> for VideoLineage {
        #[inline]
        fn from(record: Video) -> Self {
            Self { media_id: record.media_id }
        }
    }
    #[automatically_derived]
    impl<'a> ::core::convert::From<&'a Video> for VideoLineage {
        #[inline]
        fn from(record: &'a Video) -> Self {
            Self {
                media_id: ::core::clone::Clone::clone(&record.media_id),
            }
        }
    }
    #[automatically_derived]
    impl ::ingraph::__private::operator::Emits for Video {
        type Out = Self;
    }
    #[automatically_derived]
    impl ::ingraph::__private::operator::SoleProduct for Video {}
    #[automatically_derived]
    impl ::ingraph::__private::drive::Declared for Video {
        /// What a [`Video`]'s outputs become — read off the kind it was declared under.
        const EFFECT: ::ingraph::__private::drive::Effect = ::ingraph::__private::drive::Effect::Lands;
        /// Whether a [`Video`] holds a write lane of its own — read off the same kind.
        const HOLDS_LANE: bool = true;
        /// Every upstream a [`Video`] draws from, in declaration order.
        const UPSTREAMS: &'static [::ingraph::__private::drive::Upstream] = &[];
        /// Every store a [`Video`] granted itself the right to write, in declaration order.
        const GRANTS: &'static [::ingraph::__private::drive::Grant] = &[];
        type Channels = ::ingraph::__private::drive::Unchanneled;
        type Options = ();
        /// A [`Video`] wrote no `stream`, so its body wears the BUFFERED pair — an `accept` per delivery, mounted at `Blueprint::node`.
        type Pair = ::ingraph::__private::drive::Buffered;
        /// A [`Video`] emits ONE thing, so it publishes through the framework's own fan-out set — N edges of that one product, the copy taken at the set rather than asked of any driver.
        type Wires<__INGRAPH_OUT__> = ::ingraph::__private::drive::Downstream<
            __INGRAPH_OUT__,
        >;
        /// A [`Video`] wrote no `attributed`, so it attributes its outputs to nothing — the unit projection, whose `Attributes` impl is the empty program and whose value is zero-sized. Its observations stay counter-grade, which is the shipped posture for every node that emits a payload with no declared root. The product parameter is the attributed road's and is unread here.
        type Attribution<__INGRAPH_OUT__> = ();
        /// A [`Video`] wrote no mode word, so its `accept` is the blocking face's — an `Operator` body, called by either engine and answering without a future.
        type Mode = ::ingraph::__private::operator::Block;
    }
    #[automatically_derived]
    impl ::ingraph::__private::drive::Attributes<Video>
    for ::ingraph::__private::drive::RootProjection<Video> {
        /// This root family's own name, read off the root type rather than off a column name so that every record sharing a root agrees on it without saying so.
        const FAMILY: &'static str = \"uuid7\";
        /// Which root key a [`Video`] descends from — its key's FIRST column, which is the `media_id` field. The root-key registry tables one machine per family, and this is what tells it which family a record of this type belongs to.
        type Root = Uuid7;
        #[inline]
        fn root(&self, record: &Video) -> Self::Root {
            ::core::clone::Clone::clone(&record.media_id)
        }
        #[inline]
        fn observe(
            &self,
            _root: &Self::Root,
            _worker: &::ingraph::__private::drive::NodeName,
            _arrival: &::ingraph::__private::drive::Arrival,
        ) {}
    }
};
";

// ---------------------------------------------------------------------------------------------
// The persist projections. Still models built BY HAND — nothing here parses a declaration.
// ---------------------------------------------------------------------------------------------

use crate::{
  model::{
    AliasOptions, Conversion, DatabaseBackend, DatabaseKind, MongoDatabase, MySqlDatabase, Persist,
    PersistColumn, PostgresDatabase, SqliteDatabase, Storage, default_row_name,
  },
  name::RustSafeName,
};

/// A column of a stored row, with every option at its default.
fn persist_column(source: &str, name: &str, ty: syn::Type) -> PersistColumn {
  PersistColumn {
    source: ident(source),
    name: RustSafeName::new(name, proc_macro2::Span::call_site()),
    domain: ty,
    stored: None,
    copy: false,
    edge: false,
    nullable: false,
    indexed: false,
    unique: false,
    flatten: false,
    from: Conversion::Default,
    into: Conversion::Default,
  }
}

/// One database's row, over the columns given.
fn stored(record: &syn::Ident, kind: DatabaseKind, columns: Vec<PersistColumn>) -> DatabaseBackend {
  let name = default_row_name(record, kind);
  let storage = Storage {
    comparison: default_comparison_name(&name),
    name,
    from: Conversion::Default,
    into: Conversion::Default,
    columns,
    fills: Vec::new(),
    aliases: AliasOptions::default(),
  };
  match kind {
    DatabaseKind::Sqlite => DatabaseBackend::Sqlite(SqliteDatabase {
      table: None,
      schema: None,
      uniques: Vec::new(),
      storage,
    }),
    DatabaseKind::Postgres => DatabaseBackend::Postgres(PostgresDatabase {
      table: None,
      schema: None,
      uniques: Vec::new(),
      storage,
    }),
    DatabaseKind::Mysql => DatabaseBackend::MySql(MySqlDatabase {
      table: None,
      schema: None,
      uniques: Vec::new(),
      storage,
    }),
    DatabaseKind::Mongo => DatabaseBackend::Mongo(MongoDatabase {
      collection: None,
      storage,
    }),
  }
}

/// One backend's mutable [`Storage`], for a test that adjusts a column after construction.
fn storage_of(database: &mut DatabaseBackend) -> &mut Storage {
  match database {
    DatabaseBackend::Sqlite(db) => &mut db.storage,
    DatabaseBackend::Postgres(db) => &mut db.storage,
    DatabaseBackend::MySql(db) => &mut db.storage,
    DatabaseBackend::Mongo(db) => &mut db.storage,
  }
}

/// A fallible conversion with no escape — the shape a short-form `try_from = "…"` settles into.
fn fallible(path: syn::Path) -> Conversion {
  Conversion::Fallible(FallibleConversion { path, escape: None })
}

/// A path, assembled rather than parsed.
fn path(rendered: &str) -> syn::Path {
  syn::parse_str(rendered).expect("a path")
}

/// The plan's own record as a model: two SQL databases and one mongo, over the two persisted
/// fields — `checksum`, which postgres stores as a `BeU64` written infallibly and read back
/// fallibly, and `cover_id`, which nothing overrides.
///
/// The names say which way each conversion runs, by the VERB RULE: `from` BUILDS the row (a write,
/// `store`) and `into` LEAVES it (a read, `raise`).
///
fn persisted() -> RecordModel {
  let mut model = model("VideoTrack", &["media_id", "video_id"], "id");
  let record = model.record.clone();
  let bit_rate = || persist_column("checksum", "bitrate", ty("u64"));
  let cover = || persist_column("cover_id", "cover_id", generic("Option", "Uuid7"));

  let sqlite = stored(&record, DatabaseKind::Sqlite, vec![bit_rate(), cover()]);
  let mut postgres = stored(&record, DatabaseKind::Postgres, vec![bit_rate(), cover()]);
  let postgres_storage = storage_of(&mut postgres);
  postgres_storage.name = ident("VideoTrackRecord");
  // A renamed row takes its comparison with it — the parser defaults the comparison from the ROW's
  // name, so a hand-built model says so too.
  postgres_storage.comparison = default_comparison_name(&ident("VideoTrackRecord"));
  postgres_storage.columns[0].name =
    RustSafeName::new("bit_rate_v2", proc_macro2::Span::call_site());
  postgres_storage.columns[0].stored = Some(ty("BeU64"));
  postgres_storage.columns[0].copy = true;
  postgres_storage.columns[0].indexed = true;
  postgres_storage.columns[0].from = Conversion::Infallible(path("path::to::store"));
  postgres_storage.columns[0].into = fallible(path("path::to::raise"));
  let mongo = stored(&record, DatabaseKind::Mongo, vec![bit_rate(), cover()]);

  model.persist = Some(Persist {
    backends: vec![sqlite, postgres, mongo],
    table: Some(RustSafeName::new(
      "video_tracks",
      proc_macro2::Span::call_site(),
    )),
  });
  model
}

/// A one-database model whose row carries EVERY field the record declares.
///
/// `pub(crate)` so the query face's own suite — `emit::tracing_tests`, which is about what the
/// entries LOOK like rather than about the rosters this file keeps — can drive the fixture that
/// actually HAS a query face rather than assembling a second one beside it.
pub(crate) fn whole_row() -> RecordModel {
  let mut model = model("Media", &[], "id");
  let record = model.record.clone();
  let columns = model
    .fields
    .iter()
    .map(|field| {
      persist_column(
        &field.column.source.to_string(),
        &field.column.source.to_string(),
        field.column.ty.clone(),
      )
    })
    .collect();
  model.persist = Some(Persist {
    backends: vec![stored(&record, DatabaseKind::Sqlite, columns)],
    table: None,
  });
  model
}

/// [`whole_row`] with its `chapters` column declared a SEQUENCE and stored as the element it keeps —
/// the shape a collection plan is emitted for.
///
/// The record's own `chapters` field already carries `Projection::Repeated`, so this is also the
/// model where the two axes are written at once and the WORD is what the emission reads.
pub(crate) fn gathered() -> RecordModel {
  let mut model = whole_row();
  label(
    &mut model,
    "chapters",
    Marker::Framework(FrameworkMarker {
      label: Label::List,
      element: None,
    }),
  );
  let Some(persist) = model.persist.as_mut() else {
    panic!("the model stores its columns")
  };
  let columns = &mut storage_of(&mut persist.backends[0]).columns;
  let at = columns
    .iter()
    .position(|column| column.source == ident("chapters"))
    .expect("the collection column is stored");
  // The declared type is ONE element's, and the crossing into the list of them is the declaration's
  // — which is what makes the row's field and the comparison's operand one fact.
  columns[at].stored = Some(ty("Uuid7"));
  columns[at].from = Conversion::Infallible(path("path::to::store"));
  model
}

/// [`gathered`] stored in MYSQL rather than SQLite — the other dialect with no array type, and so
/// the other one whose every collection is an edge table.
pub(crate) fn gathered_in_mysql() -> RecordModel {
  let mut model = gathered();
  let record = model.record.clone();
  let Some(persist) = model.persist.as_mut() else {
    panic!("the model stores its columns")
  };
  let columns = storage_of(&mut persist.backends[0]).columns.clone();
  persist.backends = vec![stored(&record, DatabaseKind::Mysql, columns)];
  model
}

/// [`gathered`] stored in POSTGRES, whose collection column rides the row as a native array — the
/// wordless default, and the only dialect that has one.
pub(crate) fn gathered_in_postgres() -> RecordModel {
  let mut model = gathered();
  let record = model.record.clone();
  let Some(persist) = model.persist.as_mut() else {
    panic!("the model stores its columns")
  };
  let columns = storage_of(&mut persist.backends[0]).columns.clone();
  persist.backends = vec![stored(&record, DatabaseKind::Postgres, columns)];
  model
}

/// [`gathered_in_postgres`] with the WORD written — the declaration saying this element belongs in
/// an edge table after all, which is the fact `PgCollectionStorage` holds and tokens cannot read.
pub(crate) fn edge_declared_in_postgres() -> RecordModel {
  let mut model = gathered_in_postgres();
  let Some(persist) = model.persist.as_mut() else {
    panic!("the model stores its columns")
  };
  let columns = &mut storage_of(&mut persist.backends[0]).columns;
  let at = columns
    .iter()
    .position(|column| column.source == ident("chapters"))
    .expect("the collection column is stored");
  columns[at].edge = true;
  model
}

/// [`whole_row`] with its `checksum` column declared `flatten` — a COMPOSITE, which is the other
/// shape the order-by breaks on, one axis over from a collection.
fn composed() -> RecordModel {
  let mut model = whole_row();
  let Some(persist) = model.persist.as_mut() else {
    panic!("the model stores its columns")
  };
  let columns = &mut storage_of(&mut persist.backends[0]).columns;
  let at = columns
    .iter()
    .position(|column| column.source == ident("checksum"))
    .expect("the composite column is stored");
  columns[at].flatten = true;
  model
}

/// The name of the trait an impl implements, and the type it is for.
fn conversions(file: &syn::File) -> Vec<(String, String)> {
  trait_impls(file)
    .into_iter()
    .filter(|(_, trait_path)| {
      let rendered = tight(trait_path);
      rendered.contains("::From<") || rendered.contains("::TryFrom<")
    })
    .map(|(item, trait_path)| (tight(trait_path), impl_of(item)))
    .collect()
}

/// The attributes of one struct's fields, in declaration order.
fn field_attrs(item: &syn::ItemStruct) -> Vec<String> {
  named(item)
    .iter()
    .flat_map(|field| field.attrs.iter().map(tight))
    .collect()
}

/// The `FromRow` impl a SQL row carries — emitted rather than derived, so it is an item to inspect.
fn from_row_impl<'a>(file: &'a syn::File, row: &str) -> &'a syn::ItemImpl {
  trait_impls(file)
    .into_iter()
    .find(|(item, path)| impl_of(item) == row && tight(path).contains("FromRow"))
    .map(|(item, _)| item)
    .unwrap_or_else(|| panic!("`{row}` carries a `FromRow` impl"))
}

/// Every `(field, name)` pair one row's decode reads, in the order it reads them.
///
/// The PAIR is the point: a decode that read the right columns into the wrong fields would still
/// name every column, so a list of either half alone cannot see a transposition between two columns
/// of one type — which is exactly the defect this emission can produce.
///
/// The name is [`None`] for a `flatten` field, and that is the field lending none rather than a
/// failure to parse one: its type's segments are named in the HOLDER's namespace, so there is no
/// name for the read to write and the entry point it goes through is the other one.
fn decoded(file: &syn::File, row: &str) -> Vec<(String, Option<String>)> {
  methods(from_row_impl(file, row))
    .into_iter()
    .flat_map(|method| &method.block.stmts)
    .filter_map(|statement| {
      let syn::Stmt::Local(local) = statement else {
        return None;
      };
      let syn::Pat::Type(annotated) = &local.pat else {
        return None;
      };
      let syn::Pat::Ident(field) = &*annotated.pat else {
        return None;
      };
      let read = tight(local.init.as_ref()?.expr.as_ref());
      let name = read
        .split("FieldName::new(\"")
        .nth(1)
        .and_then(|rest| rest.split('"').next())
        .map(ToOwned::to_owned);
      Some((field.ident.to_string(), name))
    })
    .collect()
}

/// The pairs a test expects, owned so they compare against [`decoded`]'s.
fn binds(pairs: &[(&str, &str)]) -> Vec<(String, Option<String>)> {
  pairs
    .iter()
    .map(|(field, column)| ((*field).to_owned(), Some((*column).to_owned())))
    .collect()
}

/// One item, rendered the way a human reads an expansion back.
fn rendered(item: &syn::ItemImpl) -> String {
  let file = syn::parse2(item.to_token_stream()).expect("one item is a parsable file");
  prettyplease::unparse(&file)
}

pub(crate) fn struct_named<'a>(file: &'a syn::File, name: &str) -> &'a syn::ItemStruct {
  structs(file)
    .into_iter()
    .find(|item| item.ident == name)
    .unwrap_or_else(|| panic!("`{name}` is emitted"))
}

pub(crate) fn enum_named<'a>(file: &'a syn::File, name: &str) -> &'a syn::ItemEnum {
  file
    .items
    .iter()
    .find_map(|item| match item {
      syn::Item::Enum(item) if item.ident == name => Some(item),
      _ => None,
    })
    .unwrap_or_else(|| panic!("`{name}` is emitted"))
}

/// One concrete struct per declared database, beside the key and the lineage — not a generic
/// `Row<DB>`.
#[test]
fn every_declared_database_gets_its_own_row_type() {
  assert_eq!(
    names(&emission(&persisted())),
    [
      "VideoTrackKey",
      "VideoTrackLineage",
      "VideoTrackSqlite",
      "VideoTrackSqliteComparison",
      "VideoTrackRecord",
      "VideoTrackRecordComparison",
      "VideoTrackMongo",
      "VideoTrackMongoComparison"
    ],
    "in declaration order, each row followed by the comparison that shares its declaration — a \
     renamed row takes the name the model gives it, and its comparison follows that name rather \
     than the record's"
  );
}

/// A record with no `persist` emits no row at all — the roster the rest of these tests use.
#[test]
fn an_record_with_no_persist_emits_no_row() {
  for model in [video_track(), video(), media()] {
    assert!(model.persist.is_none());
    assert_eq!(
      names(&emission(&model)).len(),
      model.lineage.iter().count() + 1
    );
  }
}

/// A SQL row derives nothing of sqlx's — its `FromRow` is an emitted impl, so the derive list is the
/// `core` trio alone; the mongo document derives serde's pair through the shelf and says so at the
/// container. Neither derives `Eq` or `Hash` — a row carries whatever the record stores, and `f64` is
/// neither.
///
/// The asymmetry is the derive vendors': serde's takes `#[serde(crate = "…")]` and sqlx's takes no
/// crate-path key at all, so only one of the two can be reached AS A DERIVE through a re-export. See
/// [`crate::emit::sql`].
#[test]
fn each_family_carries_its_own_derives() {
  let file = emission(&persisted());
  for name in ["VideoTrackSqlite", "VideoTrackRecord"] {
    let attrs: Vec<String> = struct_named(&file, name)
      .attrs
      .iter()
      .filter(|attr| !attr.path().is_ident("doc"))
      .map(tight)
      .collect();
    // NO `PartialEq`: row equality is EMITTED beside the row, folding each field's own `ColumnEq`
    // — see `DatabaseBackend::equality`, and `the_row_writes_its_own_equality` below.
    assert_eq!(
      attrs,
      ["#[derive(::core::fmt::Debug,::core::clone::Clone)]"],
      "{name}"
    );
  }
  let attrs: Vec<String> = struct_named(&file, "VideoTrackMongo")
    .attrs
    .iter()
    .filter(|attr| !attr.path().is_ident("doc"))
    .map(tight)
    .collect();
  assert_eq!(
    attrs,
    [
      "#[derive(::core::fmt::Debug,::core::clone::Clone,::ingraph::__private::serde::Serialize,::ingraph::__private::serde::Deserialize)]",
      "#[serde(crate=\"::ingraph::__private::serde\")]"
    ]
  );
}

/// **THE ROW WRITES ITS OWN EQUALITY**, and that is the whole of what replaced `#[derive(PartialEq)]`
/// on the two types carrying an author's declared field types.
///
/// A derive demanded a std trait OF EVERY FIELD TYPE, in generated code an author cannot edit — so a
/// field type with no `PartialEq`, `regex::Regex` being the first, was an error raised inside an
/// expansion. The impl below asks each field for `ColumnEq` instead, whose row is `self == other` for
/// every type that has a `PartialEq`: the same comparison, made in this framework's own vocabulary,
/// and refused BY NAME at the field when a type has no row.
///
/// The projection is what makes the refusal land where the author can act on it — `<Ty as ColumnEq>`
/// spanned at the field, exactly as the storability audit's `StoredAs` projection is.
#[test]
fn the_row_writes_its_own_equality() {
  let file = emission(&persisted());
  let written = trait_impls(&file)
    .into_iter()
    .filter(|(item, path)| {
      impl_of(item) == "VideoTrackSqlite" && tight(path) == "::core::cmp::PartialEq"
    })
    .map(|(item, _)| tight(item))
    .collect::<Vec<_>>();

  assert_eq!(
    written,
    [concat!(
      "#[automatically_derived]",
      "impl::core::cmp::PartialEqforVideoTrackSqlite{",
      "#[inline]",
      "fneq(&self,__ingraph_other:&Self)->::core::primitive::bool{",
      "<u64as::ingraph::__private::column::ColumnEq>::column_eq(",
      "&self.bitrate,&__ingraph_other.bitrate)",
      "&&<Option<Uuid7>as::ingraph::__private::column::ColumnEq>::column_eq(",
      "&self.cover_id,&__ingraph_other.cover_id)",
      "}}"
    )],
    "one `ColumnEq` per stored column, folded, and nothing else"
  );

  // The CURSOR sum carries the same face for the same reason, one arm per variant — and a `_ => false`
  // arm, because two slots naming different columns are two values however their contents read.
  let paged = trait_impls(&emission(&composed()))
    .into_iter()
    .filter(|(item, path)| {
      impl_of(item) == "MediaSqliteCursor" && tight(path) == "::core::cmp::PartialEq"
    })
    .map(|(item, _)| tight(item))
    .collect::<Vec<_>>();
  assert_eq!(paged.len(), 1, "the page boundary compares too: {paged:?}");
  assert!(
    paged[0].contains("::ingraph::__private::column::ColumnEq>::column_eq"),
    "{}",
    paged[0]
  );
  assert!(
    paged[0].contains("#[allow(unreachable_patterns)]_=>false"),
    "a slot carries WHICH column it was written from: {}",
    paged[0]
  );
}

/// Fields in declaration order, and EVERY column's external name written out — uniformly, not only
/// when the name had to be mangled.
///
/// WHERE it is written is the family's answer. A mongo document carries `#[serde(rename = "…")]` on
/// the field, for the derive to read. A SQL row carries NO field attribute at all — `#[sqlx(…)]` is a
/// helper attribute, legal only where a derive on the same item registers it, so it left with the
/// derive — and names the column at the `try_get` that reads it instead.
#[test]
fn every_row_field_carries_its_external_name() {
  let file = emission(&persisted());
  assert_eq!(
    fields(struct_named(&file, "VideoTrackSqlite")),
    ["bitrate", "cover_id"]
  );
  assert!(
    field_attrs(struct_named(&file, "VideoTrackSqlite")).is_empty(),
    "{:?}",
    field_attrs(struct_named(&file, "VideoTrackSqlite"))
  );
  assert_eq!(
    decoded(&file, "VideoTrackSqlite"),
    binds(&[("bitrate", "bitrate"), ("cover_id", "cover_id")])
  );
  assert_eq!(
    decoded(&file, "VideoTrackRecord"),
    binds(&[("bit_rate_v2", "bit_rate_v2"), ("cover_id", "cover_id")]),
    "a per-database rename reaches the read that fetches the column"
  );
  assert_eq!(
    field_attrs(struct_named(&file, "VideoTrackMongo")),
    [
      "#[serde(rename=\"bitrate\",with=\"::ingraph::__private::query::mongo::via\")]",
      "#[serde(rename=\"cover_id\",with=\"::ingraph::__private::query::mongo::via\")]"
    ],
    "mongo has no dialect, and no parameter shaped like one — and every field crosses the via, \
     which is ONE path for every column rather than one this emitter chose per type"
  );
}

/// Every SQL row's decode binds each of its fields exactly once, in the struct's own declaration
/// order, from a column of its own.
///
/// This is the SHAPE half of the anti-transposition guard, and it is mechanical: the next row shape
/// added anywhere is checked without anyone remembering to check it. The VALUE half is
/// `ingraph-derive`'s live-database fixture, which reads a row back out of SQLite and compares the
/// columns — because two same-typed columns swapped between fields is a defect that compiles.
#[test]
fn a_sql_rows_decode_binds_every_field_once_in_declaration_order() {
  for model in [persisted(), whole_row(), aliased(wired())] {
    let file = emission(&model);
    for database in model.persist.iter().flat_map(|persist| &persist.backends) {
      if !database.kind().is_sql() {
        continue;
      }
      let row = database.name().to_string();
      let pairs = decoded(&file, &row);
      assert_eq!(
        pairs
          .iter()
          .map(|(field, _)| field.clone())
          .collect::<Vec<_>>(),
        fields(struct_named(&file, &row)),
        "`{row}` decodes its fields in declaration order, each exactly once"
      );
      // The NAMED reads alone: a `flatten` field lends none, and no declaration among these three
      // marks one — a row that did would have its rendered names fenced by `column::distinct`
      // instead, which is where a collision between segments is reachable at all.
      let mut columns: Vec<&String> = pairs
        .iter()
        .filter_map(|(_, column)| column.as_ref())
        .collect();
      assert_eq!(
        columns.len(),
        pairs.len(),
        "`{row}` names every field it reads"
      );
      columns.sort();
      let read = columns.len();
      columns.dedup();
      assert_eq!(columns.len(), read, "`{row}` reads no column twice");
    }
  }
}

/// A `type` override is what the row's field carries; without one it is the domain type.
#[test]
fn the_row_field_carries_the_stored_type() {
  let file = emission(&persisted());
  let types = |name: &str| -> Vec<String> {
    named(struct_named(&file, name))
      .iter()
      .map(|field| tight(&field.ty))
      .collect()
  };
  assert_eq!(types("VideoTrackSqlite"), ["u64", "Option<Uuid7>"]);
  assert_eq!(types("VideoTrackRecord"), ["BeU64", "Option<Uuid7>"]);
}

/// A column's name may be something Rust cannot spell: the FIELD is mangled and the DECODE reads the
/// real name.
#[test]
fn a_column_rust_cannot_spell_still_emits() {
  let mut model = whole_row();
  let database = storage_of(&mut model.persist.as_mut().expect("stored").backends[0]);
  database.columns[0].name = RustSafeName::new("bit-rate", proc_macro2::Span::call_site());
  database.columns[1].name = RustSafeName::new("type", proc_macro2::Span::call_site());
  let file = emission(&model);
  let row = struct_named(&file, "MediaSqlite");
  assert_eq!(fields(row)[..2], ["bit_rate", "type_"]);
  assert_eq!(
    decoded(&file, "MediaSqlite")[..2],
    binds(&[("bit_rate", "bit-rate"), ("type_", "type")])[..],
    "the mangling is the FIELD's; the database still sees `bit-rate` and `type`"
  );
  assert!(
    method_names(&file).contains(&"bit_rate_ref".to_owned()),
    "and the accessor takes the Rust face"
  );
}

/// A row's methods are ACCESSORS and nothing else: no `new`, because a real aggregate's positional
/// constructor is unusable and a row already has two construction paths; no mutators, because
/// nothing edits a row in place.
#[test]
fn a_row_gets_accessors_and_neither_a_constructor_nor_mutators() {
  let file = emission(&persisted());
  assert_eq!(
    methods_of(&file, "VideoTrackSqlite"),
    ["bitrate_ref", "cover_id_ref"]
  );
  assert_eq!(
    methods_of(&file, "VideoTrackRecord"),
    ["bit_rate_v2", "bit_rate_v2_ref", "cover_id_ref"],
    "`copy` in the database block adds the by-value accessor, exactly as the domain marker does"
  );
}

/// `copy` is the DATABASE's claim about the STORED type. The same column is `copy` in postgres and
/// not in sqlite, and the domain field's own marker says nothing about either.
#[test]
fn the_copy_claim_is_the_databases_not_the_domains() {
  let file = emission(&persisted());
  assert!(!methods_of(&file, "VideoTrackSqlite").contains(&"bitrate".to_owned()));
  assert!(is_const(method_of(
    &file,
    "VideoTrackRecord",
    "bit_rate_v2"
  )));
}

/// A row column is never projected through `Repeated`/`Optional`: those are the domain field's
/// shapes, and a stored column is whatever the database holds.
#[test]
fn a_row_column_is_never_projected_through_a_framework_trait() {
  let file = emission(&persisted());
  assert_eq!(
    returns(method_of(&file, "VideoTrackSqlite", "cover_id_ref")),
    "&Option<Uuid7>",
    "an `Option<_>` column is borrowed as itself — nullability is the schema's business"
  );
}

/// EXACTLY ONE of `From`/`TryFrom` per direction. `core`'s `impl<T, U: Into<T>> TryFrom<U> for T`
/// means an emitted `From` already yields a `TryFrom`, so emitting both collides under coherence.
#[test]
fn exactly_one_of_from_and_try_from_is_emitted_per_direction() {
  let file = emission(&persisted());
  let pairs = conversions(&file);
  let of = |row: &str| -> Vec<String> {
    pairs
      .iter()
      .filter(|(trait_path, target)| target == row || trait_path.contains(&format!("<{row}>")))
      .map(|(trait_path, target)| format!("{trait_path} for {target}"))
      .collect()
  };
  assert_eq!(
    of("VideoTrackSqlite"),
    ["::core::convert::From<VideoTrack> for VideoTrackSqlite"],
    "nothing is fallible, and the row is partial — so one direction, infallible"
  );
  assert_eq!(
    of("VideoTrackRecord"),
    ["::core::convert::From<VideoTrack> for VideoTrackRecord"],
    "the fallible one here is `into` — which by the VERB RULE LEAVES the row, so it is the read — \
     and the read is not emitted for a partial row. What is left is the infallible write. \
     Fallibility is decided per DIRECTION."
  );

  let mut fallible_write = persisted();
  storage_of(&mut fallible_write.persist.as_mut().expect("stored").backends[0]).columns[0].from =
    fallible(path("narrow"));
  assert!(
    conversions(&emission(&fallible_write))
      .iter()
      .any(
        |(trait_path, target)| trait_path == "::core::convert::TryFrom<VideoTrack>"
          && target == "VideoTrackSqlite"
      ),
    "and one fallible column in the direction being emitted makes that whole direction fallible"
  );
  for (trait_path, target) in &pairs {
    let both = pairs
      .iter()
      .filter(|(other, other_target)| {
        other_target == target
          && other.replace("TryFrom", "From") == trait_path.replace("TryFrom", "From")
      })
      .count();
    assert_eq!(both, 1, "`{trait_path}` for `{target}` is emitted once");
  }
}

/// The reverse direction exists only when it CAN: field-wise when the row carries every field, and
/// otherwise only when the database declared a conversion for the whole row.
#[test]
fn the_reverse_conversion_needs_a_whole_row_or_a_container_conversion() {
  assert_eq!(
    conversions(&emission(&persisted()))
      .iter()
      .filter(|(_, target)| target == "VideoTrack")
      .count(),
    0,
    "a partial row cannot rebuild the record it does not carry"
  );

  let file = emission(&whole_row());
  assert_eq!(
    conversions(&file)
      .into_iter()
      .filter(|(trait_path, target)| trait_path.contains("MediaSqlite") || target == "MediaSqlite")
      .collect::<Vec<_>>(),
    [
      (
        "::core::convert::From<Media>".to_owned(),
        "MediaSqlite".to_owned()
      ),
      (
        "::core::convert::From<MediaSqlite>".to_owned(),
        "Media".to_owned()
      ),
    ],
    "a total row goes both ways"
  );

  let mut declared = persisted();
  storage_of(&mut declared.persist.as_mut().expect("stored").backends[0]).into =
    Conversion::Infallible(path("rebuild"));
  assert!(
    conversions(&emission(&declared))
      .iter()
      .any(
        |(trait_path, target)| trait_path.contains("From<VideoTrackSqlite>")
          && target == "VideoTrack"
      ),
    "the container conversion is the seam for supplying what a partial row is missing"
  );
}

/// A declared conversion is CALLED; a `type` override without one goes through `Into`; and a
/// column that is neither is moved. Which declaration a direction reads is the VERB RULE's:
/// `from` builds the row, so it is what `impl From<Record> for Row` calls.
#[test]
fn each_column_is_converted_the_way_the_declaration_says() {
  let body = |file: &syn::File, name: &str| -> String {
    trait_impls(file)
      .into_iter()
      .find(|(item, _)| impl_of(item) == name)
      .map(|(item, _)| tight(item))
      .unwrap_or_else(|| panic!("`{name}` has a conversion"))
  };
  let file = emission(&persisted());
  assert!(
    body(&file, "VideoTrackRecord").contains("bit_rate_v2:path::to::store(record.checksum)"),
    "{}",
    body(&file, "VideoTrackRecord")
  );
  assert!(
    body(&file, "VideoTrackSqlite").contains("bitrate:record.checksum"),
    "no override and no conversion — the value is moved, with no reflexive `Into` in the way"
  );

  let mut converted = whole_row();
  storage_of(&mut converted.persist.as_mut().expect("stored").backends[0]).columns[0].stored =
    Some(ty("BeU64"));
  assert!(
    body(&emission(&converted), "MediaSqlite")
      .contains("id:::core::convert::Into::into(record.id)"),
    "a `type` override with no declared conversion goes through `Into`"
  );
}

/// The fallible read is applied with `?`, under a `TryFrom` whose error is the boxed one.
#[test]
fn a_fallible_conversion_uses_the_question_mark_and_a_boxed_error() {
  let mut model = whole_row();
  storage_of(&mut model.persist.as_mut().expect("stored").backends[0]).columns[0].into =
    fallible(path("check"));
  let file = emission(&model);
  let raise = trait_impls(&file)
    .into_iter()
    .find(|(item, path)| impl_of(item) == "Media" && tight(path).contains("TryFrom"))
    .map(|(item, _)| tight(item))
    .expect("the fallible read is a `TryFrom`");
  assert!(raise.contains("id:check(row.id)?"), "{raise}");
  assert!(
    raise.contains(
      "typeError=::std::boxed::Box<dyn::core::error::Error+::core::marker::Send+::core::marker::Sync+'static>"
    ),
    "{raise}"
  );
}

/// **A DECLARED CELL REPLACES THE BOX, AND EVERY CELL IS ITS OWN LEG'S.**
///
/// The error a fallible conversion answers with is the record's own, at the cell that crossing's LEG
/// names — so a row's WRITE, its READ and the crossing onto the wire object each answer with what
/// their own leg named, which is the correspondence a single flat error per record could not
/// express.
///
/// The WRITE leg is the one that changed. Its cell used to be a refuse-until with no impl to type,
/// so its conversion kept the box whatever a record said; `query::sql::write` is the impl, and this
/// is where the knob stopped doing nothing.
///
/// The READ cell is declared here and not asserted, deliberately: this model's row carries a key
/// this record's fields do not, so the field-wise read is not emitted at all — see
/// [`DatabaseBackend::carries_every_field`](crate::model::DatabaseBackend). What it is here for is
/// the independence claim, which is what the two assertions below really say: a third cell in the
/// same declaration reaches neither of them.
#[test]
fn a_declared_cell_types_its_own_crossing_and_reaches_no_other() {
  let mut model = ordered();
  {
    let sqlite = storage_of(&mut model.persist.as_mut().expect("stored").backends[0]);
    // One column fallible in BOTH directions, so the row carries a `TryFrom` each way and the two
    // cells have an impl apiece to land on.
    sqlite.columns[3].from = fallible(path("store"));
    sqlite.columns[3].into = fallible(path("check"));
  }
  model.errors = vec![
    crate::model::BackendError {
      crossing: crate::model::Crossing::PersistWrite,
      kind: DatabaseKind::Sqlite,
      path: path("crate::StoreRefusal"),
    },
    crate::model::BackendError {
      crossing: crate::model::Crossing::PersistRead,
      kind: DatabaseKind::Sqlite,
      path: path("crate::RowRefusal"),
    },
    crate::model::BackendError {
      crossing: crate::model::Crossing::Output,
      kind: DatabaseKind::Sqlite,
      path: path("crate::WireRefusal"),
    },
  ];
  let file = emission(&model);
  let crossing = |self_type: &str| {
    trait_impls(&file)
      .into_iter()
      .find(|(item, path)| impl_of(item) == self_type && tight(path).contains("TryFrom"))
      .map(|(item, _)| tight(item))
      .unwrap_or_else(|| panic!("`{self_type}` is the target of a fallible crossing"))
  };

  let store = crossing("VideoTrackSqlite");
  assert!(
    store.contains("typeError=crate::StoreRefusal"),
    "the WRITE leg's cell types the impl the write lane crosses through: {store}"
  );
  assert!(
    !store.contains("RowRefusal") && !store.contains("WireRefusal"),
    "and neither of the other two reaches it: {store}"
  );
  let onto_wire = crossing("VideoTrackGraphqlOutput");
  assert!(
    onto_wire.contains("typeError=crate::WireRefusal"),
    "the crossing onto the wire answers with its own, which is what a per-leg cell is for: \
     {onto_wire}"
  );
}

/// The era rule holds over the rows too: `From`/`TryFrom` are `core`'s, `FromRow` is sqlx's, and
/// nothing names the framework's own still-moving trait layer beyond the QUERY BINDINGS.
///
/// Scoped to the ROWS rather than to the emission, because the emission is no longer free of
/// framework trait impls: the COMPARISON carries the lowering, which is the item bound's other half.
/// [`the_wire_face_declares_only_the_authorised_trait_impl`] is what covers the whole emission, and
/// it checks each impl's self type against the model — so a lowering that landed on a row would be
/// refused there as well as here.
///
/// # The two the row DOES declare, and the ground they stand on
///
/// `SqlQuery`, `SqlOrdering` and `SqlWrite` are implemented on the row, because a row is what one
/// database IS here: the column names, the stored types and the table all vary with exactly that,
/// and a declaration storing two databases needs bindings that cannot collide. What they bind is the
/// emitter's own output plus the engine's settled seam — the row, the comparison, the order-by, the
/// cursor value — which is the same ground the address binding stands on.
///
/// They are named EXPLICITLY rather than allowed by shape, so a fourth framework trait arriving on a
/// **THE SCHEMA BINDING is on the RECORD, at a CONCRETE backend, once per DESCRIBABLE database** —
/// and its arm of the allowlist is what says an impl on any other self type would be refused.
///
/// The general walk over that allowlist runs on fixtures whose query face is not emitted at all, so
/// the newest authorised impl needs a roster of its own: `queried` is the smallest model in this
/// file carrying one, its id being stored, its wire face declared and its rows raisable.
///
/// What is checked is the PAIR rather than the trait: the record as the self type, and a backend a
/// declared database really is — so a blueprint at a database this declaration never named, or one
/// landed on the ROW beside its `SqlQuery`, is refused exactly as a twenty-fourth trait would be.
#[test]
fn the_schema_binding_is_on_the_record_once_per_describable_database() {
  let model = queried();
  let file = emission(&model);
  let described: Vec<String> = trait_impls(&file)
    .into_iter()
    .filter(|(_, path)| tight(path).contains("schema::Describe"))
    .map(|(item, path)| format!("{} for {}", tight(path), impl_of(item)))
    .collect();
  let backends: Vec<String> = model
    .describable()
    .into_iter()
    .map(|database| tight(database.backend_type(&model)))
    .collect();
  assert_eq!(
    described.len(),
    backends.len(),
    "one blueprint per describable database: {described:?}"
  );
  assert!(!backends.is_empty(), "`queried` describes at least one");
  for backend in &backends {
    assert!(
      described
        .iter()
        .any(|row| row.contains(backend) && row.ends_with(&format!(" for {}", model.record))),
      "the blueprint for {backend} is on the record: {described:?}"
    );
  }
  // …and the allowlist agrees, which is what keeps the two from drifting: a self type this walk
  // accepted and that predicate refused would be a rule stated twice and kept once.
  assert!(
    unauthorised_framework_impls(&model, &file)
      .iter()
      .all(|row| !row.contains("schema::Describe")),
    "and every one of them is authorised"
  );
}

/// row fails here.
#[test]
fn the_rows_declare_no_framework_trait_impl() {
  const QUERY_BINDINGS: [&str; 3] = [
    "query::sql::SqlQuery",
    "query::sql::SqlOrdering",
    "query::sql::SqlWrite",
  ];

  for model in [persisted(), whole_row()] {
    let file = emission(&model);
    let rows: Vec<String> = model
      .persist
      .iter()
      .flat_map(|persist| &persist.backends)
      .map(|database| database.name().to_string())
      .collect();
    let framework: Vec<String> = trait_impls(&file)
      .into_iter()
      .filter(|(item, _)| rows.contains(&impl_of(item)))
      .filter(|(_, path)| framework_rooted(path, &model.krate))
      .map(|(_, path)| tight(path))
      .filter(|path| !QUERY_BINDINGS.iter().any(|binding| path.contains(binding)))
      .collect();
    assert!(framework.is_empty(), "{framework:?}");
    assert!(
      framework_paths_not_through_a_private_module(&model).is_empty(),
      "and every framework path still goes through `__private`"
    );
  }
}

/// **THE QUERY BINDING NAMES THE RECORD AND THE ADDRESS, AND NO COMPARISON OF ITS OWN.**
///
/// `SqlQuery::Comparison` is gone: what a predicate over a row looks like is the RECORD's fact, and
/// the engine reads it as `<Self::Record as Record<Db>>::Comparison`. An emission that resurrected
/// the slot would give a row two answers to one question and let the two drift, which is exactly
/// what the vocabulary was landed to stop.
///
/// The set is asserted whole rather than by absence, so a slot arriving as well as leaving is
/// caught. `Address` stays — a filter says which rows are wanted and an address says which row IS.
///
/// [`whole_row`] rather than [`persisted`], because a query face needs the KEY stored and that is
/// the model whose row carries every field.
#[test]
fn the_query_binding_declares_the_record_and_the_address_alone() {
  let file = emission(&whole_row());
  let slots: Vec<Vec<String>> = trait_impls(&file)
    .into_iter()
    .filter(|(_, path)| tight(path).contains("query::sql::SqlQuery"))
    .map(|(item, _)| {
      item
        .items
        .iter()
        .filter_map(|item| match item {
          syn::ImplItem::Type(bound) => Some(bound.ident.to_string()),
          _ => None,
        })
        .collect()
    })
    .collect();
  assert_eq!(
    slots,
    [["Record".to_owned(), "Address".to_owned()]],
    "one binding per SQL database, naming the record and the address and nothing else"
  );
}

/// **THE PAGE BINDING STATES WHAT ITS TERMS COMPARE, AND ITS VALUE READS THE ROW IT DECODED.**
///
/// Two facts, and each is a place the emission could go quietly wrong.
///
/// `Subjects` is `TermColumns` because every term of an emitted order IS a column — and it is
/// STATED rather than defaulted, an associated type having none: a binding that left it out would
/// not compile, which is the full-set law holding here as it holds on the vocabulary.
///
/// `value` takes the raw driver row and the alias beside it and reads NEITHER. That is what a record
/// with no ordering term over a neighbour looks like from this seam: the page statement carries
/// nothing its own columns did not, so the decoded row answers every term. The parameters are
/// present all the same, for the reason [`At`]'s row is present at every comparison — the seam is
/// one shape whether or not a given implementor spends it.
///
/// [`At`]: ingraph::At
#[test]
fn the_page_binding_names_its_subjects_and_reads_the_decoded_row() {
  let file = emission(&whole_row());
  let bindings: Vec<(Vec<String>, usize)> = trait_impls(&file)
    .into_iter()
    .filter(|(_, path)| tight(path).contains("query::sql::SqlOrdering"))
    .map(|(item, _)| {
      let slots = item
        .items
        .iter()
        .filter_map(|item| match item {
          syn::ImplItem::Type(bound) => Some(bound.ident.to_string()),
          _ => None,
        })
        .collect();
      let arity = item
        .items
        .iter()
        .find_map(|item| match item {
          syn::ImplItem::Fn(method) if method.sig.ident == "value" => Some(method.sig.inputs.len()),
          _ => None,
        })
        .expect("the page binding projects the row into cursor values");
      (slots, arity)
    })
    .collect();
  assert_eq!(
    bindings,
    [(
      vec![
        "Order".to_owned(),
        "Value".to_owned(),
        "Subjects".to_owned()
      ],
      // `&self`, the term, the LEVEL's own leaf, the raw row and the alias the engine wrote it
      // under. The leaf is what makes a citizen that states a semantic sequence answerable per
      // level: the same word is asked once per leaf, and everything else has one leaf and is asked
      // at `0`.
      5
    )],
    "one page binding per SQL database, naming three slots and reading the row at five"
  );
}

/// [`whole_row`] with a LINEAGE and a renamed id — the model that can tell a one-column address from
/// the whole key.
///
/// [`whole_row`] itself is a ROOT, whose key IS its id, so nothing about the collapse is visible
/// there; [`ordered`] has the lineage but a PARTIAL row, so it gets no query face to read at all.
/// This is both halves: every field stored, so the row raises, and two lineage steps before the id.
fn nested_whole_row() -> RecordModel {
  let mut model = model("VideoTrack", &["media_id", "video_id"], "id");
  let record = model.record.clone();
  let columns: Vec<PersistColumn> = model
    .fields
    .iter()
    .map(|field| {
      persist_column(
        &field.column.source.to_string(),
        &field.column.source.to_string(),
        field.column.ty.clone(),
      )
    })
    .collect();

  let sqlite = stored(&record, DatabaseKind::Sqlite, columns.clone());
  let mut postgres = stored(&record, DatabaseKind::Postgres, columns);
  let storage = storage_of(&mut postgres);
  storage.name = ident("VideoTrackRecord");
  storage.comparison = default_comparison_name(&ident("VideoTrackRecord"));
  // The id, and only in this database — a tail or an address reading the KEY TYPE's spelling would
  // name a column postgres has not got.
  storage.columns[2].name = RustSafeName::new("pk", proc_macro2::Span::call_site());

  model.persist = Some(Persist {
    backends: vec![sqlite, postgres],
    table: Some(RustSafeName::new(
      "video_tracks",
      proc_macro2::Span::call_site(),
    )),
  });
  model
}

/// **THE ADDRESS IS THE ID COLUMN, ALONE — and the lineage columns are stored beside it.**
///
/// [`nested_whole_row`] is the model that can tell the two apart: its row stores `media_id`,
/// `video_id` and `id` at its head, and postgres renames the id to `pk`. So an address still reading
/// the whole key would name three columns here, and one reading the key type's own spelling would
/// name a column postgres has not got.
///
/// FOUR readings of the one fact, because they are four places it could drift: the `ADDRESS` const
/// the engine renders the predicate from, the `Address` type it renders it AS, the `address`
/// SIGNATURE that says what a caller may spend, and the body that fills the predicate in. The WIDTH
/// is checked as the general type at `1` rather than as a scalar predicate — `SqlKeyIn<_, _, 1>` is
/// the same machine a composite `Id` runs through, so the wide path cannot rot for want of a caller.
///
/// The signature is read for its QUALIFYING TRAIT as much as for its parameter: `Id` belongs to
/// `Identifiable`, qualification selects a trait's own items, and an emission naming `Transformer`
/// there would be `E0576` in every expansion.
#[test]
fn the_address_is_the_id_column_alone() {
  let file = emission(&nested_whole_row());
  let field_name = "::ingraph::__private::field::FieldName";
  let record_address = "::ingraph::__private::comparison::RecordAddress";
  let key_in = "::ingraph::__private::comparison::sql::SqlKeyIn";
  let identifiable = "::ingraph::__private::transform::Identifiable";
  let crossing = "::ingraph::__private::query::sql::CrossingError";
  let db = database_parameter();

  let bound = |item: &syn::ItemImpl, name: &str| {
    item
      .items
      .iter()
      .find_map(|item| match item {
        syn::ImplItem::Const(item) if item.ident == name => Some(tight(&item.expr)),
        syn::ImplItem::Type(item) if item.ident == name => Some(tight(&item.ty)),
        syn::ImplItem::Fn(item) if item.sig.ident == name => Some(tight(&item.block)),
        _ => None,
      })
      .unwrap_or_else(|| panic!("every binding states its `{name}`"))
  };
  let signature = |item: &syn::ItemImpl| {
    item
      .items
      .iter()
      .find_map(|item| match item {
        syn::ImplItem::Fn(item) if item.sig.ident == "addresses" => Some(tight(&item.sig)),
        _ => None,
      })
      .expect("every binding states its `addresses`")
  };

  let bindings: Vec<(String, String, String, String, String)> = trait_impls(&file)
    .into_iter()
    .filter(|(_, path)| tight(path).contains("query::sql::SqlQuery"))
    .map(|(item, _)| {
      (
        impl_of(item),
        bound(item, "ADDRESS"),
        bound(item, "Address"),
        signature(item),
        bound(item, "addresses"),
      )
    })
    .collect();

  // One per SQL database, and the id is spelled the way THAT database spells it.
  let expected = [
    ("VideoTrackSqlite", "VideoTrackSqliteCursor", "id"),
    ("VideoTrackRecord", "VideoTrackRecordCursor", "pk"),
  ];
  assert_eq!(
    bindings.len(),
    expected.len(),
    "one binding per SQL database: {bindings:?}"
  );
  for ((row, address, slot, takes, body), (name, cursor, column)) in bindings.iter().zip(expected) {
    assert_eq!(row, name, "the rows are walked in declaration order");
    assert_eq!(
      address,
      &format!(
        "{record_address}::new({field_name}::new(\"video_tracks\"),\
         &[{field_name}::new(\"{column}\")],)"
      ),
      "the address is the table and ONE column"
    );
    assert_eq!(
      slot,
      &format!("{key_in}<{cursor},{db},1>"),
      "the general row-value `IN` at width one, not a second scalar machine"
    );
    assert_eq!(
      takes,
      &format!(
        "fn addresses(ids: &[<VideoTrack as {identifiable}>::Id],) \
         -> ::core::result::Result<Self::Address, {crossing}>"
      )
      .replace(' ', ""),
      "the engine face is handed a SLICE of ids, qualified through the trait that OWNS one — one \
       predicate at every width, so `get` and an interface's id-gather lane render alike"
    );
    assert_eq!(
      body,
      &format!(
        "{{let mut __ingraph_keys=::std::vec::Vec::with_capacity(<[_]>::len(ids));\
         for __ingraph_id in ids{{::std::vec::Vec::push(&mut __ingraph_keys,\
         [{cursor}::Id(::core::clone::Clone::clone(__ingraph_id))]);}}\
         ::core::result::Result::Ok({key_in}::new([\"{column}\"],__ingraph_keys))}}"
      )
      .replace(' ', ""),
      "one part, one slot per id, and the value read off each id the caller spent"
    );
  }

  // The lineage columns did not leave storage — they are in the `SELECT` list, orderable and
  // filterable. What they left is the address above.
  let selected = plan_of(&file, "VideoTrackSqlite", "COLUMNS").expect("a stored row selects");
  let column_name = "::ingraph::__private::column::ColumnName";
  for column in ["media_id", "video_id"] {
    assert!(
      selected.contains(&format!("{column_name}::new(\"{column}\")")),
      "`{column}` is still a stored column of the row: {selected}"
    );
  }
}

/// The associated const `name` of the `SqlQuery` impl on `row`, or `None` where the binding states
/// none and takes the engine's default.
fn plan_of(file: &syn::File, row: &str, name: &str) -> Option<String> {
  trait_impls(file)
    .into_iter()
    .find(|(item, path)| impl_of(item) == row && tight(path).contains("query::sql::SqlQuery"))
    .and_then(|(item, _)| {
      item.items.iter().find_map(|item| match item {
        syn::ImplItem::Const(item) if item.ident == name => Some(tight(&item.expr)),
        _ => None,
      })
    })
}

/// **A COLLECTION COLUMN LEAVES `COLUMNS` AND ARRIVES IN `COLLECTIONS`.**
///
/// The two lists PARTITION the row's stored columns, which is the engine's own contract: a gathered
/// column has no value on the page row to select, so naming it in the `SELECT` list would ask the
/// row's own table for a column it has not got.
///
/// The plan states a PATH and a SHAPE and nothing else about the second table. Every name the
/// statement needs — the edge table, the `<field>_ordinal`, the parent keys — is derived from that
/// path by the engine, so this emission and `SqlEdgeComparison`'s lowering reach one table through
/// one derivation. A plan naming the wrong column is therefore a wrong TABLE rather than a subtly
/// wrong statement, which is what makes it visible.
#[test]
fn a_gathered_collection_leaves_the_select_list_for_the_plan() {
  let file = emission(&gathered());
  let shelf = "::ingraph::__private";
  assert_eq!(
    plan_of(&file, "MediaSqlite", "COLUMNS").expect("the query binding states its columns"),
    format!(
      "&[{shelf}::column::shape::<Uuid7>({shelf}::column::ColumnName::new(\"id\")),\
       {shelf}::column::shape::<u64>({shelf}::column::ColumnName::new(\"checksum\")),\
       {shelf}::column::shape::<Option<Uuid7>>({shelf}::column::ColumnName::new(\"cover_id\")),]"
    ),
    "`chapters` is not among them — it names no column of `media`"
  );
  assert_eq!(
    plan_of(&file, "MediaSqlite", "COLLECTIONS").expect("and states its plan"),
    format!(
      "&[{shelf}::query::sql::EdgeCollection::gather(\
       &[{shelf}::field::FieldName::new(\"chapters\")],\
       {shelf}::query::sql::EdgeShape::Sequence,\
       __ingraph_key_sqlite::<__INGRAPH_DB__>,\
       __ingraph_take_sqlite_chapters::<__INGRAPH_DB__>,),]"
    ),
    "one entry, carrying the column's path, its shape and the two typed crossings"
  );

  // A record whose columns this database keeps on the row says NOTHING: the engine defaults the
  // const, so the collection-free case pays one `is_empty` test and no emission.
  assert_eq!(
    plan_of(&emission(&whole_row()), "MediaSqlite", "COLLECTIONS"),
    None,
    "the same model without the word states no plan at all"
  );
}

/// **THE ALIAS KNOB IS PER DATABASE**, and both emissions of one record are read here — the
/// overridden one and the one beside it that took the defaults.
///
/// `ALIASES` rides one `SqlQuery<Db>` impl, which is the whole argument for putting the knob on the
/// database block: the two tables were always separate emissions, so nothing had to be widened to
/// let them differ. The record is the one the user story describes — a schema whose SQLite
/// deployment already holds legacy tables inside `__ig`, and a Postgres deployment that does not.
///
/// Both halves of the assertion are load-bearing:
///
/// * SQLITE's table is SIXTEEN entries long and every one of them wears `__mine`. An emission that
///   read the prefix and sized by `DEPTH_CEILING` anyway passes on the first eight and has nothing
///   at index eight, which is why the length is asserted through the last entry rather than a count.
/// * POSTGRES is untouched — eight entries under `__ig`. It is what makes this a knob rather than a
///   setting: an emission reading the record's first database and applying it to all of them would
///   move this one too.
#[test]
fn each_database_mints_its_aliases_in_its_own_namespace() {
  let mut model = whole_row();
  let record = model.record.clone();
  let persist = model.persist.as_mut().expect("the whole row is stored");
  let columns = storage_of(&mut persist.backends[0]).columns.clone();
  persist
    .backends
    .push(stored(&record, DatabaseKind::Postgres, columns));
  storage_of(&mut persist.backends[0]).aliases = AliasOptions {
    prefix: Some("__mine".to_owned()),
    depth: Some(16),
  };
  let file = emission(&model);

  let sqlite = plan_of(&file, "MediaSqlite", "ALIASES").expect("the row states its aliases");
  assert!(
    sqlite.starts_with("&[\"__mine_media_0__\",\"__mine_media_1__\","),
    "{sqlite}"
  );
  assert!(sqlite.ends_with("\"__mine_media_15__\"]"), "{sqlite}");

  assert_eq!(
    plan_of(&file, "MediaPostgres", "ALIASES").expect("and so does the one beside it"),
    "&[\"__ig_media_0__\",\"__ig_media_1__\",\"__ig_media_2__\",\"__ig_media_3__\",\
      \"__ig_media_4__\",\"__ig_media_5__\",\"__ig_media_6__\",\"__ig_media_7__\"]",
    "the database that named nothing keeps the framework's own answers"
  );
}

/// **THE WORD IS WHAT PUTS A POSTGRES COLLECTION IN A SECOND TABLE**, and without it the column
/// rides the row.
///
/// Postgres is the one dialect with two usable strategies, and which one an element takes is a fact
/// about the ELEMENT — a trait row (`PgCollectionStorage`) rather than a token — so the declaration
/// is where it is stated. The two halves are asserted against each other here, which is what makes
/// this a fork rather than two unrelated emissions:
///
/// * **wordless**, the default: `chapters` stays in `COLUMNS`, the row decodes it as an array, and
///   no plan is stated at all. The absence is CHECKED and not assumed — a collection with no word
///   binds `Vec<E>: Carrier<Postgres>`, so an element no array can hold is `E0277` at the derive.
/// * **worded**: `chapters` leaves `COLUMNS` exactly as a gathered column does, and the plan states
///   an AGGREGATE — one correlated subselect on the page's own SELECT list, no second statement and
///   no tear, which is the materialization only a dialect with `array_agg` can offer.
///
/// The entry is `aggregate` and not `gather`, and it carries THREE arguments rather than four: an
/// aggregate binds no membership of its own, so there is no key binder to name. That is also why
/// the binder function is absent from the expansion entirely — an emitted function nothing names is
/// `dead_code` in the crate the expansion lands in.
///
/// Mutating the emission to ignore the word turns this entry back into the wordless one, which is
/// the fork stated as a diff.
#[test]
fn the_edge_word_moves_a_postgres_collection_off_the_row() {
  let shelf = "::ingraph::__private";
  let wordless = emission(&gathered_in_postgres());
  assert_eq!(
    plan_of(&wordless, "MediaPostgres", "COLUMNS").expect("the query binding states its columns"),
    format!(
      "&[{shelf}::column::shape::<Uuid7>({shelf}::column::ColumnName::new(\"id\")),\
       {shelf}::column::shape::<u64>({shelf}::column::ColumnName::new(\"checksum\")),\
       {shelf}::column::shape::<::std::vec::Vec<Uuid7>>(\
       {shelf}::column::ColumnName::new(\"chapters\")),\
       {shelf}::column::shape::<Option<Uuid7>>({shelf}::column::ColumnName::new(\"cover_id\")),]"
    ),
    "with no word the collection is a column of the row, and the array is what the row decodes"
  );
  assert_eq!(
    plan_of(&wordless, "MediaPostgres", "COLLECTIONS"),
    None,
    "and there is no plan at all — the engine's default const is the whole of it"
  );

  let worded = emission(&edge_declared_in_postgres());
  assert_eq!(
    plan_of(&worded, "MediaPostgres", "COLUMNS").expect("the query binding states its columns"),
    format!(
      "&[{shelf}::column::shape::<Uuid7>({shelf}::column::ColumnName::new(\"id\")),\
       {shelf}::column::shape::<u64>({shelf}::column::ColumnName::new(\"checksum\")),\
       {shelf}::column::shape::<Option<Uuid7>>({shelf}::column::ColumnName::new(\"cover_id\")),]"
    ),
    "the word takes it out of the SELECT list, exactly as a gathered column leaves one"
  );
  assert_eq!(
    plan_of(&worded, "MediaPostgres", "COLLECTIONS").expect("and states its plan"),
    format!(
      "&[{shelf}::query::sql::EdgeCollection::aggregate(\
       &[{shelf}::field::FieldName::new(\"chapters\")],\
       {shelf}::query::sql::EdgeShape::Sequence,\
       __ingraph_take_postgres_chapters::<__INGRAPH_DB__>,),]"
    ),
    "an AGGREGATE entry, and no key binder beside it"
  );
  assert!(
    !tight(&worded).contains("__ingraph_key_postgres"),
    "the binder is not emitted at all where nothing gathers: {}",
    tight(&worded)
  );
}

/// **THE OTHER GATHERING DIALECT EMITS THE SAME PLAN**, and what differs is the two names it is
/// keyed on.
///
/// MySQL has no array type either — its `SET` is a fixed enumerated type of at most 64 members
/// rather than one — so `CollectionStorage` sends every collection there to an edge table, with no
/// per-element choice for the emitter to be unable to see. The plan is therefore the SQLite one:
/// same path, same shape, same two crossings.
///
/// The crossings are named from the DATABASE, which is what this asserts as a difference rather than
/// a repetition — one record holding both rows holds four functions, and the kind is what tells them
/// apart.
///
/// The STATEMENT these entries render is pinned where the engine renders it: `ingraph`'s
/// `query::sql::find::tests::mysql` carries both gathers byte for byte in MySQL's own brackets.
#[test]
fn the_other_gathering_dialect_states_the_same_plan_under_its_own_names() {
  let file = emission(&gathered_in_mysql());
  let shelf = "::ingraph::__private";
  assert_eq!(
    plan_of(&file, "MediaMysql", "COLUMNS").expect("the query binding states its columns"),
    format!(
      "&[{shelf}::column::shape::<Uuid7>({shelf}::column::ColumnName::new(\"id\")),\
       {shelf}::column::shape::<u64>({shelf}::column::ColumnName::new(\"checksum\")),\
       {shelf}::column::shape::<Option<Uuid7>>({shelf}::column::ColumnName::new(\"cover_id\")),]"
    ),
    "`chapters` names no column of `media` here either"
  );
  assert_eq!(
    plan_of(&file, "MediaMysql", "COLLECTIONS").expect("and states its plan"),
    format!(
      "&[{shelf}::query::sql::EdgeCollection::gather(\
       &[{shelf}::field::FieldName::new(\"chapters\")],\
       {shelf}::query::sql::EdgeShape::Sequence,\
       __ingraph_key_mysql::<__INGRAPH_DB__>,\
       __ingraph_take_mysql_chapters::<__INGRAPH_DB__>,),]"
    ),
    "the same entry, under the crossings this DATABASE names"
  );
}

/// **THE ORDER-BY RIDES THE STORAGE, NOT THE WIRE.**
///
/// It used to be emitted inside the `graphql(…)` block's own faces, which made a persist-only
/// record unable to name a term and therefore unable to page — `.order(…)` was a missing impl while
/// `get`, the unordered lanes and the ceiling all worked. Nothing about the type was ever a wire
/// fact: its variants are the STORED columns and its lowering is pure SQL, and no backend derive
/// was ever written on it.
///
/// Three models, one claim each: a record with no wire face declares it, a record stored nowhere
/// does not, and a record with a wire face declares it exactly once — beside the comparisons rather
/// than among the wire types, which is what `emitted_types` says and
/// [`the_enumeration_names_exactly_the_types_the_emission_declares`] holds it to.
#[test]
fn the_order_by_is_emitted_for_a_stored_record_with_no_wire_face() {
  assert!(
    whole_row().graphql.is_none(),
    "the fixture has no wire face"
  );
  assert!(
    declared_types(&emission(&whole_row())).contains(&"MediaOrderBy".to_owned()),
    "a record with no `graphql(…)` still gets its ordering term"
  );

  assert!(
    !declared_types(&emission(&video_track())).contains(&"VideoTrackOrderBy".to_owned()),
    "a record stored nowhere has no stored column to order by"
  );

  let wired = wired();
  let types = declared_types(&emission(&wired));
  assert_eq!(
    types
      .iter()
      .filter(|name| *name == "VideoTrackOrderBy")
      .count(),
    1,
    "exactly once for a record that does declare a wire face: {types:?}"
  );
  let (wire_types, _) = wired
    .graphql
    .as_ref()
    .expect("the fixture declares a wire face")
    .faces(&wired);
  let wire: syn::File = syn::parse2(wire_types).expect("the wire face is parsable");
  assert!(
    !declared_types(&wire).contains(&"VideoTrackOrderBy".to_owned()),
    "and the WIRE FACE is no longer what declares it: {:?}",
    declared_types(&wire)
  );
}

/// The rows obey the placement rule the key and lineage types do: structs at top level, impls in
/// the one anonymous const.
#[test]
fn the_rows_are_structs_outside_the_const_and_impls_inside() {
  let file = emission(&persisted());
  assert_eq!(
    file
      .items
      .iter()
      .filter(|item| matches!(item, syn::Item::Const(anonymous) if anonymous.ident == "_"))
      .count(),
    1
  );
  assert!(
    !file
      .items
      .iter()
      .any(|item| matches!(item, syn::Item::Impl(_))),
    "no impl at top level"
  );
  assert_eq!(
    structs(&file).len(),
    8,
    "the key, the lineage, and three rows each with its comparison"
  );
}

/// Every emitted row item the `missing_docs` lint covers is documented, and every method is
/// `#[inline]` — the same rules the key's items carry.
///
/// THREE exceptions, and all three recorded for the same reason: the inline rule's stated ground is
/// "a one-line cross-crate wrapper", which none of a decode of N columns (`from_row`, whose sqlx
/// original is not inlined either, and `from_document`, its bson twin) nor a lowering that threads
/// an accumulator through N columns (`apply`) is. Anything else appearing here still has to carry
/// it.
#[test]
fn the_rows_are_documented_and_inline() {
  const NOT_WRAPPERS: &[&str] = &["from_row", "from_document", "apply"];
  let file = emission(&persisted());
  for name in ["VideoTrackSqlite", "VideoTrackRecord", "VideoTrackMongo"] {
    assert!(documented(&struct_named(&file, name).attrs), "{name}");
  }
  for method in impls(&file).iter().flat_map(|item| methods(item)) {
    if NOT_WRAPPERS.contains(&method.sig.ident.to_string().as_str()) {
      continue;
    }
    assert!(
      method.attrs.iter().any(|attr| tight(attr) == "#[inline]"),
      "`{}`",
      method.sig.ident
    );
  }
}

/// The emitted decode, beside the one `#[derive(sqlx::FromRow)]` would have written for the same
/// struct: generic over the row with its own `'a`, one predicate per column in column order, and one
/// read per FIELD under the column's own name. No error is constructed — `Row::try_get` is what
/// produces `ColumnNotFound` and `ColumnDecode`, and the read seam forwards both, so the contract is
/// inherited rather than restated.
///
/// The parameter's NAME is one departure, and the golden is where it is visible: sqlx writes `R`,
/// which would shadow a declaration's own type called `R` inside this impl.
///
/// The READ is the other, and it is the one this golden exists to keep visible. sqlx's model is one
/// column per field, which cannot read a field whose type spans several; the predicate is therefore
/// `Assemble` rather than the `Decode`/`Type` pair, the `ColumnIndex` predicate is gone with the
/// direct indexing, and the column's name is a `FieldName` the walk descends from rather than a
/// string handed to `try_get`. Every one of those is a widening of what a row may hold, and a
/// reversion to the narrower shape shows up here as a diff.
///
/// A whole-shape golden rather than a set of probes, because the shape is the claim.
#[test]
fn the_emitted_decode_is_the_shape_sqlxs_derive_would_have_written() {
  assert_eq!(
    rendered(from_row_impl(&emission(&whole_row()), "MediaSqlite")),
    MEDIA_SQLITE_DECODE
  );
}

const MEDIA_SQLITE_DECODE: &str = "\
#[automatically_derived]
impl<
    'a,
    __INGRAPH_ROW__: ::ingraph::__private::sqlx::Row,
> ::ingraph::__private::sqlx::FromRow<'a, __INGRAPH_ROW__> for MediaSqlite
where
    Uuid7: ::ingraph::__private::column::Assemble<'a, __INGRAPH_ROW__>,
    u64: ::ingraph::__private::column::Assemble<'a, __INGRAPH_ROW__>,
    Vec<Uuid7>: ::ingraph::__private::column::Assemble<'a, __INGRAPH_ROW__>,
    Option<Uuid7>: ::ingraph::__private::column::Assemble<'a, __INGRAPH_ROW__>,
{
    /// Read a [`MediaSqlite`] back out of a database row, each field under its own name — and a field whose type spans several columns out of every one of them.
    fn from_row(__row: &'a __INGRAPH_ROW__) -> ::ingraph::__private::sqlx::Result<Self> {
        let id: Uuid7 = ::ingraph::__private::column::assembled(
            __row,
            ::ingraph::__private::field::FieldName::new(\"id\"),
            ::core::option::Option::None,
        )?;
        let checksum: u64 = ::ingraph::__private::column::assembled(
            __row,
            ::ingraph::__private::field::FieldName::new(\"checksum\"),
            ::core::option::Option::None,
        )?;
        let chapters: Vec<Uuid7> = ::ingraph::__private::column::assembled(
            __row,
            ::ingraph::__private::field::FieldName::new(\"chapters\"),
            ::core::option::Option::None,
        )?;
        let cover_id: Option<Uuid7> = ::ingraph::__private::column::assembled(
            __row,
            ::ingraph::__private::field::FieldName::new(\"cover_id\"),
            ::core::option::Option::None,
        )?;
        ::core::result::Result::Ok(Self {
            id,
            checksum,
            chapters,
            cover_id,
        })
    }
}
";

/// Every sqlx name an emission writes goes through the shelf — `#krate::__private::sqlx::<item>` and
/// nowhere else.
///
/// This is the guard the token walk in [`framework_paths_not_through_a_private_module`] cannot be: it
/// checks paths that NAME the framework crate, and a reverted `::sqlx::FromRow` names sqlx instead, so
/// it would pass every rule vacuously. Run over a retargeted crate path too, where a hardcoded
/// `::ingraph` prefix could not pass.
///
/// `ingraph-derive`'s fixture crate is the other half, and the stronger one: it has no `sqlx`
/// dependency, so a single unshelved path stops it compiling.
#[test]
fn every_sqlx_name_goes_through_the_shelf() {
  for mut model in [persisted(), whole_row(), aliased(wired())] {
    for krate in [
      syn::parse_quote!(::ingraph),
      syn::parse_quote!(shim::vendored::ingraph),
    ] {
      model.krate = krate;
      let unshelved = sqlx_names_outside_the_shelf(&model);
      assert!(
        unshelved.is_empty(),
        "`{}` reaches sqlx outside `__private::sqlx`: {unshelved:?}",
        model.record
      );
    }
  }
}

/// Every place the emission writes `sqlx` and is NOT `…::__private::sqlx`.
fn sqlx_names_outside_the_shelf(model: &RecordModel) -> Vec<String> {
  fn flatten(stream: proc_macro2::TokenStream, into: &mut Vec<proc_macro2::TokenTree>) {
    for tree in stream {
      match tree {
        proc_macro2::TokenTree::Group(group) => flatten(group.stream(), into),
        other => into.push(other),
      }
    }
  }
  let mut tokens = Vec::new();
  flatten(model.emit(), &mut tokens);

  let colon = |at: usize| matches!(tokens.get(at), Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == ':');
  let shelved = |at: usize| {
    at >= 3
      && colon(at - 1)
      && colon(at - 2)
      && matches!(tokens.get(at - 3), Some(proc_macro2::TokenTree::Ident(id)) if id == "__private")
  };
  (0..tokens.len())
    .filter(|at| matches!(tokens.get(*at), Some(proc_macro2::TokenTree::Ident(id)) if id == "sqlx"))
    .filter(|at| !shelved(*at))
    .map(|at| {
      tokens[at.saturating_sub(3)..(at + 3).min(tokens.len())]
        .iter()
        .map(ToString::to_string)
        .collect()
    })
    .collect()
}

/// A row is exactly as visible as the record it stores, and its fields stay private.
#[test]
fn the_rows_mirror_the_records_visibility() {
  for (model, expected) in [(persisted(), "pub"), (private(persisted()), "")] {
    let file = emission(&model);
    for name in ["VideoTrackSqlite", "VideoTrackRecord", "VideoTrackMongo"] {
      let item = struct_named(&file, name);
      assert_eq!(tight(&item.vis), expected, "{name}");
      for field in named(item) {
        assert_eq!(tight(&field.vis), "", "{name}");
      }
    }
  }
}

/// No row carries a type parameter — not the mongo document, which has no dialect to be generic
/// over, and not the SQL ones either. The ruling is CONCRETE types per database: a generic
/// `Row<DB>` was probed and works, and was declined for readable types, clean derives, and error
/// messages that name a type a reader can look up.
///
/// It walked EVERY emitted struct while a row was the only thing that could have carried a
/// parameter. The comparison carries `Db` now, so the walk is over the rows the model names, and
/// [`the_comparison_is_the_only_generic_emitted_type`] keeps the rest of the emission covered —
/// narrowing this without that would have traded the property for its exception.
#[test]
fn no_row_is_generic_over_a_dialect() {
  let model = persisted();
  let file = emission(&model);
  for database in model.persist.iter().flat_map(|persist| &persist.backends) {
    let item = struct_named(&file, &database.name().to_string());
    assert!(
      item.generics.params.is_empty() && item.generics.where_clause.is_none(),
      "`{}` carries a parameter",
      item.ident
    );
  }
}

/// The comparison is the ONE emitted type with a parameter, it is the database, and what bounds it
/// is [`Backend`](ingraph::Backend) plus the crossings rather than a dialect.
///
/// A parameter and not a spelled `Sqlite`: the comparison KINDS are generic over it, one
/// `SqlScalarComparison<V, Db>` serving three dialects, and naming a dialect in an expansion would
/// put a backend's crate there — which is what the shelf exists to prevent. What makes the field
/// types well formed is `Backend` plus the crossing, one predicate per column, all discharged where
/// a caller writes `Comparison<Sqlite>`.
#[test]
fn the_comparison_is_the_only_generic_emitted_type() {
  let model = persisted();
  let file = emission(&model);
  let comparisons: Vec<String> = model
    .persist
    .iter()
    .flat_map(|persist| &persist.backends)
    .map(|database| database.comparison_name().to_string())
    .collect();
  for item in structs(&file) {
    let parameters: Vec<String> = item.generics.params.iter().map(tight).collect();
    if comparisons.contains(&item.ident.to_string()) {
      assert_eq!(parameters, [database_parameter()], "`{}`", item.ident);
      assert!(
        tight(&item.generics.where_clause).contains(&format!(
          "{}:::ingraph::__private::comparison::Backend",
          database_parameter()
        )),
        "`{}` is generic over a database and does not say it IS one, so a `where F: \
         ToDatabaseComparison<V, Db>` beside it is not well formed",
        item.ident
      );
    } else {
      assert!(parameters.is_empty(), "`{}`: {parameters:?}", item.ident);
    }
  }
}

/// **Every generic TYPE parameter the emission introduces is inside the framework's namespace.**
///
/// A parameter is a type name, and a proc macro has no hygiene for those: a bare one shadows a
/// declaration's own type of that name inside the item that declares it, silently. The rule is
/// general rather than a fix for the one parameter that had the defect, so the check is a WALK —
/// a parameter added later is covered without anyone remembering this file exists.
///
/// LIFETIMES are deliberately not covered. `ingraph-derive` refuses a generic declaration outright,
/// so no lifetime of a declarer's is ever in scope where an emitted `'a` or `'q` is bound, and a
/// lifetime cannot shadow a type in any case.
#[test]
fn every_generic_parameter_the_emission_introduces_is_namespaced() {
  let file = emission(&wired());
  let declared = structs(&file)
    .into_iter()
    .map(|item| (item.ident.to_string(), &item.generics))
    .chain(
      impls(&file)
        .into_iter()
        .map(|item| (impl_of(item), &item.generics)),
    );
  for (subject, generics) in declared {
    for parameter in &generics.params {
      let syn::GenericParam::Type(parameter) = parameter else {
        continue;
      };
      let name = parameter.ident.to_string();
      assert!(
        name.starts_with("__") && name.ends_with("__"),
        "`{name}` on `{subject}` is a bare parameter, and shadows a declaration's own type of that \
         name"
      );
    }
  }
}

/// A model whose single backend is mongo — `whole_row()`'s columns, stored the other family's way.
fn whole_document() -> RecordModel {
  let mut model = whole_row();
  // A backend IS its kind now, so switching family means building the mongo backend rather than
  // overwriting a discriminant — which is the split doing its job.
  let columns = model.persist.as_ref().expect("stored").backends[0]
    .columns()
    .to_vec();
  model.persist.as_mut().expect("stored").backends =
    vec![stored(&ident("Media"), DatabaseKind::Mongo, columns)];
  model
}

/// The mongo document, on its own terms: serde's pair, serde's rename, and nothing sqlx.
///
/// "Nothing sqlx" is asserted over the WHOLE emission rather than the document alone, because the SQL
/// family's decode is an emitted impl now: a mongo-only record must reach neither the shelf's sqlx nor
/// the crate, or a mongo declarer would be back to needing a SQL dependency for a database it does
/// not use.
#[test]
fn the_mongo_document_names_nothing_of_the_sql_family() {
  let model = whole_document();
  let file = emission(&model);
  let document = struct_named(&file, "MediaMongo");
  let rendered = tight(document);
  assert!(
    rendered.contains("::ingraph::__private::serde::Serialize"),
    "{rendered}"
  );
  assert!(
    rendered.contains("::ingraph::__private::serde::Deserialize"),
    "{rendered}"
  );
  let whole = tight(model.emit());
  assert!(!whole.contains("sqlx"), "{whole}");
  assert!(!whole.contains("FromRow"), "{whole}");
  assert!(
    field_attrs(document)
      .iter()
      .all(|attr| attr.starts_with("#[serde(rename=")),
    "{:?}",
    field_attrs(document)
  );
}

/// The EXTRACTION a mongo document carries: one call per column, under the key this database spells
/// it, at the type the row's field holds.
///
/// It is the `FromRow` discipline's bson twin, and what this pins is the discipline rather than the
/// spelling: every column is read through ONE function, so a typed refusal survives to the caller
/// with the field's name on it. A decode that reached into the document directly — which is what a
/// `#[serde(deserialize_with = "…")]` would have produced — loses both.
///
/// The TYPE ARGUMENT is what fixes which row of the decode table runs, so it is asserted too: an
/// `Option<…>` field is what makes a missing key an answer rather than a refusal, and it is the
/// declaration that decided the field is optional.
#[test]
fn the_mongo_document_reads_every_column_through_one_extraction() {
  let file = emission(&whole_document());
  let extraction = tight(
    all_items(&file)
      .into_iter()
      .filter_map(|item| match item {
        syn::Item::Impl(item) => Some(item),
        _ => None,
      })
      .flat_map(methods)
      .find(|method| method.sig.ident == "from_document")
      .expect("the document carries its extraction"),
  );
  let field = "::ingraph::__private::query::mongo::field";

  // Written with its spaces and stripped the way [`tight`] strips them, so the expectation reads as
  // the signature rather than as the run-together form the comparison is made on.
  let signature =
    "pub fn from_document(__ingraph_document: &::ingraph::__private::bson::Document,) \
                   -> ::core::result::Result<Self, \
                   ::ingraph::__private::query::mongo::MongoExtractionError>"
      .replace(' ', "");
  assert!(extraction.contains(&signature), "{extraction}");
  for (column, ty, key) in [
    ("id", "Uuid7", "_id"),
    ("checksum", "u64", "checksum"),
    ("chapters", "Vec<Uuid7>", "chapters"),
    ("cover_id", "Option<Uuid7>", "cover_id"),
  ] {
    assert!(
      extraction.contains(&format!(
        "{column}:{field}::<{ty}>(__ingraph_document,\"{key}\")?"
      )),
      "`{column}` in {extraction}"
    );
  }
}

/// **A SQL ROW'S `flatten` DOES NOT REACH THE DOCUMENT'S EXTRACTION.**
///
/// A flattened column used to take the extraction away for the whole row: its type's keys were the
/// document's own, so a read at the column's name found nothing, and a partial extraction leaves a
/// field unset, which is not a shape Rust has. That reasoning was sound and its premise is gone —
/// `flatten` is now one SQL storage's naming act, and a document nests a held value under this
/// field's key whatever a SQL row beside it does.
///
/// So the extraction is written, and the METHOD ENUMERATION agrees: both ask
/// `DatabaseBackend::extracts`. The pair is asserted here rather than left to two call sites reading
/// one rule.
#[test]
fn a_sql_rows_flatten_leaves_the_documents_extraction_alone() {
  let model = flattened_document();
  let file = emission(&model);
  let extractions = all_items(&file)
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Impl(item) => Some(item),
      _ => None,
    })
    .flat_map(methods)
    .filter(|method| method.sig.ident == "from_document")
    .count();

  assert_eq!(extractions, 1, "the document reads itself back");
  assert!(
    model
      .emitted_methods()
      .iter()
      .any(|method| method.name == "from_document"),
    "and the enumeration claims the name the emission declares"
  );
  assert!(
    !field_attrs(struct_named(&file, "MediaMongo"))
      .iter()
      .any(|attr| attr == "#[serde(flatten)]"),
    "and no field of the document is flattened: {:?}",
    field_attrs(struct_named(&file, "MediaMongo"))
  );

  // The predicate is the FAMILY's, and this is what says so. A mongo column carrying the word is a
  // state no declaration can reach — `mongo(flatten)` is refused — so a model built by hand is the
  // only place the question can be put, and putting it is what keeps the old condition from
  // creeping back in: with it restored, this row loses the extraction it must always have.
  // Measured — the mutation that restores it is caught here and nowhere else.
  let mut marked = whole_document();
  for database in marked
    .persist
    .iter_mut()
    .flat_map(|persist| &mut persist.backends)
    .filter(|database| !database.kind().is_sql())
  {
    storage_of(database).columns[0].flatten = true;
  }
  assert!(
    marked
      .emitted_methods()
      .iter()
      .any(|method| method.name == "from_document"),
    "a document extracts because it is a document, not because of what its columns carry"
  );
}

/// [`whole_document`] with its first column flattened WHEREVER THE WORD EXISTS — which is the SQL
/// family and not the document one, so the mongo row beside it is untouched.
fn flattened_document() -> RecordModel {
  let mut model = whole_document();
  flatten_the_first_sql_column(&mut model);
  model
}

/// The first column marked `flatten` in every SQL backend, and in no document one.
///
/// The skip is not tidiness: `flatten` is one storage's act of dropping a prefix, and mongo has no
/// prefix to drop, so `mongo(flatten)` is refused at the declaration. A hand-built model that marked
/// it would be a model no grammar can produce, and a test written against one asserts nothing.
fn flatten_the_first_sql_column(model: &mut RecordModel) {
  for database in model
    .persist
    .iter_mut()
    .flat_map(|persist| &mut persist.backends)
    .filter(|database| database.kind().is_sql())
  {
    storage_of(database).columns[0].flatten = true;
  }
}

/// **THE ID IS STORED AS `_id`, IN BOTH PLACES THAT NAME IT.**
///
/// MongoDB mints an `_id` for every document that arrives without one and indexes it uniquely, so a
/// document carrying that beside a declared `id` would be one row with two identities. The
/// declaration and the wire face still say `id`, which leaves the mapping in two emitted places —
/// the derive's `rename`, which is what a WRITE goes out under, and the extraction's key, which is
/// what a READ comes back under.
///
/// Both come from `DatabaseBackend::external`, so they cannot differ; this is what reads them back
/// beside each other, which is the check that would catch it if they ever did.
///
/// A record whose id is stored in NO mongo column has no such field and renames nothing —
/// [`persisted`] is that case, and it is asserted here so the mapping is keyed on the ADDRESS rather
/// than on the word `id`.
#[test]
fn the_mongo_document_reads_the_id_out_of_underscore_id() {
  let file = emission(&whole_document());
  let document = struct_named(&file, "MediaMongo");

  assert_eq!(
    field_attrs(document),
    [
      "#[serde(rename=\"_id\",with=\"::ingraph::__private::query::mongo::via\")]",
      "#[serde(rename=\"checksum\",with=\"::ingraph::__private::query::mongo::via\")]",
      "#[serde(rename=\"chapters\",with=\"::ingraph::__private::query::mongo::via\")]",
      "#[serde(rename=\"cover_id\",with=\"::ingraph::__private::query::mongo::via\")]",
    ]
  );

  // The stored id is what decides it, so a document that stores no id renames nothing.
  let without = emission(&persisted());
  assert_eq!(
    field_attrs(struct_named(&without, "VideoTrackMongo")),
    [
      "#[serde(rename=\"bitrate\",with=\"::ingraph::__private::query::mongo::via\")]",
      "#[serde(rename=\"cover_id\",with=\"::ingraph::__private::query::mongo::via\")]"
    ]
  );
  // …and the SQL family renames nothing at all, its decode naming each column at the read instead.
  assert!(field_attrs(struct_named(&without, "VideoTrackSqlite")).is_empty());
}

/// serde is reached through the shelf in BOTH halves, and BOTH retarget with the declarer's crate
/// path: the derive path, which resolves the macro, and `#[serde(crate = "…")]`, which is what binds
/// serde's own expansion to the same place. The first alone leaves the generated code saying
/// `extern crate serde`, so a consumer without serde as a direct dependency still would not compile.
///
/// A string literal is not an ident, so the token walk in
/// [`framework_paths_not_through_a_private_module`] cannot see the second half — which is why it is
/// pinned here, over a retargeted crate path where a hardcoded `::ingraph` could not pass.
#[test]
fn the_mongo_document_reaches_serde_through_the_shelf() {
  for (krate, shelf) in [
    (syn::parse_quote!(::ingraph), "::ingraph::__private::serde"),
    (
      syn::parse_quote!(shim::vendored::ingraph),
      "shim::vendored::ingraph::__private::serde",
    ),
  ] {
    let mut model = whole_document();
    model.krate = krate;
    let file = emission(&model);
    let attrs: Vec<String> = struct_named(&file, "MediaMongo")
      .attrs
      .iter()
      .filter(|attr| !attr.path().is_ident("doc"))
      .map(tight)
      .collect();
    assert_eq!(
      attrs,
      [
        format!(
          "#[derive(::core::fmt::Debug,::core::clone::Clone,{shelf}::Serialize,{shelf}::Deserialize)]"
        ),
        format!("#[serde(crate=\"{shelf}\")]")
      ]
    );
    // THE VIA retargets with the crate path too, and it is the THIRD half of reaching serde through
    // the shelf. It is a string literal like `crate = "…"`, so the token walk cannot see it either —
    // which is why both are pinned here rather than left to `ill_formed_shelf_paths`.
    let via = format!("{}::query::mongo::via", shelf.trim_end_matches("::serde"));
    for attr in field_attrs(struct_named(&file, "MediaMongo")) {
      assert!(
        attr.contains(&format!("with=\"{via}\"")),
        "every field crosses the via, at the declarer's own crate path: {attr}"
      );
    }
  }
}

// ---------------------------------------------------------------------------------------------
// The wire face and the comparison layer.
// ---------------------------------------------------------------------------------------------

use crate::model::{
  AsyncGraphql, Face, FrameworkMarker, Graphql, GraphqlBackend, GraphqlField, Label, Marker,
  WirePosition, default_comparison_name, default_filter_name, default_input_name,
  default_key_output_name, default_order_by_name, default_output_name,
};

/// `persisted()` with a wire face: `checksum` exposed as `bitRate`, `cover_id` exposed unrenamed.
pub(crate) fn wired() -> RecordModel {
  let mut model = persisted();
  let base = model.record.clone();
  let face = |sdl: &str, attrs: proc_macro2::TokenStream| Face {
    name: RustSafeName::new(sdl, proc_macro2::Span::call_site()),
    attrs,
  };
  let field = |source: &str, sdl: &str, ty: syn::Type| GraphqlField {
    source: ident(source),
    domain: ty,
    wire: None,
    output_crossing: WirePosition::default(),
    input_crossing: WirePosition::default(),
    input: face(sdl, proc_macro2::TokenStream::new()),
    output: face(sdl, quote::quote!(desc = "bits per second")),
    output_field: None,
  };
  model.graphql = Some(Graphql {
    backends: vec![GraphqlBackend::AsyncGraphql(AsyncGraphql {
      skipped: Vec::new(),
      attrs: quote::quote!(complexity = 5),
      fields: vec![
        field("checksum", "bitRate", ty("u64")),
        field("cover_id", "coverId", generic("Option", "Uuid7")),
      ],
    })],
    input: RustSafeName::from_ident(&default_input_name(&base)),
    output: RustSafeName::from_ident(&default_output_name(&base)),
    key_output: RustSafeName::from_ident(&default_key_output_name(&base)),
    // The address's two faces take the base above, which is the state a declaration that named
    // neither of them is in.
    key_object: None,
    key_argument: None,
    filter: RustSafeName::from_ident(&default_filter_name(&base)),
    plural: None,
    // The default page names — this fixture declares no `connection(rename)` or `edge(rename)`,
    // so the emission takes the specification's own words through the alias.
    connection: None,
    edge: None,
    skipped: Vec::new(),
  });
  model
}

/// The square's FOURTH corner: a `graphql(…)` block and no `persist(…)` at all.
///
/// A shape the derive really admits rather than one only a hand-built model can hold. A field
/// carrying `graphql` must be stored — the parser refuses one that is not — so a declaration with no
/// storage exposes NO FIELD, and this model is that: a container block naming its backend, with an
/// empty field list. What the emission writes for it is an output object with no members, a filter
/// with no columns, and the key object, which is mechanical from the key rather than from storage.
fn wire_only() -> RecordModel {
  let mut model = video_track();
  let base = model.record.clone();
  model.graphql = Some(Graphql {
    backends: vec![GraphqlBackend::AsyncGraphql(AsyncGraphql {
      skipped: Vec::new(),
      attrs: proc_macro2::TokenStream::new(),
      fields: Vec::new(),
    })],
    input: RustSafeName::from_ident(&default_input_name(&base)),
    output: RustSafeName::from_ident(&default_output_name(&base)),
    key_output: RustSafeName::from_ident(&default_key_output_name(&base)),
    // The address's two faces take the base above, which is the state a declaration that named
    // neither of them is in.
    key_object: None,
    key_argument: None,
    filter: RustSafeName::from_ident(&default_filter_name(&base)),
    plural: None,
    // The default page names — this fixture declares no `connection(rename)` or `edge(rename)`,
    // so the emission takes the specification's own words through the alias.
    connection: None,
    edge: None,
    skipped: Vec::new(),
  });
  model
}

/// [`wired`] with its KEY stored, which is what an ordering can end with.
///
/// `wired`'s key is three record fields no `persist(…)` block names, so it has no tail to append and
/// gets no ordering lowering at all — the two models together are both halves of that rule.
///
/// The key columns are PREPENDED, so the stored order (`media_id`, `video_id`, `id`, `bitrate`,
/// `cover_id`) and the key's own (`media_id`, `video_id`, `id`) are not the same list; and postgres
/// renames the id, so a tail that read the key type's names rather than this database's would render
/// a column postgres has not got.
fn ordered() -> RecordModel {
  let mut model = wired();
  let key = |name: &str| persist_column(name, name, ty("Uuid7"));
  for database in model
    .persist
    .iter_mut()
    .flat_map(|persist| &mut persist.backends)
  {
    let storage = storage_of(database);
    let mut columns = vec![key("media_id"), key("video_id"), key("id")];
    columns.append(&mut storage.columns);
    storage.columns = columns;
  }
  let postgres = model
    .persist
    .iter_mut()
    .flat_map(|persist| &mut persist.backends)
    .find(|database| database.kind() == DatabaseKind::Postgres)
    .expect("`wired` stores a postgres row");
  storage_of(postgres).columns[2].name = RustSafeName::new("pk", proc_macro2::Span::call_site());
  model
}

/// [`ordered`] whose rows can be RAISED, which is the last of the three conditions a query face is
/// emitted under — and therefore the smallest model in this file that has a SINGLE LEG.
///
/// The other two are [`ordered`]'s own: a wire face, and the key's id column actually stored. What
/// this adds is the way back — a declared container conversion, so a row carrying some of the
/// record's fields can still hand a record over. Without it `queryable()` is empty and every leg is
/// nothing at all, which is what `a_row_that_cannot_become_a_record_gets_no_query_face` pins from
/// the other side.
pub(crate) fn queried() -> RecordModel {
  let mut model = ordered();
  for database in model
    .persist
    .iter_mut()
    .flat_map(|persist| &mut persist.backends)
  {
    storage_of(database).into = fallible(path("path::to::raise"));
  }
  model
}

/// NO BACKEND DERIVE ON THE STRUCTURES. `InputObject` and `OneofObject` are async-graphql's TRAITS,
/// and implementing a backend's traits is the work the era rule holds back — so this piece emits
/// the structures and the enum, and nothing that binds them to a library.
///
/// The OUTPUT object's face is not among the derives it could ever have carried, and this is where
/// that is pinned: the accessor law puts the public face on the borrows beside the members, so what
/// renders an output is an `#[Object]` attribute over those and never a derive over the
/// `pub(crate)` substrate.
///
/// The external names are not lost: they are on the MODEL, which is what the derive round reads.
#[test]
fn the_wire_types_carry_no_backend_derive_and_no_backend_attribute() {
  let file = emission(&wired());
  let stated = |name: &str, attrs: &[syn::Attribute]| {
    let attrs: Vec<String> = attrs
      .iter()
      .filter(|attr| !attr.path().is_ident("doc"))
      .map(tight)
      .collect();
    assert!(
      attrs.iter().all(|attr| attr.starts_with("#[derive(")),
      "`{name}` carries a non-derive attribute: {attrs:?}"
    );
    assert!(
      !attrs.iter().any(|attr| attr.contains("graphql")),
      "`{name}` names a backend: {attrs:?}"
    );
  };
  for name in [
    "VideoTrackGraphqlInput",
    "VideoTrackGraphqlOutput",
    "VideoTrackKeyOutput",
    "VideoTrackFilter",
  ] {
    let item = struct_named(&file, name);
    stated(name, &item.attrs);
    assert!(
      field_attrs(item).is_empty(),
      "`{name}` puts a backend attribute on a field: {:?}",
      field_attrs(item)
    );
  }
  // The order-by is the one wire type that is an ENUM, so the walk over structs above cannot see
  // it — and it is the one whose derive would be easiest to reach for, its SHAPE having been
  // chosen for `OneofObject`.
  let order_by = enum_named(&file, "VideoTrackOrderBy");
  stated("VideoTrackOrderBy", &order_by.attrs);
  for variant in &order_by.variants {
    assert!(
      variant.attrs.iter().all(|attr| attr.path().is_ident("doc")),
      "`VideoTrackOrderBy::{}` puts a backend attribute on a variant",
      variant.ident
    );
  }

  let wired = wired();
  let backend = &wired.graphql.as_ref().expect("wired").backends[0];
  assert_eq!(
    backend.fields()[0].output.name.to_string(),
    "bitRate",
    "and the SDL name the derive round needs is on the MODEL, not thrown away"
  );
  assert_eq!(
    backend.kind().output_object(),
    "::async_graphql::Object",
    "and the output's face is the ACCESSOR attribute — `SimpleObject` would publish layer 1, the \
     `pub(crate)` substrate no rename word may move, so the field-rendering derive cannot be what \
     an output object is written with"
  );
  assert_eq!(
    backend.kind().order_by_derive(),
    "::async_graphql::OneofObject",
    "and the order-by's is the ONEOF derive — the plain `Enum` one would render bare column names, \
     which is the face this stopped being"
  );

  let output = struct_named(&file, "VideoTrackGraphqlOutput");
  assert_eq!(
    fields(output),
    ["id", "key", "checksum", "cover_id"],
    "the framework's two address members lead, and every member after them is the RECORD FIELD's \
     own name — `checksum` is exposed as `bitRate` and the struct never says so, the schema name \
     being the client's and the camelCase the backend's own act"
  );
}

/// **EVERY EMITTED WIRE MEMBER IS THE CRATE'S SUBSTRATE** — `pub(crate)`, at every one of the four
/// types, whether or not a word could ever have reached it.
///
/// LAYER 1 of the three-layer naming law, and the visibility is the half that makes it a substrate
/// rather than a convention. Not PRIVATE, because an emitted-to-emitted read spends the FIELD and an
/// expansion lands where its declaration is written — so which reads compile would otherwise be a
/// fact about where an author put a `mod`. Not `pub`, because a member is not API: what a downstream
/// crate is offered is the accessor face beside it, which is the layer a rename word may move.
///
/// Asserted over the whole field list of every type rather than over a representative, because the
/// spelling is written at four emission sites and the one that drifts is the one nobody looked at.
/// `emit::substrate` is what they all call; this is the check that they all call it.
#[test]
fn every_emitted_wire_member_carries_the_substrate_visibility() {
  let file = emission(&ordered());
  for name in [
    "VideoTrackGraphqlInput",
    "VideoTrackGraphqlOutput",
    "VideoTrackKeyOutput",
    "VideoTrackFilter",
  ] {
    let item = struct_named(&file, name);
    let spelled: Vec<String> = named(item).iter().map(|field| tight(&field.vis)).collect();
    assert!(!spelled.is_empty(), "`{name}` emits no member to check");
    assert!(
      spelled.iter().all(|vis| vis == "pub(crate)"),
      "`{name}` does not spell every member `pub(crate)`: {spelled:?}"
    );
  }
}

/// **`output(field = "…")` MOVES THE ACCESSOR AND THE MEMBER STAYS THE DOMAIN NAME** — the semantic
/// revision, read off one emission.
///
/// The word's REACH is what changed; its grammar did not. Layer 1 is the record field's own name and
/// no word reaches it, which is what makes it the substrate an emitted-to-emitted read spends; layer
/// 2 is the accessor, and that is where every Rust-side rename word lands now.
///
/// Four readings, because a change that moved only some of them would leave an object whose accessor
/// and whose crossing disagree about which member they mean: the member itself, the accessor's NAME,
/// the accessor's BODY, and the row crossing that fills the member. The last two are the pair that
/// has to agree — a body reading `self.mass` beside a crossing writing `checksum:` is `E0609` inside
/// an expansion, so they are asserted together rather than separately.
///
/// The SCHEMA name is unmoved by any of it and stays on the model, which is where the derive round
/// reads it from — `bitRate` is what `wired` declared and `mass` does not disturb it.
#[test]
fn the_output_field_word_moves_the_accessor_and_leaves_the_member() {
  let mut model = wired();
  match &mut model.graphql.as_mut().expect("wired").backends[0] {
    GraphqlBackend::AsyncGraphql(backend) => backend.fields[0].output_field = Some(ident("mass")),
  }
  let file = emission(&model);

  let output = struct_named(&file, "VideoTrackGraphqlOutput");
  assert_eq!(
    fields(output),
    ["id", "key", "checksum", "cover_id"],
    "LAYER 1: the member is the RECORD FIELD's name, and `field = \"mass\"` did not move it"
  );

  assert_eq!(
    methods_of(&file, "VideoTrackGraphqlOutput"),
    [
      "id_ref",
      "key_ref",
      "mass_ref",
      "cover_id_ref",
      "__async_graphql_id",
      "__async_graphql_key",
      "__async_graphql_checksum",
      "__async_graphql_cover_id"
    ],
    "LAYER 2: the accessor is what the word moved — `checksum_ref` is gone and `mass_ref` is there, \
     while the field that named no word keeps its own. LAYER 1 AND LAYER 2 ARE BOTH VISIBLE HERE, \
     and their independence is the whole claim: the WIRE face's methods are named after the members \
     — `__async_graphql_checksum`, whose stem the word did not move — and read through the \
     accessors above them, so the two axes cannot collide and a rename on either leaves the other \
     alone. The PREFIX is on the wire methods and on nothing else: an accessor is the Rust read \
     road and keeps its name."
  );

  let body = tight(&method_of(&file, "VideoTrackGraphqlOutput", "mass_ref").block);
  assert!(
    body.contains("&self.checksum"),
    "the moved accessor reads the PINNED member, which is what keeps the two layers one value: \
     {body}"
  );

  let crossing = tight(&file);
  assert!(
    crossing.contains("checksum:"),
    "and the row crossing fills that same member — an emitted-to-emitted write, so it names layer \
     1 and never the face"
  );
  assert!(
    !crossing.contains("mass:"),
    "…and names the accessor's word nowhere: a crossing writing `mass:` would be `E0560` inside \
     the expansion"
  );

  let backend = &model.graphql.as_ref().expect("wired").backends[0];
  assert_eq!(
    (
      backend.fields()[0].output.name.to_string(),
      backend.fields()[0].accessor().to_string()
    ),
    ("bitRate".to_owned(), "mass".to_owned()),
    "LAYER 3 is untouched by either — the schema name is still on the model for the derive round"
  );
}

/// **ONE COLUMN, FOUR NAMES, AND EACH BELONGS TO EXACTLY ONE LAYER.**
///
/// `wired`'s `checksum` is the column that can say this on its own: the record field is `checksum`,
/// sqlite stores it as `bitrate`, postgres renames it again to `bit_rate_v2`, and the wire calls it
/// `bitRate`. Before the law reached this zone, three of those four could end up on a Rust ident —
/// the filter's member followed `bitRate`, and the comparison's member and the order-by's variant
/// each followed whichever database was declared first.
///
/// | name | layer | where it may appear |
/// |---|---|---|
/// | `checksum` | 1 | every emitted member and the order-by variant |
/// | `bitRate` | 3 | the SDL, and nothing in Rust |
/// | `bitrate` / `bit_rate_v2` | — | SQL strings at render time, and nothing else |
///
/// Asserted as ONE test rather than four, because what is being claimed is that they do not mix: a
/// change that moved any single member back onto a rendered name would still pass three of four
/// separate assertions.
#[test]
fn one_column_carries_four_names_and_each_stays_in_its_layer() {
  let model = wired();
  let file = emission(&model);

  // LAYER 1 — every emitted member, at all three types that carry one for this column.
  assert_eq!(
    fields(struct_named(&file, "VideoTrackFilter"))[0],
    "checksum"
  );
  assert_eq!(
    fields(struct_named(&file, "VideoTrackSqliteComparison"))[0],
    "checksum"
  );
  assert_eq!(
    fields(struct_named(&file, "VideoTrackRecordComparison"))[0],
    "checksum",
    "the POSTGRES comparison too, and it is the one that proves the point: its column is renamed \
     again, so a member following the rendered name would differ from sqlite's and an interface's \
     consistency equation could not name one accessor for both"
  );
  assert_eq!(
    enum_named(&file, "VideoTrackOrderBy").variants[0].ident,
    "Checksum",
    "and the order-by VARIANT, which is what the `OneofObject` derive renders as a schema key"
  );

  // LAYER 3 — the SDL name is untouched by the member's move, and is still the declared one.
  let backend = &model.graphql.as_ref().expect("wired").backends[0];
  let (member, sdl, _) = backend.filter_field(model.stored_columns()[0]);
  assert_eq!(
    (member.to_string(), sdl),
    ("checksum".to_owned(), "bitRate".to_owned())
  );

  // The SQL strings — the one place a storage rename is allowed to reach, and it still does.
  assert!(
    tight(&method_of(&file, "VideoTrackOrderBy", "sqlite_column").block).contains("\"bitrate\""),
    "sqlite still renders its own column name"
  );
  assert!(
    tight(&method_of(&file, "VideoTrackOrderBy", "postgres_column").block)
      .contains("\"bit_rate_v2\""),
    "and postgres still renders its own"
  );
  let lowering = tight(&file);
  assert!(
    lowering.contains("FieldName::new(\"bitrate\")")
      && lowering.contains("FieldName::new(\"bit_rate_v2\")"),
    "and each comparison pushes its OWN database's column as the address frame, off a member both \
     of them spell `checksum`"
  );
}

/// **A STORAGE RENAME DOES NOT REACH THE ORDER-BY VARIANT**, which is what keeps it off the wire.
///
/// The variant used to be built from the FIRST declared database's column name, so
/// `<db>(rename)` moved it — and the `OneofObject` derive renders a variant as a schema
/// key, so the rename left the database and landed in the SDL. Two deployments of one record could
/// not agree on the vocabulary a client writes.
///
/// Both halves are asserted from one model: the variant is the record field whatever the rename
/// says, and the resolver beside it still answers with the renamed column. Byte-for-byte, a
/// declaration that renamed NOTHING is unaffected — its column name and its field name are the same
/// string — which is why this change moves no schema that was already correct.
#[test]
fn an_order_by_variant_is_the_record_field_whatever_storage_renamed() {
  let mut model = ordered();
  let first = model
    .persist
    .as_mut()
    .expect("ordered persists")
    .backends
    .first_mut()
    .expect("a first database");
  storage_of(first).columns[3].name =
    RustSafeName::new("renamed_here", proc_macro2::Span::call_site());

  let file = emission(&model);
  let variants: Vec<String> = enum_named(&file, "VideoTrackOrderBy")
    .variants
    .iter()
    .map(|variant| variant.ident.to_string())
    .collect();
  assert_eq!(
    variants,
    ["MediaId", "VideoId", "Id", "Checksum", "CoverId"],
    "the record's own field names — `RenamedHere` is what this list used to hold, and it was a \
     storage name in a client's query document"
  );
  assert!(
    tight(&method_of(&file, "VideoTrackOrderBy", "sqlite_column").block).contains(
      "Self::Checksum(_)=>::core::result::Result::Ok(\
         ::ingraph::__private::field::FieldName::new(\"renamed_here\"))"
    ),
    "…while the rename still reaches the SQL the resolver renders, which is the whole of what it \
     was ever for"
  );
}

/// The FILTER takes every STORED column, not every exposed one: a field is filterable because it
/// is stored, so there is no marker to write and none to forget.
#[test]
fn the_filter_takes_the_stored_columns() {
  let mut model = wired();
  match &mut model.graphql.as_mut().expect("wired").backends[0] {
    GraphqlBackend::AsyncGraphql(backend) => backend.fields.pop(),
  };
  let file = emission(&model);
  let filter = struct_named(&file, "VideoTrackFilter");
  assert_eq!(
    fields(filter),
    ["checksum", "cover_id"],
    "`cover_id` is no longer exposed on the output and is still filterable — and BOTH members are \
     the record field's own name. `checksum` is exposed with `input(rename = \"bitRate\")` and the \
     member does not follow it, a wire word moving the schema name alone; `cover_id` declares no \
     wire name at all and takes its field's"
  );
  let types: Vec<String> = named(filter).iter().map(|f| tight(&f.ty)).collect();
  assert_eq!(
    types,
    [
      "::core::option::Option<<<u64as::ingraph::__private::marker::DefaultMarker>::Markeras::ingraph::__private::graphql::ToGraphqlFilter>::ColumnFilter>",
      "::core::option::Option<<<Option<Uuid7>as::ingraph::__private::marker::DefaultMarker>::Markeras::ingraph::__private::graphql::ToGraphqlFilter>::ColumnFilter>"
    ],
    "each field its type's FILTER, not its value — so a client gets the whole operator vocabulary, \
     and a nullable column keeps its three states because the null test rides its filter. The \
     domain type is written VERBATIM and asked TWICE: what it MEANS, then what guards that \
     meaning. Stripping the `Option` here would hand a nullable column the filter of a `NOT NULL` \
     one, and picking the marker here instead of asking the type would read an aliased collection \
     as a scalar."
  );
}

/// A DECLARED marker replaces the inner projection, and the two shapes cannot be unified: an impl
/// is not overridable per field, so an override BYPASSES the map rather than feeding it.
///
/// It reaches both faces of one column — the wire filter's field and the comparison the filter
/// crosses into — because a marker chosen for the wire and not for the crossing would give a column
/// two filters. The FIELD's type is applied to the marker, which is why a declaration names
/// `their::RollMarker` and not `their::RollMarker<Roll<Tag>>`.
#[test]
fn a_declared_marker_replaces_the_inference_in_every_projection() {
  let mut model = wired();
  label(
    &mut model,
    "checksum",
    Marker::Framework(FrameworkMarker {
      label: Label::Set,
      element: None,
    }),
  );
  label(
    &mut model,
    "cover_id",
    Marker::Path(syn::parse_quote!(their::RollMarker)),
  );
  let file = emission(&model);
  let shorthand = "<::ingraph::__private::marker::SetMarker<u64>as::ingraph::__private::graphql::ToGraphqlFilter>::ColumnFilter";
  let declared = "<their::RollMarker<Option<Uuid7>>as::ingraph::__private::graphql::ToGraphqlFilter>::ColumnFilter";
  assert_eq!(
    named(struct_named(&file, "VideoTrackFilter"))
      .iter()
      .map(|field| tight(&field.ty))
      .collect::<Vec<_>>(),
    [
      format!("::core::option::Option<{shorthand}>"),
      format!("::core::option::Option<{declared}>")
    ],
    "a word reaches the framework's own marker through the shelf; a path is carried verbatim, \
     because it resolves in the DECLARER's namespace and nowhere else"
  );
  let db = database_parameter();
  assert_eq!(
    named(struct_named(&file, "VideoTrackSqliteComparison"))
      .iter()
      .map(|field| tight(&field.ty))
      .collect::<Vec<_>>(),
    [
      format!(
        "<{shorthand}as::ingraph::__private::comparison::ToDatabaseComparison<u64,{db}>>::Comparison"
      ),
      format!(
        "<{declared}as::ingraph::__private::comparison::ToDatabaseComparison<Option<Uuid7>,{db}>>::Comparison"
      )
    ],
    "and the crossing starts from the SAME filter, so a column cannot end up with two"
  );
}

/// A record whose three stored columns are the whole of the collapse: an OPTIONAL collection, the
/// same collection declared BARE, and an `Option<Vec<u8>>` carrying no word at all.
///
/// The two collections name the same word, so what separates them in the emission is the `Option`
/// and nothing else — which is what lets the assertion be an EQUALITY between two columns rather
/// than a reading of one.
fn optional_collections() -> RecordModel {
  let mut model = model("Strip", &[], "id");
  let record = model.record.clone();
  // The record's own fields, because a stored column PROJECTS one — and a label is the field's, so
  // a column whose field the record does not declare has nowhere to read its word from.
  model.fields = [
    ("tags", syn::parse_quote!(Option<Vec<String>>)),
    ("labels", syn::parse_quote!(Vec<String>)),
    ("cover", syn::parse_quote!(Option<Vec<u8>>)),
  ]
  .into_iter()
  .map(|(name, ty)| Field {
    column: column_of(name, ty),
    identity: false,
    marker: None,
    sortable: false,
    indexed: false,
    reference: None,
    skip: None,
    docs: Vec::new(),
    condition: Condition::always(),
    build: Build::default(),
  })
  .collect();
  let column = |name: &str, ty: syn::Type| persist_column(name, name, ty);
  model.persist = Some(Persist {
    backends: vec![stored(
      &record,
      DatabaseKind::Sqlite,
      vec![
        column("tags", syn::parse_quote!(Option<Vec<String>>)),
        column("labels", syn::parse_quote!(Vec<String>)),
        column("cover", syn::parse_quote!(Option<Vec<u8>>)),
      ],
    )],
    table: None,
  });
  let face = |name: &str| Face {
    name: RustSafeName::new(name, proc_macro2::Span::call_site()),
    attrs: proc_macro2::TokenStream::new(),
  };
  let field = |source: &str, ty: syn::Type| GraphqlField {
    source: ident(source),
    domain: ty,
    wire: None,
    output_crossing: WirePosition::default(),
    input_crossing: WirePosition::default(),
    input: face(source),
    output: face(source),
    output_field: None,
  };
  model.graphql = Some(Graphql {
    backends: vec![GraphqlBackend::AsyncGraphql(AsyncGraphql {
      skipped: Vec::new(),
      attrs: proc_macro2::TokenStream::new(),
      fields: vec![
        field("tags", syn::parse_quote!(Option<Vec<String>>)),
        field("labels", syn::parse_quote!(Vec<String>)),
        field("cover", syn::parse_quote!(Option<Vec<u8>>)),
      ],
    })],
    input: RustSafeName::from_ident(&default_input_name(&record)),
    output: RustSafeName::from_ident(&default_output_name(&record)),
    key_output: RustSafeName::from_ident(&default_key_output_name(&record)),
    // The address's two faces take the base above, which is the state a declaration that named
    // neither of them is in.
    key_object: None,
    key_argument: None,
    filter: RustSafeName::from_ident(&default_filter_name(&record)),
    plural: None,
    // The default page names — this fixture declares no `connection(rename)` or `edge(rename)`,
    // so the emission takes the specification's own words through the alias.
    connection: None,
    edge: None,
    skipped: Vec::new(),
  });
  for name in ["tags", "labels"] {
    label(
      &mut model,
      name,
      Marker::Framework(FrameworkMarker {
        label: Label::List,
        element: None,
      }),
    );
  }
  model
}

/// **THE SHARED QUERY VOCABULARY IS THE DECLARATION'S**, so a column one database narrows away
/// KEEPS its filter word and its order-by word — and the database that has not got it keeps no
/// comparison member for it.
///
/// The law is the framework's own — *a client must never see a schema that varies with a
/// deployment's storage choice* — and reading it as *shrink to the intersection* was the mistake
/// this list is the correction of: a word that came and went with a deployment's storage would be
/// exactly the varying schema the law forbids. The schema states the DECLARATION's truth, and the
/// deployment answers at runtime with a named refusal.
///
/// The two lists therefore come APART, which is the measurable content of the flip: the filter's
/// rows are the declaration's and a narrowing database's comparison is shorter, so the crossing
/// joins them by source rather than zipping them.
///
/// Driven by taking a column out of one backend's list, which is exactly what the derive's mask does
/// for `<db>(skip(default = "…"))` and for a bare `<db>` narrowing.
#[test]
fn a_column_one_database_narrows_away_keeps_the_shared_vocabulary() {
  let mut model = wired();
  let persist = model.persist.as_mut().expect("stored");
  let taken = storage_of(&mut persist.backends[1]).columns.remove(0);

  assert!(
    model.persist.as_ref().expect("stored").backends[0]
      .columns()
      .iter()
      .any(|column| column.source == taken.source),
    "the column is still a column of the database that kept it"
  );
  assert!(
    model
      .stored_columns()
      .iter()
      .any(|column| column.source == taken.source),
    "and it stays in the shared list, which every wire vocabulary is built from"
  );
  assert!(
    model
      .queried_columns()
      .iter()
      .any(|(_, column)| column.source == taken.source),
    "so the filter still names it"
  );
  assert!(
    model
      .ordered_columns()
      .iter()
      .any(|(_, column)| column.source == taken.source),
    "and so does an order"
  );
  // The DECLARATION order survives the union: a narrowing database has a shorter list, so the walk
  // is the record's own fields and never a merge of two backends' lists.
  assert_eq!(
    model
      .stored_columns()
      .iter()
      .map(|column| column.source.to_string())
      .collect::<Vec<_>>(),
    model.persist.as_ref().expect("stored").backends[0]
      .columns()
      .iter()
      .map(|column| column.source.to_string())
      .collect::<Vec<_>>(),
    "the shared list is the declaring order, taken from the database that has every column"
  );
  // The COMPARISON is storage-true and therefore SHORTER, which is what the crossing's join exists
  // for: a member for a column this table has not got would render a predicate nothing can name.
  assert_eq!(
    model.persist.as_ref().expect("stored").backends[1]
      .compared(&model)
      .len(),
    model.queried_columns().len() - 1,
    "the narrowing database's comparison is one member shorter than the filter"
  );
  assert!(
    !model.persist.as_ref().expect("stored").backends[1]
      .compared(&model)
      .iter()
      .any(|column| column.source == taken.source),
    "and the member it is short of is the narrowed one"
  );
  assert_eq!(
    model.persist.as_ref().expect("stored").backends[0]
      .compared(&model)
      .len(),
    model.queried_columns().len(),
    "while the database that kept every column compares every one of them"
  );
}

/// **A COMPOSITE IS NOT ORDERABLE EITHER, AND IT FAILS ONE AXIS OVER.**
///
/// A collection is MANY-VALUED and a composite is MANY-COLUMNED, and the order-by breaks on both
/// the same way: `ORDER BY checksum` names the composite's own field name, and a composite has no
/// column of that name — its parts are `checksum_num`/`checksum_den`, or, marked `flatten`, the
/// record's own bare ones. The term rendered a column no table has.
///
/// **The CURSOR value leaks with it, and that is why the composite fence sits where it does.** A
/// cursor slot is one value at one column, and a composite is neither; the slot's type would be the
/// composite's own, which is not a thing any dialect binds. `ordered_columns` is what the order-by
/// is built from and what `DatabaseBackend::paged_columns` narrows, so a column this fence drops is dropped from
/// both — asserted here as the two emitted TYPES rather than as the one function. That is the
/// difference from the COLLECTION, which the narrowing keeps in one list and out of the other.
///
/// Reverting the `flatten` half of the fence restores `Checksum` to both lists.
#[test]
fn a_composite_column_is_orderable_in_neither_face() {
  let file = emission(&composed());
  let variants = |item: &syn::ItemEnum| -> Vec<String> {
    item
      .variants
      .iter()
      .map(|variant| variant.ident.to_string())
      .collect()
  };
  assert_eq!(
    variants(enum_named(&file, "MediaOrderBy")),
    ["Id", "Chapters", "CoverId"],
    "the `flatten` column is gone and its neighbours are untouched"
  );
  assert_eq!(
    variants(enum_named(&file, "MediaSqliteCursor")),
    ["Id", "Chapters", "CoverId"],
    "and the cursor value carries exactly the same set, from the same fence"
  );

  // The same model WITHOUT the marker keeps it, so what the fence reads is the declaration and not
  // the column's type — which it could not read anyway.
  let plain = emission(&whole_row());
  assert_eq!(
    variants(enum_named(&plain, "MediaOrderBy")),
    ["Id", "Checksum", "Chapters", "CoverId"],
    "an UNMARKED composite is a scalar to anything holding tokens, and stays in"
  );
}

/// **A COLLECTION-CLASSIFIED COLUMN IS AN ORDER SUBJECT, AND A CURSOR SLOT WHERE THIS DIALECT KEEPS
/// IT IN A COLUMN.**
///
/// The two vocabularies part here, and the fence that used to close both is the ORDER half being
/// PostgreSQL-ignorant: `ORDER BY <array column>` is legal there and compares element by element,
/// which is the rule this framework pins — so a collection field is an order subject like any other,
/// and what each backend can do with one is the capability frame's answer rather than an absence in
/// the emitted enum.
///
/// The CURSOR half narrowed the same way one release later. What is true is about the DIALECT: a
/// boundary is a value this database can bind, so an EDGE-STORED collection has no slot to be, and
/// an array-stored one does — `Carrier<Postgres>` binds the whole list as one `E[]` and
/// `CursorValue` writes it into one slot with its own inner framing. That is
/// `DatabaseBackend::paged_columns`, and its input is `edge_stored`, the same authority the term's
/// subject reads.
///
/// This test is SQLite's side of it: no array type, so the collection is edge-stored and no slot.
/// The PostgreSQL side is the test below, and the two together are the fence stated as a fork rather
/// than as a rule about collections.
///
/// Both halves are asserted as emitted TYPES rather than as the two functions, and on two models
/// because only one of them has a stored id to have a cursor at all.
///
/// Mutating `paged_columns` to drop the `edge_stored` filter puts `Chapters` in SQLite's cursor,
/// which is the split stated as a diff — and mutating `ordered_columns` back to the old collection
/// fence empties the first assertion.
#[test]
fn a_collection_word_is_an_order_subject_and_not_a_cursor_slot() {
  let model = optional_collections();
  assert_eq!(
    model
      .stored_columns()
      .iter()
      .map(|column| column.name.to_string())
      .collect::<Vec<_>>(),
    ["tags", "labels", "cover"],
    "all three are stored, and the word is what tells them apart rather than participation"
  );
  assert!(
    model
      .fields
      .iter()
      .all(|field| field.column.project == Projection::Borrowed),
    "and not one of them writes `repeated`, which is the OTHER axis this must not read"
  );

  let variants = |item: &syn::ItemEnum| -> Vec<String> {
    item
      .variants
      .iter()
      .map(|variant| variant.ident.to_string())
      .collect()
  };
  let file = emission(&model);
  assert_eq!(
    variants(enum_named(&file, "StripOrderBy")),
    ["Tags", "Labels", "Cover"],
    "the two `list` columns are order subjects, beside the blob that was never in question"
  );

  // The cursor half needs a model with a stored id, which is what a query face is emitted for at
  // all: `gathered` is `whole_row` with its `chapters` column declared a sequence.
  let paged = emission(&gathered());
  assert_eq!(
    variants(enum_named(&paged, "MediaOrderBy")),
    ["Id", "Checksum", "Chapters", "CoverId"],
    "the collection is an order subject here too"
  );
  assert_eq!(
    variants(enum_named(&paged, "MediaSqliteCursor")),
    ["Id", "Checksum", "CoverId"],
    "and on SQLite, where it is edge-stored, it is the one column a cursor has no slot for"
  );
}

/// **AN ARRAY-STORED COLLECTION IS A CURSOR SLOT, AND THE SLOT HOLDS THE WHOLE LIST.**
///
/// The other side of the fork above, and the line the array cursor opened. The three fixtures are
/// `edge_stored`'s three answers, read here through the emitted CURSOR rather than through the term:
///
/// | model | the collection is | the slot |
/// |---|---|---|
/// | `gathered` (SQLite) | an edge table, the dialect having no array | absent |
/// | `gathered_in_postgres` | a native array, the wordless default | `Chapters(Vec<Uuid7>)` |
/// | `edge_declared_in_postgres` | an edge table, the WORD saying so | absent |
///
/// The slot's TYPE is the whole list and not one element, which is what makes the boundary the row's
/// own value: the declared type is one element's — the comparison binds one member at a time — and
/// the row's field holds the list, so the cursor reads `row_field` rather than spelling a second
/// answer.
///
/// The order-by is unmoved in all three: the collection is an order subject wherever it lives, and
/// what varies is only what a page can resume at.
///
/// Mutating `paged_columns` to drop the `edge_stored` filter puts `Chapters` in the third model's
/// cursor, where the boundary would be bound against a table the row has no column for; mutating
/// `cursor_type` to spell `column.ty()` for a collection makes the slot one element, which is a
/// boundary that resumes at the wrong row and renders perfectly well.
#[test]
fn an_array_stored_collection_is_a_cursor_slot_holding_the_whole_list() {
  let variants = |item: &syn::ItemEnum| -> Vec<String> {
    item
      .variants
      .iter()
      .map(|variant| variant.ident.to_string())
      .collect()
  };

  let postgres = emission(&gathered_in_postgres());
  assert_eq!(
    variants(enum_named(&postgres, "MediaOrderBy")),
    ["Id", "Checksum", "Chapters", "CoverId"],
    "the order-by is what it was"
  );
  assert_eq!(
    variants(enum_named(&postgres, "MediaPostgresCursor")),
    ["Id", "Checksum", "Chapters", "CoverId"],
    "and the array-stored collection now has a slot of its own"
  );

  let slot = enum_named(&postgres, "MediaPostgresCursor")
    .variants
    .iter()
    .find(|variant| variant.ident == "Chapters")
    .expect("the collection has a slot");
  assert_eq!(
    tight(&slot.fields),
    "(::std::vec::Vec<Uuid7>)",
    "and the slot holds the LIST, which is what the row's field holds"
  );

  // The WORD sends the same column to a table of its own, and the slot goes with it.
  let worded = emission(&edge_declared_in_postgres());
  assert_eq!(
    variants(enum_named(&worded, "MediaOrderBy")),
    ["Id", "Checksum", "Chapters", "CoverId"],
    "still an order subject, which is the term's own answer"
  );
  assert_eq!(
    variants(enum_named(&worded, "MediaPostgresCursor")),
    ["Id", "Checksum", "CoverId"],
    "and no slot, on the same dialect, because the storage form is what decides"
  );
}

/// **THE ROW'S PROJECTION ANSWERS AT AN ARRAY-STORED COLLECTION AND STILL DECLINES AT AN EDGE-STORED
/// ONE.**
///
/// `SqlOrdering::value` is the other end of the slot: the cursor sum says a boundary CAN be taken
/// here, and this is what takes it. The two have to agree column for column, or a page mints a
/// cursor with a `None` where its own order has a term.
///
/// Mutating the emission to answer `None` for an array-stored collection leaves the slot in the sum
/// and never fills it, which is a page that resumes at a `NULL` the column cannot hold — and
/// `Cursor::resume` refuses it, one layer later and for the wrong reason.
#[test]
fn the_row_projects_a_value_at_an_array_stored_collection_and_none_at_an_edge_stored_one() {
  let value_of = |model: &RecordModel| -> String {
    let file = emission(model);
    let ordering = wrote(&file, "SqlOrdering").expect("the page binding is emitted");
    let value = methods(ordering)
      .into_iter()
      .find(|method| method.sig.ident == "value")
      .expect("the row's projection into cursor values");
    tight(&value.block)
  };

  let array = value_of(&gathered_in_postgres());
  assert!(
    array.contains(
      "MediaOrderBy::Chapters(_)=>::core::result::Result::Ok(::core::option::Option::Some(\
       MediaPostgresCursor::Chapters(::core::clone::Clone::clone(&self.chapters)),))"
    ),
    "the array-stored collection projects the row's whole list: {array}"
  );

  let worded = value_of(&edge_declared_in_postgres());
  assert!(
    worded.contains(
      "MediaOrderBy::Chapters(_)=>::core::result::Result::Ok(::core::option::Option::None)"
    ),
    "and the edge-stored one still declines, on the same dialect: {worded}"
  );
}

/// **THE TERM'S SUBJECT IS THE STORAGE FORM, AND `edge_stored` IS THE ONE PARTY THAT DECIDES IT.**
///
/// This is where the capability frame gets its input. `OrderTerm::array` says *a collection in a
/// column of this row*, which PostgreSQL orders element by element and the frame therefore pushes;
/// `OrderTerm::edge` says *a collection in a table of its own*, which no backend's `ORDER BY` has a
/// column for. Emitting the wrong one is a statement ordered by a column the table has not got, or
/// a refusal for an order PostgreSQL renders perfectly well.
///
/// The three fixtures are the three answers `edge_stored` gives: SQLite has no array type, so every
/// collection is edge-stored there; PostgreSQL's wordless default rides the row as a native array;
/// and `postgres(edge)` sends it to the table after all, which is the fact
/// `PgCollectionStorage` holds and a macro holding tokens cannot read.
///
/// The scalar beside it takes the WIDTH pair — `OrderTerm::spanning`, with its type's own segments —
/// which is the fence: what the storage form forks is the collection's arm alone. The two forks
/// cannot meet, because a collection is one column whatever it holds and so has no segments to
/// state.
#[test]
fn an_order_term_names_the_collection_s_storage_form() {
  let term_of = |model: &RecordModel, kind: &str| -> String {
    tight(&method_of(&emission(model), "MediaOrderBy", &format!("{kind}_term")).block)
  };

  let sqlite = term_of(&gathered(), "sqlite");
  assert!(
    sqlite.contains("Self::Chapters(direction)=>::ingraph::__private::cursor::OrderTerm::edge("),
    "SQLite has no array type, so every collection is a table of its own: {sqlite}"
  );
  assert!(
    sqlite.contains("Self::Id(direction)=>::ingraph::__private::cursor::OrderTerm::spanning("),
    "and the scalars beside it take the width constructor, not the subject one: {sqlite}"
  );

  let postgres = term_of(&gathered_in_postgres(), "postgres");
  assert!(
    postgres.contains("Self::Chapters(direction)=>::ingraph::__private::cursor::OrderTerm::array("),
    "the wordless default rides the row as a native array: {postgres}"
  );

  let worded = term_of(&edge_declared_in_postgres(), "postgres");
  assert!(
    worded.contains("Self::Chapters(direction)=>::ingraph::__private::cursor::OrderTerm::edge("),
    "and the word sends the same column to a table of its own: {worded}"
  );
}

/// A COLLECTION-classified column resolves as if the `Option` had not been written — so its wire
/// face carries no null test, and it is the SAME face the bare collection beside it carries.
///
/// A collection has no null state: an edge table holds one observable for a column holding nothing,
/// where the Rust type spells two. The equality between the first two entries is the whole claim —
/// same word, same emitted projection, the `Option` making no difference — and the third is the
/// FENCE that keeps it from being a rule about the shape `Option<Vec<…>>`: an `Option<Vec<u8>>`
/// naming no word is a nullable BLOB, a real two-state null, and it still reaches the inference
/// through its own `Option`.
///
/// Restoring the wrap breaks the EQUALITY and leaves the fence where it is — measured: the first
/// entry becomes `ListMarker<Option<Vec<String>>>` while the second stays `ListMarker<Vec<String>>`,
/// and the third does not move at all. Which is the scope of the change stated as a diff: it reaches
/// the columns a word classified, and no others.
#[test]
fn a_collection_classified_column_sheds_the_option_and_a_blob_keeps_it() {
  let file = emission(&optional_collections());
  // TWO segments, because the projection's two halves live on two: the READING is the crate's own
  // vocabulary and the FILTER it resolves to is the GraphQL axis's answer, so an expansion names
  // `marker::` for the first and `graphql::` for the second.
  let marker = "::ingraph::__private::marker";
  let shelf = "::ingraph::__private::graphql";
  let listed =
    format!("<{marker}::ListMarker<Vec<String>>as{shelf}::ToGraphqlFilter>::ColumnFilter");
  let inferred = format!(
    "<<Option<Vec<u8>>as{marker}::DefaultMarker>::Markeras{shelf}::ToGraphqlFilter>::ColumnFilter"
  );
  assert_eq!(
    named(struct_named(&file, "StripFilter"))
      .iter()
      .map(|field| tight(&field.ty))
      .collect::<Vec<_>>(),
    [
      format!("::core::option::Option<{listed}>"),
      format!("::core::option::Option<{listed}>"),
      format!("::core::option::Option<{inferred}>")
    ],
    "the optional collection and the bare one are one face, and the marker is applied to the \
     COLLECTION — an `Option<Vec<String>>` inside the marker would carry the null test the ruling \
     says the column does not have"
  );
  let db = database_parameter();
  let crossing = |filter: &str, stored: &str| {
    format!(
      "<{filter}as::ingraph::__private::comparison::ToDatabaseComparison<{stored},{db}>>::Comparison"
    )
  };
  assert_eq!(
    named(struct_named(&file, "StripSqliteComparison"))
      .iter()
      .map(|field| tight(&field.ty))
      .collect::<Vec<_>>(),
    [
      crossing(&listed, "Option<Vec<String>>"),
      crossing(&listed, "Vec<String>"),
      crossing(&inferred, "Option<Vec<u8>>")
    ],
    "and the collapse reaches the crossing's SELF TYPE, which is where the `Nullable` wrapper would \
     otherwise compose over a collection's comparison. The STORED type is untouched — it is the column's \
     own declaration, and an edge-table column declares the ELEMENT type it keeps"
  );
}

/// The collapse reads a WRITTEN `Option<…>`, so an alias hiding one is left exactly as declared —
/// and that is the limit stated rather than hidden.
///
/// It is the only place this emitter reads a type's spelling, and what makes it admissible is
/// where it STOPS: the marker lands on the alias, `MaybeTags: ListFilterMarker` is unsatisfied, and
/// rustc names the type at the declaration. The syntactic reading this crate refuses for the
/// PROJECTIONS answers instead — it hands an aliased collection back as a scalar's borrow, with no
/// diagnostic anywhere. Measured on the other side too: mutating the collapse away makes
/// [`a_collection_classified_column_sheds_the_option_and_a_blob_keeps_it`]'s own fixture fail with
/// exactly that bound, at the `#[ingraph::record(…)]`.
///
/// The last SEGMENT is what is matched, so a fully qualified `core::option::Option<…>` is the same
/// written shape a bare one is.
#[test]
fn an_alias_hiding_the_option_is_left_alone_and_a_qualified_one_is_not() {
  let marker = "::ingraph::__private::marker";
  let shelf = "::ingraph::__private::graphql";
  let emitted = |domain: syn::Type| {
    let mut model = optional_collections();
    let Some(persist) = model.persist.as_mut() else {
      panic!("the model stores its columns")
    };
    storage_of(&mut persist.backends[0]).columns[0].domain = domain.clone();
    match &mut model.graphql.as_mut().expect("wired").backends[0] {
      GraphqlBackend::AsyncGraphql(backend) => backend.fields[0].domain = domain,
    }
    let file = emission(&model);
    tight(&named(struct_named(&file, "StripFilter"))[0].ty)
  };
  assert_eq!(
    emitted(syn::parse_quote!(MaybeTags)),
    format!(
      "::core::option::Option<<{marker}::ListMarker<MaybeTags>as{shelf}::ToGraphqlFilter>::ColumnFilter>"
    ),
    "an alias is carried verbatim — the emitter cannot see through one, and the column is refused \
     at the declaration rather than resolved to the wrapped filter"
  );
  assert_eq!(
    emitted(syn::parse_quote!(core::option::Option<Vec<String>>)),
    format!(
      "::core::option::Option<<{marker}::ListMarker<Vec<String>>as{shelf}::ToGraphqlFilter>::ColumnFilter>"
    ),
    "and a written `Option` is one however it is spelled"
  );
}

/// One comparison per DATABASE, and a field is the comparison KIND its column's filter crosses
/// into — the operator set, not one storage-typed value.
///
/// The three projections answer different halves, and the postgres row is where that is visible:
/// the DOMAIN type `u64` picks its INTERPRETATION and that picks the filter, so the kind is
/// whatever a `u64` MEANS is filtered with, while the STORED type is the declared `BeU64`, so that
/// is what the kind's operands are. `type = "BeU64"` changed the storage and not the question, and
/// every authority is one the ROW reads — which is why they cannot drift apart.
///
/// None of the projections is resolved here. The macro writes the declared types verbatim into a
/// qualification and the compiler answers, so a downstream type joins by implementing the traits
/// and `Option<Uuid7>` reaches its nullable kind without anything here inspecting the spelling —
/// which it must not, since an aliased `Vec` and a scalar are the same tokens.
#[test]
fn the_comparison_holds_a_crossing_per_column_per_database() {
  let file = emission(&wired());
  let db = database_parameter();
  let types = |name: &str| -> Vec<String> {
    named(struct_named(&file, name))
      .iter()
      .map(|field| tight(&field.ty))
      .collect()
  };
  let held = |domain: &str, stored: &str| {
    format!(
      "<<<{domain}as::ingraph::__private::marker::DefaultMarker>::Markeras::ingraph::__private::graphql::ToGraphqlFilter>::ColumnFilteras::ingraph::__private::comparison::ToDatabaseComparison<{stored},{db}>>::Comparison"
    )
  };
  assert_eq!(
    types("VideoTrackSqliteComparison"),
    [held("u64", "u64"), held("Option<Uuid7>", "Option<Uuid7>")]
  );
  assert_eq!(
    types("VideoTrackRecordComparison"),
    [held("u64", "BeU64"), held("Option<Uuid7>", "Option<Uuid7>")],
    "the `type` override reaches the OPERANDS exactly as it reaches the row — one authority — and \
     the filter is still chosen by the domain type, because storage is not the question"
  );
  assert_eq!(
    fields(struct_named(&file, "VideoTrackRecordComparison")),
    ["checksum", "cover_id"],
    "and the member is the RECORD FIELD's — LAYER 1. It used to be this database's column name, \
     which gave one column two member names across two backends (`bit_rate_v2` here, `bitrate` on \
     sqlite) and made an interface's consistency equation, which reads a member's comparison \
     through an accessor built from the pinned field name, break on a neighbour's storage rename"
  );
  assert_eq!(
    returns(method_of(
      &file,
      &format!("VideoTrackSqliteComparison<{db}>"),
      "checksum_ref"
    )),
    format!("&{}", held("u64", "u64")),
    "and the accessor hands back the KIND, not an `Option<&value>` — whether the column is compared \
     at all is the kind's own emptiness, and a second encoding of one fact can disagree with the \
     first"
  );
}

/// The comparison carries `Debug`, `Clone` and `Default` no longer — not derived, and not written
/// out either. All three went with the shape, and the reason is measured rather than a preference.
///
/// A derive fails: its body needs each field's projection to carry the trait, which the crossing the
/// struct assumes does not imply. Stating the bound fails too —
/// `<F as ToDatabaseComparison<V, Db>>::Comparison: Debug` has a concrete self type, so rustc
/// resolves the projection through the impl that defines it and demands the `Db: sqlx::Database` an
/// expansion may not write.
///
/// And the escape from THAT — an associated-type binding with one impl parameter per column
/// (`Comparison = C0`) — holds only while no two columns share a crossing. Three `i64` columns,
/// which `ingraph-derive`'s `Frame` fixture has, bind one trait-ref to three parameters and none of
/// them can be inferred (`E0284`). Deduplicating the parameters does not repair it: the emitter may
/// key only on what a declaration WROTE, and a type alias makes two spellings of one crossing —
/// measured, and it fails the same way.
#[test]
fn the_comparison_carries_no_derive_and_only_the_lowering() {
  let file = emission(&wired());
  let attrs: Vec<String> = struct_named(&file, "VideoTrackSqliteComparison")
    .attrs
    .iter()
    .filter(|attr| !attr.path().is_ident("doc"))
    .map(tight)
    .collect();
  assert!(attrs.is_empty(), "no derive survives the shape: {attrs:?}");

  let written: Vec<String> = trait_impls(&file)
    .into_iter()
    .filter(|(item, _)| impl_of(item).starts_with("VideoTrackSqliteComparison"))
    .map(|(_, path)| tight(path))
    .collect();
  assert_eq!(
    written,
    [format!(
      "::ingraph::__private::comparison::ComplexComparison<{}>",
      database_parameter()
    )],
    "the LOWERING is the one impl the type carries, and it needs none of the three: its body calls \
     the trait methods the crossing's item bound already promises of each field"
  );
}

/// `Default` went with the shape and the fields are private, so the comparison could be NAMED and
/// not built. `new` is what it gets instead: one predicate per column, positional, in the order this
/// database stores them.
///
/// Positional is the only shape available. A `new()` yielding the EMPTY comparison would need
/// `Default` on each field's projection, and a bound on a projection cannot be stated — see
/// [`the_comparison_carries_no_derive_and_only_the_lowering`] and the emitter's own note. So the
/// empty predicate is assembled from the KINDS' own `Default`, one argument at a time.
#[test]
fn the_comparison_gains_the_constructor_the_shape_took_away() {
  let db = database_parameter();
  let file = emission(&wired());
  let new = method_of(&file, &format!("VideoTrackSqliteComparison<{db}>"), "new");
  assert!(
    is_const(new),
    "moving a predicate into a struct drops nothing"
  );
  let parameters: Vec<String> = new
    .sig
    .inputs
    .iter()
    .map(|input| match input {
      syn::FnArg::Typed(typed) => tight(&typed.pat),
      syn::FnArg::Receiver(_) => panic!("`new` takes no self"),
    })
    .collect();
  assert_eq!(
    parameters,
    ["checksum", "cover_id"],
    "in column order, each named by the record field it compares"
  );
  assert_eq!(
    tight(&new.sig.output),
    "->Self",
    "the comparison, not a builder — it has no invariant to guard"
  );
  assert_eq!(
    methods_of(&file, &format!("VideoTrackSqliteComparison<{db}>")),
    ["new", "checksum_ref", "cover_id_ref"],
    "`new`, then each column's borrow — no mutators, because a predicate is built and then lowered"
  );
}

/// A database storing NO column still gets a `new`, and it takes nothing: the `PhantomData` the
/// marker case adds is the emitter's, not a caller's to supply.
#[test]
fn a_database_with_no_column_gets_a_nullary_constructor() {
  let mut model = wired();
  for database in model
    .persist
    .iter_mut()
    .flat_map(|persist| &mut persist.backends)
  {
    storage_of(database).columns.clear();
  }
  let file = emission(&model);
  let new = method_of(
    &file,
    &format!("VideoTrackSqliteComparison<{}>", database_parameter()),
    "new",
  );
  assert!(new.sig.inputs.is_empty());
  assert_eq!(
    tight(&new.block),
    "{Self{db:::core::marker::PhantomData,}}",
    "and the marker is filled in rather than left for `Default`, which this type does not have"
  );
}

/// A database that stores no column still gets a well-formed comparison: the database parameter
/// occurs in no field, so it needs a `PhantomData` to occur in, and `E0392` would otherwise land
/// inside an expansion its author cannot edit.
///
/// The marker is emitted ONLY then, and that is also why its name cannot collide with a
/// declaration's own field called `db`: the marker exists exactly when there is no column beside
/// it. `ingraph-derive`'s `Pipeline` fixture declares such a field and takes the other branch —
/// column present, marker absent — which is the pair that makes the claim total.
#[test]
fn a_database_with_no_column_gets_the_marker_and_no_other_does() {
  let mut model = persisted();
  for database in model
    .persist
    .iter_mut()
    .flat_map(|persist| &mut persist.backends)
  {
    storage_of(database).columns.clear();
  }
  let file = emission(&model);
  assert_eq!(
    named(struct_named(&file, "VideoTrackSqliteComparison"))
      .iter()
      .map(|field| tight(&field.ty))
      .collect::<Vec<String>>(),
    [format!(
      "::core::marker::PhantomData<fn()->{}>",
      database_parameter()
    )]
  );
  assert!(
    !fields(struct_named(
      &emission(&persisted()),
      "VideoTrackSqliteComparison"
    ))
    .contains(&"db".to_owned())
  );
}

/// **The comparison LOWERS and does not CROSS**, and the asymmetry is measured rather than an
/// omission.
///
/// Both once needed the same thing the type-level map did not: a BOUND on
/// `<F as ToDatabaseComparison<V, Db>>::Comparison`. A projection whose self type is concrete
/// resolves through the impl that defines it, so such a bound demands whatever that impl demands of
/// `Db`. For most filter kinds that is `sqlx::Database`; for `ListFilter` — which every `Vec<T>`
/// column crosses through — it is `CollectionStorage<V>`, which `Db: sqlx::Database` does not
/// give. One spelled bound cannot serve both, and the emitter cannot ask which kind a column is:
/// it sees the type's tokens, and `Vec<Uuid7>` may be an alias for anything.
///
/// The LOWERING escaped that by moving to where it can be discharged: it is an ITEM bound on
/// `ToDatabaseComparison::Comparison`, so each row proves it at a concrete dialect and a caller —
/// this emission included — states only the crossing.
///
/// The CROSSING cannot follow, and that is refuted rather than pending. A collection's crossing
/// lands on `SqlEdgeComparison` wherever a dialect keeps a value list in an edge table, and that
/// comparison is constructed WITH its addressing — the correlated table and the parent's key
/// columns, none of which is in the filter — so `TryFromFilter`, which takes a filter and nothing
/// else, is deliberately not its crossing. An item bound demanding it would delete two dialects'
/// rows.
///
/// The single-authority property is unaffected: the ROW's crossing still goes through the column's
/// declaration alone — pinned by `each_column_is_converted_the_way_the_declaration_says` — and the
/// comparison still carries that same declared storage type, pinned just above. The two cannot
/// diverge because neither is derived from the other; both read one `PersistColumn`.
#[test]
fn the_lowering_is_emitted_and_the_crossing_from_a_filter_is_not() {
  let file = emission(&wired());
  let by = |needle: &str| -> Vec<String> {
    trait_impls(&file)
      .into_iter()
      .filter(|(_, path)| tight(path).contains(needle))
      .map(|(item, path)| format!("{} for {}", tight(path), impl_of(item)))
      .collect()
  };
  assert!(
    by("FromFilter").is_empty(),
    "a filter carries no VALUES into a comparison: the bound that would say so cannot be stated \
     here, and cannot move onto the map either — the edge-table strategy is constructed with \
     addressing the filter does not carry: {:?}",
    by("FromFilter")
  );
  let db = database_parameter();
  assert_eq!(
    by("ComplexComparison"),
    [
      format!(
        "::ingraph::__private::comparison::ComplexComparison<{db}> for VideoTrackSqliteComparison<{db}>"
      ),
      format!(
        "::ingraph::__private::comparison::ComplexComparison<{db}> for VideoTrackRecordComparison<{db}>"
      ),
      format!(
        "::ingraph::__private::comparison::ComplexComparison<{db}> for VideoTrackMongoComparison<{db}>"
      ),
    ],
    "one per database, and each is what discharges the item bound the map's associated type carries"
  );
  // The TYPE-LEVEL map is emitted, and the comparison is still storage-typed.
  assert!(names(&file).contains(&"VideoTrackRecordComparison".to_owned()));
}

/// The lowering is emitted for a comparison with NO wire face too, because the type is a comparison
/// either way — and because a database that stores no column still has to lower to nothing.
#[test]
fn the_lowering_rides_with_the_comparison_rather_than_with_the_map() {
  let db = database_parameter();
  let file = emission(&persisted());
  let lowerings: Vec<String> = trait_impls(&file)
    .into_iter()
    .filter(|(_, path)| tight(path).contains("ComplexComparison"))
    .map(|(item, _)| impl_of(item))
    .collect();
  assert_eq!(
    lowerings,
    [
      format!("VideoTrackSqliteComparison<{db}>"),
      format!("VideoTrackRecordComparison<{db}>"),
      format!("VideoTrackMongoComparison<{db}>"),
    ],
    "no filter is declared, so no map is emitted — and the lowering is still here"
  );

  let mut model = persisted();
  for database in model
    .persist
    .iter_mut()
    .flat_map(|persist| &mut persist.backends)
  {
    storage_of(database).columns.clear();
  }
  let file = emission(&model);
  let empty = trait_impls(&file)
    .into_iter()
    .find(|(item, path)| {
      tight(path).contains("ComplexComparison") && impl_of(item).starts_with("VideoTrackSqlite")
    })
    .map(|(item, _)| tight(item))
    .expect("the empty comparison lowers too");
  assert!(
    empty.contains("fnconjuncts(&self)->::core::primitive::usize{0}"),
    "a comparison with no column renders no conjunct: {empty}"
  );
  assert!(
    empty.contains("::core::result::Result::Ok(__ingraph_builder)"),
    "and hands the accumulator straight back: {empty}"
  );
}

/// Every `Record<Db>` impl in an emission: the backend it names, and every type it binds, in the
/// order the emission writes them — the row, then the comparison.
fn vocabularies(file: &syn::File) -> Vec<(String, Vec<String>)> {
  trait_impls(file)
    .into_iter()
    .filter(|(_, path)| {
      let shelved: Vec<String> = path
        .segments
        .iter()
        .skip_while(|segment| segment.ident != "__private")
        .skip(1)
        .map(|segment| segment.ident.to_string())
        .collect();
      shelved == ["transform", "Record"]
    })
    .map(|(item, path)| {
      let backend = storage_argument(path).expect("the vocabulary names its backend");
      let bound: Vec<String> = item
        .items
        .iter()
        .filter_map(|item| match item {
          syn::ImplItem::Type(bound) => Some(tight(&bound.ty)),
          _ => None,
        })
        .collect();
      (backend, bound)
    })
    .collect()
}

/// **THE VOCABULARY IS ONE IMPL PER DECLARED DATABASE, EACH NAMING A CONCRETE BACKEND.**
///
/// This is the one emitted item whose backend is not a parameter, and that is the whole of what it
/// buys: `<Row>Comparison<Sqlite>` written at a concrete backend is well-formed-checked HERE, so
/// every column's crossing at that database is discharged at the declaration rather than deferred to
/// a call site. The comparison each names is THIS database's — a renamed row takes its comparison
/// with it, which is why the Postgres entry is `VideoTrackRecordComparison` and not the default.
///
/// **The ROW is bound beside it, and the Postgres entry is the reason the member exists**: the row
/// there is `VideoTrackRecord`, so nothing that appended a suffix to the record's name could have
/// found it. A neighbour's expansion reads `<VideoTrack as Record<Postgres>>::Row` and gets the
/// renamed type; no other party knows the name at all.
///
/// Mongo's backend is this crate's own name rather than a sqlx one, because a MongoDB comparison has
/// no dialect to remember and there is no driver unit struct to borrow.
///
/// **The ORDER is the third member, and it is the same type at all three.** That is the transitional
/// truth rather than a redundancy the seat could have done without: a term of the record's order-by
/// lowers through `<db>_term` into that database's own `OrderTerm`, so the enum IS what each of them
/// sorts by today. What the per-database seat buys is the day they diverge — a citizen's one wire
/// word expanding into a dialect's own level sequence, which no database-free type can hold two of
/// — and the retired `Orderable` is what could not have carried it. Until then this row is three
/// copies of one name, and a reader should read it as the seat rather than as the answer.
#[test]
fn the_vocabulary_is_one_impl_per_declared_database_at_a_concrete_backend() {
  const SQLITE: &str = "::ingraph::__private::sqlx::Sqlite";
  const POSTGRES: &str = "::ingraph::__private::sqlx::Postgres";
  const MONGO: &str = "::ingraph::__private::comparison::mongo::Mongo";
  const ORDER: &str = "VideoTrackOrderBy";

  assert_eq!(
    vocabularies(&emission(&persisted())),
    [
      (
        SQLITE.to_owned(),
        vec![
          "VideoTrackSqlite".to_owned(),
          format!("VideoTrackSqliteComparison<{SQLITE}>"),
          ORDER.to_owned(),
        ]
      ),
      (
        POSTGRES.to_owned(),
        vec![
          "VideoTrackRecord".to_owned(),
          format!("VideoTrackRecordComparison<{POSTGRES}>"),
          ORDER.to_owned(),
        ]
      ),
      (
        MONGO.to_owned(),
        vec![
          "VideoTrackMongo".to_owned(),
          format!("VideoTrackMongoComparison<{MONGO}>"),
          ORDER.to_owned(),
        ]
      ),
    ]
  );
}

/// **A RECORD THAT PERSISTS NOWHERE GETS NO VOCABULARY IMPL AND NO GATE.**
///
/// The entity binding already says so from the other side — its row form is `()` — and `()`
/// implements none of the vocabulary. An impl here would be an audit of a record that becomes no
/// row.
#[test]
fn a_record_that_persists_nowhere_answers_no_vocabulary() {
  let model = video_track();
  assert!(model.persist.is_none(), "the fixture is pure compute");
  assert!(vocabularies(&emission(&model)).is_empty());
  assert!(gated(&model).is_empty(), "and nothing rides a gate");
}

/// **EVERY VOCABULARY IMPL RIDES ITS OWN DATABASE'S GATE, AND SO DOES THE ONE OTHER ITEM THAT NAMES
/// A BACKEND'S OWN TYPES.**
///
/// Read off the emission AS WRITTEN rather than through [`emission`], which opens the gates: what a
/// build WITHOUT a backend sees is decided by the wrapper, so the wrapper is what this asserts.
///
/// The equality is exact in both directions. One way it says the audit cannot be dodged — an impl
/// emitted ungated would name a backend a build may not have, and would break declare-many /
/// build-one for every consumer. The other way it says a gate is not a hiding place: what a gate
/// holds is listed here, so an item that acquired one to escape a rule shows up.
///
/// The MongoDB backend rides TWO, and the second one is the EXTRACTION — the empty group, since it
/// is an inherent impl and this walk lists trait impls. It qualifies on the same ground the
/// vocabulary does and no other: every name it writes is a type only a build with that backend has.
/// A THIRD group appearing here is a claim that has to be made in this doc before it is made in the
/// list.
#[test]
fn the_vocabulary_rides_its_databases_gate_and_nothing_else_does() {
  let record = |backend: &str| {
    vec![format!(
      "::ingraph::__private::transform::Record<{backend}> for VideoTrack"
    )]
  };
  assert_eq!(
    gated(&persisted()),
    [
      (
        "if_sqlite".to_owned(),
        record("::ingraph::__private::sqlx::Sqlite")
      ),
      (
        "if_postgres".to_owned(),
        record("::ingraph::__private::sqlx::Postgres")
      ),
      // The document's own extraction: an INHERENT impl, so it holds no trait for this walk to
      // name, and it rides the gate because `bson::Document` and the extraction it calls exist only
      // where the backend was compiled in.
      ("if_mongo".to_owned(), Vec::new()),
      (
        "if_mongo".to_owned(),
        record("::ingraph::__private::comparison::mongo::Mongo")
      ),
    ]
  );
}

/// [`persisted`] with its FIRST column marked `flatten`, in every database — the marker is common, so
/// a model that carried it in one and not another could not have come from a declaration.
///
/// The second column is left unmarked deliberately: every assertion below is a comparison between
/// the two, one attribute apart, inside one emission.
fn flattened() -> RecordModel {
  let mut model = persisted();
  flatten_the_first_sql_column(&mut model);
  model
}

/// **`flatten` is the absence of a frame.** A marked column hands its comparison the address the
/// record's own comparison was handed; an unmarked one pushes a segment first, and that segment is
/// the only difference between the two statements.
#[test]
fn a_flattened_column_pushes_no_frame_and_every_other_column_still_does() {
  let file = emission(&flattened());
  let lowering = trait_impls(&file)
    .into_iter()
    .find(|(item, path)| {
      tight(path).contains("ComplexComparison") && impl_of(item).starts_with("VideoTrackSqlite")
    })
    .map(|(item, _)| tight(item))
    .expect("the sqlite lowering");

  assert!(
    lowering.contains("apply(&self.checksum,__ingraph_at,__ingraph_builder,)"),
    "the marked column is applied at the address this comparison was handed, and it is read through \
     the MEMBER — layer 1, the record field's name, where the frame below is the SQL string: \
     {lowering}"
  );
  assert!(
    !lowering.contains("FieldName::new(\"bitrate\")"),
    "and no segment is made for it at all: {lowering}"
  );
  assert!(
    lowering.contains("FieldName::new(\"cover_id\")"),
    "while the unmarked column beside it still pushes its own: {lowering}"
  );
}

/// The marker's whole compile-time half: a marked column crosses through `ToFlattenedComparison`, which
/// is the crossing REFINED to a comparison of more than one column, and an unmarked one crosses
/// through the plain map.
///
/// The refinement carries the plain crossing as its supertrait, so a marked column states ONE
/// predicate and the projection beside it stays well formed.
#[test]
fn a_flattened_column_states_the_refined_crossing_and_no_other_column_does() {
  let file = emission(&flattened());
  let clause = tight(
    struct_named(&file, "VideoTrackSqliteComparison")
      .generics
      .where_clause
      .as_ref()
      .expect("the comparison assumes its crossings"),
  );

  assert!(
    clause.contains("ToFlattenedComparison<u64,"),
    "the marked column's crossing is the refined one: {clause}"
  );
  assert!(
    clause.contains("ToDatabaseComparison<Option<Uuid7>,"),
    "and the unmarked column's is the plain one: {clause}"
  );
  assert!(
    !clause.contains("ToFlattenedComparison<Option<Uuid7>,"),
    "nothing else picks up the refinement: {clause}"
  );
  assert!(
    !tight(
      struct_named(&emission(&persisted()), "VideoTrackSqliteComparison")
        .generics
        .where_clause
        .as_ref()
        .expect("the comparison assumes its crossings")
    )
    .contains("ToFlattenedComparison"),
    "and an unmarked declaration states it nowhere"
  );
}

/// **And the DECODE takes the same word.** A marked field lends no name, so its type's segments are
/// read in the holder's own namespace and there is no name for the read to write; an unmarked one
/// beside it still writes its own.
///
/// This is the read half of what `an_inline_column_pushes_no_frame_and_every_other_column_still
/// _does` asserts for the predicate and what the `COLUMNS` entry asserts for the statement — one
/// declaration, one word, three lanes that have to agree about it.
#[test]
fn a_flattened_column_is_read_without_a_name_and_every_other_column_with_one() {
  assert_eq!(
    decoded(&emission(&flattened()), "VideoTrackSqlite"),
    [
      ("bitrate".to_owned(), None),
      ("cover_id".to_owned(), Some("cover_id".to_owned())),
    ],
  );
  assert_eq!(
    decoded(&emission(&persisted()), "VideoTrackSqlite"),
    binds(&[("bitrate", "bitrate"), ("cover_id", "cover_id")]),
    "and the same declaration without the word names both"
  );
}

/// **Every SQL row's RENDERED names are fenced, one assertion per field**, and each carries a
/// sentence naming the field it is about.
///
/// A `const` message is a literal, so nothing it says can be assembled from what collided — which is
/// why the question is asked once per field rather than once over the list. The assertion that fires
/// is then the field that introduced the collision, and its name was written into the sentence at
/// expansion, where it was known.
///
/// MongoDB gets none, and that is structural rather than an omission: its block has no `flatten` at
/// all, its default being the nested subdocument, so no segment of its can reach a holder's
/// namespace to collide in.
#[test]
fn every_sql_rows_rendered_names_are_fenced_one_field_at_a_time() {
  let emitted = tight(emission(&persisted()));
  for (at, column) in ["bitrate", "cover_id"].into_iter().enumerate() {
    assert!(
      emitted.contains(&format!("distinct(__INGRAPH_COLUMNS__,{at}usize)")),
      "the {at}th field is fenced: {emitted}"
    );
    assert!(
      emitted.contains(&format!("wouldrender`{column}`intoacolumn")),
      "and the sentence names `{column}`: {emitted}"
    );
  }
  for row in ["VideoTrackSqlite", "VideoTrackRecord"] {
    assert!(
      emitted.contains(&format!("`{row}`wouldrender")),
      "both SQL rows carry one: {emitted}"
    );
  }
  assert!(
    !emitted.contains("`VideoTrackMongo`wouldrender"),
    "while the document family has no `flatten` to fence: {emitted}"
  );
}

/// **A DOCUMENT NAMES EVERY COLUMN**, including one the SQL rows beside it flattened.
///
/// `flatten` is a SQL family's naming act — dropping a prefix that only the SQL family renders — and
/// a document has none to drop: a held value is a subdocument under this field's own key, which is
/// mongo's composite form. So the mongo row carries a name where it used to carry serde's flattening
/// entry, and the two families' rows differ because the word reached one of them.
#[test]
fn a_document_names_every_column_whatever_the_sql_rows_flattened() {
  assert_eq!(
    field_attrs(struct_named(&emission(&flattened()), "VideoTrackMongo")),
    [
      "#[serde(rename=\"bitrate\",with=\"::ingraph::__private::query::mongo::via\")]",
      "#[serde(rename=\"cover_id\",with=\"::ingraph::__private::query::mongo::via\")]"
    ]
  );
}

/// A comparison rides beside its row whether or not the record has a wire face — it is the storage
/// form of a PREDICATE, and a programmatic query needs one. Only the conversion needs a filter.
#[test]
fn a_comparison_is_emitted_without_a_wire_face() {
  let file = emission(&persisted());
  assert!(names(&file).contains(&"VideoTrackSqliteComparison".to_owned()));
  assert!(
    !trait_impls(&file)
      .iter()
      .any(|(_, path)| tight(path).contains("Filter")),
    "and nothing converts into it, because there is no filter to convert from"
  );
}

/// The comparison's name follows the ROW's, so a renamed row takes its comparison with it.
#[test]
fn the_comparison_follows_the_rows_name() {
  assert_eq!(
    default_comparison_name(&ident("VideoTrackRecord")),
    "VideoTrackRecordComparison"
  );
}

/// The era rule over the wire face: the authorised map and nothing else, and no BACKEND trait impl
/// at all — the wire types are still plain structures and an enum.
///
/// `wired()` is where the allowlist earns its keep: it declares three databases AND a filter, so it
/// is the only fixture that emits the authorised impl at all, and any second framework trait an
/// expansion grew would land here.
#[test]
fn the_wire_face_declares_only_the_authorised_trait_impl() {
  let model = wired();
  let file = emission(&model);
  let framework = unauthorised_framework_impls(&model, &file);
  assert!(framework.is_empty(), "{framework:?}");
  assert!(framework_paths_not_through_a_private_module(&model).is_empty());
}

/// THE FILTER REACHES EACH DATABASE'S COMPARISON, and the ROW is what tells the three apart.
///
/// `ToDatabaseComparison<V, Db>` asks *what does a filter of this kind cross into, for this storage
/// type, on this backend*. A column's filter answers with the column's stored type; the RECORD's
/// filter answers with the ROW — so one filter maps to three comparisons without the three impls
/// colliding, and a caller names which one it means by naming the row rather than by spelling the
/// comparison out.
///
/// `Db` stays free. The map is the same whichever database engine answers it — which is the
/// property that keeps this impl backend-neutral, mongo's row included.
#[test]
fn the_filter_maps_to_each_databases_comparison_through_its_row() {
  let file = emission(&wired());
  let maps: Vec<(String, String)> = trait_impls(&file)
    .into_iter()
    .filter(|(_, path)| tight(path).contains("ToDatabaseComparison"))
    .map(|(item, path)| {
      let comparison = item
        .items
        .iter()
        .find_map(|item| match item {
          syn::ImplItem::Type(item) => Some(tight(&item.ty)),
          _ => None,
        })
        .expect("the map names a comparison");
      (format!("{} for {}", tight(path), impl_of(item)), comparison)
    })
    .collect();
  let db = database_parameter();
  let map = |row: &str, comparison: &str| {
    (
      format!(
        "::ingraph::__private::comparison::ToDatabaseComparison<{row},{db}> for VideoTrackFilter"
      ),
      format!("{comparison}<{db}>"),
    )
  };
  assert_eq!(
    maps,
    [
      map("VideoTrackSqlite", "VideoTrackSqliteComparison"),
      map("VideoTrackRecord", "VideoTrackRecordComparison"),
      map("VideoTrackMongo", "VideoTrackMongoComparison"),
    ],
    "one per declared database, keyed on that database's ROW — and a renamed row takes its \
     comparison with it, which `VideoTrackRecord` is"
  );
}

/// The map's `where` clause is the STRUCT's, verbatim: it asserts nothing the comparison does not
/// already assume, so a declaration whose column has no crossing is reported once, at the type.
#[test]
fn the_map_assumes_exactly_what_the_comparison_assumes() {
  let file = emission(&wired());
  let clause = |item: &syn::ItemImpl| {
    tight(
      item
        .generics
        .where_clause
        .as_ref()
        .expect("the crossings are assumed"),
    )
  };
  let map = trait_impls(&file)
    .into_iter()
    .find(|(item, path)| {
      tight(path).contains("ToDatabaseComparison<VideoTrackSqlite") && impl_of(item) != "()"
    })
    .map(|(item, _)| clause(item))
    .expect("the sqlite map");
  let comparison = struct_named(&file, "VideoTrackSqliteComparison");
  assert_eq!(
    map,
    tight(
      comparison
        .generics
        .where_clause
        .as_ref()
        .expect("the comparison assumes its crossings")
    )
  );
}

/// Every `std` name an expansion writes, and the ONLY form it may take: the tail of an ABSOLUTE
/// path. A bare one resolves in the module the expansion lands in, which the framework does not
/// control.
const STD_NAMES: &[&str] = &[
  "Debug",
  "Clone",
  "Copy",
  "PartialEq",
  "Eq",
  "Hash",
  "Default",
  "Option",
  "Result",
  "Some",
  "None",
  "Ok",
  "Err",
  "From",
  "TryFrom",
  "Into",
  "Box",
  "Vec",
  "String",
];

/// A model whose every field type is an ALIAS, so no `std` name in the emission came from the
/// declaration. Anything the walk finds is therefore the emitter's own.
fn aliased(mut model: RecordModel) -> RecordModel {
  for field in &mut model.fields {
    field.column.ty = ty("MaybeCover");
  }
  for column in model.key.path.iter_mut().chain([&mut model.key.id]) {
    column.ty = ty("Uuid7");
  }
  if let Some(lineage) = model.lineage.as_mut() {
    for column in lineage.path_mut() {
      column.ty = ty("Uuid7");
    }
  }
  for database in model
    .persist
    .iter_mut()
    .flat_map(|persist| &mut persist.backends)
  {
    for column in &mut storage_of(database).columns {
      column.domain = ty("MaybeCover");
      column.stored = column.stored.as_ref().map(|_| ty("StoredCover"));
    }
  }
  for backend in model
    .graphql
    .iter_mut()
    .flat_map(|graphql| &mut graphql.backends)
  {
    let GraphqlBackend::AsyncGraphql(backend) = backend;
    for field in &mut backend.fields {
      field.domain = ty("MaybeCover");
    }
  }
  model
}

/// Every `std` name in an emission sits at the end of an ABSOLUTE path.
///
/// This is the guard the shadowing fixture CANNOT be: a derive macro resolves in the MACRO
/// namespace, and a `trait Debug {}` declaration lives in the type namespace — so declaring one
/// does not shadow `#[derive(Debug)]`, and a fixture built that way passes while every derive in
/// the emission is bare. Measured: seven derive mutations survived that fixture. This walks the
/// tokens instead, so it sees both namespaces and needs nobody to remember which is which.
///
/// The fixture is still the other half — it proves a real compile in a hostile module, where this
/// proves a shape.
#[test]
fn every_std_name_the_emission_writes_is_absolutely_pathed() {
  for model in [aliased(wired()), aliased(whole_row())] {
    let bare = bare_std_names(&model);
    assert!(
      bare.is_empty(),
      "`{}` writes a bare `std` name — it would resolve in the module the expansion lands in: \
       {bare:?}",
      model.record
    );
  }
}

/// Every place the emission names a `std` item WITHOUT `::` in front of it.
fn bare_std_names(model: &RecordModel) -> Vec<String> {
  fn flatten(stream: proc_macro2::TokenStream, into: &mut Vec<proc_macro2::TokenTree>) {
    for tree in stream {
      match tree {
        proc_macro2::TokenTree::Group(group) => {
          // A `#[derive(…)]` is a Group, and its contents are exactly what has to be checked.
          flatten(group.stream(), into);
        }
        other => into.push(other),
      }
    }
  }
  let mut tokens = Vec::new();
  flatten(model.emit(), &mut tokens);

  let colon = |at: usize| {
    at < tokens.len()
      && matches!(&tokens[at], proc_macro2::TokenTree::Punct(p) if p.as_char() == ':')
  };
  (0..tokens.len())
    .filter(|at| {
      matches!(&tokens[*at], proc_macro2::TokenTree::Ident(id)
        if STD_NAMES.contains(&id.to_string().as_str()))
    })
    // Absolute means the two tokens before it are `::` — `::core::fmt::Debug` ends that way, and
    // so does the `Debug` in `::core::fmt::Debug`. A bare `Debug` has no `::` before it at all.
    .filter(|at| !(*at >= 2 && colon(at - 1) && colon(at - 2)))
    .map(|at| {
      tokens[at.saturating_sub(4)..(at + 1).min(tokens.len())]
        .iter()
        .map(ToString::to_string)
        .collect::<String>()
    })
    .collect()
}

/// The filter's BUILDERS speak filters too, not values — otherwise the operator vocabulary would be
/// reachable only by constructing the struct's private fields, which nothing outside can do.
#[test]
fn the_filter_builders_take_and_return_filters() {
  let file = emission(&wired());
  let filter = "VideoTrackFilter";
  let parameters: Vec<String> = method_of(&file, filter, "with_checksum")
    .sig
    .inputs
    .iter()
    .filter_map(|input| match input {
      syn::FnArg::Typed(typed) => Some(tight(&typed.ty)),
      syn::FnArg::Receiver(_) => None,
    })
    .collect();
  assert_eq!(
    parameters,
    [
      "<<u64as::ingraph::__private::marker::DefaultMarker>::Markeras::ingraph::__private::graphql::ToGraphqlFilter>::ColumnFilter"
    ],
    "`with_*` takes the FILTER — its type changed and its role did not, which is why the verb did \
     not change either"
  );
  assert_eq!(
    returns(method_of(&file, filter, "checksum_ref")),
    "::core::option::Option<&<<u64as::ingraph::__private::marker::DefaultMarker>::Markeras::ingraph::__private::graphql::ToGraphqlFilter>::ColumnFilter>",
    "and the accessor hands back the filter, not a value"
  );
}

/// An order-by variant resolves to a NAME, not to a string — the type the ordering seam takes,
/// which quotes what it is handed.
///
/// A `&'static str` compiled just as well and was the wrong answer: the same builder's expression
/// slot is spelled `&str` and legitimately takes `*` and `count(*)`, so a resolver answering there
/// would have rendered an identifier nothing quoted. The type is the only thing that tells the two
/// positions apart, which is why it is pinned here rather than left to whoever wires the ordering.
///
/// `const` travels with it: the arms are literals viewed through a constant constructor, so a
/// consumer can still resolve a variant in a constant.
///
/// **The answer is FALLIBLE, and that is the declaration-truth vocabulary's own half.** The
/// order-by publishes every declared column's word wherever the service runs, so a variant this
/// deployment's database has no column for is a state the type admits; the resolver refuses it by
/// name rather than handing back a name that would render into `no such column`. A record that
/// narrows nothing — this one — writes `Ok` on every arm and pays nothing for it.
#[test]
fn an_order_by_variant_resolves_to_a_field_name_per_database() {
  let file = emission(&wired());
  let order_by = "VideoTrackOrderBy";
  for database in ["sqlite", "postgres", "mongo"] {
    let resolver = method_of(&file, order_by, &format!("{database}_column"));
    assert_eq!(
      returns(resolver),
      "::core::result::Result<&'static::ingraph::__private::field::FieldName,\
       ::ingraph::__private::query::ColumnNotStored>",
      "`{database}_column` answers in the ordering seam's own type, or refuses by name"
    );
    assert!(is_const(resolver), "`{database}_column` is still const");
  }
  assert_eq!(
    tight(&method_of(&file, order_by, "sqlite_column").block),
    "{matchself{Self::Checksum(_)=>::core::result::Result::Ok(\
     ::ingraph::__private::field::FieldName::new(\"bitrate\")),\
     Self::CoverId(_)=>::core::result::Result::Ok(\
     ::ingraph::__private::field::FieldName::new(\"cover_id\")),}}",
    "every arm BUILDS the name — a bare literal would be the `&str` this stopped returning. The two \
     halves of the arm are the two layers: the VARIANT is the record field (`Checksum`) and the \
     name it resolves to is what sqlite renders (`bitrate`)"
  );
  assert_eq!(
    tight(&method_of(&file, order_by, "postgres_column").block),
    "{matchself{Self::Checksum(_)=>::core::result::Result::Ok(\
     ::ingraph::__private::field::FieldName::new(\"bit_rate_v2\")),\
     Self::CoverId(_)=>::core::result::Result::Ok(\
     ::ingraph::__private::field::FieldName::new(\"cover_id\")),}}",
    "and it is the PER-DATABASE name that is wrapped, which is what makes one resolver per \
     database worth emitting — the SAME variant, two rendered names, which is the whole of what a \
     storage rename is allowed to move"
  );
}

/// **A NARROWED COLUMN'S RESOLVER REFUSES BY NAME**, naming the column and the dialect — the
/// runtime half of the declaration-truth schema.
///
/// The variant is still emitted, because the vocabulary is the DECLARATION's: the same service
/// deployed against two databases publishes one order-by. What differs is the ANSWER, and this is
/// where the difference is spoken. The identity is the RECORD FIELD's own name — what the schema
/// published and what a client wrote — rather than a column name of the databases that do store it.
#[test]
fn a_narrowed_columns_resolver_refuses_by_column_and_dialect() {
  let mut model = wired();
  let persist = model.persist.as_mut().expect("stored");
  let taken = storage_of(&mut persist.backends[0]).columns.remove(0);
  assert_eq!(taken.source.to_string(), "checksum");

  let file = emission(&model);
  let order_by = "VideoTrackOrderBy";
  assert_eq!(
    tight(&method_of(&file, order_by, "sqlite_column").block),
    "{matchself{Self::Checksum(_)=>::core::result::Result::Err(\
     ::ingraph::__private::query::ColumnNotStored::new(\
     ::ingraph::__private::cursor::TermName::new(\"checksum\"),\"sqlite\")),\
     Self::CoverId(_)=>::core::result::Result::Ok(\
     ::ingraph::__private::field::FieldName::new(\"cover_id\")),}}",
    "the narrowed column's arm refuses and its neighbour is untouched"
  );
  assert_eq!(
    tight(&method_of(&file, order_by, "postgres_column").block),
    "{matchself{Self::Checksum(_)=>::core::result::Result::Ok(\
     ::ingraph::__private::field::FieldName::new(\"bit_rate_v2\")),\
     Self::CoverId(_)=>::core::result::Result::Ok(\
     ::ingraph::__private::field::FieldName::new(\"cover_id\")),}}",
    "and the database that KEPT the column answers with it, which is what makes the refusal the \
     deployment's rather than the declaration's"
  );
}

/// **The wire's identity is the RECORD FIELD's name, and it is the one no database supplies.**
/// `ToSubjectPath` is what the order decode compares terms by, so what it answers with decides
/// which orders a client may write at all.
///
/// One column of `wired` carries THREE names, which is what makes this measurable rather than
/// arguable: the record field is `checksum`, sqlite stores it as `bitrate` — which is where the
/// VARIANT's own spelling comes from — and postgres renames it again to `bit_rate_v2`. Only the
/// first is the same at every deployment. An identity taking a rendered one would make which orders
/// are legal depend on the dialect a deployment stores, and where two columns' renames crossed it
/// would call two subjects one and refuse an order naming both. This is the choice `identity`
/// states one method up and the one `complete()`'s key dedupe makes by matching the VARIANT; the
/// assertion below holds the two to it as ONE expression rather than two that agree today.
///
/// A PATH of one segment, because that is what today's terms are: every emitted variant is a column
/// of THIS record. `cover.title` is the shape the type is built for and no declaration reaches yet,
/// and the segment list is what keeps that day from being a change to the uniqueness rule.
///
/// The GATE is the second claim, and `wired` is the fixture that proves it: this model's id is
/// stored nowhere, so it gets no `identity`, no term and no `complete` — and it still gets a wire
/// order to decode. The page vocabulary is the SQL clause machine's; a decode is every
/// order-capable record's.
///
/// `match *self` is pinned in the body below and is not a style. The trait takes `&self`, a
/// reference is always considered INHABITED, and `match self {}` on a record whose stored columns
/// are every one of them collections or flattened is `E0004` — which is what `ingraph-derive`'s
/// `SheetOrderBy` fixture caught, by refusing to compile. No token walk could have seen it.
#[test]
fn an_order_by_names_its_subject_under_the_name_no_rename_moves() {
  let file = emission(&wired());
  assert!(
    !methods_of(&file, "VideoTrackOrderBy").contains(&"identity".to_owned()),
    "the fixture stores no id, so the PAGE's identity is absent — and the wire's is not"
  );

  let subject = wrote(&file, "ToSubjectPath").expect("the wire's identity is emitted");
  assert_eq!(
    impl_of(subject),
    "VideoTrackOrderBy",
    "on the ORDER-BY, which is the type a client's list decodes into"
  );

  let path = "::ingraph::__private::graphql::SubjectPath";
  let name = "::ingraph::__private::cursor::TermName";
  let arm = |variant: &str, field: &str| {
    format!(
      "Self::{variant}(_)=>{{const__INGRAPH_SUBJECT:{path}={path}::new(&[{name}::new(\
       \"{field}\")]);__INGRAPH_SUBJECT}}"
    )
  };
  let written = methods(subject);
  let [method] = written.as_slice() else {
    panic!("the trait has one method, not {}", written.len());
  };
  assert_eq!(method.sig.ident, "subject_path");
  assert_eq!(
    tight(&method.block),
    format!(
      "{{match*self{{{}{}}}}}",
      arm("Checksum", "checksum"),
      arm("CoverId", "cover_id")
    ),
    "the RECORD FIELD's name in every arm — and the VARIANT is now that same name, so the arm \
     reads `Self::Checksum(_) => …new(\"checksum\")` rather than pairing a storage-derived variant \
     with a domain identity"
  );

  // A `const` ITEM per arm, and not a bare `&[…]` or an inline `const { … }` block: neither makes
  // the borrow `'static`, and both are `E0716`. The emitted spelling is the one that compiles,
  // which is why it is pinned rather than left to read as a style.
  assert!(
    tight(&method.block).contains("const__INGRAPH_SUBJECT"),
    "the path is a constant, so no subject is built per request"
  );

  // ONE identity, read twice. `ordered` stores its key, so it gets the PAGE's `identity` beside the
  // wire's subject — and the names in the two bodies are the same names.
  let paged = emission(&ordered());
  let identity = tight(&method_of(&paged, "VideoTrackOrderBy", "identity").block);
  let subject = wrote(&paged, "ToSubjectPath").expect("a paged model has both");
  let subject = tight(&methods(subject)[0].block);
  for field in ["media_id", "video_id", "id", "checksum", "cover_id"] {
    let quoted = format!("{name}::new(\"{field}\")");
    assert!(identity.contains(&quoted), "`identity` names {field}");
    assert!(subject.contains(&quoted), "`subject_path` names {field}");
  }
  assert!(
    !subject.contains("bit_rate_v2") && !subject.contains("\"bitrate\"") && !subject.contains("pk"),
    "and neither database's rendering reaches the subject: {subject}"
  );

  // A record with NO wire face gets one too: an order-by is emitted wherever a column is stored,
  // and the decode is the same decode.
  let plain = emission(&whole_row());
  assert_eq!(
    wrote(&plain, "ToSubjectPath").map(impl_of),
    Some("MediaOrderBy".to_owned()),
    "the `graphql(…)` block names the type; it does not decide whether the type has an identity"
  );
}

/// ONE ordering term is one value: a variant carries the direction it runs in, so a column and its
/// direction cannot be paired wrongly — there is no index to line up and no second list to be a
/// different length.
///
/// The SHAPE is `OneofObject`'s, and it is the shape rather than a preference. That derive takes an
/// ENUM OF SINGLE-VALUE TUPLE VARIANTS and refuses everything else — a struct with one
/// `Option<OrderDirection>` field per column, which is the obvious reading of the `@oneOf` SDL this
/// renders as, is `error: InputObject can only be applied to an enum.` — so the variant's arity and
/// its payload are what make the ruled wire face reachable when the derive round arrives. The
/// derive itself is not emitted, and `ingraph`'s `graphql::tests::wire` is where the schema-level
/// "exactly one field" that shape buys is measured.
///
/// The MEMBERSHIP is the emitter's standing doctrine, not a rule of its own: a column is orderable
/// because it is stored. `chapters` and the key's `id` are record fields here and neither is
/// persisted, so neither is spellable in an order — where `cover_id` is persisted and unexposed and
/// is.
#[test]
fn an_order_by_term_carries_a_direction_for_each_stored_column_and_no_other() {
  let file = emission(&wired());
  let order_by = enum_named(&file, "VideoTrackOrderBy");
  let direction = "::ingraph::__private::graphql::OrderDirection";

  let variants: Vec<String> = order_by
    .variants
    .iter()
    .map(|variant| format!("{}{}", variant.ident, tight(&variant.fields)))
    .collect();
  assert_eq!(
    variants,
    [
      format!("Checksum({direction})"),
      format!("CoverId({direction})")
    ],
    "one single-value tuple variant per STORED column, each carrying the direction — and nothing \
     for a field the declaration never persisted"
  );

  let accessor = method_of(&file, "VideoTrackOrderBy", "direction");
  assert_eq!(returns(accessor), direction);
  assert!(
    is_const(accessor),
    "`direction` is const beside the resolvers, so a whole term resolves in a constant"
  );
  assert_eq!(
    tight(&accessor.block),
    "{matchself{Self::Checksum(direction)|Self::CoverId(direction)=>direction,}}",
    "ONE method rather than one per database: a direction is not a storage fact, so nothing about \
     it is renamed by `<db>(rename)`"
  );
}

/// **Every written order ends with the id**: what a client requested, then one column ascending.
///
/// ONE column is what a total order needs, and the id is the one that gives it: a framework-emitted
/// table's id is UNIQUE, so no two rows tie on it. `ordered` prepends `media_id`, `video_id`, `id`
/// to a row that already stored `bitrate` and `cover_id` — so the LINEAGE columns are stored, and
/// orderable, and a client may still name one; what they no longer are is a tail the walk appends.
///
/// The NAME is this database's. Postgres renames the id to `pk`, and a tail that read the key type's
/// spelling instead would order by a column postgres has not got.
#[test]
fn every_written_order_ends_with_the_id() {
  let file = emission(&ordered());
  let field_name = "::ingraph::__private::field::FieldName";
  let sqlite = tight(&method_of(&file, "VideoTrackOrderBy", "sqlite_order_by").block);

  // The requested terms, in the order the CALL carries them — one call per term, each asking the
  // same value for both halves so a column and its direction cannot come from two entries.
  assert!(
    sqlite.contains(
      "letmut__ingraph_builder=__ingraph_builder.order_by(\
       __ingraph_first.sqlite_column()?,__ingraph_first.direction().is_descending(),);\
       for__ingraph_termin__ingraph_rest{__ingraph_builder=__ingraph_builder.order_by(\
       __ingraph_term.sqlite_column()?,__ingraph_term.direction().is_descending(),);}"
    ),
    "{sqlite}"
  );

  // Then the id, ASCENDING whatever the terms did — the tail is the cursor's spine rather than a
  // preference — guarded, which is the dedupe.
  assert!(
    sqlite.contains(&format!(
      "__ingraph_builder=__ingraph_builder.order_by({field_name}::new(\"id\"),false);"
    )),
    "the id ends the order ascending: {sqlite}"
  );
  // And the lineage columns are NOT in it. They are stored, and a term may name either, but the
  // walk appends neither — which is the whole of the collapse at this site.
  for column in ["media_id", "video_id"] {
    assert!(
      !sqlite.contains(&format!(
        "__ingraph_builder=__ingraph_builder.order_by({field_name}::new(\"{column}\"),false);"
      )),
      "`{column}` is a lineage column and no longer ends an order: {sqlite}"
    );
  }

  // The same walk at the other database, differing in exactly the two things a database decides:
  // which resolver answers, and what it calls the id.
  let postgres = tight(&method_of(&file, "VideoTrackOrderBy", "postgres_order_by").block);
  assert!(
    postgres.contains("__ingraph_first.postgres_column()?"),
    "{postgres}"
  );
  assert!(
    postgres.contains(&format!("{field_name}::new(\"pk\")"))
      && !postgres.contains(&format!("{field_name}::new(\"id\")")),
    "the tail takes THIS database's name for the id: {postgres}"
  );
}

/// **Ordering by nothing has no spelling.** The first term is a parameter of its own, so a caller
/// holding no term cannot reach this at all — its statement stays where it was, un-ordered, which is
/// the answer SQL already has for a query that wrote no order.
///
/// The SIGNATURE is the whole of the enforcement, which is why this reads the parameter types rather
/// than the body. A run-time refusal would be a branch to write, a message to phrase and an error
/// every caller has to handle; a slice that may be empty would instead need SOMETHING rendered for
/// the empty case, and whatever that was would be an order no client asked for.
///
/// Both SQL databases, because a signature is emitted per backend and one of them could drift.
#[test]
fn an_order_over_no_terms_has_no_spelling() {
  let file = emission(&ordered());
  let builder = format!(
    "::ingraph::__private::comparison::sql::QueryBuilder<{},{},{}>",
    crate::emit::parameter("CLAUSE"),
    database_parameter(),
    crate::emit::parameter("HOLDER"),
  );
  for database in ["sqlite", "postgres"] {
    let lowering = method_of(&file, "VideoTrackOrderBy", &format!("{database}_order_by"));
    let parameters: Vec<String> = lowering
      .sig
      .inputs
      .iter()
      .map(|input| match input {
        syn::FnArg::Typed(typed) => tight(&typed.ty),
        syn::FnArg::Receiver(_) => panic!("an ordering is over terms, so it takes no self"),
      })
      .collect();
    assert_eq!(
      parameters,
      ["&Self", "&[Self]", builder.as_str()],
      "one term, then the rest, then the statement being ordered"
    );
  }
}

/// **A term naming the id moves that column rather than repeating it**, and the guard is a VARIANT
/// test rather than a name comparison: one variant is one column at every database, where the name
/// is what `<db>(rename)` moves.
///
/// Dedupe rather than the redundant clause, and both halves were measured rather than argued.
/// It changes no result set — within a tie group of an earlier term the repeated column is constant,
/// so a later term over it reorders nothing — and it is not free to leave in: SQLite folds no
/// duplicate, widening the sorter key from `k(2,-B,B)` to `k(3,-B,B,B)` with an extra `Column`
/// opcode per row. TOTALITY is what had to survive it, and does: the id leaves the tail only when
/// the order already holds it, so it appears exactly once either way and a permutation of a unique
/// tuple is still unique.
#[test]
fn a_term_naming_the_id_is_not_appended_twice() {
  let file = emission(&ordered());
  let body = tight(&method_of(&file, "VideoTrackOrderBy", "sqlite_order_by").block);

  // Both halves of the split are searched: the first term is one value rather than a slice, so a
  // guard that asked only the rest would repeat the column the client's leading term already named.
  assert!(
    body.contains(
      "if!::core::iter::once(__ingraph_first).chain(__ingraph_rest).any(|__ingraph_term|\
       ::core::matches!(__ingraph_term,Self::Id(_)))"
    ),
    "the `Id` tail is guarded by a variant test over every term: {body}"
  );
  // A stored column that is not the id has no guard, because it is not in the tail to trim — the
  // two LINEAGE columns among them, which is what the collapse moved out of the tail.
  for variant in ["MediaId", "VideoId", "Bitrate", "CoverId"] {
    assert!(
      !body.contains(&format!("Self::{variant}(_)")),
      "`{variant}` does not end the order and has nothing to dedupe: {body}"
    );
  }
}

/// A database that does not store the ID gets no ordering lowering, and the absence is the answer
/// rather than an omission.
///
/// The tail is what makes an order total, and an id the row has not got is nothing to end on:
/// rendering a column the table has not got is a query error one whole lifecycle later, and an order
/// without a unique tail pages with exactly the skipped and repeated rows the law exists to prevent.
/// `wired` is that declaration: its key is three record fields no `persist(…)` block names.
///
/// It cannot fire on the MANDATED path — a framework-emitted table stores the column its rows are
/// addressed by — so what is pinned here is the CAPABILITY guard, over a hand-built model.
///
/// Both directions, because an emitter that emitted nothing at all would pass one of them.
#[test]
fn a_database_that_does_not_store_the_id_cannot_be_ordered() {
  assert!(
    wired().id_column_stored().is_none(),
    "`wired` persists none of its key columns, the id included"
  );
  assert_eq!(
    ordered().id_column_stored(),
    Some(2),
    "`ordered` prepends `media_id`, `video_id`, `id`, so the id is the row's third column — and the \
     two lineage columns before it are stored without being addressed by"
  );

  let names = methods_of(&emission(&wired()), "VideoTrackOrderBy");
  assert_eq!(
    names,
    [
      "sqlite_column",
      "postgres_column",
      "mongo_column",
      "direction"
    ],
    "the resolvers and the direction survive; the walk that would need a tail does not, and \
     neither does the page vocabulary that spends the same tail"
  );
  assert_eq!(
    methods_of(&emission(&ordered()), "VideoTrackOrderBy"),
    [
      "sqlite_column",
      "postgres_column",
      "mongo_column",
      "direction",
      "identity",
      "sqlite_term",
      "postgres_term",
      "complete",
      "sqlite_order_by",
      "postgres_order_by"
    ],
    "one lowering per SQL database — the clause machine it walks is the SQL family's, and how a \
     mongo `find` takes a sort is unsettled"
  );
}

/// A MONGO-ONLY declaration with a wire face reaches nothing of the SQL family, ordering included.
///
/// [`the_mongo_document_names_nothing_of_the_sql_family`] makes the same claim over a record with no
/// wire face, so it cannot see this one: the ordering lowering is emitted from the order-by, which
/// only a `graphql(…)` record has, and it names the clause machine and sqlx's own builder. Emitting
/// one per DECLARED database rather than per SQL one would put both in a mongo declarer's expansion
/// — a SQL dependency for a database it does not use, rendering into an `ORDER BY` a `find` has not
/// got.
#[test]
fn a_mongo_only_record_with_a_wire_face_still_names_nothing_of_the_sql_family() {
  let mut model = ordered();
  model
    .persist
    .as_mut()
    .expect("`ordered` stores rows")
    .backends
    .retain(|database| !database.kind().is_sql());

  let file = emission(&model);
  assert_eq!(
    methods_of(&file, "VideoTrackOrderBy"),
    ["mongo_column", "direction"],
    "the resolver and the direction are all a mongo order-by has"
  );
  let rendered = tight(&file);
  assert!(
    !rendered.contains("__private::sqlx"),
    "a mongo-only expansion reaches sqlx: {rendered}"
  );
}

/// The MEASUREMENT the host family rests on: which databases ship a backend.
///
/// `store/progress/` holds `sqlite/` and `postgres/`. The constructor is the authority — a front end
/// asks it rather than testing a list — and this is what makes the measurement a visible edit:
/// admitting a third database means changing this test beside the arm.
#[test]
fn only_the_databases_with_a_backend_can_host_a_framework_table() {
  use crate::model::{DatabaseKind, ProgressHost};

  for kind in DatabaseKind::ALL {
    let hosts = matches!(kind, DatabaseKind::Sqlite | DatabaseKind::Postgres);
    assert_eq!(
      ProgressHost::of(kind).map(|host| host.kind()),
      hosts.then_some(kind),
      "`store/progress/` ships a ledger for sqlite and postgres alone: {}",
      kind.as_str()
    );
    // The predicate is `of`'s question without its answer, so the two cannot disagree — asserted
    // rather than assumed, because it is what a caller reads the fact off.
    assert_eq!(ProgressHost::hosts(kind), ProgressHost::of(kind).is_some());
  }
}

/// The query FACE is emitted per SQL database and nowhere else, and a MONGO database gets none of
/// it — not the entry points, not the read-transaction sugar, not the cursor value.
///
/// # The snapshot is the sharpest half of that
///
/// A read transaction whose statements see one state of the database is something all three SQL
/// dialects can open and a standalone `mongod` cannot: a multi-statement snapshot there needs a
/// session and a replica set. So the method does not EXIST on a face that could not keep the
/// promise, which is the per-dialect honesty the duration kinds already set the precedent for —
/// rather than existing and doing nothing.
///
/// Both directions, because an emitter that emitted nothing at all would pass one of them.
#[test]
fn the_query_face_is_emitted_per_sql_database_and_never_for_mongo() {
  let mut model = whole_row();
  let record = model.record.clone();
  let columns = model
    .persist
    .as_ref()
    .expect("`whole_row` stores rows")
    .backends[0]
    .columns()
    .to_vec();
  model
    .persist
    .as_mut()
    .expect("`whole_row` stores rows")
    .backends
    .push(stored(&record, DatabaseKind::Mongo, columns));

  let named = methods_of(&emission(&model), "Media");
  for wanted in ["find_sqlite", "find_sqlite_snapshot", "get_sqlite"] {
    assert!(
      named.iter().any(|method| method == wanted),
      "a SQL database gets `{wanted}`: {named:?}"
    );
  }
  for refused in ["find_mongo", "find_mongo_snapshot", "get_mongo"] {
    assert!(
      !named.iter().any(|method| method == refused),
      "and a mongo database gets no `{refused}`: {named:?}"
    );
  }
  assert!(
    !declared_types(&emission(&model))
      .iter()
      .any(|declared| declared == "MediaMongoCursor"),
    "nor a cursor value, which is a page's and a page is the SQL family's"
  );
}

/// A database whose row cannot be turned back into the record gets NO query face, because a query
/// returns records.
///
/// `ordered` is that declaration: its row carries some of the record's fields and declares no
/// container conversion, so the emitted conversions carry no way back — and a `find` that could not
/// hand a record over would have nothing to return. The absence is the answer, and a call site
/// naming one fails to resolve.
#[test]
fn a_row_that_cannot_become_a_record_gets_no_query_face() {
  let model = ordered();
  assert!(
    model.queryable().is_empty(),
    "a partial row with no declared conversion cannot raise a record"
  );
  let file = emission(&model);
  let named = methods_of(&file, "VideoTrack");
  assert!(
    !named
      .iter()
      .any(|method| method.starts_with("find_") || method.starts_with("get_")),
    "so the record gets no entry point: {named:?}"
  );
  assert!(
    !declared_types(&file)
      .iter()
      .any(|declared| declared.ends_with("Cursor")),
    "and no cursor value either"
  );
}

/// A declaration that REFERS: two of its columns address one record and a third addresses another,
/// so the pairing's grouping and its arity are both under test — and it declares a reverse position
/// of its own, so both directions are emitted from one model.
fn referring() -> RecordModel {
  let mut model = model("VideoTrack", &["media_id"], "id");
  model.fields = [
    ("media_id", ty("MediaId"), "Media", Through::Value),
    ("video_id", ty("VideoId"), "Video", Through::Value),
    ("replaces", ty("VideoId"), "Video", Through::Value),
    ("scenes", generic("Vec", "SceneId"), "Scene", Through::Held),
  ]
  .into_iter()
  .map(|(name, ty, target, through)| Field {
    column: column_of(name, ty),
    identity: false,
    marker: None,
    sortable: false,
    indexed: false,
    skip: None,
    docs: Vec::new(),
    condition: Condition::always(),
    build: Build::default(),
    reference: Some(Reference {
      target: syn::parse_str(target).expect("a type path"),
      through,
    }),
  })
  .collect();
  model.derived = vec![
    Derived {
      name: ident("clips"),
      source: syn::parse_str("Clip").expect("a type path"),
      field: None,
    },
    Derived {
      name: ident("takes"),
      source: syn::parse_str("Take").expect("a type path"),
      field: Some(syn::parse_quote!("track_id")),
    },
  ];
  model
}

/// Every `ref` field states the id equation, and a field the declaration put in a CONTAINER states
/// it about what the container HOLDS — through the projection layer, never through the tokens.
#[test]
fn a_ref_states_the_id_equation_through_the_declared_projection() {
  let emitted = tight(referring().relations());
  assert!(
    emitted.contains("refers_to::<MediaId,Media>"),
    "a bare field's own type IS the referring value: {emitted}"
  );
  assert!(
    emitted.contains(
      "refers_to::<<Vec<SceneId>as::ingraph::__private::state::State<::ingraph::__private::state::\
       Extracted<::ingraph::__private::state::Inner>>>::Output,Scene>"
    ),
    "and a collection's is what the TYPE says it holds: {emitted}"
  );
}

/// ONE impl per (source, target) PAIR — two fields naming one record are one relation with two ways
/// through it, and two impls of one pair would be `E0119`.
#[test]
fn the_pairing_is_one_impl_per_target() {
  let file = emission(&referring());
  let pairings: Vec<String> = trait_impls(&file)
    .into_iter()
    .filter(|(_, path)| tight(path).contains("transform::Related"))
    .map(|(_, path)| tight(path))
    .collect();
  assert_eq!(
    pairings.len(),
    3,
    "one per target, not one per field: {pairings:?}"
  );
  let fields = |target: &str| {
    trait_impls(&file)
      .into_iter()
      .find(|(_, path)| tight(path).ends_with(&format!("Related<{target}>")))
      .map(|(item, _)| {
        item
          .items
          .iter()
          .find_map(|item| match item {
            syn::ImplItem::Type(item) => Some(tight(&item.ty)),
            _ => None,
          })
          .expect("the pairing binds `Fields`")
      })
      .expect("a pairing at that target")
  };
  assert_eq!(
    fields("Video"),
    "(VideoTrackVideoIdRef,VideoTrackReplacesRef,)",
    "two fields at one target are two members of one list"
  );
  assert_eq!(fields("Media"), "(VideoTrackMediaIdRef,)");
}

/// The evidence names the referring columns as the DECLARATION writes them, in `Fields`' order.
#[test]
fn the_pairing_carries_the_referring_columns() {
  let emitted = tight(referring().relations());
  assert!(
    emitted.contains(
      "constCOLUMNS:&'static[&'static::ingraph::__private::field::FieldName]=&[::ingraph::\
       __private::field::FieldName::new(\"video_id\"),::ingraph::__private::field::FieldName::new(\
       \"replaces\")]"
    ),
    "{emitted}"
  );
}

/// A MEMBERSHIP emits its EVIDENCE and nothing else — one impl per interface the declaration
/// named, carrying nothing, inside the const like the rest of the relation half.
///
/// The evidence is what an interface's own expansion asserts, and it exists because the two derives
/// cannot see each other: an interface claiming a membership its member never agreed to would be a
/// promise made on somebody else's behalf.
#[test]
fn a_membership_emits_the_evidence_an_interface_asserts() {
  let mut model = referring();
  model.implements = vec![
    syn::parse_str("Media").expect("a type path"),
    syn::parse_str("media::Playable").expect("a type path"),
  ];
  let emitted = tight(model.relations());

  assert!(
    emitted.contains("impl::ingraph::__private::transform::Implements<Media>forVideoTrack{}"),
    "{emitted}"
  );
  assert!(
    emitted
      .contains("impl::ingraph::__private::transform::Implements<media::Playable>forVideoTrack{}"),
    "an alias in the path is transparent: nothing here resolves it: {emitted}"
  );
  assert!(
    !declared_types(&emission(&model))
      .iter()
      .any(|declared| declared == "Media"),
    "a membership declares no type"
  );
}

/// A membership at an interface the declaration NEVER named is refused by the era rule, exactly as a
/// fifteenth framework trait would be — the allowlist reads the model rather than the spelling.
#[test]
fn a_membership_the_declaration_never_named_is_unauthorised() {
  let mut model = referring();
  model.implements = vec![syn::parse_str("Media").expect("a type path")];
  let file = emission(&model);
  assert_eq!(
    unauthorised_framework_impls(&model, &file),
    Vec::<String>::new()
  );

  // The same emission, read against a model that declares no membership at all.
  let mut undeclared = referring();
  undeclared.implements = Vec::new();
  assert_eq!(
    unauthorised_framework_impls(&undeclared, &file),
    ["::ingraph::__private::transform::Implements<Media> for VideoTrack"]
  );
}

/// A reverse position emits an AUDIT and no type: the shorthand's is a bound, the full form's a
/// constant, and neither declares anything the declaring scope can see.
#[test]
fn a_reverse_position_emits_an_audit_and_no_type() {
  let model = referring();
  let emitted = tight(model.relations());
  assert!(
    emitted.contains("one_field_points_back::<Clip,VideoTrack>"),
    "the shorthand asks the evidence to pick the one field: {emitted}"
  );
  assert!(
    emitted.contains(
      "refers_through(<Takeas::ingraph::__private::transform::Related<VideoTrack>>\
                      ::COLUMNS,\"track_id\")"
    ),
    "and the full form names it: {emitted}"
  );
  assert!(
    !declared_types(&emission(&model))
      .iter()
      .any(|declared| declared == "clips" || declared == "takes"),
    "no storage, no field, no lie"
  );
}

/// The artifacts live INSIDE the record's anonymous const, so a relation costs the declaring scope
/// no name.
#[test]
fn the_reference_artifacts_stay_inside_the_const() {
  let file = emission(&referring());
  assert!(
    !names(&file).iter().any(|name| name.ends_with("Ref")),
    "nothing at top level: {:?}",
    names(&file)
  );
  let inside: Vec<String> = declared_types(&file)
    .into_iter()
    .filter(|declared| declared.ends_with("Ref"))
    .collect();
  assert_eq!(
    inside,
    [
      "VideoTrackMediaIdRef",
      "VideoTrackVideoIdRef",
      "VideoTrackReplacesRef",
      "VideoTrackScenesRef",
    ],
    "one per referring field, named after it"
  );
}

/// An artifact seals its own CONSTRUCTION: `struct …Ref(())`, whose private field refuses a value
/// in the shape rather than in the placement.
///
/// This assertion is the whole tooth. A bare unit struct satisfies every other rule written here —
/// the names, the placement, the visibility, the `Fields` binding — and the const's scope hides the
/// constructor whether or not the shape does, so nothing else reds when the seal comes off.
#[test]
fn a_reference_artifact_seals_its_own_construction() {
  let file = emission(&referring());
  let artifacts: Vec<&syn::ItemStruct> = all_items(&file)
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Struct(item) if item.ident.to_string().ends_with("Ref") => Some(item),
      _ => None,
    })
    .collect();
  assert!(
    !artifacts.is_empty(),
    "the walk found no artifact to seal, so the rest of this would pass vacuously"
  );
  for item in artifacts {
    let syn::Fields::Unnamed(sealed) = &item.fields else {
      panic!("`{}` carries no sealing field: {}", item.ident, tight(item));
    };
    assert_eq!(
      sealed.unnamed.len(),
      1,
      "`{}` is sealed by ONE field: {}",
      item.ident,
      tight(item)
    );
    let field = sealed.unnamed.first().expect("the sealing field");
    assert_eq!(
      tight(&field.ty),
      "()",
      "`{}` seals with the unit",
      item.ident
    );
    assert!(
      matches!(field.vis, syn::Visibility::Inherited),
      "`{}`'s field is PRIVATE — a visible one would mint the value it exists to refuse",
      item.ident
    );
  }
}

/// A relation's impls are the emission's, and the allowlist knows them — checked against the MODEL,
/// so a pairing at a target this declaration never named would be refused like any stray trait.
#[test]
fn a_relation_declares_only_authorised_impls() {
  let model = referring();
  let file = emission(&model);
  assert!(
    unauthorised_framework_impls(&model, &file).is_empty(),
    "{:?}",
    unauthorised_framework_impls(&model, &file)
  );
}

/// **TWO INPUT FACES REACH THE WIRE, and `@oneOf` is on the order-by ALONE.**
///
/// The order-by is the `@oneOf` input object the argument `orderBy: [<T>OrderBy!]` is a list of, and
/// it is the one emitted face whose every field type is the FRAMEWORK's — `OrderDirection` — so it
/// can be emitted for every record without asking the declaration for a wire form it may not have.
///
/// The KEY ARGUMENT joined it, and it demands nothing more: every field crosses through
/// `ToGraphqlInput`, whose row a key column's type already has wherever a `get(id:)` can spell one.
/// It is a PRODUCT — `InputObjectType` and no `OneofObjectType` — which is the whole of how a face
/// says the exactly-one rule is not its own, and the reason the third row is the assertion here
/// rather than an incidental detail of the list.
///
/// `wired`'s key is COMPOUND, which is what puts the face in this reading at all: a root's address
/// crosses inward as its id and mints no type — see `emit::graphql`'s `key_input`. See `emit::wire`
/// for the rows the remaining faces would demand and who can supply each.
#[test]
fn the_order_by_carries_a_oneof_wire_face_and_the_key_argument_a_product_one() {
  let file = emission(&wired());
  let faces: Vec<String> = trait_impls(&file)
    .into_iter()
    .filter(|(_, path)| tight(path).contains("async_graphql"))
    .map(|(item, path)| format!("{} for {}", tight(path), impl_of(item)))
    .collect();
  assert_eq!(
    faces,
    [
      "::ingraph::__private::async_graphql::InputType for VideoTrackKeyInput",
      "::ingraph::__private::async_graphql::InputObjectType for VideoTrackKeyInput",
      "::ingraph::__private::async_graphql::InputType for VideoTrackOrderBy",
      "::ingraph::__private::async_graphql::InputObjectType for VideoTrackOrderBy",
      "::ingraph::__private::async_graphql::OneofObjectType for VideoTrackOrderBy",
    ],
    "the two input faces, and the choice marker on the order-by alone"
  );
}

/// **A ROOT's ADDRESS MINTS NO ARGUMENT OBJECT** — the other half of the fork, asserted where the
/// list above cannot say it: `wired`'s key is compound, so that reading proves the type exists and
/// this one proves the condition is a condition.
///
/// The row on the `*Key` is still written — its `Input` is the ID's own wire form — so what is
/// absent is the TYPE and not the crossing. A root that published a single-field input object would
/// be a second shape for an address whose form the schema already carries at every `get(id:)`.
#[test]
fn a_root_key_crosses_inward_as_its_id_and_declares_no_argument_object() {
  // [`wire_only`]'s own shape over the ROOT fixture — a backend named, no field exposed — because
  // every wire fixture beside it descends from a record with a lineage, and what is under test here
  // is precisely the absence of one.
  let mut model = media();
  let base = model.record.clone();
  model.graphql = Some(Graphql {
    backends: vec![GraphqlBackend::AsyncGraphql(AsyncGraphql {
      skipped: Vec::new(),
      attrs: proc_macro2::TokenStream::new(),
      fields: Vec::new(),
    })],
    input: RustSafeName::from_ident(&default_input_name(&base)),
    output: RustSafeName::from_ident(&default_output_name(&base)),
    key_output: RustSafeName::from_ident(&default_key_output_name(&base)),
    // The address's two faces take the base above, which is the state a declaration that named
    // neither of them is in.
    key_object: None,
    key_argument: None,
    filter: RustSafeName::from_ident(&default_filter_name(&base)),
    plural: None,
    connection: None,
    edge: None,
    skipped: Vec::new(),
  });
  assert!(
    !model.key.compound(),
    "`{}` is the ROOT fixture this reading needs",
    model.record
  );
  let named: Vec<String> = model
    .emitted_types()
    .iter()
    .map(|declared| declared.name.to_string())
    .collect();
  assert!(
    !named.iter().any(|name| name.ends_with("KeyInput")),
    "a root enumerated an argument object: {named:?}"
  );
  let emitted = model.emit().to_string();
  assert!(
    !emitted.contains("KeyInput"),
    "a root emitted an argument object"
  );
  assert!(
    emitted.contains("ToGraphqlInput for"),
    "a root emitted no inward crossing at all"
  );
}

/// **THE FIELD NAMES ARE THE FILTER's**, because an order-by term and a filter field name ONE column
/// at ONE schema position — the input side. A client that had to spell `bitRate` in a filter and
/// something else in an order would be reading a schema this framework should not be able to write.
///
/// `wired`'s first column is `checksum`, exposed under the INPUT name `bitRate`, which is what makes
/// this more than a reading of the field's own name.
#[test]
fn an_order_by_subject_takes_the_name_the_filter_gave_its_column() {
  let emitted = wired().emit().to_string().replace(' ', "");
  assert!(
    emitted.contains(r#"String::from("bitRate")"#),
    "the subject is named as the filter names it"
  );
  assert!(
    !emitted.contains(r#"String::from("checksum")"#),
    "and not by the record field's own name"
  );
  assert!(emitted.contains("oneof:true"), "the `@oneOf` flag is set");
}

/// **NO DESCRIPTION IS WRITTEN INTO THE REGISTRY ENTRY**, on the type or on any of its fields.
///
/// The emitted order-by carries generated prose on the enum AND on every variant, and
/// async-graphql's derives lift rustdoc unconditionally — so the face being HAND-WRITTEN is what
/// keeps the ruling (*descriptions come from `attrs(desc = …)` and nowhere else*) true here. The
/// entry is ours, so the `None` is a fact of the emission.
#[test]
fn the_wire_face_writes_no_description_anywhere() {
  let emitted = wired().emit().to_string().replace(' ', "");
  assert!(
    emitted.contains("description:::core::option::Option::None"),
    "the entry writes the `None` explicitly"
  );
  assert!(
    !emitted.contains("description:::core::option::Option::Some"),
    "and never a `Some`"
  );
}

/// **THE `__async_graphql_` PREFIX PIN, ON BOTH EMITTED `#[Object]` FACES** — every generated
/// FUNCTION wears the prefix, and every name a client reads is SPELLED beside it (ruled 2026-08-10,
/// and given the BACKEND's name by the ruling of 2026-08-13).
///
/// Three claims, and the third is the one the first two exist for.
///
/// 1. **Every wire method is `__async_graphql_`-prefixed.** The idents inside an `#[Object]` are
///    nobody's API — the face is reached through the schema — so they go where no declaration
///    writes, in the namespace of the BACKEND whose face this is: a second GraphQL binding mints
///    `__smear_<name>` beside these and neither is the reason the other cannot be written. `wired`
///    exposes two fields and the framework adds two address members, which is four.
/// 2. **Every one carries exactly one attribute, and it is the name.** Not only the renamed ones:
///    the library's default is its rename rule over the METHOD IDENT, and after the prefix that
///    ident is `__async_graphql_cover_id`, so a field that declared nothing needs its name spelled
///    just as much as one that declared a word.
/// 3. **No published name moved.** `bitRate` is the declared word verbatim, and `coverId` is what a
///    field declaring NOTHING publishes — camelCase over the member, computed by this emission
///    rather than by async-graphql over an ident that no longer carries the member alone. The pair
///    is what makes the prefix invisible on the wire, which is the whole claim of the sweep.
///
/// The KEY face is the same rule where no word can be written at all: no `graphql(…)` reaches a key
/// column, so every one of its names is the computed fallback.
#[test]
fn every_wire_method_wears_the_prefix_and_spells_its_own_client_name() {
  /// The wire methods of one emitted face, as `(ident, the whole attribute)`.
  fn face(file: &syn::File, owner: &str) -> Vec<(String, String)> {
    inherent(file)
      .into_iter()
      .filter(|item| owner_of(item) == owner)
      .flat_map(methods)
      .filter(|method| method.sig.asyncness.is_some())
      .map(|method| {
        let attrs: Vec<String> = method.attrs.iter().map(tight).collect();
        assert_eq!(
          attrs.len(),
          1,
          "ONE attribute on `{}`, and it is the client's name — a doc attribute here would publish \
           prose, and a missing name would publish the prefix: {attrs:?}",
          method.sig.ident
        );
        (
          method.sig.ident.to_string(),
          attrs.into_iter().next().expect("just counted"),
        )
      })
      .collect()
  }

  // A field that declared NO output word, beside `wired`'s two that did — the fallback and the
  // verbatim arm in one emission.
  let mut model = wired();
  match &mut model.graphql.as_mut().expect("wired").backends[0] {
    GraphqlBackend::AsyncGraphql(backend) => {
      backend.fields[1].output.name = RustSafeName::from_ident(&ident("cover_id"));
    }
  }
  let file = emission(&model);

  assert_eq!(
    face(&file, "VideoTrackGraphqlOutput"),
    [
      (
        "__async_graphql_id".to_owned(),
        r#"#[graphql(name="id")]"#.to_owned()
      ),
      (
        "__async_graphql_key".to_owned(),
        r#"#[graphql(name="key")]"#.to_owned()
      ),
      (
        "__async_graphql_checksum".to_owned(),
        r#"#[graphql(name="bitRate")]"#.to_owned()
      ),
      (
        "__async_graphql_cover_id".to_owned(),
        r#"#[graphql(name="coverId")]"#.to_owned()
      ),
    ],
    "the OUTPUT object: prefixed idents, and the wire names the library used to derive"
  );

  assert_eq!(
    face(&file, "VideoTrackKeyOutput"),
    [
      (
        "__async_graphql_media_id".to_owned(),
        r#"#[graphql(name="mediaId")]"#.to_owned()
      ),
      (
        "__async_graphql_video_id".to_owned(),
        r#"#[graphql(name="videoId")]"#.to_owned()
      ),
      (
        "__async_graphql_id".to_owned(),
        r#"#[graphql(name="id")]"#.to_owned()
      ),
    ],
    "the ADDRESS object: no word can reach a key column, so every name here is the computed one"
  );

  // The ACCESSORS are the other side of the line, and they are in the same expansion: the Rust read
  // road keeps its names, so a caller still writes `cover_id_ref()`.
  let accessors = methods_of(&file, "VideoTrackGraphqlOutput");
  assert!(
    accessors.contains(&"cover_id_ref".to_owned())
      && !accessors.contains(&"__async_graphql_cover_id_ref".to_owned()),
    "the prefix is the WIRE face's and reaches no accessor: {accessors:?}"
  );
}

/// **THE FACE RIDES THE BINDING GATE**, which is what keeps a build with no GraphQL library from
/// having to resolve async-graphql's names at all.
#[test]
fn the_wire_face_is_emitted_inside_the_binding_gate() {
  let emitted = wired().emit().to_string().replace(' ', "");
  assert!(emitted.contains("::ingraph::__private::gate::if_async_graphql!"));
}

/// A record with NO ORDERABLE COLUMN gets no ORDER-BY face, and the absence is the answer: an input
/// object with no fields is not a GraphQL type, so a schema naming one would be invalid.
///
/// **What such a record still gets is the two OUTPUT faces**, and the difference is which side of the
/// wire each type is on. An order-by over no column is uninhabited and unrenderable; an output object
/// always has an address, so it always has a field and is always a legal type. The binding gate is
/// therefore present where it used to be absent, and the assertion moved onto the thing that is
/// actually gone.
#[test]
fn a_record_with_nothing_to_order_by_gets_no_wire_face() {
  let mut model = wired();
  model.persist = None;
  let emitted = model.emit().to_string().replace(' ', "");
  assert!(
    !emitted.contains("OneofObjectType"),
    "a record that stores nothing has no order to write"
  );
  assert!(
    emitted.contains("if_async_graphql"),
    "and the output faces are there anyway — an address is a field, so the object is a legal type"
  );
}

/// Every `#[…]` in an emitted expansion, as the text between its brackets — walked over the TOKEN
/// STRING rather than over a `syn::File`, so that an attribute written inside a gate's macro body is
/// seen too. A structural walk sees a gate as one unparsed `Macro` and everything in it as tokens.
fn attributes(emitted: &str) -> Vec<String> {
  let bytes = emitted.as_bytes();
  let mut found = Vec::new();
  let mut at = 0;
  while let Some(hit) = emitted[at..].find("#[") {
    let open = at + hit + 1;
    let mut depth = 0usize;
    let mut end = None;
    for (step, byte) in bytes[open..].iter().enumerate() {
      match byte {
        b'[' => depth += 1,
        b']' => {
          depth -= 1;
          if depth == 0 {
            end = Some(open + step);
            break;
          }
        }
        _ => {}
      }
    }
    let Some(end) = end else { break };
    found.push(emitted[open + 1..end].to_owned());
    at = end + 1;
  }
  found
}

/// The async-graphql attributes among them that are MISSING the redirect — the rule
/// `emit::wire`'s BUILD PIN states, as a predicate.
///
/// Two halves, and an attribute needs both: its own PATH must be the shelf's, or the attribute does
/// not resolve in a declaring crate at all; and `crate = "…"` must name the same shelf, or every
/// path the attribute EXPANDS TO resolves to nothing there.
fn attributes_missing_the_crate_key(emitted: &str) -> Vec<String> {
  const SHELF: &str = "::ingraph::__private::async_graphql";
  attributes(emitted)
    .into_iter()
    .filter(|attribute| attribute.contains("async_graphql") && !attribute.starts_with("doc"))
    .filter(|attribute| {
      !attribute.starts_with(SHELF) || !attribute.contains(&format!(r#"crate="{SHELF}""#))
    })
    .collect()
}

/// **THE #157 BUILD PIN.** async-graphql's attribute family takes a `crate = "…"` key, and every
/// emitted one must pass it — that redirect is the whole reason the fourth vendored shelf entry
/// exists, and without it a DECLARING crate would need async-graphql in its own manifest.
///
/// **Measured at this tip: the emission writes NO async-graphql attribute at all.** The order door
/// is three hand-written impls carrying `#[automatically_derived]`, and every async-graphql NAME
/// inside them is already rooted through the shelf. So the corpus half of this test is a rule over
/// an empty set today, and the FIXTURE half is what keeps that from being vacuous: the predicate is
/// run against a compliant attribute and against each of the two ways to get it wrong.
///
/// `model::GraphqlKind`'s `output_object`/`input_derive`/`order_by_derive` and `enumeration.rs`'s
/// `Enum` all answer a bare `::async_graphql::…` path — half a rule each, and none of them emitted
/// yet. Whichever round first spends one lands here.
#[test]
fn no_emitted_async_graphql_attribute_is_missing_the_crate_key() {
  // The walker and the predicate, proven on text where the answer is known — a rule over an empty
  // set proves nothing about the rule.
  const SHELF: &str = "::ingraph::__private::async_graphql";
  let compliant = format!(r#"#[{SHELF}::Object(crate="{SHELF}")]structX;"#);
  assert!(
    attributes_missing_the_crate_key(&compliant).is_empty(),
    "the shelf path AND the key is what compliance looks like"
  );
  assert_eq!(
    attributes_missing_the_crate_key("#[::async_graphql::Object]structX;").len(),
    1,
    "a bare path with no key is caught"
  );
  assert_eq!(
    attributes_missing_the_crate_key(&format!(r#"#[{SHELF}::Object]structX;"#)).len(),
    1,
    "the shelf path alone is not enough — the expansion still needs the key"
  );
  assert_eq!(
    attributes_missing_the_crate_key(&format!(
      r#"#[::async_graphql::Object(crate="{SHELF}")]f();"#
    ))
    .len(),
    1,
    "and the key alone is not enough — the ATTRIBUTE itself has to resolve"
  );
  // Attributes with brackets inside them are one attribute, not two — the walker matches its own.
  assert!(
    attributes_missing_the_crate_key("#[serde(with=\"x\")]#[doc=\"async_graphql\"]structX;")
      .is_empty(),
    "a doc mentioning the crate is not an attribute of it"
  );

  for (label, model) in [("wired", wired()), ("referring", referring())] {
    let emitted = model.emit().to_string().replace(' ', "");
    assert!(
      attributes_missing_the_crate_key(&emitted).is_empty(),
      "{label}: {:?}",
      attributes_missing_the_crate_key(&emitted)
    );
  }

  // The VOCABULARY joins the walk, so the rule covers its emission rather than the record's alone.
  // Its wire face writes no async-graphql attribute either — the impls are hand-written and every
  // name in them is already rooted through the shelf — so the set is empty here for the same
  // reason, and the walk is already over it the day one appears.
  let face = crate::enumeration::EnumModel {
    krate: syn::parse_quote!(::ingraph),
    vis: syn::parse_quote!(pub),
    name: syn::parse_quote!(Codec),
    width: None,
    variants: vec![crate::enumeration::EnumVariant {
      ident: syn::parse_quote!(H264),
      rename: None,
      names: std::collections::BTreeMap::new(),
      upstream: None,
      escape: None,
      carrier: None,
    }],
    forms: std::collections::BTreeMap::new(),
    wire_name: None,
    error: None,
    remote: None,
  }
  .emit()
  .to_string()
  .replace(' ', "");
  assert!(
    attributes_missing_the_crate_key(&face).is_empty(),
    "the vocabulary's emission: {:?}",
    attributes_missing_the_crate_key(&face)
  );
}

/// A node whose intake is a mixed fan-in and whose output is a pair of products — the shape the
/// topology emission exists for, as a model.
fn fused_and_forked() -> RecordModel {
  let mut model = model("Describe", &["media_id"], "id");
  model.kind = NodeKind::Operator;
  model.subscriptions = Some(Subscription {
    upstreams: vec![
      upstream("media::Frame", true, None),
      upstream("asr::Segment", true, None),
      upstream("media::Scene", false, None),
      upstream("vision::Detector", false, Some("Boxes")),
    ],
  });
  model.products = Some(Products {
    products: vec![product("Caption"), product("Summary")],
  });
  model
}

/// One entry of a `subscribe(…)` container, as the front end would have settled it.
fn upstream(node: &str, keyed: bool, out: Option<&str>) -> Upstream {
  let node: syn::Path = syn::parse_str(node).expect("a path");
  let out = out.map(ident);
  let variant = out.clone().unwrap_or_else(|| {
    node
      .segments
      .last()
      .expect("a path has a last segment")
      .ident
      .clone()
  });
  Upstream {
    node,
    keyed,
    out,
    variant,
    channel: None,
    changes: None,
    notify: false,
  }
}

/// One product `emits` named, as the front end would have settled it.
fn product(ty: &str) -> Product {
  let ty: syn::Path = syn::parse_str(ty).expect("a path");
  let variant = ty
    .segments
    .last()
    .expect("a path has a last segment")
    .ident
    .clone();
  Product { ty, variant }
}

/// The fan-in enum: the keyed group as ONE variant carrying both payloads, and the straights beside
/// it — in the order the declaration wrote them.
#[test]
fn the_fan_in_carries_the_group_as_one_variant_and_the_straights_beside_it() {
  let model = fused_and_forked();
  let file = emission(&model);
  let fan_in = enum_named(&file, &default_in_name(&model.record).to_string());
  assert_eq!(
    fan_in
      .variants
      .iter()
      .map(|variant| variant.ident.to_string())
      .collect::<Vec<_>>(),
    [crate::emit::PAIRED, "Scene", "Boxes"],
    "the group takes the first keyed entry's place, and each straight takes its own"
  );
  let paired = &fan_in.variants[0];
  assert_eq!(
    paired.fields.len(),
    2,
    "one payload per member of the group"
  );
  assert_eq!(
    paired
      .fields
      .iter()
      .map(|field| tight(&field.ty))
      .collect::<Vec<_>>(),
    [
      "<media::Frameas::ingraph::__private::operator::Emits>::Out",
      "<asr::Segmentas::ingraph::__private::operator::Emits>::Out",
    ],
    "each payload is the upstream's OWN statement of what it emits"
  );
}

/// A selected product is projected through the upstream's own vocabulary — the ordinal crosses the
/// wall, the word stays in the declaration.
#[test]
fn a_selected_product_is_projected_through_the_upstreams_vocabulary() {
  let model = fused_and_forked();
  let file = emission(&model);
  let fan_in = enum_named(&file, &default_in_name(&model.record).to_string());
  let boxes = fan_in
    .variants
    .iter()
    .find(|variant| variant.ident == "Boxes")
    .expect("the selected edge");
  assert_eq!(
    tight(&boxes.fields.iter().next().expect("one payload").ty),
    "<vision::Detectoras::ingraph::__private::operator::Emits<{vision::DetectorOutKind::Boxesasusize}>>::Out",
  );
}

/// The product face: the sum, the vocabulary, and the downstream beside them.
#[test]
fn a_multi_product_node_emits_its_sum_its_vocabulary_and_its_downstream() {
  let model = fused_and_forked();
  let file = emission(&model);
  let record = &model.record;

  let out = enum_named(&file, &default_out_name(record).to_string());
  assert_eq!(
    out
      .variants
      .iter()
      .map(|variant| (variant.ident.to_string(), variant.fields.len()))
      .collect::<Vec<_>>(),
    [("Caption".to_owned(), 1), ("Summary".to_owned(), 1)],
  );
  let kind = enum_named(&file, &default_out_kind_name(record).to_string());
  assert!(
    kind
      .variants
      .iter()
      .all(|variant| variant.fields.is_empty()),
    "the vocabulary carries identities and no payloads"
  );

  let downstream = structs(&file)
    .into_iter()
    .find(|item| item.ident == default_downstream_name(record))
    .expect("the downstream is emitted");
  assert_eq!(
    downstream
      .fields
      .iter()
      .map(|field| tight(&field.ty))
      .collect::<Vec<_>>(),
    [
      "::std::vec::Vec<::ingraph::__private::drive::Outbox<::ingraph::__private::drive::ItemId,Caption>>",
      "::std::vec::Vec<::ingraph::__private::drive::Outbox<::ingraph::__private::drive::ItemId,Summary>>",
    ],
    "one out-edge LIST per product — several subscribers to one product is the ordinary road — and \
     a list's emptiness IS the connection state"
  );
}

/// The routing lives on the DOWNSTREAM and never on a product — the coherence law, held as a fact
/// about the emission rather than as a sentence about it.
#[test]
fn the_routing_impl_is_on_the_downstream_at_the_nodes_own_sum() {
  let model = fused_and_forked();
  let file = emission(&model);
  let routing: Vec<String> = trait_impls(&file)
    .into_iter()
    .filter(|(_, path)| tight(path).contains("drive::Sink"))
    .map(|(item, path)| format!("{} for {}", tight(path), impl_of(item)))
    .collect();
  assert_eq!(
    routing,
    [format!(
      "::ingraph::__private::drive::Sink<{}> for {}",
      default_out_name(&model.record),
      default_downstream_name(&model.record),
    )],
    "one impl, on the downstream the node declares, at the sum it declares beside it"
  );
}

/// What a node EMITS is stated for the declarations that cannot see it — one row per product where
/// several were declared.
#[test]
fn several_products_are_stated_one_row_apiece() {
  let file = emission(&fused_and_forked());
  let rows: Vec<String> = trait_impls(&file)
    .into_iter()
    .filter(|(_, path)| tight(path).contains("operator::Emits"))
    .map(|(item, path)| {
      let associated = item
        .items
        .iter()
        .filter_map(|item| match item {
          syn::ImplItem::Type(ty) => Some(tight(&ty.ty)),
          _ => None,
        })
        .collect::<Vec<_>>()
        .join(",");
      format!("{} = {associated}", tight(path))
    })
    .collect();
  assert_eq!(
    rows,
    [
      "::ingraph::__private::operator::Emits<0usize> = Caption",
      "::ingraph::__private::operator::Emits<1usize> = Summary",
    ],
  );
  assert!(
    !trait_impls(&file)
      .iter()
      .any(|(_, path)| tight(path).contains("SoleProduct")),
    "a node that emits several carries no sole-product marker"
  );
}

/// A node with ONE product states it and carries the marker an unselected subscription discharges.
#[test]
fn one_product_is_stated_as_the_declared_struct_and_carries_the_marker() {
  let file = emission(&video_track());
  let rows: Vec<String> = trait_impls(&file)
    .into_iter()
    .filter(|(_, path)| tight(path).contains("operator::"))
    .map(|(item, path)| format!("{} for {}", tight(path), impl_of(item)))
    .collect();
  assert_eq!(
    rows,
    [
      "::ingraph::__private::operator::Emits for VideoTrack",
      "::ingraph::__private::operator::SoleProduct for VideoTrack",
    ],
  );
  assert!(
    structs(&file)
      .iter()
      .all(|item| item.ident != default_downstream_name(&ident("VideoTrack"))),
    "and it declares no downstream of its own — the framework's holder is its shape"
  );
}

/// A subscription that named no product discharges the audit; one that named a product does not
/// need it, because its payload projection already names the row.
#[test]
fn an_unselected_subscription_discharges_the_one_product_audit() {
  let emitted = tight(fused_and_forked().emit());
  assert!(
    emitted.contains("__ig_takes_one_product"),
    "the audit is emitted"
  );
  for upstream in ["media::Frame", "asr::Segment", "media::Scene"] {
    assert!(
      emitted.contains(&format!(
        "__ig_takes_one_product::<{}>",
        upstream.replace(' ', "")
      )),
      "`{upstream}` named no product, so it must emit one"
    );
  }
  assert!(
    !emitted.contains("__ig_takes_one_product::<vision::Detector>"),
    "the entry that named a product is audited by its own projection"
  );
}

/// A node that neither fans in nor forks out emits NOTHING from this family beyond the one row every
/// node states — the N=1 pin.
#[test]
fn a_plain_node_gains_no_topology_types() {
  let before = names(&emission(&video_track()));
  assert_eq!(
    before,
    ["TrackAddress", "TrackScope"],
    "the key and the lineage, and no fan-in, sum, vocabulary or downstream beside them"
  );
}