ingraph-derive 0.1.0

The attribute and derive macros for ingraph: the words a record, node, key, filter and vocabulary declaration is written in.
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
//! The parser's acceptance: the three real mediaschema shapes it must accept, and every
//! declaration it must refuse.

use ingraph_codegen::prelude::*;
use quote::ToTokens as _;

/// The pass under test, at the kind this module is about.
///
/// Every assertion below is a rule of the shared grammar, and the shared grammar is read the same
/// way whichever derive opened it — so the kind is supplied here once rather than at each call. The
/// rules that DIFFER by kind are the storage ones, and those are asserted through
/// [`operator`](self::operator) beside their record twin, where the two answers can be read
/// together.
fn parse(input: &syn::DeriveInput) -> syn::Result<RecordModel> {
  under(input, NodeKind::Record)
}

/// The same pass under the macro that holds no storage.
fn operator(input: &syn::DeriveInput) -> syn::Result<RecordModel> {
  under(input, NodeKind::Operator)
}

/// One declaration, split the way the attribute form takes it — see
/// [`host::split`](crate::host::split) for why the suites below keep writing it in one piece.
fn under(input: &syn::DeriveInput, kind: NodeKind) -> syn::Result<RecordModel> {
  let (host, options) = crate::host::split(input);
  crate::parse::parse(&host, &options, kind)
}

/// The lineage idents of a model, in the order the key will lay them out.
fn lineage_names(model: &RecordModel) -> Vec<String> {
  model
    .lineage
    .iter()
    .flat_map(|lineage| lineage.path().iter())
    .map(|column| column.name.to_string())
    .collect()
}

/// One of the record's own fields, by name.
fn field<'a>(model: &'a RecordModel, name: &str) -> &'a Field {
  model
    .fields
    .iter()
    .find(|field| field.column.name == name)
    .unwrap_or_else(|| panic!("`{name}` is a field of the record"))
}

/// A path as it would be written, with the token spacing removed.
fn rendered(path: &syn::Path) -> String {
  path.to_token_stream().to_string().replace(' ', "")
}

/// A type as it would be written, with the token spacing removed.
fn rendered_type(ty: &syn::Type) -> String {
  ty.to_token_stream().to_string().replace(' ', "")
}

#[test]
fn video_track_model_orders_lineage_root_first() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media_id, video_id)))]
    struct VideoTrack { #[ingraph(id)] id: Uuid7, media_id: Uuid7, video_id: Uuid7, bit_rate: u64 }
  })
  .expect("the grandchild shape is the one T1 exists to prove");
  assert_eq!(m.record, "VideoTrack");
  assert_eq!(m.key.id.name, "id");
  assert_eq!(lineage_names(&m), ["media_id", "video_id"], "root-first");
  assert!(
    m.lineage
      .iter()
      .flat_map(|lineage| lineage.path().iter())
      .all(|column| matches!(column.ty, syn::Type::Path(_))),
    "each lineage field carries the declared type, copied verbatim"
  );
}

#[test]
fn media_has_no_lineage() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct Media { #[ingraph(id)] id: Uuid7, files: Vec<Uuid7>, video_id: Option<Uuid7> }
  })
  .expect("a root record omits the lineage block");
  assert!(m.lineage.is_none(), "absence by omission");
  assert_eq!(
    m.key.id.name, "id",
    "the `Option<Uuid7>` FK and the `Vec<Uuid7>` reverse lookup are ignored entirely"
  );
}

#[test]
fn emitted_names_default_to_the_suffix_convention() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media_id)))]
    struct Video { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
  })
  .expect("naming nothing is the ordinary case");
  assert_eq!(m.key.name, "VideoKey");
  assert_eq!(
    m.lineage.expect("a child has a lineage").name,
    "VideoLineage"
  );
}

#[test]
fn both_renames_override_the_convention() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite,
      lineage(fields(media_id, video_id), rename = "TrackScope"),
      key(rename = "TrackAddress"),
    )]
    struct VideoTrack { #[ingraph(id)] id: Uuid7, media_id: Uuid7, video_id: Uuid7 }
  })
  .expect("both blocks may name their type");
  assert_eq!(m.key.name, "TrackAddress");
  assert_eq!(
    m.lineage.expect("renamed, still present").name,
    "TrackScope"
  );
}

/// A rename is a STRING parsed into an ident, which is what keeps a raw identifier spellable.
#[test]
fn a_rename_may_be_a_raw_identifier() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, key(rename = "r#type"))]
    struct S { #[ingraph(id)] id: Uuid7 }
  })
  .expect("`r#type` is a legal type name");
  assert_eq!(m.key.name.to_string(), "r#type");
}

/// `#[ingraph(copy)]` is a per-field marker: it says the column's type is cheap to copy, which
/// changes the accessor and mutator shapes the emitter gives it.
#[test]
fn a_key_column_may_be_marked_copy() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media_id, video_id)))]
    struct VideoTrack {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(copy)] media_id: Uuid7,
      video_id: Uuid7,
    }
  })
  .expect("a marked lineage column");
  let lineage = m.lineage.expect("a grandchild has a path");
  assert_eq!(
    lineage.path()[0].project,
    Projection::Copied,
    "`media_id` was marked"
  );
  assert_eq!(
    lineage.path()[1].project,
    Projection::Borrowed,
    "`video_id` was not"
  );
  assert_eq!(m.key.id.project, Projection::Borrowed, "nor was the id");
}

/// Both markers are `ingraph` entries, so one attribute may carry both.
#[test]
fn id_and_copy_may_share_one_attribute() {
  for input in [
    syn::parse_quote! { #[ingraph(sqlite)] struct S { #[ingraph(id, copy)] id: Uuid7 } },
    syn::parse_quote! { #[ingraph(sqlite)] struct S { #[ingraph(id)] #[ingraph(copy)] id: Uuid7 } },
  ] {
    let m = parse(&input).expect("both spellings mark the same field twice over");
    assert_eq!(m.key.id.project, Projection::Copied);
  }
}

/// A marker says one thing about one field, so declaring it twice is ambiguous exactly the way a
/// repeated record-level option is — and silently keeping the first would be the accept-and-ignore
/// the rest of this grammar refuses. Caught within one attribute and across two.
#[test]
fn refuses_a_repeated_field_marker() {
  for input in [
    syn::parse_quote! { struct S { #[ingraph(id, id)] id: Uuid7 } },
    syn::parse_quote! { struct S { #[ingraph(id)] #[ingraph(id)] id: Uuid7 } },
    syn::parse_quote! { struct S { #[ingraph(id, copy, copy)] id: Uuid7 } },
    syn::parse_quote! { struct S { #[ingraph(id)] #[ingraph(copy)] #[ingraph(copy)] id: Uuid7 } },
  ] {
    let e = parse(&input).unwrap_err();
    assert!(e.to_string().contains("declared more than once"), "{e}");
  }
}

/// `copy` is meaningful on ANY field now that the record gets an impl of its own — a data field's
/// accessor is shaped by the marker exactly as a key column's is. It was refused on a non-key
/// field while only `*Key` and `*Lineage` were emitted; that refusal is gone with its reason.
#[test]
fn any_field_may_be_marked_copy_now_that_the_record_is_emitted_too() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media_id)))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      media_id: Uuid7,
      #[ingraph(copy)] checksum: u64,
      chapters: Vec<Uuid7>,
    }
  })
  .expect("a data field carries the marker too");
  let checksum = field(&m, "checksum");
  assert_eq!(
    checksum.column.project,
    Projection::Copied,
    "the marker reached the data field"
  );
  assert!(!checksum.identity, "and it bears no identity");
  assert_eq!(field(&m, "chapters").column.project, Projection::Borrowed);
}

/// The record's own fields reach the model in DECLARED order, each knowing whether it bears
/// identity — the id and every lineage step do, and nothing else does.
#[test]
fn every_field_reaches_the_model_and_knows_whether_it_bears_identity() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media_id)))]
    struct Video {
      #[ingraph(id)] id: Uuid7,
      media_id: Uuid7,
      total_scenes: u32,
      tracks: Vec<Uuid7>,
    }
  })
  .expect("a child with data fields");
  assert_eq!(
    m.fields
      .iter()
      .map(|f| f.column.name.to_string())
      .collect::<Vec<_>>(),
    ["id", "media_id", "total_scenes", "tracks"],
    "declared order, data fields included"
  );
  assert_eq!(
    m.fields
      .iter()
      .filter(|f| f.identity)
      .map(|f| f.column.name.to_string())
      .collect::<Vec<_>>(),
    ["id", "media_id"],
    "the id and the lineage step, and nothing else"
  );
}

/// The emitted types are as visible as the record and no more, so the model carries the source
/// struct's own `vis` rather than assuming `pub`.
#[test]
fn the_model_carries_the_source_visibility() {
  for (declaration, expected) in [
    (
      syn::parse_quote! { #[ingraph(sqlite)] pub struct S { #[ingraph(id)] id: Uuid7 } },
      "pub",
    ),
    (
      syn::parse_quote! { #[ingraph(sqlite)] pub(crate) struct S { #[ingraph(id)] id: Uuid7 } },
      "pub(crate)",
    ),
    (
      syn::parse_quote! { #[ingraph(sqlite)] struct S { #[ingraph(id)] id: Uuid7 } },
      "",
    ),
  ] {
    let m = parse(&declaration).expect("visibility is not a rule, only a fact to carry");
    assert_eq!(
      m.vis.to_token_stream().to_string().replace(' ', ""),
      expected
    );
  }
}

#[test]
fn crate_path_defaults_and_overrides() {
  let d = parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct A { #[ingraph(id)] id: Uuid7 }
  })
  .expect("no `crate` option is the ordinary case");
  assert_eq!(rendered(&d.krate), "::ingraph");

  let o = parse(&syn::parse_quote! {
    #[ingraph(sqlite, crate = "shim::vendored::ingraph")]
    struct B { #[ingraph(id)] id: Uuid7 }
  })
  .expect("a re-export shim names itself");
  assert_eq!(rendered(&o.krate), "shim::vendored::ingraph");
}

#[test]
fn refuses_a_crate_value_that_is_not_a_path() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(crate = "not a path!")]
    struct S { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err();
  assert!(e.to_string().contains("must be a path"), "{e}");
}

#[test]
fn refuses_a_crate_value_that_is_not_a_string() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(crate = 7)]
    struct S { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err();
  assert!(e.to_string().contains("must be a path"), "{e}");
}

#[test]
fn refuses_a_repeated_crate_option() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(crate = "a::b", crate = "c::d")]
    struct S { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err();
  assert!(e.to_string().contains("declared more than once"), "{e}");
}

/// A block names ONE type. Two of them is a declaration whose second half would be silently
/// dropped, so it is refused instead.
#[test]
fn refuses_a_repeated_block() {
  for input in [
    syn::parse_quote! {
      #[ingraph(lineage(fields(media_id)), lineage(fields(video_id)))]
      struct S { #[ingraph(id)] id: Uuid7, media_id: Uuid7, video_id: Uuid7 }
    },
    syn::parse_quote! {
      #[ingraph(key(rename = "A"), key(rename = "B"))]
      struct S { #[ingraph(id)] id: Uuid7 }
    },
  ] {
    let e = parse(&input).unwrap_err();
    assert!(e.to_string().contains("declared more than once"), "{e}");
  }
}

#[test]
fn refuses_a_repeated_option_inside_a_block() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(key(rename = "A", rename = "B"))]
    struct S { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err();
  assert!(e.to_string().contains("declared more than once"), "{e}");
}

/// Never accept-and-ignore: an entry this version does not understand is a rule the author
/// believes they declared.
#[test]
fn refuses_an_unknown_entry_inside_a_block() {
  for input in [
    syn::parse_quote! {
      #[ingraph(key(mystery = "x"))]
      struct S { #[ingraph(id)] id: Uuid7 }
    },
    syn::parse_quote! {
      #[ingraph(lineage(fields(media_id), mystery))]
      struct S { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
    },
  ] {
    let e = parse(&input).unwrap_err();
    assert!(e.to_string().contains("unknown entry in"), "{e}");
  }
}

/// The flat shorthand is GONE, and the refusal is the upgrade instruction: it names `fields(…)`.
#[test]
fn refuses_the_old_flat_lineage_shorthand() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(lineage(media_id, video_id))]
    struct S { #[ingraph(id)] id: Uuid7, media_id: Uuid7, video_id: Uuid7 }
  })
  .unwrap_err();
  let message = e.to_string();
  assert!(message.contains("unknown entry in"), "{message}");
  assert!(
    message.contains("fields(…)"),
    "it names the replacement: {message}"
  );
}

#[test]
fn refuses_a_lineage_block_without_fields() {
  for input in [
    syn::parse_quote! {
      #[ingraph(lineage(rename = "TrackScope"))]
      struct S { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
    },
    syn::parse_quote! {
      #[ingraph(lineage())]
      struct S { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
    },
  ] {
    let e = parse(&input).unwrap_err();
    assert!(e.to_string().contains("needs `fields(…)`"), "{e}");
  }
}

/// An empty path is spelled by omitting the block, not by declaring an empty one.
///
/// Exactly ONE error: syn's own nested walk refuses an empty group on its terms ("unexpected end
/// of input"), so `fields()` is answered before it is walked and that second, worse-worded message
/// never reaches the author.
#[test]
fn refuses_an_empty_fields_list() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields()))]
    struct S { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err();
  let messages: Vec<String> = e.into_iter().map(|e| e.to_string()).collect();
  assert_eq!(messages.len(), 1, "{messages:?}");
  assert!(messages[0].contains("at least one field"), "{messages:?}");
}

#[test]
fn refuses_a_rename_that_is_not_an_identifier() {
  for input in [
    syn::parse_quote! {
      #[ingraph(key(rename = "Not An Ident"))]
      struct S { #[ingraph(id)] id: Uuid7 }
    },
    syn::parse_quote! {
      #[ingraph(key(rename = 7))]
      struct S { #[ingraph(id)] id: Uuid7 }
    },
  ] {
    let e = parse(&input).unwrap_err();
    assert!(e.to_string().contains("must be a valid identifier"), "{e}");
  }
}

#[test]
fn refuses_colliding_key_and_lineage_names() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media_id), rename = "Both"), key(rename = "Both"))]
    struct S { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
  })
  .unwrap_err();
  assert!(e.to_string().contains("already the key type"), "{e}");
}

/// A collision against a DEFAULT is still a collision: renaming only the lineage onto the key's
/// conventional name is caught too.
#[test]
fn refuses_a_rename_that_collides_with_the_others_default() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media_id), rename = "SKey"))]
    struct S { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
  })
  .unwrap_err();
  assert!(
    e.to_string().contains("already the key type"),
    "a rename onto another emitted type's DEFAULT is the same comparison as onto a rename — a \
     defaulted type's name is simply the name it has: {e}"
  );
}

#[test]
fn refuses_a_rename_equal_to_the_records_own_name() {
  for input in [
    syn::parse_quote! {
      #[ingraph(sqlite, key(rename = "Video"))]
      struct Video { #[ingraph(id)] id: Uuid7 }
    },
    syn::parse_quote! {
      #[ingraph(sqlite, lineage(fields(media_id), rename = "Video"))]
      struct Video { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
    },
  ] {
    let e = parse(&input).unwrap_err();
    assert!(e.to_string().contains("the record's own name"), "{e}");
  }
}

#[test]
fn refuses_missing_id() {
  let e = parse(&syn::parse_quote! { struct S { a: u32 } }).unwrap_err();
  assert!(e.to_string().contains("exactly one `#[ingraph(id)]`"));
}

#[test]
fn refuses_two_id_fields() {
  let e = parse(&syn::parse_quote! {
    struct S { #[ingraph(id)] a: u32, #[ingraph(id)] b: u32 }
  })
  .unwrap_err();
  assert!(e.to_string().contains("exactly one `#[ingraph(id)]`"));
}

#[test]
fn refuses_a_lineage_name_that_is_not_a_field() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(lineage(fields(parent_id)))]
    struct S { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err();
  assert!(e.to_string().contains("names fields of this struct"), "{e}");
}

#[test]
fn refuses_the_id_field_in_lineage() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(lineage(fields(id)))]
    struct S { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err();
  assert!(
    e.to_string().contains("cannot also be a lineage field"),
    "{e}"
  );
}

#[test]
fn refuses_a_duplicate_lineage_name() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(lineage(fields(media_id, media_id)))]
    struct S { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
  })
  .unwrap_err();
  assert!(e.to_string().contains("named twice"), "{e}");
}

#[test]
fn refuses_a_generic_record() {
  let e = parse(&syn::parse_quote! {
    struct Media<Id = Uuid7> { #[ingraph(id)] id: Id }
  })
  .unwrap_err();
  assert!(
    e.to_string().contains("generic records are not supported"),
    "{e}"
  );
}

#[test]
fn refuses_a_lifetime_parameter_and_a_const_parameter_too() {
  for input in [
    syn::parse_quote! { struct S<'a> { #[ingraph(id)] id: &'a u32 } },
    syn::parse_quote! { struct S<const N: usize> { #[ingraph(id)] id: [u8; N] } },
  ] {
    let e = parse(&input).unwrap_err();
    assert!(
      e.to_string().contains("generic records are not supported"),
      "{e}"
    );
  }
}

#[test]
fn refuses_a_where_clause_even_without_parameters() {
  let e = parse(&syn::parse_quote! {
    struct S where u32: Copy { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err();
  assert!(
    e.to_string().contains("generic records are not supported"),
    "{e}"
  );
}

#[test]
fn refuses_a_tuple_struct() {
  let e = parse(&syn::parse_quote! { struct S(u32, u32); }).unwrap_err();
  assert!(e.to_string().contains("named fields"), "{e}");
}

#[test]
fn refuses_a_unit_struct() {
  let e = parse(&syn::parse_quote! { struct S; }).unwrap_err();
  assert!(e.to_string().contains("named fields"), "{e}");
}

#[test]
fn refuses_an_enum() {
  let e = parse(&syn::parse_quote! { enum E { A, B } }).unwrap_err();
  assert!(e.to_string().contains("structs only"), "{e}");
}

#[test]
fn refuses_a_union() {
  let e = parse(&syn::parse_quote! { union U { a: u32 } }).unwrap_err();
  assert!(e.to_string().contains("structs only"), "{e}");
}

#[test]
fn refuses_an_unknown_ingraph_attribute() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(mystery)]
    struct S { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err();
  assert!(e.to_string().contains("unknown"), "{e}");
}

/// Two INDEPENDENT violations in one declaration, reported together. Accumulation is the property
/// hand-rolled parsing loses first, so it is pinned here rather than left to a reviewer's eye.
#[test]
fn two_independent_violations_are_both_reported_in_one_pass() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(lineage(fields(parent_id)))]
    struct S { a: u32 }
  })
  .unwrap_err();
  let messages: Vec<String> = e.into_iter().map(|e| e.to_string()).collect();
  assert_eq!(messages.len(), 2, "{messages:?}");
  assert!(
    messages
      .iter()
      .any(|m| m.contains("names fields of this struct")),
    "the unknown lineage name: {messages:?}"
  );
  assert!(
    messages
      .iter()
      .any(|m| m.contains("exactly one `#[ingraph(id)]`")),
    "and the missing id: {messages:?}"
  );
}

/// Accumulation survives the block grammar too: a bad rename in one block does not hide a bad
/// entry in the other.
#[test]
fn violations_in_two_different_blocks_are_both_reported() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media_id), mystery), key(rename = "Not An Ident"))]
    struct S { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
  })
  .unwrap_err();
  let messages: Vec<String> = e.into_iter().map(|e| e.to_string()).collect();
  assert_eq!(messages.len(), 2, "{messages:?}");
  assert!(messages.iter().any(|m| m.contains("unknown entry in")));
  assert!(
    messages
      .iter()
      .any(|m| m.contains("must be a valid identifier"))
  );
}

/// A repeated FIELD marker does not swallow the rest of the pass either: the field level
/// accumulates with the record level, in one report.
#[test]
fn a_repeated_field_marker_and_an_record_level_violation_are_both_reported() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(parent_id)))]
    struct S { #[ingraph(id, id)] id: Uuid7 }
  })
  .unwrap_err();
  let messages: Vec<String> = e.into_iter().map(|e| e.to_string()).collect();
  assert_eq!(messages.len(), 2, "{messages:?}");
  assert!(
    messages
      .iter()
      .any(|m| m.contains("declared more than once")),
    "the repeated marker: {messages:?}"
  );
  assert!(
    messages
      .iter()
      .any(|m| m.contains("names fields of this struct")),
    "and the unknown lineage name: {messages:?}"
  );
}

/// Accumulation survives a whole bad lineage list rather than stopping at its first entry.
#[test]
fn every_offending_lineage_name_is_reported_not_only_the_first() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(nope, id, media_id, media_id)))]
    struct S { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
  })
  .unwrap_err();
  assert_eq!(
    e.into_iter().count(),
    3,
    "an unknown name, the id itself, and a repeat"
  );
}

/// The framework namespaces its own columns `__name__`, so a user column may not take that shape.
/// A NAMESPACE rather than a list is what makes the rule checkable in this crate at all — the list
/// it replaces had to be copied out of `ingraph`, which this crate cannot depend on.
///
/// The edges are pinned rather than left to reading: a degenerate middle is still inside the
/// fence.
#[test]
fn refuses_a_column_inside_the_frameworks_namespace() {
  for reserved in ["__seq__", "__x__", "__", "___", "____"] {
    let name = syn::Ident::new(reserved, proc_macro2::Span::call_site());
    let e = parse(&syn::parse_quote! {
      #[ingraph(lineage(fields(#name)))]
      struct S { #[ingraph(id)] id: Uuid7, #name: Uuid7 }
    })
    .unwrap_err();
    assert!(
      e.to_string().contains("framework's namespace"),
      "`{reserved}` is inside the fence: {e}"
    );
  }
}

#[test]
fn accepts_a_column_that_only_looks_reserved() {
  for allowed in ["__internal", "internal__", "_internal_"] {
    let name = syn::Ident::new(allowed, proc_macro2::Span::call_site());
    parse(&syn::parse_quote! {
      #[ingraph(sqlite, lineage(fields(#name)))]
      struct S { #[ingraph(id)] id: Uuid7, #name: Uuid7 }
    })
    .unwrap_or_else(|e| panic!("`{allowed}` is outside the fence: {e}"));
  }
}

/// The check is on the EFFECTIVE name: a scoped rename would otherwise walk straight past it.
#[test]
fn refuses_a_rename_into_the_frameworks_namespace() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media_id)))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(key(rename = "__seq__"))] media_id: Uuid7,
    }
  })
  .unwrap_err();
  assert!(e.to_string().contains("framework's namespace"), "{e}");
}

/// A field that reaches no emitted column may be named anything — the fence guards COLUMNS, and a
/// `skip`ped field has none.
///
/// The subject moved with the participation law: it used to be any DATA field, which reached no
/// column because a column needed the per-field `persist` marker. Every data field is a column now,
/// so the fence reaches all of them and `skip` is the one way back out from under it — asserted
/// against `__value__`, which the fence refuses one line into the row.
#[test]
fn a_skipped_field_may_carry_a_reserved_shape() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(skip)] __value__: Vec<u8> }
  })
  .expect("`__value__` is not a column of any emitted type here");
  assert_eq!(columns(&m, DatabaseKind::Sqlite), ["id"]);
}

/// A rename is SCOPED: the key's columns become the record table's, the lineage's become the
/// degraded table's, and two tables may name a column differently.
#[test]
fn a_field_may_be_renamed_per_scope() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media_id, video_id)))]
    struct VideoTrack {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(lineage(rename = "media"))] media_id: Uuid7,
      #[ingraph(key(rename = "video"))] video_id: Uuid7,
    }
  })
  .expect("each scope names its own column");
  assert_eq!(
    m.key
      .columns()
      .map(|column| column.name.to_string())
      .collect::<Vec<_>>(),
    ["media_id", "video", "id"],
    "the key takes the `key` rename and leaves the `lineage` one alone"
  );
  assert_eq!(
    m.lineage
      .as_ref()
      .expect("a grandchild has a path")
      .path()
      .iter()
      .map(|column| column.name.to_string())
      .collect::<Vec<_>>(),
    ["media", "video_id"],
    "and the lineage takes the other"
  );
  assert_eq!(
    m.key
      .columns()
      .map(|column| column.source.to_string())
      .collect::<Vec<_>>(),
    ["media_id", "video_id", "id"],
    "both keep the record field they project, for the conversions"
  );
  assert_eq!(
    m.fields
      .iter()
      .map(|f| f.column.name.to_string())
      .collect::<Vec<_>>(),
    ["id", "media_id", "video_id"],
    "and the record keeps its own Rust names"
  );
}

/// The same name in both scopes is fine — they are different types, so nothing collides.
#[test]
fn one_name_may_be_used_in_both_scopes() {
  parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media_id)))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(key(rename = "media"), lineage(rename = "media"))] media_id: Uuid7,
    }
  })
  .expect("two types, one name each");
}

/// A scoped rename needs the scope to HAVE a column for the field. Unlike `copy`, these can never
/// gain a subject: a data column's rename will be its own scope once the persisted row is emitted.
#[test]
fn refuses_a_scoped_rename_with_no_subject() {
  for input in [
    syn::parse_quote! {
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(key(rename = "c"))] checksum: u64 }
    },
    syn::parse_quote! {
      #[ingraph(lineage(fields(media_id)))]
      struct S { #[ingraph(id, lineage(rename = "x"))] id: Uuid7, media_id: Uuid7 }
    },
    syn::parse_quote! {
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(lineage(rename = "c"))] checksum: u64 }
    },
  ] {
    let e = parse(&input).unwrap_err();
    assert!(e.to_string().contains("has none there"), "{e}");
    assert!(
      e.to_string().contains("persisted row"),
      "it names the future scope: {e}"
    );
  }
}

/// A BARE `rename` is the COLUMN's, in every database that does not override it — the field seat's
/// bare axis being storage, exactly as the container's is. The three scoped renames are unchanged.
#[test]
fn a_bare_field_rename_names_the_column_in_every_database() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, postgres)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, rename = "bitRate")] bit_rate: u64,
    }
  })
  .expect("the storage rename parses");

  for db in [DatabaseKind::Sqlite, DatabaseKind::Postgres] {
    assert_eq!(stored(&m, db, "bit_rate").name.external(), "bitRate");
  }
}

/// One field, one column name — a repeat is ambiguous exactly as every other repeated option is.
#[test]
fn refuses_a_repeated_field_rename() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, rename = "a", rename = "b")] bit_rate: u64,
    }
  });
  assert!(e.contains("`rename` is declared more than once"), "{e}");
}

/// Two columns of ONE emitted type cannot share a name. Across the two types they may.
#[test]
fn refuses_two_columns_of_one_type_resolving_to_one_name() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(lineage(fields(media_id, video_id)))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(key(rename = "same"))] media_id: Uuid7,
      #[ingraph(key(rename = "same"))] video_id: Uuid7,
    }
  })
  .unwrap_err();
  assert!(
    e.to_string().contains("would have two columns called"),
    "{e}"
  );
}

/// A column's name reaches an emitted METHOD through five derived shapes — `x`, `x_ref`,
/// `x_slice`, `set_x`, `with_x` — and nothing keeps them clear of each other or of the fixed
/// `new`. What the refusal buys is not a caught bug but a MOVED error: every one of these is
/// `E0592`, reported at `#[ingraph::record(…)]` with no mention of the column that caused it.
#[test]
fn refuses_a_column_whose_emitted_method_is_already_taken() {
  let cases: [(syn::DeriveInput, &str); 4] = [
    (
      syn::parse_quote! { #[ingraph(sqlite)] struct S { #[ingraph(id, copy)] new: Uuid7 } },
      "`SKey` would declare `new` twice",
    ),
    (
      syn::parse_quote! {
        #[ingraph(sqlite)]
        struct S { #[ingraph(id)] id: Uuid7, x: u64, #[ingraph(copy)] set_x: u64 }
      },
      "`S` would declare `set_x` twice",
    ),
    // No marker on either side: one column's SETTER is the other's BORROW.
    (
      syn::parse_quote! {
        #[ingraph(sqlite)]
        struct S { #[ingraph(id)] id: Uuid7, x_ref: u64, set_x: u64 }
      },
      "`S` would declare `set_x_ref` twice",
    ),
    // The rule is the EMITTER's, so it covers every type the emitter writes — here a row, under
    // the names `rename = "…"` gave its columns rather than the record's own.
    (
      syn::parse_quote! {
        #[ingraph(sqlite)]
        struct S {
          #[ingraph(id)] id: Uuid7,
          #[ingraph(scalar, rename = "a_ref", sqlite(copy))] b: u64,
          #[ingraph(scalar, rename = "a")] c: u64,
        }
      },
      "`SSqlite` would declare `a_ref` twice",
    ),
  ];
  for (declaration, taken) in cases {
    let e = parse(&declaration).unwrap_err();
    assert!(e.to_string().contains(taken), "{e}");
  }
}

/// A duplicate column NAME is ONE violation, not one per emitted method. Both families collide at
/// every member at once, so the method rule stays silent where the two sides name the same column
/// and lets the rule that was actually broken be the one reported.
#[test]
fn a_duplicate_column_name_is_reported_once() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media_id, video_id)))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(key(rename = "same"))] media_id: Uuid7,
      #[ingraph(key(rename = "same"))] video_id: Uuid7,
    }
  })
  .unwrap_err();
  assert_eq!(
    e.into_iter().count(),
    1,
    "the column rule, and no restatement of it"
  );
}

/// The refusal names BOTH sides, which is the whole of what the compiler's own message withholds:
/// which column, and what its method met.
#[test]
fn the_method_collision_names_the_column_on_each_side() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S { #[ingraph(id)] id: Uuid7, x: u64, #[ingraph(copy)] set_x: u64 }
  })
  .unwrap_err();
  let reported = e.to_string();
  assert!(reported.contains("the `x` column's setter"), "{reported}");
  assert!(
    reported.contains("the `set_x` column's value accessor"),
    "{reported}"
  );
}

/// The near misses, which are ordinary English field names and must go straight through.
/// Over-refusing is the failure mode this rule has, so the boundary is pinned from both sides.
///
/// `new` is among them twice. Unmarked, its accessors are `new_ref` / `set_new` / `with_new` and
/// the constructor is untouched — only the `copy` marker's by-value accessor takes the bare name.
/// And marked on a field the KEY does not carry, it lands on the record, which has no generated
/// constructor to collide with.
#[test]
fn accepts_columns_that_only_look_like_an_emitted_method() {
  let declarations: [syn::DeriveInput; 4] = [
    syn::parse_quote! {
      #[ingraph(sqlite)]
      struct S {
        #[ingraph(id)] id: Uuid7,
        new_thing: u64,
        set: u64,
        with: u64,
        x_reference: u64,
      }
    },
    syn::parse_quote! { #[ingraph(sqlite)] struct S { #[ingraph(id)] new: Uuid7 } },
    syn::parse_quote! {
      #[ingraph(sqlite)]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(copy)] new: u64 }
    },
    // A derived shape with nothing to derive it from: `set_x` alone, and `x` alone.
    syn::parse_quote! {
      #[ingraph(sqlite)]
      struct S { #[ingraph(id)] id: Uuid7, set_x: u64, y: u64 }
    },
  ];
  for declaration in declarations {
    parse(&declaration).unwrap_or_else(|e| panic!("a near miss is not a collision: {e}"));
  }
}

#[test]
fn refuses_a_repeated_scoped_rename() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media_id)))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(key(rename = "a", rename = "b"))] media_id: Uuid7,
    }
  })
  .unwrap_err();
  assert!(e.to_string().contains("declared more than once"), "{e}");
}

/// The projection markers say WHICH projection, and nothing about the type — which is how an
/// aliased `Vec` or `Option` reaches the right accessor at all.
#[test]
fn the_projection_markers_reach_the_model() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct Media {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(repeated)] files: Ids,
      #[ingraph(optional)] duration: MaybeDuration,
      checksum: u64,
    }
  })
  .expect("both markers are field-level");
  assert_eq!(field(&m, "files").column.project, Projection::Repeated);
  assert_eq!(field(&m, "duration").column.project, Projection::Optional);
  assert_eq!(
    field(&m, "checksum").column.project,
    Projection::Borrowed,
    "nothing is inferred — an unmarked field keeps the plain borrow"
  );
}

/// Each marker names a different way to hand a column out, and a column has one.
#[test]
fn refuses_two_projection_markers_on_one_field() {
  for input in [
    syn::parse_quote! { struct S { #[ingraph(id)] id: Uuid7, #[ingraph(repeated, optional)] a: T } },
    syn::parse_quote! { struct S { #[ingraph(id)] id: Uuid7, #[ingraph(copy, repeated)] a: T } },
    syn::parse_quote! { struct S { #[ingraph(id)] id: Uuid7, #[ingraph(copy, optional)] a: T } },
    syn::parse_quote! { struct S { #[ingraph(id)] id: Uuid7, #[ingraph(optional)] #[ingraph(copy)] a: T } },
  ] {
    let e = parse(&input).unwrap_err();
    assert!(
      e.to_string()
        .contains("each names a different way to hand the column out"),
      "{e}"
    );
  }
}

#[test]
fn refuses_a_repeated_projection_marker() {
  for marker in ["repeated", "optional"] {
    let name = syn::Ident::new(marker, proc_macro2::Span::call_site());
    let e = parse(&syn::parse_quote! {
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(#name, #name)] a: T }
    })
    .unwrap_err();
    assert!(e.to_string().contains("declared more than once"), "{e}");
  }
}

/// One database of a parsed model, by kind.
fn database(model: &RecordModel, kind: DatabaseKind) -> &DatabaseBackend {
  model
    .persist
    .as_ref()
    .unwrap_or_else(|| panic!("the record declares a `persist(…)` block"))
    .backends
    .iter()
    .find(|database| database.kind() == kind)
    .unwrap_or_else(|| panic!("`{}` is declared", kind.as_str()))
}

/// One column of one database, by the record field it projects.
fn stored<'a>(model: &'a RecordModel, kind: DatabaseKind, source: &str) -> &'a PersistColumn {
  database(model, kind)
    .columns()
    .iter()
    .find(|column| column.source == source)
    .unwrap_or_else(|| panic!("`{source}` is stored in {}", kind.as_str()))
}

/// The external names of one database's columns, in emission order.
fn columns(model: &RecordModel, kind: DatabaseKind) -> Vec<String> {
  database(model, kind)
    .columns()
    .iter()
    .map(|column| column.name.to_string())
    .collect()
}

/// The plan's own example declaration — every part of the grammar in one record, so the shape a
/// reader of the documentation writes is the shape under test.
fn declared() -> RecordModel {
  parse(&syn::parse_quote! {
    #[ingraph(
      lineage(fields(media_id, video_id)),
      table = "video_tracks",
      sqlite,
      postgres(schema = "public", row(rename = "VideoTrackRecord")),
      mongo(collection = "tracks"))]
    pub struct VideoTrack {
      #[ingraph(id)] id: Uuid7,
      media_id: Uuid7,
      video_id: Uuid7,

      #[ingraph(scalar,
        rename = "bitrate",
        sqlite(indexed),
        postgres(indexed, type = "BeU64", copy,
                 rename = "bit_rate_v2",
                 try_from = "path::to::try_from",
                 into     = "path::to::into"),
      )]
      bit_rate: u64,

      #[ingraph(scalar, optional)] stream_index: Option<u32>,
      #[ingraph(skip)] cached_probe: OnceCell<Probe>,
    }
  })
  .expect("the documented declaration parses")
}

/// The declared DATABASES are the storage selection — three blocks, three rows, in the order they
/// were written.
#[test]
fn the_declared_databases_are_the_rows_that_get_emitted() {
  let m = declared();
  let persist = m.persist.as_ref().expect("declared");
  assert_eq!(
    persist
      .backends
      .iter()
      .map(|database| (database.kind(), database.name().to_string()))
      .collect::<Vec<_>>(),
    [
      (DatabaseKind::Sqlite, "VideoTrackSqlite".to_owned()),
      (DatabaseKind::Postgres, "VideoTrackRecord".to_owned()),
      (DatabaseKind::Mongo, "VideoTrackMongo".to_owned()),
    ],
    "a bare block takes the suffix convention; a `rename` names the emitted STRUCT"
  );
  assert!(
    !persist
      .backends
      .iter()
      .any(|database| database.kind() == DatabaseKind::Mysql),
    "a database nobody declared emits nothing"
  );
}

/// Every field is persisted and `skip` is the ONE exit.
///
/// It used to claim the inverse — participation was a per-field `persist` marker, an unmarked field
/// reached no row, and the id and the lineage steps were among the unmarked. Inverting the default
/// moved four of this fixture's six fields into the row and left `cached_probe`, which now says so
/// in a word: the list below is the declaration order minus the skip, and the id leading it is what
/// gives every record a queryable row.
#[test]
fn every_unskipped_field_is_persisted() {
  let m = declared();
  for kind in [DatabaseKind::Sqlite, DatabaseKind::Postgres] {
    assert_eq!(
      database(&m, kind)
        .columns()
        .iter()
        .map(|column| column.source.to_string())
        .collect::<Vec<_>>(),
      ["id", "media_id", "video_id", "bit_rate", "stream_index"],
      "`cached_probe` wears `skip` and is the only field missing"
    );
  }
}

/// A common `rename` names the column in every database; a per-database one names it in that
/// database alone.
#[test]
fn a_column_takes_the_common_rename_unless_its_database_overrides_it() {
  let m = declared();
  assert_eq!(
    columns(&m, DatabaseKind::Sqlite),
    ["id", "media_id", "video_id", "bitrate", "stream_index"]
  );
  assert_eq!(
    columns(&m, DatabaseKind::Postgres),
    ["id", "media_id", "video_id", "bit_rate_v2", "stream_index"],
    "postgres names its own column and leaves the other alone"
  );
  assert_eq!(
    columns(&m, DatabaseKind::Mongo),
    ["id", "media_id", "video_id", "bitrate", "stream_index"]
  );
}

/// The common scope reaches a KEY field's column exactly as it reaches any other's: one `rename`,
/// the same name in every database.
///
/// What it does NOT reach is the key type. A `persist` rename names a DATABASE column, so the
/// record's own field and the key type's column keep their Rust names whatever the row calls them.
#[test]
fn a_key_field_may_take_a_common_rename() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(lineage(fields(media_id)), sqlite, postgres, mongo)]
    struct Clip {
      #[ingraph(id, rename = "clip")] id: Uuid7,
      #[ingraph(rename = "media")] media_id: Uuid7,
      #[ingraph(scalar)] bit_rate: u64,
    }
  })
  .expect("a common rename is one name for every database");
  for kind in [
    DatabaseKind::Sqlite,
    DatabaseKind::Postgres,
    DatabaseKind::Mongo,
  ] {
    assert_eq!(columns(&m, kind), ["clip", "media", "bit_rate"]);
  }
  assert_eq!(
    (m.key.id.name.to_string(), m.key.path[0].name.to_string()),
    ("id".to_owned(), "media_id".to_owned()),
    "the KEY type's columns are the `key` scope's, untouched by a `persist` rename"
  );
}

/// A key field with no `type` override is stored as the type it DECLARES, in every database: the
/// domain type reaches the row untouched, which is the default any column takes.
///
/// `bit_rate` is the data column beside them, overriding that default in postgres alone — so the two
/// halves read as one rule about `type` rather than as a rule about which fields may carry it.
#[test]
fn a_key_field_stores_the_type_it_declares() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(lineage(fields(media_id)), sqlite, postgres)]
    struct Clip {
      #[ingraph(id)] id: Uuid7,
       media_id: Uuid7,
      #[ingraph(scalar, postgres(type = "BeU64"))] bit_rate: u64,
    }
  })
  .expect("a key column stores the type its field declares");
  for source in ["id", "media_id"] {
    for kind in [DatabaseKind::Sqlite, DatabaseKind::Postgres] {
      let column = stored(&m, kind, source);
      assert_eq!(rendered_type(column.ty()), "Uuid7");
      assert!(
        column.stored.is_none(),
        "nothing was written, so nothing is recorded — `ty()` fell through to the domain type"
      );
    }
  }
  assert_eq!(
    rendered_type(stored(&m, DatabaseKind::Postgres, "bit_rate").ty()),
    "BeU64",
    "and a column that DID override one is stored as it asked"
  );
}

/// A key column is per database exactly as a data column is: each database's block names its own
/// column and stores its own type, on the id and on a lineage step alike.
///
/// The dialects are what make this ordinary rather than exotic — a name one engine reserves is legal
/// in the next, and `uuid` in postgres is a `BLOB` in sqlite — so a key column needs the two scopes
/// for the reason every other column does.
///
/// The last assertion is why the two scopes are independent: a key's columns are RUST fields
/// carrying the record's declared types, so the key type states no stored name and no stored type at
/// all. Both live in the row, one per database.
#[test]
fn a_key_field_takes_each_databases_own_name_and_stored_type() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(lineage(fields(media_id)), sqlite, postgres)]
    struct Clip {
      #[ingraph(id, sqlite(rename = "clip"), postgres(rename = "pk", type = "BeU128"))]
      id: Uuid7,
      #[ingraph(rename = "media", sqlite(type = "Vec<u8>"), postgres(rename = "media_uuid"))]
      media_id: Uuid7,
      #[ingraph(scalar)] bit_rate: u64,
    }
  })
  .expect("a key column is refined per database like any other");
  assert_eq!(
    columns(&m, DatabaseKind::Sqlite),
    ["clip", "media", "bit_rate"],
    "sqlite names the id its own way and takes the common rename for the lineage step"
  );
  assert_eq!(
    columns(&m, DatabaseKind::Postgres),
    ["pk", "media_uuid", "bit_rate"],
    "postgres names both of them its own way, overriding the common rename on the second"
  );
  assert_eq!(
    [
      rendered_type(stored(&m, DatabaseKind::Sqlite, "id").ty()),
      rendered_type(stored(&m, DatabaseKind::Postgres, "id").ty()),
      rendered_type(stored(&m, DatabaseKind::Sqlite, "media_id").ty()),
      rendered_type(stored(&m, DatabaseKind::Postgres, "media_id").ty()),
    ],
    ["Uuid7", "BeU128", "Vec<u8>", "Uuid7"],
    "and each row stores the type ITS database asked for, the domain type where none did"
  );
  assert_eq!(
    (
      m.key.id.name.to_string(),
      rendered_type(&m.key.id.ty),
      m.key.path[0].name.to_string(),
      rendered_type(&m.key.path[0].ty),
    ),
    (
      "id".to_owned(),
      "Uuid7".to_owned(),
      "media_id".to_owned(),
      "Uuid7".to_owned()
    ),
    "the KEY type is untouched by all four: its columns are the record's Rust fields, carrying the \
     types the record declared"
  );
}

/// `type` is per database: the same field is a `BeU64` in one row and its own type in the next.
#[test]
fn the_stored_type_is_the_type_override_or_the_domain_type() {
  let m = declared();
  assert_eq!(
    rendered_type(stored(&m, DatabaseKind::Postgres, "bit_rate").ty()),
    "BeU64"
  );
  assert_eq!(
    rendered_type(stored(&m, DatabaseKind::Sqlite, "bit_rate").ty()),
    "u64",
    "no override, so the row carries the domain type"
  );
  assert_eq!(
    rendered_type(&stored(&m, DatabaseKind::Postgres, "bit_rate").domain),
    "u64",
    "and the domain type is kept beside it, for the conversions"
  );
}

/// `indexed` and `copy` are each one database's claim about one column.
#[test]
fn indexed_and_copy_are_per_database() {
  let m = declared();
  assert!(stored(&m, DatabaseKind::Sqlite, "bit_rate").indexed);
  assert!(stored(&m, DatabaseKind::Postgres, "bit_rate").indexed);
  assert!(!stored(&m, DatabaseKind::Mongo, "bit_rate").indexed);
  assert!(
    stored(&m, DatabaseKind::Postgres, "bit_rate").copy,
    "the STORED type is `Copy`, which the domain field's own marker cannot imply"
  );
  assert!(!stored(&m, DatabaseKind::Sqlite, "bit_rate").copy);
}

/// `flatten` is ONE DATABASE's, so a field flattened in SQLite and left alone in Postgres is two
/// answers about one field — which is the whole reason the word moved into the block.
#[test]
fn flatten_is_one_databases_naming_decision() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, postgres)]
    struct Clip {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, sqlite(flatten))] rate: Timebase,
      #[ingraph(string)] title: String,
    }
  })
  .expect("a marked field parses");

  assert!(stored(&m, DatabaseKind::Sqlite, "rate").flatten);
  assert!(
    !stored(&m, DatabaseKind::Postgres, "rate").flatten,
    "the other database keeps the prefix"
  );
  assert!(
    !stored(&m, DatabaseKind::Sqlite, "title").flatten,
    "and the word is the field's, not the record's"
  );
}

/// The DIALECT-FREE `flatten` speaks to every database that has a prefix to drop, and each answers
/// with what it has — a SQL dialect drops the segment, and a document store mints nothing.
#[test]
fn the_dialect_free_flatten_reaches_every_sql_database() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, postgres, mongo)]
    struct Clip {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, flatten)] rate: Timebase,
      #[ingraph(string)] title: String,
    }
  })
  .expect("one word for every database parses");

  assert!(stored(&m, DatabaseKind::Sqlite, "rate").flatten);
  assert!(stored(&m, DatabaseKind::Postgres, "rate").flatten);
  assert!(
    !stored(&m, DatabaseKind::Mongo, "rate").flatten,
    "a document store has no prefix to drop, so one written word mints nothing there"
  );
  assert!(
    !stored(&m, DatabaseKind::Sqlite, "title").flatten,
    "and the word is the field's, not the record's"
  );
}

/// It is a LAYOUT and not a name, so a value or a block beside it is a rule with nothing to apply.
#[test]
fn the_dialect_free_flatten_is_a_bare_word() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct Clip {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, flatten = "yes")] rate: Timebase,
    }
  });
  assert!(e.contains("`flatten` is a BARE word"), "{e}");
}

/// MongoDB's block has no `flatten`, and the refusal teaches rather than reporting an unknown word:
/// its default IS the nested subdocument, so there is no prefix to drop.
#[test]
fn refuses_flatten_on_the_document_database() {
  let e = refused(syn::parse_quote! {
    #[ingraph(mongo)]
    struct Clip {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, mongo(flatten))] rate: Timebase,
    }
  });
  assert!(e.contains("has no columns"), "{e}");
  assert!(e.contains("nested subdocument"), "{e}");
}

/// A word says one thing about one column in one database, so declaring it twice is ambiguous
/// exactly as a repeated option is.
#[test]
fn refuses_a_repeated_flatten() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct Clip {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, sqlite(flatten, flatten))] rate: Timebase,
    }
  });
  assert!(e.contains("`flatten` is declared more than once"), "{e}");
}

/// Nullability follows the `optional` MARKER — never the field's spelled type, and never an
/// override, because there is none.
#[test]
fn nullability_follows_the_optional_marker() {
  let m = declared();
  for kind in [
    DatabaseKind::Sqlite,
    DatabaseKind::Postgres,
    DatabaseKind::Mongo,
  ] {
    assert!(
      stored(&m, kind, "stream_index").nullable,
      "`#[ingraph( optional)]`"
    );
    assert!(!stored(&m, kind, "bit_rate").nullable, "`` is NOT NULL");
  }
}

/// A `Option<_>` field WITHOUT the marker is not nullable: the macro sees tokens, so the marker is
/// the only thing that can say so.
#[test]
fn a_spelled_option_without_the_marker_is_not_nullable() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] cover: Option<Uuid7> }
  })
  .expect("an unmarked `Option<_>` is an ordinary column");
  assert!(
    !stored(&m, DatabaseKind::Sqlite, "cover").nullable,
    "the type's spelling says nothing — a type alias for `Option<_>` is the case that proves it"
  );
}

/// The conversions are settled into THREE states, one per direction. The SLOTS are the spellings —
/// `from`/`try_from` fill one, `into`/`try_into` the other — and the VERB RULE says which way each
/// runs: `from` builds the row (a write), `into` leaves it (a read).
#[test]
fn the_conversions_collapse_into_three_states() {
  let m = declared();
  let column = stored(&m, DatabaseKind::Postgres, "bit_rate");
  assert!(
    matches!(&column.from, Conversion::Fallible(leg) if rendered(&leg.path) == "path::to::try_from"
      && leg.escape.is_none()),
    "{:?}",
    column.from
  );
  assert!(
    matches!(&column.into, Conversion::Infallible(path) if rendered(path) == "path::to::into"),
    "{:?}",
    column.into
  );
  let plain = stored(&m, DatabaseKind::Sqlite, "bit_rate");
  assert_eq!(plain.from, Conversion::Default);
  assert_eq!(plain.into, Conversion::Default);
}

/// `try_from` without `type` is LEGAL: the same stored and domain type, with a fallible read —
/// validation, or an extra operation on the way in.
#[test]
fn a_fallible_conversion_needs_no_type_override() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, sqlite(try_from = "validate"))] bit_rate: u64,
    }
  })
  .expect("a fallible read of the same type is a validation, not a mistake");
  let column = stored(&m, DatabaseKind::Sqlite, "bit_rate");
  assert!(column.stored.is_none());
  assert!(column.from.fallible());
}

/// `table` is common and each database may override it in its own vocabulary.
#[test]
fn the_table_name_is_common_and_overridable() {
  let m = declared();
  let persist = m.persist.as_ref().expect("declared");
  assert_eq!(
    persist.table.as_ref().map(ToString::to_string),
    Some("video_tracks".to_owned())
  );
  assert_eq!(
    persist
      .table_of(database(&m, DatabaseKind::Sqlite))
      .map(ToString::to_string),
    Some("video_tracks".to_owned()),
    "a database that named none takes the common one"
  );
  assert_eq!(
    persist
      .table_of(database(&m, DatabaseKind::Mongo))
      .map(ToString::to_string),
    Some("tracks".to_owned()),
    "and `collection` is mongo's word for the same option"
  );
  assert_eq!(
    database(&m, DatabaseKind::Postgres).schema(),
    Some("public")
  );
}

/// A common `rename` names the projection as a whole — the base every row's suffix attaches to.
#[test]
fn a_common_rename_is_the_base_every_row_suffixes() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(rename = "Track", sqlite, postgres, mysql, mongo)]
    struct VideoTrack { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] bit_rate: u64 }
  })
  .expect("`rename` names the thing its block is about, at its level");
  assert_eq!(
    m.persist
      .expect("declared")
      .backends
      .iter()
      .map(|database| database.name().to_string())
      .collect::<Vec<_>>(),
    ["TrackSqlite", "TrackPostgres", "TrackMysql", "TrackMongo"],
    "sqlx's own spellings"
  );
}

/// An ENTITY is persisted nowhere — absence by the macro, no sentinel.
///
/// The claim used to be a `record`'s, made by omitting `persist(…)`: absence by omission. A record
/// IS rows now and the omission is refused, so the tier that made the claim is the one that got its
/// own word — the same declaration, the same key family and accessors, and no row anywhere.
#[test]
fn an_entity_is_persisted_nowhere() {
  let m = under(
    &syn::parse_quote! { struct S { #[ingraph(id)] id: Uuid7, checksum: u64 } },
    NodeKind::Entity,
  )
  .expect("a pure-compute node");
  assert!(m.persist.is_none());
}

/// A column name Rust cannot spell as a FIELD is ordinary — the field is mangled, the column is not.
#[test]
fn a_column_may_be_named_something_rust_cannot_spell() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, rename = "bitRate")] bit_rate: u64,
      #[ingraph(scalar, rename = "type")] kind: u32,
    }
  })
  .expect("`bitRate` and `type` are ordinary column names");
  let names: Vec<(String, String)> = database(&m, DatabaseKind::Sqlite)
    .columns()
    .iter()
    .map(|column| (column.name.to_string(), column.name.safe().to_string()))
    .collect();
  assert_eq!(
    names,
    [
      ("id".to_owned(), "id".to_owned()),
      ("bitRate".to_owned(), "bit_rate".to_owned()),
      ("type".to_owned(), "type_".to_owned()),
    ],
    "the mangling is the FIELD's: `bitRate` is folded to snake case and `type` gains an underscore"
  );
}

/// **The anti-drift device.** The wire rule is not a charset this crate chose, it is GraphQL's own
/// production — a Name is `[_A-Za-z][_0-9A-Za-z]*` — and the derive states it a second time because
/// nothing it can call states it for it.
///
/// `grammar` below is that production written out INDEPENDENTLY of the implementation — explicit
/// character ranges and a tail scan rather than the `is_ascii_*` helpers the predicate uses — so this
/// is two statements of one rule agreeing rather than a function compared with itself. The expected
/// verdict is asserted too, so a reference implementation that was itself wrong fails here rather
/// than agreeing its way past the test.
///
/// The interesting rows are the boundaries rather than the ordinary names: empty, digit-leading, `-`,
/// `.`, `$`, whitespace, non-ASCII, a bare underscore, and a name longer than any buffer either side
/// might have reached for.
#[test]
fn the_wire_name_rule_is_graphqls_name_grammar() {
  // GraphQL spec, `Name :: NameStart NameContinue*`, with `NameStart :: Letter | '_'` and
  // `NameContinue :: Letter | Digit | '_'`, over ASCII letters and digits only.
  fn grammar(name: &str) -> bool {
    let start = |c: char| matches!(c, 'a'..='z' | 'A'..='Z' | '_');
    let continues = |c: char| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '_');
    let mut chars = name.chars();
    match chars.next() {
      Some(first) if start(first) => chars.all(continues),
      _ => false,
    }
  }

  let long = "b".repeat(4096);
  let cases: Vec<(&str, bool)> = vec![
    ("bitRate", true),
    ("bit_rate", true),
    ("_", true),
    ("__typename", true),
    ("a1", true),
    ("Z9_", true),
    (long.as_str(), true),
    ("", false),
    ("9lives", false),
    ("0", false),
    ("bit-rate", false),
    ("-", false),
    ("bit rate", false),
    ("bit.rate", false),
    ("$where", false),
    ("a!b", false),
    ("a:b", false),
    ("débit", false),
    ("é", false),
    ("a\0", false),
    ("\"quoted\"", false),
  ];
  for (name, expected) in cases {
    assert_eq!(
      grammar(name),
      expected,
      "the grammar written out is wrong about {name:?}"
    );
    assert_eq!(
      crate::wire::is_graphql_name(name),
      grammar(name),
      "the derive's rule and GraphQL's Name grammar disagree about {name:?}"
    );
  }
}

/// A wire `rename` reaches the SDL, where GraphQL's grammar requires a Name. ONE refusal, not one per
/// position: a common `rename` sets both faces, and the grammar is one authority for the whole schema
/// rather than a rule each position applies separately.
#[test]
fn a_wire_name_the_sdl_grammar_forbids_is_refused_once() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(rename = "bit-rate"))] bit_rate: u64,
    }
  })
  .unwrap_err();
  let messages: Vec<String> = e.into_iter().map(|e| e.to_string()).collect();
  assert_eq!(
    messages.len(),
    1,
    "one name, one mistake, one refusal: {messages:?}"
  );
  assert!(
    messages[0].contains("`bit-rate` is not a GraphQL name"),
    "{messages:?}"
  );
  assert!(
    messages[0].contains("[_A-Za-z][_0-9A-Za-z]*"),
    "the message names the grammar: {messages:?}"
  );
}

/// **A `persist` rename does not move the wire name**, and this is what shows it. The field is renamed
/// for the STORE, which is where a name Rust can spell but GraphQL cannot is otherwise unremarkable;
/// the WIRE face still defaults to the field's OWN name, and no GraphQL schema can carry that. One
/// refusal, against the name the schema would have exposed.
#[test]
fn a_persist_rename_does_not_supply_the_wire_name() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, rename = "debit")] débit: u64,
    }
  })
  .unwrap_err();
  let messages: Vec<String> = e.into_iter().map(|e| e.to_string()).collect();
  assert_eq!(messages.len(), 1, "{messages:?}");
  assert!(
    messages[0].contains("`débit` is not a GraphQL name"),
    "the refusal names the field's own spelling, not the rename: {messages:?}"
  );
}

/// The two SCHEMA POSITIONS are named separately, so two bad names are two mistakes — the dedup is on
/// the NAME, not on the field.
#[test]
fn each_position_carries_its_own_wire_name() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(async_graphql(
        input(rename = "in-name"),
        output(rename = "out-name"),
      )))]
      bit_rate: u64,
    }
  })
  .unwrap_err();
  let messages: Vec<String> = e.into_iter().map(|e| e.to_string()).collect();
  assert_eq!(messages.len(), 2, "{messages:?}");
  assert!(
    messages.iter().any(|m| m.contains("`in-name`")),
    "{messages:?}"
  );
  assert!(
    messages.iter().any(|m| m.contains("`out-name`")),
    "{messages:?}"
  );
}

/// The rule is SCOPED to the wire face, exactly as the store rule is scoped to declared stores: a
/// field that is stored and not exposed answers to the stores alone. `bitRate` is the control — a name
/// both authorities admit.
#[test]
fn a_column_that_reaches_no_wire_face_answers_to_no_grammar() {
  parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, rename = "bitRate")] bit_rate: u64,
    }
  })
  .expect("a name every store holds, exposed on no wire face");

  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(rename = "9lives"))] bit_rate: u64,
    }
  });
  assert!(e.contains("`9lives` is not a GraphQL name"), "{e}");
}

// ---------------------------------------------------------------------------------------------
// The refusals. One test per row of the rule table, each asserting the sentence names the rule.
// ---------------------------------------------------------------------------------------------

/// The error a declaration produces, as one string.
fn refused(input: syn::DeriveInput) -> String {
  parse(&input).unwrap_err().to_string()
}

/// EVERY refusal a declaration produces. `refused` reads the first alone — which is all `Display` on
/// a combined [`syn::Error`] yields — so a rule that fires beside another is asserted through this.
fn refusals(input: syn::DeriveInput) -> Vec<String> {
  parse(&input)
    .unwrap_err()
    .into_iter()
    .map(|e| e.to_string())
    .collect()
}

/// Whether any of `messages` names `rule`.
fn names(messages: &[String], rule: &str) -> bool {
  messages.iter().any(|message| message.contains(rule))
}

/// `from` and `try_from` name the same direction, and a conversion either can fail or it cannot.
#[test]
fn refuses_both_spellings_of_one_conversion_direction() {
  for (plain, fallible) in [("from", "try_from"), ("into", "try_into")] {
    let plain = syn::Ident::new(plain, proc_macro2::Span::call_site());
    let fallible = syn::Ident::new(fallible, proc_macro2::Span::call_site());
    let e = refused(syn::parse_quote! {
      #[ingraph(sqlite)]
      struct S {
        #[ingraph(id)] id: Uuid7,
        #[ingraph(scalar, sqlite(#plain = "a", #fallible = "b"))] bit_rate: u64,
      }
    });
    assert!(e.contains("there is no third answer"), "{e}");
    assert!(
      e.contains(&plain.to_string()) && e.contains(&fallible.to_string()),
      "both spellings are named: {e}"
    );
  }
}

/// The same rule, for the conversion that describes the whole row.
#[test]
fn refuses_both_spellings_on_the_container_too() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite(from = "a", try_from = "b"))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] bit_rate: u64 }
  });
  assert!(e.contains("there is no third answer"), "{e}");
}

/// A field's block refines a column in a database the record stores it in — it cannot add one.
#[test]
fn refuses_a_field_block_for_an_undeclared_database() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, mongo)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, postgres(indexed))] bit_rate: u64,
    }
  });
  assert!(e.contains("not one of the databases"), "{e}");
  assert!(
    e.contains("`sqlite`, `mongo`"),
    "it names the declared set: {e}"
  );
}

/// A per-database option written in the common scope names the block it belongs in.
///
/// The COMMON SCOPE the rule is about is the FIELD's `persist(…)`, which is the only one left. A
/// record had one too — `persist(…)`'s own head-level scope — and the unwrap dissolved it into the
/// head, where `indexed` and `schema` are two words among every word a record does not take: they
/// reach the head's vocabulary sentence, which names the store words the two belong inside. Both
/// halves are asserted, because the pair is what shows the rule moved rather than went.
///
/// # `indexed` LEFT this list at the FIELD, and it left with a sharper sentence
///
/// The word is spoken at TWO seats now — one column's index inside a database's block, and a
/// COLLECTION's value-led access path bare on the field — so the field seat READS it rather than
/// letting it fall through to the sentence below, and a scalar reaches a redirect that also says why
/// the two seats differ. See [`refuses_the_access_word_on_a_field_with_no_elements`], which is this
/// test's other half. `unique` takes its place here, being a per-database word with no second seat;
/// the head-level arm below still carries `indexed`, that scope having none either.
#[test]
fn refuses_a_per_database_option_in_the_common_scope() {
  for input in [
    syn::parse_quote! {
      #[ingraph(sqlite)]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar, unique)] a: u64 }
    },
    syn::parse_quote! {
      #[ingraph(sqlite)]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar, type = "BeU64")] a: u64 }
    },
  ] {
    let e = refused(input);
    assert!(e.contains("is a PER-DATABASE option"), "{e}");
    assert!(
      e.contains("postgres("),
      "it names the shape it belongs in: {e}"
    );
  }

  for input in [
    syn::parse_quote! {
      #[ingraph(indexed, sqlite)]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
    },
    syn::parse_quote! {
      #[ingraph(schema = "public", sqlite)]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
    },
  ] {
    let e = refused(input);
    assert!(
      e.contains("unknown `ingraph` record attribute — a record takes its STORE WORDS bare"),
      "the head answers for the scope it absorbed: {e}"
    );
  }
}

/// A field's storage words on a record that names no store are answered at the RECORD.
///
/// The rule used to be the field's — a field's `persist` needed the record to declare somewhere to
/// store it, and the refusal read *declares no `persist(…)` block*. Every half of it moved. A record
/// that names no store is refused as a record now, before any field is read; the participation the
/// marker granted is the default; and the marker itself is retired, refused by its own name with
/// where its vocabulary went. So the two declarations earn two successors and neither is the
/// sentence they shared.
#[test]
fn refuses_a_field_persist_on_a_record_that_names_no_store() {
  let bare = refusals(syn::parse_quote! {
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar, persist)] a: u64 }
  });
  assert!(names(&bare, "`persist` is retired at a field"), "{bare:?}");
  assert!(names(&bare, "holds rows and names no store"), "{bare:?}");
  assert!(
    !names(&bare, "declares no `persist(…)` block"),
    "the block it would have named does not exist to be missing: {bare:?}"
  );

  let refining = refused(syn::parse_quote! {
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar, rename = "b")] a: u64 }
  });
  assert!(
    refining.contains("holds rows and names no store"),
    "a block that REFINES a column is answered wherever the columns were to have been: {refining}"
  );
}

/// A head that names no database holds rows and names no store.
///
/// It used to be `persist(…)`'s own emptiness rule — a block naming no database had nothing to emit,
/// and a record stored nowhere omitted the block rather than writing an empty one. The block is
/// gone, so its emptiness is simply the record naming no store, and both declarations below reach
/// the record's own refusal: the one that writes a common entry with no store word beside it, and
/// the one that writes the other.
#[test]
fn refuses_a_head_that_names_no_database() {
  for input in [
    syn::parse_quote! {
      #[ingraph(rename = "T")]
      struct S { #[ingraph(id)] id: Uuid7 }
    },
    syn::parse_quote! {
      #[ingraph(table = "s")]
      struct S { #[ingraph(id)] id: Uuid7 }
    },
  ] {
    let e = refused(input);
    assert!(e.contains("holds rows and names no store"), "{e}");
    assert!(
      e.contains("declare it an `entity`"),
      "and the sentence names the other exit: {e}"
    );
  }
}

/// **One block per database, and this is now the ONLY thing enforcing it.**
///
/// `Persist::backends` is a `Vec<DatabaseBackend>`, chosen so DECLARATION ORDER survives into the
/// emission — which an `Option` per backend could not do. The cost is that the model can HOLD two
/// sqlite backends where four `Option`s could not, so what was structural is now checked, and this
/// refusal is the whole of the check. Pinned separately from the other repeats for that reason, and
/// mutation-proven.
#[test]
fn refuses_a_repeated_database_block() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, sqlite)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });
  assert!(
    e.contains("`sqlite` is declared more than once — one block per database"),
    "the store words are the head's now, so the sentence names no block around them: {e}"
  );

  // And the FIRST one is kept, so the model a repeat leaves behind is still a settled one rather
  // than two backends of the same kind.
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, postgres, sqlite)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });
  assert!(m.is_err(), "the repeat is refused");
}

/// The same rule for a GraphQL backend, whose `Vec` carries the same tradeoff.
#[test]
fn refuses_a_repeated_graphql_backend_block() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, async_graphql))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });
  assert!(
    e.contains(
      "`async_graphql` is declared more than once in `graphql(…)` — one block per backend"
    ),
    "{e}"
  );
}

/// A repeated block and a repeated option are the existing rule, unchanged.
///
/// Two of the five rows moved with the shapes they were written on. `persist(…), persist(…)` at the
/// head was the repeated BLOCK, and there is no block to repeat — the head's own repeated store word
/// is what stands in its place; `persist, persist` on a field was the repeated MARKER, and the bare
/// word is gone — the repeated field-level BLOCK is what stands in its place, under the same
/// one-marker-one-field sentence.
#[test]
fn refuses_a_repeated_persist_block_or_option() {
  for input in [
    syn::parse_quote! {
      #[ingraph(sqlite, sqlite)]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
    },
    syn::parse_quote! {
      #[ingraph(table = "a", table = "b", sqlite)]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
    },
    syn::parse_quote! {
      #[ingraph(sqlite)]
      struct S {
        #[ingraph(id)] id: Uuid7,
        #[ingraph(scalar, rename = "a", rename = "b")] a: u64,
      }
    },
    syn::parse_quote! {
      #[ingraph(sqlite)]
      struct S {
        #[ingraph(id)] id: Uuid7,
        #[ingraph(scalar, sqlite(indexed, indexed))] a: u64,
      }
    },
  ] {
    let e = refused(input);
    assert!(e.contains("declared more than once"), "{e}");
  }
}

/// The framework's namespace is checked on the EFFECTIVE column name, per database.
#[test]
fn refuses_a_persist_column_inside_the_frameworks_namespace() {
  for input in [
    syn::parse_quote! {
      #[ingraph(sqlite)]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] __seq__: u64 }
    },
    syn::parse_quote! {
      #[ingraph(sqlite)]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar, rename = "__seq__")] a: u64 }
    },
    syn::parse_quote! {
      #[ingraph(sqlite, postgres)]
      struct S {
        #[ingraph(id)] id: Uuid7,
        #[ingraph(scalar, postgres(rename = "__seq__"))] a: u64,
      }
    },
  ] {
    let e = refused(input);
    assert!(e.contains("framework's namespace"), "{e}");
  }
}

/// **A declared TABLE inside either namespace is refused**, which is the noun an alias actually
/// competes with — the column fence predates the mint and reaches the wrong one on its own.
///
/// Both spellings of the knob: the common `table = "…"` and one database's override.
#[test]
fn refuses_a_table_inside_the_frameworks_namespace() {
  for input in [
    syn::parse_quote! {
      #[ingraph(table = "__ig_scene_0__", sqlite)]
      struct S { #[ingraph(id)] id: Uuid7 }
    },
    syn::parse_quote! {
      #[ingraph(sqlite(table = "__ignore"))]
      struct S { #[ingraph(id)] id: Uuid7 }
    },
    syn::parse_quote! {
      #[ingraph(mongo(collection = "__ig_shots"))]
      struct S { #[ingraph(id)] id: Uuid7 }
    },
  ] {
    let e = refused(input);
    assert!(e.contains("framework's namespace"), "{e}");
  }
}

/// **A name inside BOTH namespaces is refused ONCE**, under the older and more specific rule.
///
/// The two fences overlap by construction — every alias the framework mints ends `__` as well as
/// beginning `__ig` — so a check per fence would report one mistake twice and leave a reader
/// guessing which rule to act on.
#[test]
fn a_name_in_both_namespaces_is_refused_once() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] __ig_x__: u64 }
  });

  assert_eq!(e.matches("framework's namespace").count(), 1, "{e}");
  assert!(e.contains("`__` at both ends"), "{e}");
}

/// **The prefix the derive fences is the prefix the mint uses and the engine reserves.**
///
/// THREE crates hold that string, and none of them can hold it for the others: `ingraph-codegen`
/// mints under it, `ingraph` reserves it, and this crate refuses declarations inside it — while the
/// dependency edges run codegen → derive and (dev only) derive → ingraph. So this is the one context
/// that can see all three at once, and seeing them is the whole test.
#[test]
fn the_reserved_prefix_is_the_one_the_framework_mints() {
  assert_eq!(
    ingraph_codegen::alias::ALIAS_PREFIX,
    ingraph::comparison::sql::ALIAS_PREFIX,
    "the mint and the engine disagree about the reserved namespace",
  );
  assert!(
    crate::alias::Fence::default()
      .caught(ingraph_codegen::alias::ALIAS_PREFIX)
      .is_some(),
    "the mint writes `{}`, which the derive does not fence",
    ingraph_codegen::alias::ALIAS_PREFIX,
  );
}

/// **The knob is per DATABASE**, which is the whole reason it rides a database block: one override
/// and one default in the same declaration, each landing on its own row.
#[test]
fn each_database_mints_in_its_own_namespace() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite(alias(prefix = "__mine", depth = 16)), postgres)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  })
  .expect("each database answers for itself");

  let sqlite = &database(&m, DatabaseKind::Sqlite).storage().aliases;
  assert_eq!(sqlite.prefix_in(&EmissionPrefix::default()), "__mine");
  assert_eq!(sqlite.depth(), 16);

  let postgres = &database(&m, DatabaseKind::Postgres).storage().aliases;
  assert_eq!(postgres.prefix, None, "an absent prefix stays absent");
  assert_eq!(
    postgres.prefix_in(&EmissionPrefix::default()),
    ingraph_codegen::alias::ALIAS_PREFIX
  );
  assert_eq!(postgres.depth(), ingraph_codegen::alias::DEPTH_CEILING);
}

/// **Either knob alone is a legal block**, the other staying at the framework's answer.
#[test]
fn a_knob_written_alone_moves_only_itself() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite(alias(depth = 12)), postgres(alias(prefix = "__pg")))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  })
  .expect("both halves are optional");

  let sqlite = &database(&m, DatabaseKind::Sqlite).storage().aliases;
  assert_eq!(
    (sqlite.prefix_in(&EmissionPrefix::default()), sqlite.depth()),
    ("__ig", 12)
  );

  let postgres = &database(&m, DatabaseKind::Postgres).storage().aliases;
  assert_eq!(
    (
      postgres.prefix_in(&EmissionPrefix::default()),
      postgres.depth()
    ),
    ("__pg", ingraph_codegen::alias::DEPTH_CEILING)
  );
}

/// **The FENCE is the UNION of every declared prefix plus the default**, because a field is the
/// DOMAIN's and a prefix is one database's.
///
/// A record declaring `sqlite(alias(prefix = "__mine"))` beside a defaulting `postgres` stores each
/// field in both tables, so a column called `__mine_x` collides in the first and `__ig_x` in the
/// second — and neither collision is loud. Both are refused, and each names the prefix that caught
/// it.
///
/// The mutation this catches is a fence that still checks only the default: `__mine_x` would sail
/// through, and every existing fence pin — all of them about `__ig` — would still pass.
#[test]
fn the_fence_is_the_union_of_every_declared_prefix() {
  let declared = refused(syn::parse_quote! {
    #[ingraph(sqlite(alias(prefix = "__mine")), postgres)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] __mine_x: u64 }
  });
  assert!(declared.contains("names beginning `__mine`"), "{declared}");

  let defaulted = refused(syn::parse_quote! {
    #[ingraph(sqlite(alias(prefix = "__mine")), postgres)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] __ig_x: u64 }
  });
  assert!(defaulted.contains("names beginning `__ig`"), "{defaulted}");
}

/// **A record that overrode EVERY database hands the default namespace back**, which is the other
/// half of the union rule and the one a reader is likeliest to doubt.
///
/// Nothing over this record mints a name beginning `__ig` any more, so refusing one would be
/// reserving a namespace nobody is using — and `__ignore`, the accepted grab the default costs, is a
/// legal column again. The knob's own prefix takes its place.
#[test]
fn overriding_every_database_returns_the_default_namespace() {
  parse(&syn::parse_quote! {
    #[ingraph(
      sqlite(alias(prefix = "__mine")),
      postgres(alias(prefix = "__mine"))
    )]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] __ignore: u64 }
  })
  .expect("no database mints in `__ig`, so nothing reserves it");

  let e = refused(syn::parse_quote! {
    #[ingraph(
      sqlite(alias(prefix = "__mine")),
      postgres(alias(prefix = "__mine"))
    )]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] __mine_x: u64 }
  });
  assert!(e.contains("names beginning `__mine`"), "{e}");
}

/// **The fence reaches a declared TABLE too**, per database and under the union — a table is the
/// noun an alias actually competes with.
#[test]
fn the_union_fence_reaches_a_declared_table() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite(alias(prefix = "__mine"), table = "__mine_legacy"), postgres)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });

  assert!(e.contains("table `__mine_legacy`"), "{e}");
  assert!(e.contains("names beginning `__mine`"), "{e}");
}

/// **Every rule the mint states about a prefix or a depth is reported at the declaration**, each
/// naming what it is about.
///
/// The sentences are `ingraph_codegen::alias::refused`'s — one authority for what the mint can spend
/// — and what this crate adds is the span. So the assertions are about which rule fired rather than
/// about the wording, which its own tests pin.
#[test]
fn the_mints_rules_reach_the_declaration() {
  for (declaration, expected) in [
    (
      syn::parse_quote! {
        #[ingraph(sqlite(alias(depth = 0)))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
      "aliases nothing",
    ),
    (
      syn::parse_quote! {
        #[ingraph(sqlite(alias(prefix = "mine")))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
      "does not begin `__`",
    ),
    (
      syn::parse_quote! {
        #[ingraph(sqlite(alias(prefix = "__my-name")))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
      "which an alias cannot carry",
    ),
  ] {
    let e = refused(declaration);
    assert!(e.contains(expected), "{e}");
  }
}

/// **A block naming NEITHER knob is refused**, and the sentence names both.
///
/// It is the one shape that cannot mean anything: `alias()` written and left empty leaves both
/// halves at the framework's answers, which is what omitting the block already says. Accepting it
/// would be the accept-and-ignore this grammar refuses everywhere else.
#[test]
fn an_alias_block_naming_no_knob_is_refused() {
  for declaration in [
    syn::parse_quote! {
      #[ingraph(sqlite(alias()))]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
    },
    syn::parse_quote! {
      #[ingraph(sqlite(alias))]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
    },
  ] {
    let e = refused(declaration);
    assert!(e.contains("names neither knob"), "{e}");
    assert!(e.contains("`prefix = \"…\"` and `depth = N`"), "{e}");
  }
}

/// One block per database, and the entries inside it are read once each.
#[test]
fn refuses_a_repeated_alias_block_or_knob() {
  for (declaration, expected) in [
    (
      syn::parse_quote! {
        #[ingraph(sqlite(alias(prefix = "__a"), alias(prefix = "__b")))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
      "`alias(…)` is declared more than once",
    ),
    (
      syn::parse_quote! {
        #[ingraph(sqlite(alias(prefix = "__a", prefix = "__b")))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
      "`prefix` is declared more than once",
    ),
    (
      syn::parse_quote! {
        #[ingraph(sqlite(alias(depth = 9, depth = 10)))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
      "`depth` is declared more than once",
    ),
    (
      syn::parse_quote! {
        #[ingraph(sqlite(alias(namespace = "__a")))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
      "unknown entry in `alias(…)`",
    ),
  ] {
    let e = refused(declaration);
    assert!(e.contains(expected), "{e}");
  }
}

/// **The mint's default depth and the engine's are ONE number.**
///
/// `SqlQuery::ALIASES` is a SLICE, so a disagreement between the two is no longer an `E0308` inside
/// an expansion — which is exactly why the numbers need saying out loud. What they answer is the
/// declaration that named no `alias(depth = …)`, and each crate holds its own copy because the
/// dependency runs one way; a drift would leave the engine's own note describing a default no record
/// actually has, with nothing failing anywhere.
#[test]
fn the_mint_fills_the_depth_ceiling() {
  use ingraph_codegen::alias::{ALIAS_PREFIX, DEPTH_CEILING, aliases};

  assert_eq!(DEPTH_CEILING, ingraph::query::sql::DEPTH_CEILING);
  assert_eq!(
    aliases(ALIAS_PREFIX, "scene", DEPTH_CEILING).len(),
    ingraph::query::sql::DEPTH_CEILING,
  );
}

/// Two rows may not take one name, and no row may take a name the declaration already emits.
#[test]
fn refuses_two_rows_resolving_to_one_name() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite(row(rename = "Row")), postgres(row(rename = "Row")))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });
  assert!(e.contains("already the `sqlite` row"), "{e}");
  assert!(
    e.contains("the `postgres` row would be named `Row`"),
    "it names both: {e}"
  );
}

#[test]
fn refuses_a_row_named_after_a_type_the_record_already_emits() {
  for (rename, what) in [
    ("S", "already the record's own name"),
    ("SKey", "already the key type"),
    ("SLineage", "already the lineage type"),
  ] {
    let rename = syn::LitStr::new(rename, proc_macro2::Span::call_site());
    let e = refused(syn::parse_quote! {
      #[ingraph(lineage(fields(media_id)), sqlite(row(rename = #rename)))]
      struct S { #[ingraph(id)] id: Uuid7, media_id: Uuid7, #[ingraph(scalar)] a: u64 }
    });
    assert!(e.contains(what), "{e}");
  }
}

/// Two columns of ONE database cannot share a name. Across databases they may.
#[test]
fn refuses_two_columns_of_one_database_resolving_to_one_name() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, sqlite(rename = "same"))] a: u64,
      #[ingraph(scalar, sqlite(rename = "same"))] b: u64,
    }
  });
  assert!(e.contains("as one column called `same`"), "{e}");
  assert!(e.contains("`a`") && e.contains("`b`"), "it names both: {e}");
}

/// Two external names that MANGLE to one field are the same collision, one step later: the row
/// would not compile, and the error would name a field nobody wrote.
#[test]
fn refuses_two_columns_whose_rust_faces_collide() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, rename = "bitRate")] a: u64,
      #[ingraph(scalar, rename = "bit_rate")] b: u64,
    }
  });
  assert!(e.contains("as one column"), "{e}");
}

#[test]
fn one_column_name_may_be_used_in_two_databases() {
  parse(&syn::parse_quote! {
    #[ingraph(sqlite, postgres)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, sqlite(rename = "same"))] a: u64,
      #[ingraph(scalar, postgres(rename = "same"))] b: u64,
    }
  })
  .expect("two databases, one name each");
}

/// Nullability is not overridable, and the refusal names the marker that decides it.
#[test]
fn refuses_required_and_nullable_as_options() {
  for name in ["required", "nullable"] {
    let name = syn::Ident::new(name, proc_macro2::Span::call_site());
    for input in [
      syn::parse_quote! {
        #[ingraph(sqlite)]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar, #name)] a: u64 }
      },
      syn::parse_quote! {
        #[ingraph(sqlite)]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar, sqlite(#name))] a: u64 }
      },
      syn::parse_quote! {
        #[ingraph(sqlite(#name))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
    ] {
      let e = refused(input);
      assert!(e.contains("nullability follows the `optional`"), "{e}");
    }
  }
}

/// A conversion for the whole row REPLACES the field-wise body, so declaring both is ambiguous.
#[test]
fn refuses_a_container_conversion_beside_a_field_one() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite(from = "whole_row"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, sqlite(from = "one_column"))] a: u64,
    }
  });
  assert!(e.contains("replaces the field-wise body"), "{e}");
}

/// Per DIRECTION, though: a container `from` says nothing about how a column is written.
#[test]
fn a_container_conversion_leaves_the_other_direction_alone() {
  parse(&syn::parse_quote! {
    #[ingraph(sqlite(from = "whole_row"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, sqlite(into = "one_column"))] a: u64,
    }
  })
  .expect("the read is the container's and the write is field-wise — neither is ambiguous");
}

/// Each family keeps its own word for a table, and the other one is refused by name.
#[test]
fn refuses_the_other_familys_word_for_a_table() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite(collection = "x"))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });
  assert!(e.contains("`sqlite` names it `table"), "{e}");
  let e = refused(syn::parse_quote! {
    #[ingraph(mongo(table = "x"))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });
  assert!(e.contains("`mongo` names it `collection"), "{e}");
  let e = refused(syn::parse_quote! {
    #[ingraph(mongo(schema = "x"))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });
  assert!(e.contains("`schema` is a SQL notion"), "{e}");
}

/// An option is refused by the scope it landed in, in both directions: a column option in the
/// record's block names the field, and a table option in a field's block names the record.
#[test]
fn refuses_an_option_in_the_wrong_half_of_the_declaration() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite(indexed))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });
  assert!(e.contains("describes one COLUMN"), "{e}");
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar, sqlite(table = "x"))] a: u64 }
  });
  assert!(e.contains("names where the whole ROW lives"), "{e}");
}

/// Accumulation survives the `persist` grammar: three independent violations, one report.
///
/// The misplaced per-database option moved from the record's common scope to the FIELD's, that
/// being the common scope the unwrap left standing — the same rule against the same word, one level
/// down, so the four rules the pass has to report are still four.
///
/// The misplaced word is `unique` rather than `indexed` now, and only because `indexed` stopped
/// being misplaceable at this seat: it is a word the FIELD takes, for a collection, and a scalar
/// gets its own redirect instead of this list's sentence. Nothing about accumulation moved with it.
#[test]
fn independent_persist_violations_are_all_reported_in_one_pass() {
  let e = parse(&syn::parse_quote! {
    #[ingraph(sqlite(row(rename = "S")))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar,
        unique,
        mongo(indexed),
        sqlite(from = "a", try_from = "b"),
      )]
      bit_rate: u64,
    }
  })
  .unwrap_err();
  let messages: Vec<String> = e.into_iter().map(|e| e.to_string()).collect();
  assert_eq!(messages.len(), 4, "{messages:?}");
  for expected in [
    "is a PER-DATABASE option",
    "already the record's own name",
    "not one of the databases",
    "there is no third answer",
  ] {
    assert!(
      messages.iter().any(|m| m.contains(expected)),
      "{expected}: {messages:?}"
    );
  }
}

// ---------------------------------------------------------------------------------------------
// The wire face.
// ---------------------------------------------------------------------------------------------

/// The one declared backend of a parsed model.
fn wire(model: &RecordModel) -> &GraphqlBackend {
  &model
    .graphql
    .as_ref()
    .unwrap_or_else(|| panic!("the record declares a `graphql(…)` block"))
    .backends[0]
}

/// ONE published field of the one declared backend, named by the record field behind it.
///
/// By NAME rather than by position: every column a record holds is on the face now, so a positional
/// read would be an assertion about the DECLARATION ORDER where the test means one field.
fn wire_field<'a>(model: &'a RecordModel, source: &str) -> &'a GraphqlField {
  wire(model)
    .fields()
    .iter()
    .find(|field| field.source == source)
    .unwrap_or_else(|| panic!("`{source}` is published"))
}

/// The plan's own wire declaration.
fn exposed() -> RecordModel {
  parse(&syn::parse_quote! {
    #[ingraph(
      table = "video_tracks", sqlite, postgres(schema = "public"),
      graphql(async_graphql(attrs(complexity = 5))))]
    pub struct VideoTrack {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(rename = "bitRate",
                              async_graphql(output(attrs(desc = "bits per second")))))]
      bit_rate: u64,
      #[ingraph(enum)] codec: VideoCodec,
      cached_probe: OnceCell<Probe>,
    }
  })
  .expect("the documented wire declaration parses")
}

/// The SDL name is the EXTERNAL face and the Rust one the safe face — `bitRate` reaches a client,
/// `bit_rate` reaches the emitted struct.
#[test]
fn a_wire_field_carries_both_faces() {
  let m = exposed();
  let backend = wire(&m);
  assert_eq!(backend.kind(), GraphqlKind::AsyncGraphql);
  let graphql = m.graphql.as_ref().expect("declared");
  assert_eq!(graphql.output.to_string(), "VideoTrackGraphqlOutput");
  assert_eq!(graphql.key_output.to_string(), "VideoTrackKeyOutput");
  assert_eq!(
    graphql.filter.to_string(),
    "VideoTrackFilter",
    "ONE per record, not one per backend — a client must never see a schema that varies with a \
     deployment's storage choice"
  );
  assert_eq!(m.order_by.to_string(), "VideoTrackOrderBy");
  assert_eq!(
    backend
      .fields()
      .iter()
      .map(|field| (field.source.to_string(), field.output.name.to_string()))
      .collect::<Vec<_>>(),
    [
      ("id".to_owned(), "id".to_owned()),
      ("bit_rate".to_owned(), "bitRate".to_owned()),
      ("codec".to_owned(), "codec".to_owned()),
      ("cached_probe".to_owned(), "cached_probe".to_owned()),
    ],
    "EVERY column the record holds, and only the declared rename: a declaration naming a backend \
     publishes what it holds, and a field's word refines a place it already has"
  );
  assert_eq!(
    graphql.output.safe().to_string(),
    "VideoTrackGraphqlOutput",
    "one `rename` sets both faces, so a DEFAULTED type's schema name is its Rust name"
  );
}

/// `attrs(…)` is verbatim passthrough — the grammar never reads it, which is what stops it from
/// having to track a backend's feature set.
#[test]
fn attrs_reach_the_model_uninterpreted() {
  let m = exposed();
  let backend = wire(&m);
  assert_eq!(backend.attrs().to_string().replace(' ', ""), "complexity=5");
  assert_eq!(
    backend.fields()[1]
      .output
      .attrs
      .to_string()
      .replace(' ', ""),
    "desc=\"bitspersecond\"",
    "a description comes from here and from nowhere else"
  );
  assert!(backend.fields()[2].output.attrs.is_empty());
  assert!(
    backend.fields()[1].input.attrs.is_empty(),
    "an `output(attrs(…))` says nothing about the INPUT position — they are two schema positions"
  );
}

/// **A FIELD HAS ONE WIRE FORM, AND THE POSITIONS DIFFER ONLY IN NAME.**
///
/// The form used to be per POSITION, which made an input spelling differing from its output
/// spelling declarable — a schema a client reads twice. It is the field's own now, and it defaults
/// to the domain type where nothing declared one.
#[test]
fn a_field_has_one_wire_form_and_two_names() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar)] plain: u64,
      #[ingraph(enum, graphql(
        type = "String",
        async_graphql(input(rename = "codecFilter")),
      ))]
      codec: VideoCodec,
    }
  })
  .expect("the wire form is the field's own");
  let plain = wire_field(&m, "plain");
  let codec = wire_field(&m, "codec");
  assert_eq!(rendered_type(plain.wire_ty()), "u64");
  assert!(plain.wire.is_none(), "nothing declared one");
  assert_eq!(rendered_type(codec.wire_ty()), "String");
  assert_eq!(
    codec.input.name.to_string(),
    "codecFilter",
    "each position carries its own NAME — an input field and an output field are different schema \
     positions and may differ there"
  );
  assert_eq!(codec.output.name.to_string(), "codec");
}

/// **THE MOVED ENTRIES ARE NAMED REFUSALS, NOT UNKNOWN ONES.**
///
/// A position's `type` and its conversions each have a home now, and the sentence points at it: the
/// form is one per field, and a crossing has a ROW on one side of it, so it is one per database.
#[test]
fn a_position_refuses_the_entries_that_moved() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(async_graphql(output(type = "String"))))] a: u64,
    }
  });
  assert!(e.contains("`type` moved to the field's own block"), "{e}");

  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(async_graphql(output(from = "f"))))] a: u64,
    }
  });
  assert!(e.contains("gained a DATABASE"), "{e}");
}

/// **THE INPUT HALF ADMITS ONE CROSSING, AND THE OTHER TWO ARE REFUSED BY NAME.**
///
/// An order carries a column and a direction; a page carries a cursor whose values speak `persist`'s
/// own vocabulary. Neither has an OPERAND, which is the thing a conversion crosses.
#[test]
fn the_input_half_admits_only_the_comparison() {
  let refuse = |position: proc_macro2::TokenStream| {
    refused(syn::parse_quote! {
      #[ingraph(sqlite, graphql(async_graphql))]
      struct S {
        #[ingraph(id)] id: Uuid7,
        #[ingraph(scalar, graphql(input(#position)))] a: u64,
      }
    })
  };
  let e = refuse(quote::quote!(orderby(sqlite(into = "f"))));
  assert!(
    e.contains("an order carries a COLUMN and a DIRECTION"),
    "{e}"
  );
  let e = refuse(quote::quote!(pagination(sqlite(into = "f"))));
  assert!(e.contains("a cursor is an opaque round trip"), "{e}");
}

/// **A LEG'S ESCAPE NESTS INSIDE IT**, so a cross-leg reference is unspellable.
///
/// One block may carry both directions, and an escape written BESIDE them could not say which it
/// maps. Nested, there is no place to write one that names the other.
#[test]
fn a_fallible_leg_carries_its_escape_and_a_plain_one_cannot() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, sqlite(
        type = "i64",
        from = "widen",
        try_into(fn = "positive", error_with = "wrap"),
      ))]
      a: u64,
    }
  })
  .expect("the structured leg is a leg");
  let column = stored(&m, DatabaseKind::Sqlite, "a");
  assert!(
    matches!(&column.into, Conversion::Fallible(leg)
      if rendered(&leg.path) == "positive"
        && leg.escape.as_ref().is_some_and(|e| rendered(e) == "wrap")),
    "{:?}",
    column.into
  );

  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, sqlite(type = "i64", from(fn = "widen", error_with = "wrap")))]
      a: u64,
    }
  });
  assert!(e.contains("an INFALLIBLE leg cannot fail"), "{e}");

  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, sqlite(type = "i64", from = "widen", try_into(error_with = "wrap")))]
      a: u64,
    }
  });
  assert!(e.contains("maps an error and names no function"), "{e}");
}

/// **A CELL SITS AT THE PATH ITS CROSSING DOES, AND RIDES ITS LEG.**
///
/// Two axes, both the FIELD grammar's read one level up: a database name always opens a block, and
/// inside it the cell is written under the same leg word the field's own conversion is. So the
/// comparison's cell is `try_into` and not `try_from` — a wire value LEAVES for a row, which is
/// exactly what the field-level leg says.
///
/// `persist` carries TWO in one block, which is what makes the leg the identity rather than the
/// block: a row's read and its write are two impls with two callers, and a declaration may name them
/// differently without saying anything twice.
#[test]
fn the_error_cells_ride_their_own_crossings_block() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(
      sqlite(
        try_from(error = "crate::StoreRefusal"),
        try_into(error = "crate::RowRefusal"),
      ),
      graphql(
        output(sqlite(try_from(error = "crate::WireRefusal"))),
        input(comparison(sqlite(try_into(error = "crate::OperandRefusal")))),
        async_graphql,
        // The one fixture in this file whose id is STORED, so it is the one that answers a PAGE —
        // and a one-letter name has no plural the pluraliser can find, which the plural rule
        // refuses rather than publishing a page under the single's own name. The word is written
        // here so this test stays about its own subject.
        plural = "esses",
      )
    )]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar)] a: u64,
    }
  })
  .expect("every cell is at its own crossing's path");
  let cell = |crossing: ingraph_codegen::model::Crossing| {
    m.errors
      .iter()
      .find(|error| error.crossing == crossing && error.kind == DatabaseKind::Sqlite)
      .map(|error| rendered(&error.path))
  };
  use ingraph_codegen::model::Crossing;
  assert_eq!(
    cell(Crossing::PersistWrite).as_deref(),
    Some("crate::StoreRefusal")
  );
  assert_eq!(
    cell(Crossing::PersistRead).as_deref(),
    Some("crate::RowRefusal")
  );
  assert_eq!(
    cell(Crossing::Output).as_deref(),
    Some("crate::WireRefusal")
  );
  assert_eq!(
    cell(Crossing::Comparison).as_deref(),
    Some("crate::OperandRefusal")
  );
}

/// A wire field is populated from a stored column, and a published field HAS one.
///
/// This was a refusal — `graphql` with no `persist` beside it was exposed and stored nowhere, and
/// the sentence said to add the word. Participation is the default, so the state it refused is no
/// longer reachable by silence: the same declaration stores `a` and publishes it. The refusal itself
/// survives for the field that DECLARES its absence and publishes anyway, which
/// `skip_tests::stored_nowhere_and_published_is_refused_by_name` holds.
#[test]
fn a_published_field_is_stored_by_default() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  })
  .expect("`graphql` alone no longer leaves a field unstored");
  assert!(columns(&m, DatabaseKind::Sqlite).iter().any(|c| c == "a"));
  assert!(wire(&m).fields().iter().any(|field| field.source == "a"));
}

/// `persist` participation already implies both, so neither marker exists to write or to forget.
#[test]
fn refuses_filterable_and_orderable() {
  for name in ["filterable", "orderable"] {
    let name = syn::Ident::new(name, proc_macro2::Span::call_site());
    for input in [
      syn::parse_quote! {
        #[ingraph(sqlite, graphql(#name, async_graphql))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
      syn::parse_quote! {
        #[ingraph(sqlite, graphql(async_graphql(#name)))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
    ] {
      let e = refused(input);
      assert!(
        e.contains("filterable and orderable BECAUSE it is stored"),
        "{e}"
      );
    }
  }
}

/// A backend block for a backend the record did not declare mirrors the database rule.
#[test]
fn refuses_an_undeclared_backend_block() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(mystery(output(attrs(a)))))] a: u64,
    }
  });
  assert!(
    e.contains("unknown entry in `graphql(…)` on a field"),
    "{e}"
  );
}

/// A description is never leaked from a source comment: it comes from `attrs(desc = …)`, and the
/// refusal says so rather than reporting an unknown entry.
#[test]
fn refuses_a_description_option_and_names_the_passthrough() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(async_graphql(output(desc = "x"))))] a: u64,
    }
  });
  assert!(e.contains("passed through verbatim"), "{e}");
  assert!(e.contains("deliberately NOT published"), "{e}");
}

/// The wire block follows the storage block's rules: naming no backend is refused, and a field
/// marker without a record block is too.
#[test]
fn the_wire_block_follows_the_storage_blocks_rules() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(rename = "Wire"))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });
  assert!(
    e.contains("names the backends that render the record"),
    "{e}"
  );

  // `name` MOVED rather than vanished, and the refusal says where to.
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(name = "S", async_graphql))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });
  assert!(e.contains("`name` moved into `output(…)`"), "{e}");

  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar, graphql(rename = "a"))] a: u64 }
  });
  assert!(e.contains("declares no `graphql(…)` block"), "{e}");

  // Reachable only through a `rename`: the suffixes mean a defaulted wire name can never equal the
  // record's, so this is the one shape that can collide.
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(rename = "T", async_graphql))]
    struct TGraphqlOutput { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });
  assert!(e.contains("already the record's own name"), "{e}");
}

/// **TWO SDL NAMES WITH ONE RUST SPELLING ARE TWO FIELDS**, and the refusal they used to get went
/// with the violation that created it.
///
/// `bitRate` beside `bit_rate` is two perfectly good, DISTINCT GraphQL names. They collided only
/// because the filter's members were the MANGLED INPUT NAMES — a wire word standing on layer 1 —
/// and normalisation happened to collapse them onto one member. The members are the record's own
/// field names now, in both positions, so there is nothing left to collapse and the pair compiles.
///
/// It is the passing half that carries the argument, in `tests/columns.rs`'s shape: a fence that
/// refused the pair for the old reason would still refuse it, and only a compilation notices.
#[test]
fn two_schema_names_with_one_rust_spelling_are_two_fields() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(rename = "bitRate"))] a: u64,
      #[ingraph(scalar, graphql(rename = "bit_rate"))] b: u64,
    }
  })
  .expect("two distinct schema names are two schema fields");
  assert_eq!(
    (
      wire_field(&m, "a").input.name.to_string(),
      wire_field(&m, "b").input.name.to_string()
    ),
    ("bitRate".to_owned(), "bit_rate".to_owned()),
    "both wire names survive — layer 3 carries them and nothing normalises one onto the other"
  );
  assert_eq!(
    (
      wire_field(&m, "a").source.to_string(),
      wire_field(&m, "b").source.to_string()
    ),
    ("a".to_owned(), "b".to_owned()),
    "…standing on two members, which are the record's own field names"
  );
}

/// **TWO FIELDS CANNOT SHARE ONE WIRE NAME**, in either position — and the input half has to say so
/// EXPLICITLY now.
///
/// It used to be free: the filter's members were the mangled input names, so one wire name meant one
/// duplicate struct field and rustc reported it. That availability was the layer-1 violation's own
/// artifact. With the members distinct by construction there is no duplicate for the compiler to
/// find, and two fields renamed onto one name would reach a schema and render an input object with
/// the same field twice — so the front end names both fields and the wire name they share.
#[test]
fn refuses_two_wire_fields_sharing_one_input_name() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(async_graphql(input(rename = "bitRate"))))] a: u64,
      #[ingraph(scalar, graphql(async_graphql(input(rename = "bitRate"))))] b: u64,
    }
  });
  assert!(e.contains("one field called `bitRate`"), "{e}");
  assert!(e.contains("in its input"), "it names the POSITION: {e}");
  assert!(e.contains("`a`") && e.contains("`b`"), "it names both: {e}");
}

/// **THE TWO OUTPUT RENAME AXES ARE INDEPENDENT**, and one field writing both says two facts.
///
/// `rename` is what a CLIENT sees — LAYER 3 — and `field` is what the emitted object READS the field
/// through — LAYER 2. Neither reads the other, and each defaults on its own: an unrenamed schema
/// name is the field's, and an unnamed accessor is the field's too, which is how they can be equal
/// without being one knob.
///
/// Neither reaches LAYER 1. The emitted MEMBER is the domain name whatever is written here, which is
/// what `ingraph-codegen`'s emission tests pin from the other side.
#[test]
fn the_output_names_a_schema_field_and_a_rust_accessor_separately() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(string, graphql(async_graphql(output(rename = "titleText", field = "headline"))))]
      title: String,
      #[ingraph(scalar, graphql(async_graphql(output(rename = "bitRate"))))] bit_rate: u64,
      #[ingraph(scalar, graphql(async_graphql(output(field = "weight"))))] mass: u64,
    }
  })
  .expect("both axes, together and apart");
  let title = wire_field(&m, "title");
  assert_eq!(
    (title.output.name.to_string(), title.accessor().to_string()),
    ("titleText".to_owned(), "headline".to_owned()),
    "both written: the client sees one name and the object is read through another, and neither is \
     derived from the other"
  );
  let bit_rate = wire_field(&m, "bit_rate");
  assert_eq!(
    (
      bit_rate.output.name.to_string(),
      bit_rate.accessor().to_string()
    ),
    ("bitRate".to_owned(), "bit_rate".to_owned()),
    "a SCHEMA rename moves nothing in Rust — the accessor is the record field's own name"
  );
  let mass = wire_field(&m, "mass");
  assert_eq!(
    (mass.output.name.to_string(), mass.accessor().to_string()),
    ("mass".to_owned(), "weight".to_owned()),
    "and an ACCESSOR rename moves nothing a client sees"
  );
  assert_eq!(
    title.input.name.to_string(),
    "title",
    "`output(…)` is one schema position — the input face is untouched by either word"
  );
}

/// **A `field` THE FIELD-LEVEL `rename` COULD HAVE SUPPLIED IS NOT SUPPLIED BY IT.**
///
/// `graphql(rename = "…")` is one SCHEMA name written once for two positions. Letting the Rust
/// accessor fall back on it would re-couple the two axes at the one spelling that reaches both
/// faces.
#[test]
fn the_common_rename_is_a_schema_name_and_reaches_no_member() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(rename = "bitRate"))] a: u64,
    }
  })
  .expect("a field-level rename is a schema name");
  let field = wire_field(&m, "a");
  assert_eq!(field.output.name.to_string(), "bitRate");
  assert_eq!(field.input.name.to_string(), "bitRate");
  assert_eq!(field.accessor().to_string(), "a");
}

/// **TWO FIELDS CANNOT NAME ONE ACCESSOR**, and `field` is the only word that can ask them to: the
/// MEMBERS are the domain names, which are distinct by construction, so nothing else reaches this
/// rule.
///
/// It is not the emitted-method audit's, and the guard there is why: that rule steps over a pair
/// sharing an ORIGIN, and two fields renamed onto one accessor share one — the same column ident and
/// the same family member.
#[test]
fn refuses_two_fields_renamed_onto_one_output_accessor() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(async_graphql(output(field = "weight"))))] a: u64,
      #[ingraph(scalar, graphql(async_graphql(output(field = "weight"))))] b: u64,
    }
  });
  assert!(e.contains("through one accessor, `weight_ref`"), "{e}");
  assert!(e.contains("`a`") && e.contains("`b`"), "it names both: {e}");

  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar)] weight: u64,
      #[ingraph(scalar, graphql(async_graphql(output(field = "weight"))))] b: u64,
    }
  });
  assert!(
    e.contains("through one accessor, `weight_ref`"),
    "a rename onto another field's DEFAULT accessor is the same collision: {e}"
  );
}

/// **THE WORD IS AN IDENTIFIER**, where a schema name is a string: what it names is a Rust METHOD,
/// built from it by suffix, and no mangling stands in for one.
#[test]
fn refuses_an_output_accessor_that_is_not_an_identifier() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(async_graphql(output(field = "bit-rate"))))] a: u64,
    }
  });
  assert!(e.contains("as an identifier in a string literal"), "{e}");
}

/// **AN ACCESSOR RENAMED ONTO THE OBJECT'S ADDRESS IS THE EMITTED-METHOD RULE'S**, and it reaches
/// that rule only because the rule asks what the emission actually declares.
///
/// The audit reads LAYER 2 — the accessor — so `field = "key"` collides with the address accessor
/// the object always has. Read on the schema name instead it would see `a`, find nothing, and let
/// the expansion emit two `key_ref` methods: `E0592` inside the expansion, at a span the author
/// cannot edit, naming no column.
///
/// The two origins DIFFER here — one is the address member's, one a column's — which is what lets
/// this pair through the audit's own guard, where two fields renamed onto one accessor are stopped
/// by the `graphql(…)` pass instead.
#[test]
fn refuses_an_accessor_renamed_onto_the_objects_own_address() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(async_graphql(output(field = "key"))))] a: u64,
    }
  });
  assert!(e.contains("would declare `key_ref` twice"), "{e}");
  assert!(e.contains("the output object's own address member"), "{e}");
}

/// **THE WORD BELONGS TO ONE POSITION AND TO ONE BLOCK**, and each wrong home is named rather than
/// swept into "unknown entry": the input face has no second ident to move, and the field's own
/// `output(…)` is the row-to-wire CROSSING.
#[test]
fn the_member_word_is_refused_where_nothing_would_read_it() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(async_graphql(input(field = "weight"))))] a: u64,
    }
  });
  assert!(e.contains("names the OUTPUT object's accessor"), "{e}");

  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(output(field = "weight")))] a: u64,
    }
  });
  assert!(e.contains("this block is the row-to-wire CROSSING"), "{e}");

  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(async_graphql(output(field = "a", field = "b"))))] a: u64,
    }
  });
  assert!(e.contains("one member, one name"), "{e}");
}

/// **THE OUTPUT POSITION COLLIDES ON THE SCHEMA NAME AND ON NOTHING ELSE.**
///
/// Two fields cannot share one SDL name — that is the schema's own rule and it did not move. What
/// moved is everything below it: the struct members are the record's field names, so the mangling
/// question the input half still asks has no answer to give here.
#[test]
fn the_output_position_collides_on_the_schema_name_alone() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(async_graphql(output(rename = "same"))))] a: u64,
      #[ingraph(scalar, graphql(async_graphql(output(rename = "same"))))] b: u64,
    }
  });
  assert!(e.contains("in its output"), "{e}");
  assert!(e.contains("one field called `same`"), "{e}");

  parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(async_graphql(output(rename = "bitRate"))))] a: u64,
      #[ingraph(scalar, graphql(async_graphql(output(rename = "bit_rate"))))] b: u64,
    }
  })
  .expect("two distinct schema names on two distinct record fields");
}

/// The external check is still its own rule: one SDL name twice is refused whatever the mangling.
#[test]
fn refuses_two_wire_fields_sharing_one_schema_name() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(rename = "same"))] a: u64,
      #[ingraph(scalar, graphql(rename = "same"))] b: u64,
    }
  });
  assert!(e.contains("one field called `same`"), "{e}");
  assert!(
    !e.contains("two schema names with one Rust spelling"),
    "sharing an SDL name and colliding only after normalisation are different mistakes, and this \
     is the first: {e}"
  );
}

/// The INPUT position is checked on its own terms — a collision there is a collision even when the
/// outputs are distinct.
#[test]
fn refuses_a_collision_in_the_input_position_alone() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, graphql(async_graphql(input(rename = "same"), output(rename = "a"))))] a: u64,
      #[ingraph(scalar, graphql(async_graphql(input(rename = "same"), output(rename = "b"))))] b: u64,
    }
  });
  assert!(e.contains("in its input"), "{e}");
}

/// A camelCase wire name reaches the model with BOTH faces: snake_case for Rust, verbatim for SDL.
#[test]
fn a_camel_case_wire_name_keeps_both_faces() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar, graphql(rename = "bitRate"))] a: u64 }
  })
  .expect("a camelCase schema name is ordinary");
  let field = wire_field(&m, "a");
  assert_eq!(
    field.output.name.to_string(),
    "bitRate",
    "what a client sees"
  );
  assert_eq!(
    field.output.name.safe().to_string(),
    "bit_rate",
    "and what the emitted struct is allowed to call it"
  );
}

/// The interpretation one field declared, as a comparison can read it: the word for one of the
/// framework's own, the path as written for anything else.
///
/// Read off the RECORD's fields, which is where a label lives — so a column stored and not exposed
/// answers here exactly as an exposed one does.
fn spelled_marker(model: &RecordModel, source: &str) -> Option<String> {
  match declared_marker(model, source)? {
    Marker::Framework(marker) => Some(marker.label.as_str().to_owned()),
    Marker::Path(path) => Some(rendered(path)),
  }
}

/// The whole marker one field declared.
fn declared_marker<'a>(model: &'a RecordModel, source: &str) -> Option<&'a Marker> {
  model
    .fields
    .iter()
    .find(|field| field.column.source == source)
    .unwrap_or_else(|| panic!("`{source}` is a field of the record"))
    .marker
    .as_ref()
}

/// The spelling a field's own word replaces is REFUSED, and the refusal says what to write.
///
/// A field is one migration away from compiling, so the sentence names the word rather than only
/// the rule: the word `marker` carried is the word the label keeps, and a collection word is told
/// that it now carries its element.
#[test]
fn refuses_the_older_spelling_and_names_the_word_to_write() {
  for (written, expected) in [
    (quote::quote!(marker = duration), "write `duration`"),
    (
      quote::quote!(marker = set),
      "write `set(<the element's own word>)`",
    ),
    (
      quote::quote!(marker = "their::RollMarker"),
      "write `label = \"their::RollMarker\"`",
    ),
  ] {
    let e = refused(syn::parse_quote! {
      #[ingraph(sqlite, graphql(async_graphql))]
      struct S {
        #[ingraph(id)] id: Uuid7,
        #[ingraph( graphql(#written))] a: Vec<String>,
      }
    });
    assert!(e.contains("`marker` is not an option"), "{e}");
    assert!(
      e.contains(expected),
      "{written} migrates to {expected}: {e}"
    );
  }
}

/// A value this grammar cannot read has no specific word to offer, so the refusal offers the
/// vocabulary — the same table every other label sentence is generated from.
#[test]
fn the_older_spelling_carrying_an_unreadable_value_is_offered_the_words() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(list(string), graphql(marker = 3))] a: Vec<String>,
    }
  });
  assert!(e.contains("`marker` is not an option"), "{e}");
  for label in Label::ALL {
    assert!(e.contains(&format!("`{}`", label.as_str())), "{e}");
  }
  assert!(e.contains("`label = \"a::marker::Path\"`"), "{e}");
}

/// What a wire field's block takes, in the sentence a misspelling gets: a rename and the backends.
#[test]
fn the_wire_fields_entry_list_names_what_the_block_takes() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph( graphql(markers = set))] a: Vec<String>,
    }
  });
  assert!(
    e.contains("unknown entry in `graphql(…)` on a field"),
    "{e}"
  );
  assert!(e.contains("`rename = \"…\"`"), "{e}");
  assert!(e.contains("async_graphql"), "{e}");
}

/// The ELEMENT word a field's label named, for a comparison — [`spelled_marker`]'s twin one level in.
fn spelled_element(model: &RecordModel, source: &str) -> Option<String> {
  match declared_marker(model, source)? {
    Marker::Framework(marker) => marker.element.map(|label| label.as_str().to_owned()),
    Marker::Path(_) => None,
  }
}

/// The field speaks its own family, at the TOP level and bare — the grammar this arc opens with.
#[test]
fn a_field_writes_its_own_family_word() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(duration)] length: SignedDuration,
      #[ingraph(bytes)] checksum: Vec<u8>,
    }
  })
  .expect("a field names its own family, bare and at the top level");
  assert_eq!(spelled_marker(&m, "length").as_deref(), Some("duration"));
  assert_eq!(spelled_marker(&m, "checksum").as_deref(), Some("bytes"));
}

/// Every VALUE word is writable bare, off the same table the older spelling reads.
///
/// The two collection words are absent here and not forgotten: they take an element, and
/// [`a_collection_label_names_its_element`] is where they are covered.
#[test]
fn every_value_word_is_written_bare() {
  for label in Label::ALL.into_iter().filter(|label| !label.collection()) {
    let word = syn::Ident::new(label.as_str(), proc_macro2::Span::call_site());
    let m = parse(&syn::parse_quote! {
      #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
      struct S {
        #[ingraph(id)] id: Uuid7,
        #[ingraph(#word)] a: Vec<String>,
      }
    })
    .unwrap_or_else(|e| panic!("`{}` is a word this grammar names: {e}", label.as_str()));
    assert_eq!(spelled_marker(&m, "a").as_deref(), Some(label.as_str()));
  }
}

/// The keyword word is written bare, and the escape reaches the same row.
///
/// `enum` is a Rust keyword and reaches the field's own entry list as a token — `syn`'s meta parser
/// reads an entry's name with `Ident::parse_any`, so the ruled word arrives; `unraw` is what makes
/// `r#enum` the same word rather than an unknown one.
#[test]
fn the_keyword_word_is_written_bare_and_escaped() {
  for spelled in [
    syn::Ident::new("enum", proc_macro2::Span::call_site()),
    syn::Ident::new_raw("enum", proc_macro2::Span::call_site()),
  ] {
    let m = parse(&syn::parse_quote! {
      #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
      struct S {
        #[ingraph(id)] id: Uuid7,
        #[ingraph(#spelled)] grade: Grade,
      }
    })
    .unwrap_or_else(|e| panic!("`{spelled}` is a spelling of a word this grammar names: {e}"));
    assert_eq!(spelled_marker(&m, "grade").as_deref(), Some("enum"));
  }
}

/// FULL NESTING: a collection names the element's own family inside it, and both halves survive.
#[test]
fn a_collection_label_names_its_element() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(list(string))] speakers: Vec<String>,
      #[ingraph(set(scalar))] waveform: Vec<u8>,
      // The THIRD collection word, whose element is read exactly as the other two read theirs: the
      // narrowing is about what the COLLECTION publishes, and a member is still asked in its own
      // vocabulary.
      #[ingraph(quantified(scalar))] scores: Vec<u64>,
    }
  })
  .expect("a collection label names its element");
  assert_eq!(spelled_marker(&m, "speakers").as_deref(), Some("list"));
  assert_eq!(spelled_element(&m, "speakers").as_deref(), Some("string"));
  assert_eq!(spelled_marker(&m, "waveform").as_deref(), Some("set"));
  assert_eq!(spelled_element(&m, "waveform").as_deref(), Some("scalar"));
  assert_eq!(spelled_marker(&m, "scores").as_deref(), Some("quantified"));
  assert_eq!(spelled_element(&m, "scores").as_deref(), Some("scalar"));
}

/// `label = "…"` is the general form every word is short for — the FIELD's escape.
#[test]
fn the_custom_escape_is_written_at_the_field() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(label = "their::RollMarker")] roll: Roll<Tag>,
    }
  })
  .expect("a path in a string literal is the field's escape");
  assert_eq!(
    spelled_marker(&m, "roll").as_deref(),
    Some("their::RollMarker"),
    "carried verbatim — the emitter applies the field type to it"
  );
  assert_eq!(
    spelled_element(&m, "roll"),
    None,
    "a path has no element word; its family is a fact about its trait impls"
  );
}

/// **A label is an OVERRIDE**, and the two cells the macro still answers for are the two it can.
///
/// It used to be MANDATORY, on every field carrying a face, and the refusal recited the vocabulary
/// it was asking for. Its subject was the set of fields wearing `persist` — which is every data
/// field a record has now — so the rule would have demanded a word on all of them, and the word it
/// demanded is one the TYPE already answers: an unlabelled column resolves through
/// `<T as DefaultMarker>::Marker`, and a type with no row there is an `E0277` naming that type,
/// which is a better report than a macro error naming a field.
///
/// Two cells stay, and only two, because only these are things a declaration alone can say. A
/// KEY-SIDE column's vocabulary is the sealed `Id` trait, so it writes no label and a label on it is
/// refused; and `sortable` orders a COLLECTION, which no macro holding tokens can read off
/// a type. Both are asserted here, in the seat the mandatory rule used to occupy.
#[test]
fn the_two_label_rules_the_macro_still_answers_for() {
  let key_side = refusals(syn::parse_quote! {
    #[ingraph(sqlite, lineage(fields(media_id)), graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id, scalar)] id: Uuid7,
      #[ingraph(list(string))] media_id: Uuid7,
    }
  });
  for field in [
    "`id` is a key-side column",
    "`media_id` is a key-side column",
  ] {
    assert!(
      names(&key_side, field),
      "the id and every lineage step: {key_side:?}"
    );
  }
  assert!(
    names(&key_side, "a key's vocabulary is the sealed `Id` trait"),
    "{key_side:?}"
  );

  let unorderable = refusals(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(sortable)] lines: Vec<String>,
    }
  });
  assert!(
    names(&unorderable, "`sortable` orders a COLLECTION"),
    "the one cell a declaration alone can fill: {unorderable:?}"
  );

  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
       lines: Vec<String>,
    }
  })
  .expect("an unlabelled column is read through its type's own marker");
  assert_eq!(spelled_marker(&m, "lines"), None);
}

/// A field carrying no WORD carries no marker, and nothing asks it for one.
///
/// The claim used to rest on absence: a field with neither face reached no column, so a word about a
/// reading nothing reaches would have been a word about nothing. `scratch` IS a column now —
/// participation is the default — and the conclusion survives the loss of its premise, because the
/// rule that would have asked went with it: an unlabelled column is read through
/// `<T as DefaultMarker>::Marker`, and the model carries no marker of its own for it.
#[test]
fn a_field_with_no_label_carries_no_marker() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(string)] title: String,
      scratch: Vec<String>,
    }
  })
  .expect("a field declaring nothing is a plain Rust field with a column");
  assert_eq!(spelled_marker(&m, "scratch"), None);
  assert!(
    columns(&m, DatabaseKind::Sqlite)
      .iter()
      .any(|c| c == "scratch")
  );
}

/// A KEY-SIDE column is exempt, and it is the one exemption: its admission vocabulary is the sealed
/// `Id` trait, which is a stronger statement than any family word. So `id` and every lineage step
/// carry a face and no label, and the record parses.
#[test]
fn a_key_side_column_carries_a_face_and_no_label() {
  parse(&syn::parse_quote! {
    #[ingraph(lineage(fields(media_id)), sqlite, graphql(async_graphql))]
    struct Clip {
      #[ingraph(id)] id: Uuid7,
       media_id: Uuid7,
      #[ingraph(scalar)] bit_rate: u64,
    }
  })
  .expect("a key column's vocabulary is the sealed `Id`, so it writes no word");
}

/// A collection word written BARE is refused, and the refusal names the nesting rule.
#[test]
fn refuses_a_collection_with_no_element_label() {
  for word in ["list", "set", "quantified"] {
    let spelled = syn::Ident::new(word, proc_macro2::Span::call_site());
    let e = refused(syn::parse_quote! {
      #[ingraph(sqlite, graphql(async_graphql))]
      struct S {
        #[ingraph(id)] id: Uuid7,
        #[ingraph(#spelled)] a: Vec<String>,
      }
    });
    assert!(e.contains(&format!("`{word}` names a COLLECTION")), "{e}");
    assert!(e.contains("Every level of a label names its family"), "{e}");
  }
}

/// A collection of collections is refused, and the refusal is the MEASUREMENT rather than a taste.
///
/// The tree is read WHOLE first: `list(list(scalar))` is three levels the parser builds and then
/// declines, which is what lets one sentence answer the whole shape instead of a parse error
/// landing on the second `list`.
#[test]
fn refuses_a_collection_of_collections() {
  for nested in [
    quote::quote!(list(list(scalar))),
    quote::quote!(list(set)),
    quote::quote!(set(list(string))),
  ] {
    let all = refusals(syn::parse_quote! {
      #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
      struct S {
        #[ingraph(id)] id: Uuid7,
        #[ingraph(#nested)] a: Vec<Vec<String>>,
      }
    });
    assert!(
      names(&all, "no backend carries a collection of collections"),
      "{nested}: {all:?}"
    );
    assert_eq!(
      all.len(),
      1,
      "one mistake, one sentence — the element's own complaint is not the one that answers: {all:?}"
    );
  }
}

/// `map` is RESERVED with the family, so the word is answered rather than treated as a misspelling.
#[test]
fn refuses_the_reserved_map_word() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(map(string, scalar))] a: BTreeMap<String, i64>,
    }
  });
  assert!(e.contains("`map` is RESERVED with the map family"), "{e}");
}

/// An ELEMENT-level custom marker is reserved, and the refusal says where the escape does live.
#[test]
fn refuses_an_element_level_custom_marker() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(list(label = "their::RollMarker"))] a: Vec<Roll<Tag>>,
    }
  });
  assert!(
    e.contains("an element-level custom marker is RESERVED"),
    "{e}"
  );
  assert!(e.contains("is the FIELD's escape"), "{e}");
}

/// A VALUE family carrying an element is refused: a value has no elements to name.
#[test]
fn refuses_an_element_label_on_a_value_family() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(string(scalar))] a: String,
    }
  });
  assert!(e.contains("`string` names a VALUE family"), "{e}");
}

/// **A collection column naming its ELEMENT's stored type owes the crossing in both directions**,
/// and the refusal names the column, the database and the verbs that are missing.
///
/// The row holds the LIST of elements where `type` names one, so the two shapes differ by a `Vec`
/// and nothing infers the step between them. Half-declared, it used to compile as far as the
/// emission and land there as `E0308: expected Vec<T>, found T` at the `#[ingraph::record(…)]`, naming
/// no column.
///
/// Both shapes are asserted, because the sentence differs in one place: neither verb lists both
/// spellings and reads `are`, and one verb lists the one that is missing and reads `is`.
#[test]
fn refuses_a_half_declared_collection_crossing() {
  let neither = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(list(string), sqlite(type = "String"))] a: Vec<String>,
    }
  });
  assert!(
    neither.contains("`a` is a COLLECTION and `sqlite` stores its ELEMENTS"),
    "{neither}"
  );
  assert!(
    neither.contains("`from`/`try_from` and `into`/`try_into` are missing"),
    "{neither}"
  );

  let half = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(set(string), sqlite(type = "String", from = "w"))] a: Vec<String>,
    }
  });
  assert!(half.contains("`into`/`try_into` is missing"), "{half}");
}

/// **`edge` is Postgres's word and nobody else's**, because Postgres is the only dialect with two
/// usable strategies to pick between.
///
/// The other three are refused where the word is written, each with the clause naming what decides
/// instead — the shape `nullable` is refused in, and for its reason: a tolerated no-op reads as a
/// choice that was made.
#[test]
fn refuses_a_storage_strategy_where_the_dialect_has_none_to_choose() {
  for (db, instead) in [
    (
      "sqlite",
      "every collection it stores is already an edge table",
    ),
    (
      "mysql",
      "every collection it stores is already an edge table",
    ),
    ("mongo", "a document holds its own array"),
  ] {
    let spelled = syn::Ident::new(db, proc_macro2::Span::call_site());
    let e = refused(syn::parse_quote! {
      #[ingraph(sqlite, mysql, mongo)]
      struct S {
        #[ingraph(id)] id: Uuid7,
        #[ingraph(list(string), #spelled(edge))] a: Vec<String>,
      }
    });
    assert!(
      e.contains(&format!(
        "`edge` names a storage STRATEGY and `{db}` has none to choose"
      )),
      "{e}"
    );
    assert!(e.contains(instead), "{e}");
  }

  assert!(
    parse(&syn::parse_quote! {
      #[ingraph(postgres)]
      struct S {
        #[ingraph(id)] id: Uuid7,
        #[ingraph(list(string), postgres(edge, type = "String", from = "w", into = "r"))]
        a: Vec<String>,
      }
    })
    .is_ok(),
    "and the one dialect with a choice takes the word"
  );
}

/// **`edge` names how a COLLECTION is stored**, so a column holding one value has no strategy for it
/// to select — refused at parse, because the collection word is on the same field and the derive can
/// therefore tell.
#[test]
fn refuses_a_storage_strategy_on_a_column_that_is_not_a_collection() {
  let e = refused(syn::parse_quote! {
    #[ingraph(postgres)]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(string, postgres(edge))] a: String,
    }
  });
  assert!(
    e.contains("`a` is not a COLLECTION and `edge` names how one is STORED"),
    "{e}"
  );
}

/// **The rule is triggered by `type`, and that is what keeps it off a bare `persist`.**
///
/// A column naming no stored type keeps whatever its domain already is and has no crossing to
/// declare — which is the shape the three `label_*` refusal fixtures write, and why a parse refusal
/// here cannot mask the WORD refusal they exist to pin. A `type` on a column the declaration did not
/// call a collection is likewise none of this rule's business.
#[test]
fn the_collection_crossing_rule_asks_for_a_declared_element_type() {
  assert!(
    parse(&syn::parse_quote! {
      #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
      struct S {
        #[ingraph(id)] id: Uuid7,
        #[ingraph(list(scalar))] a: Vec<u8>,
      }
    })
    .is_ok(),
    "a collection naming no stored type owes no crossing"
  );

  let scalar = parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(string, sqlite(type = "String"))] a: String,
    }
  });
  assert!(
    scalar.is_ok(),
    "and a column no word called a collection is not asked either"
  );
}

/// A collection holds one type, so its label names ONE element.
#[test]
fn refuses_a_collection_naming_two_elements() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(list(string, scalar))] a: Vec<String>,
    }
  });
  assert!(e.contains("a collection's label names ONE element"), "{e}");
}

/// The word IS the value, so a word carrying one is refused with the two spellings that take one.
#[test]
fn refuses_a_family_word_carrying_a_value() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar = 3)] a: i64,
    }
  });
  assert!(e.contains("a family label is a bare WORD"), "{e}");
}

/// An element word this framework does not name is refused WITHOUT the string-literal door, which
/// is a door the element position does not have.
#[test]
fn refuses_an_unknown_element_word() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(list(bag))] a: Vec<String>,
    }
  });
  assert!(e.contains("`bag` is not an interpretation"), "{e}");
  assert!(
    e.contains("an element-level custom marker is reserved"),
    "{e}"
  );
  assert!(
    !e.contains("in a string literal"),
    "the field's door is not the element's: {e}"
  );
}

/// One field, one interpretation — a second label is ambiguous exactly as a repeated option is.
#[test]
fn refuses_a_repeated_label() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar, string)] a: i64,
    }
  });
  assert!(
    e.contains("a family label is declared more than once"),
    "{e}"
  );
}

/// A KEY-side column carries no family label: its vocabulary is the sealed `Id`, which says more.
///
/// Both sides of the key, because they are two declarations: the `id` marker on the field, and
/// membership in the record's own `lineage(fields(…))`.
#[test]
fn refuses_a_family_label_on_a_key_side_field() {
  for declaration in [
    quote::quote! {
      #[ingraph(sqlite, graphql(async_graphql))]
      struct S {
        #[ingraph(id, scalar)] id: Uuid7,
        #[ingraph(scalar)] a: i64,
      }
    },
    quote::quote! {
      #[ingraph(lineage(fields(media_id)), sqlite, graphql(async_graphql))]
      struct S {
        #[ingraph(id)] id: Uuid7,
        #[ingraph(scalar)] media_id: Uuid7,
        #[ingraph(scalar)] a: i64,
      }
    },
  ] {
    let all = refusals(syn::parse_quote!(#declaration));
    assert!(
      names(&all, "a key's vocabulary is the sealed `Id` trait"),
      "{all:?}"
    );
  }
}

/// Every emitted type is renamable, each through its OWN block, and a block overrides only its own.
#[test]
fn every_emitted_type_is_renamable_through_its_own_block() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(
      sqlite(row(rename = "TrackRow"), comparison(rename = "TrackWhere")),
      graphql(
        output(rename = "TrackWire"),
        key(rename = "TrackKeyWire"),
        filter(rename = "TrackFilter"),
        order_by(rename = "TrackSort"),
        async_graphql,
      ))]
    struct VideoTrack { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] bit_rate: u64 }
  })
  .expect("six blocks, six names");
  let database = database(&m, DatabaseKind::Sqlite);
  assert_eq!(database.name().to_string(), "TrackRow");
  assert_eq!(database.comparison_name().to_string(), "TrackWhere");
  let graphql = m.graphql.as_ref().expect("declared");
  assert_eq!(graphql.output.to_string(), "TrackWire");
  assert_eq!(graphql.key_output.to_string(), "TrackKeyWire");
  assert_eq!(graphql.filter.to_string(), "TrackFilter");
  assert_eq!(m.order_by.to_string(), "TrackSort");
  assert_eq!(
    graphql.output.safe().to_string(),
    "TrackWire",
    "one `rename` sets BOTH faces — a type name is Rust, so neither face is mangled"
  );
}

/// A block overrides ONLY its own: renaming the row leaves the comparison defaulting FROM it, and
/// renaming one wire type leaves the other three at their conventional names.
#[test]
fn a_rename_overrides_only_its_own_type() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite(row(rename = "TrackRow")), graphql(filter(rename = "TrackWhere"), async_graphql))]
    struct VideoTrack { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] bit_rate: u64 }
  })
  .expect("one block each");
  let database = database(&m, DatabaseKind::Sqlite);
  assert_eq!(database.name().to_string(), "TrackRow");
  assert_eq!(
    database.comparison_name().to_string(),
    "TrackRowComparison",
    "the comparison defaults FROM the row's name, so one rename moves both"
  );
  let graphql = m.graphql.as_ref().expect("declared");
  assert_eq!(graphql.filter.to_string(), "TrackWhere");
  assert_eq!(graphql.output.to_string(), "VideoTrackGraphqlOutput");
  assert_eq!(graphql.key_output.to_string(), "VideoTrackKeyOutput");
  assert_eq!(m.order_by.to_string(), "VideoTrackOrderBy");
}

/// Two emitted types renamed onto ONE name, across the per-database set and across categories —
/// which is what one unified pass buys over a check per category.
#[test]
fn refuses_two_emitted_types_renamed_onto_one_name() {
  for (input, expected) in [
    (
      syn::parse_quote! {
        #[ingraph(sqlite(row(rename = "Row")), postgres(row(rename = "Row")))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
      "already the `sqlite` row",
    ),
    (
      syn::parse_quote! {
        #[ingraph(sqlite, postgres(comparison(rename = "SSqlite")))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
      "already the `sqlite` row",
    ),
    (
      syn::parse_quote! {
        #[ingraph(sqlite, graphql(filter(rename = "SGraphqlOutput"), async_graphql))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
      "already the wire output",
    ),
    (
      syn::parse_quote! {
        #[ingraph(sqlite(row(rename = "SKey")))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
      "already the key type",
    ),
    (
      syn::parse_quote! {
        #[ingraph(sqlite(row(rename = "S")))]
        struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
      },
      "already the record's own name",
    ),
  ] {
    let e = refused(input);
    assert!(e.contains(expected), "{expected}: {e}");
  }
}

/// A repeated `rename` in one block, and a block with no `rename` at all — naming the type is the
/// only thing these blocks are for.
#[test]
fn refuses_a_repeated_or_absent_rename_in_a_type_block() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite(row(rename = "A", rename = "B")))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });
  assert!(e.contains("declared more than once in `row(…)`"), "{e}");

  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite(comparison))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });
  assert!(e.contains("the only thing it is for"), "{e}");
}

/// A type name must BE an identifier, where a COLUMN name need not: a column reaches SQL and is
/// mangled into a field, a type reaches only Rust and mangling would snake_case it.
#[test]
fn refuses_a_type_rename_that_is_not_an_identifier() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite(row(rename = "Track Row")))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  });
  assert!(e.contains("must be a valid identifier"), "{e}");
}

// ---------------------------------------------------------------------------------------------
// The DERIVED family, and the three that left for nodes of their own. Nothing here emits: the
// ledger reaches the model, and every declaration a record no longer owns is refused with the
// migration that names where it went.
// ---------------------------------------------------------------------------------------------

/// A ledger is DERIVED: what it certifies is the unit's close, which every stored record has, so
/// being stored is the whole condition and it is not one a declaration can opt out of. Its hosts are
/// the `persist(…)` databases, in the order they were written.
#[test]
fn a_ledger_is_derived_from_the_storage() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(lineage(fields(media_id)), sqlite, postgres)]
    pub struct Keyframe {
      #[ingraph(id)] id: Uuid7,
      media_id: Uuid7,
      #[ingraph(scalar)] width: u64,
    }
  })
  .expect("the documented declaration parses");
  assert_eq!(
    m.progress
      .as_ref()
      .expect("derived from the storage")
      .hosts
      .iter()
      .map(ProgressHost::kind)
      .collect::<Vec<_>>(),
    [DatabaseKind::Sqlite, DatabaseKind::Postgres],
    "one host per PERSIST database, in the order `persist(…)` wrote them"
  );

  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  })
  .expect("a `persist`-only record");
  assert_eq!(
    m.progress
      .expect("every stored record has a close to certify")
      .hosts
      .iter()
      .map(ProgressHost::kind)
      .collect::<Vec<_>>(),
    [DatabaseKind::Sqlite]
  );

  // The rowless tier is an `entity` now — a record IS rows, so *a record with no storage* is not a
  // declaration the ladder still has.
  let m = under(
    &syn::parse_quote! { struct S { #[ingraph(id)] id: Uuid7 } },
    NodeKind::Entity,
  )
  .expect("a pure-compute node");
  assert!(
    m.progress.is_none(),
    "the control tables live in the `persist` pool, and this node has none"
  );

  // The one case a ledger is absent from a STORED record, and it is a framework gap rather than a
  // rule: `store/progress/` ships sqlite and postgres, so a mongo-only record has nowhere to put one.
  let m = parse(&syn::parse_quote! {
    #[ingraph(mongo)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
  })
  .expect("mongo stores rows, and no rule here refuses it");
  assert!(m.progress.is_none());
}

/// The word left the grammar, and it is refused by the reason it left rather than as an unknown
/// entry — an author who writes it has a concrete idea, already recorded elsewhere.
#[test]
fn refuses_a_declaration_that_is_derived() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, progress(sqlite))]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(string)] a: SmolStr }
  });
  assert!(
    e.contains("`progress(…)` is not a declaration — it is derived from the storage families")
      && e.contains("A ledger's control tables live in"),
    "{e}"
  );
}

/// A field renamed in a DATABASE is still that field's column, so the rule reads the field it was
/// declared from rather than the name a row gave it.
#[test]
fn a_renamed_column_still_satisfies_the_storage_rule() {
  parse(&syn::parse_quote! {
    #[ingraph(sqlite, graphql(async_graphql, plural = "many"))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(string, rename = "caption")] description: SmolStr,
    }
  })
  .expect("the column's NAME is not what the rule is about");
}

/// The word left the record at BOTH scopes, and each refusal names the macro that carries the
/// declaration now — a macro that SHIPS, so the sentence sends an author somewhere rather than
/// telling them to wait.
///
/// Both spellings the block took reach the same sentence — a bare word, a block of engines, a field's
/// per-engine conversions and the `= "path"` value — because what the block and the value carried is
/// the conversion, and a conversion describes entry into the index node.
#[test]
fn refuses_full_text_at_either_scope() {
  for declaration in ["fulltext", "fulltext(tantivy)", "fulltext(tantivy, sqlite)"] {
    let block: proc_macro2::TokenStream = declaration.parse().expect("a family");
    let e = refused(syn::parse_quote! {
      #[ingraph(sqlite, #block)]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(string)] a: SmolStr }
    });
    assert!(
      e.contains("a record owns no full-text index — an index is its OWN node")
        && e.contains("`fulltext` macro, on a type whose `upstream(…)` names this record"),
      "{declaration}: {e}"
    );
    assert!(
      e.contains("One node holds ONE storage") && e.contains("carries no `id` of its own"),
      "the refusal carries the ruling it follows from: {e}"
    );
  }

  for marker in [
    "fulltext",
    r#"fulltext = "text::render""#,
    r#"fulltext(tantivy(from = "text::render"))"#,
    r#"fulltext(tantivy(each), sqlite(join(sep = ", ")))"#,
  ] {
    let marker: proc_macro2::TokenStream = marker.parse().expect("a marker");
    let e = refused(syn::parse_quote! {
      #[ingraph(sqlite)]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(string, #marker)] a: SmolStr }
    });
    assert!(
      e.contains("`fulltext` marks a field for an index that is its OWN node")
        && e.contains("per-engine conversion its block carried"),
      "{e}"
    );
  }
}

/// The artifact family left the record the same way, and its refusal carries the FENCE: a `Vec<u8>`
/// column is a value in this record's own row, spelled `bytes` beside `persist`, and it is not what
/// left. The two are one word apart, so the sentence that refuses one names the other.
#[test]
fn refuses_the_artifact_store_at_either_scope() {
  for declaration in ["blob", "blob(fs)", r#"blob(fs, extension = "jpg")"#] {
    let block: proc_macro2::TokenStream = declaration.parse().expect("a family");
    let e = refused(syn::parse_quote! {
      #[ingraph(sqlite, #block)]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
    });
    assert!(
      e.contains("a record owns no artifact store — a blob family is its OWN node")
        && e.contains("`blob` macro, on a type whose `upstream(…)` names this record"),
      "{declaration}: {e}"
    );
    assert!(
      e.contains("`extension` is part of the ADDRESS that node's key renders"),
      "the address option travels with the stores: {e}"
    );
    assert!(
      e.contains("A column of BYTES is a different thing and stays"),
      "the fence around the column family: {e}"
    );
  }

  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(bytes, blob)] b: Vec<u8> }
  });
  assert!(
    e.contains("`blob` marks a field as an artifact's payload")
      && e.contains("A `Vec<u8>` COLUMN is a different thing and stays"),
    "{e}"
  );
}

/// A `bytes` COLUMN is untouched by any of it: the label names a value this record's own row holds,
/// and the artifact family that left was never what it declared.
#[test]
fn a_bytes_column_is_not_the_artifact_family() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(bytes)] thumbnail: Vec<u8> }
  })
  .expect("a byte column is a column");
  assert_eq!(
    stored(&m, DatabaseKind::Sqlite, "thumbnail")
      .name
      .external(),
    "thumbnail",
    "the bytes are a column of the row, exactly as they were"
  );
}

/// The embedding index left the record the same way, and the refusal carries what its BLOCK carried:
/// `element` and `filter` describe the embeddings, so they go where the engines go.
#[test]
fn refuses_the_embedding_index_at_either_scope() {
  for declaration in [
    "vector",
    "vector(lance)",
    r#"vector(lance, element = "element::F16", filter = "KeyframeScope")"#,
  ] {
    let block: proc_macro2::TokenStream = declaration.parse().expect("a family");
    let e = refused(syn::parse_quote! {
      #[ingraph(sqlite, #block)]
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(scalar)] a: u64 }
    });
    assert!(
      e.contains("a record owns no embedding index — an index is its OWN node")
        && e.contains("`vector` macro, on a type whose `upstream(…)` names this record"),
      "{declaration}: {e}"
    );
    assert!(
      e.contains("`element` and `filter` describe the EMBEDDINGS rather than these rows"),
      "the two record types travel with the engines: {e}"
    );
  }

  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite)]
    struct S { #[ingraph(id)] id: Uuid7, #[ingraph(string, vector)] e: Arc<[f32]> }
  });
  assert!(
    e.contains("`vector` marks a field as an embedding, and an embedding index is its OWN node")
      && e.contains("One node holds ONE storage"),
    "{e}"
  );
}

/// The accumulation property, over the declarations a record no longer owns: one compile reports
/// every one of them, so a migration is one pass rather than one error at a time.
#[test]
fn every_misplaced_storage_declaration_is_reported_at_once() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(
      sqlite,
      fulltext(tantivy),
      vector(lance),
      blob(fs, extension = "png"),
      progress(sqlite))]
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(scalar)] a: u64,
    }
  });
  for rule in [
    "a record owns no full-text index",
    "a record owns no embedding index",
    "a record owns no artifact store",
    "`progress(…)` is not a declaration",
  ] {
    assert!(names(&e, rule), "missing `{rule}` in: {e:?}");
  }
}

/// THE EDGE: one upstream, spelled as a type path in a string, reaching the model as the path that
/// was written.
///
/// A string for this grammar's own reason — every type it names is one — and it is not stringly
/// typed, because nothing here resolves it. The path is EMITTED and the compiler resolves it there,
/// which is what makes a wrong one an ordinary compile error at the declaration.
#[test]
fn a_node_names_its_upstream_and_the_path_reaches_the_model_verbatim() {
  let m = operator(&syn::parse_quote! {
    #[ingraph(subscribe = "asr::TranscriptSegment")]
    struct Attribution { #[ingraph(id)] id: Uuid7, speaker: String }
  })
  .expect("a subscriber");
  assert_eq!(
    rendered(m.subscribe.as_ref().expect("the upstream")),
    "asr::TranscriptSegment"
  );
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct Media { #[ingraph(id)] id: Uuid7 }
  })
  .expect("a source node");
  assert!(
    m.subscribe.is_none(),
    "and a node driven by nothing says so by omission"
  );
}

/// THE GOODBYE, opted into: a bare word on the node's own attribute, read as the fact that this
/// declaration's constructed value has something to await before the process leaves it.
#[test]
fn a_node_may_opt_its_value_into_the_shutdown_s_goodbye() {
  let model = operator(&syn::parse_quote! {
    #[ingraph(teardown)]
    struct Decode { #[ingraph(id)] id: Uuid7 }
  })
  .expect("a bare word");
  assert!(model.teardown);
}

/// And a declaration that says nothing is torn down by `Drop`, which is the shipped posture rather
/// than an omission.
#[test]
fn a_node_that_says_nothing_is_torn_down_by_drop() {
  let model = operator(&syn::parse_quote! {
    struct Decode { #[ingraph(id)] id: Uuid7 }
  })
  .expect("nothing to refuse");
  assert!(!model.teardown);
}

/// The word carries nothing, and both shapes that would carry something are refused by name: what
/// to SAY is the `AsyncTeardown` impl's, so there is nothing at the declaration to configure.
#[test]
fn the_goodbye_word_takes_neither_a_value_nor_a_block() {
  for spelling in [
    quote::quote!(teardown = "flush"),
    quote::quote!(teardown(flush)),
  ] {
    let e = operator(&syn::parse_quote! {
      #[ingraph(#spelling)]
      struct Decode { #[ingraph(id)] id: Uuid7 }
    })
    .unwrap_err()
    .to_string();
    assert!(
      e.contains("`teardown` is a bare word")
        && e.contains("the goodbye itself is the `AsyncTeardown` impl"),
      "{e}"
    );
  }
}

/// One declaration says goodbye once.
#[test]
fn the_goodbye_word_is_refused_twice_over() {
  let e = operator(&syn::parse_quote! {
    #[ingraph(teardown, teardown)]
    struct Decode { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err()
  .to_string();
  assert!(e.contains("`teardown` is declared more than once"), "{e}");
}

/// THE ROOT PROJECTION, opted into: a bare word on the node's own attribute, read as the fact that
/// this declaration's OUTPUTS descend from a content root the framework may project.
#[test]
fn a_node_may_opt_its_outputs_into_the_root_projection() {
  let model = operator(&syn::parse_quote! {
    #[ingraph(attributed)]
    struct Decode { #[ingraph(id)] id: Uuid7 }
  })
  .expect("a bare word");
  assert!(model.attributed);
}

/// And a declaration that says nothing attributes nothing — its observations stay counter-grade,
/// which is the shipped posture rather than an omission.
#[test]
fn a_node_that_says_nothing_attributes_nothing() {
  let model = operator(&syn::parse_quote! {
    struct Decode { #[ingraph(id)] id: Uuid7 }
  })
  .expect("nothing to refuse");
  assert!(!model.attributed);
}

/// The word carries nothing, and both shapes that would carry something are refused by name: the
/// projection is the `Attributes` impl the OUTPUT's own declaration emitted, so there is nothing at
/// this declaration to name.
#[test]
fn the_attribution_word_takes_neither_a_value_nor_a_block() {
  for spelling in [
    quote::quote!(attributed = "media"),
    quote::quote!(attributed(media)),
  ] {
    let e = operator(&syn::parse_quote! {
      #[ingraph(#spelling)]
      struct Decode { #[ingraph(id)] id: Uuid7 }
    })
    .unwrap_err()
    .to_string();
    assert!(
      e.contains("`attributed` is a bare word")
        && e.contains("the projection is the `Attributes` impl"),
      "{e}"
    );
  }
}

/// One declaration attributes its outputs once.
#[test]
fn the_attribution_word_is_refused_twice_over() {
  let e = operator(&syn::parse_quote! {
    #[ingraph(attributed, attributed)]
    struct Decode { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err()
  .to_string();
  assert!(e.contains("`attributed` is declared more than once"), "{e}");
}

/// It is on an AXIS OF ITS OWN and composes with every word that says what a body is: the pair, the
/// mode and the kind describe the BODY, and this describes what the framework does with what the
/// body emits — so nothing here is a pair to refuse.
#[test]
fn the_attribution_word_composes_with_the_body_words() {
  let model = operator(&syn::parse_quote! {
    #[ingraph(stream, async, attributed, teardown)]
    struct Decode { #[ingraph(id)] id: Uuid7 }
  })
  .expect("four words on four axes");
  assert!(model.attributed && model.teardown);
  assert!(model.streaming.is_some() && model.asynchronous.is_some());
}

/// A STORAGE declaration takes it too, for the reason the goodbye does: every mount a deployment
/// launches emits something, and whether that something has a root is the mount's question rather
/// than the tier's.
#[test]
fn a_storage_declaration_may_attribute_as_well() {
  let model = under(
    &syn::parse_quote! {
      #[ingraph(sqlite, attributed)]
      struct Frames { #[ingraph(id)] id: Uuid7 }
    },
    NodeKind::Record,
  )
  .expect("a bare word");
  assert!(model.attributed);
}

/// A STORAGE declaration takes it too, and that is the tier rather than an oversight: every mount a
/// deployment launches is a value somebody's `AsyncConstructor` built, so every one of them may have
/// something to await before it is left.
#[test]
fn a_storage_declaration_may_opt_in_as_well() {
  let model = under(
    &syn::parse_quote! {
      #[ingraph(sqlite, teardown)]
      struct Frames { #[ingraph(id)] id: Uuid7 }
    },
    NodeKind::Record,
  )
  .expect("a bare word");
  assert!(model.teardown);
}

/// FUSION is the other reading of several upstreams, and it is the one a node that MINTS an id
/// takes: `upstream(…)` here names an upstream and designates the key parent, and PROJECTS NOTHING.
///
/// The refusal points at the derived indexes as well, because a node whose every field comes from
/// ONE upstream message is not fusion at all and those three macros are what it wanted.
#[test]
fn a_fusion_source_names_an_upstream_and_projects_nothing() {
  let e = operator(&syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", key, speaker = "name"), lineage(fields(media_id)))]
    struct Attribution { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
  })
  .unwrap_err()
  .to_string();
  assert!(
    e.contains("`upstream(…)` on an operator names ONE upstream of a fusion")
      && e.contains("It projects nothing")
      && e.contains("`fulltext`, `vector` or `blob` macro"),
    "{e}"
  );
}

/// **`key` IS THE MODE SELECTOR.** Written, the upstreams JOIN. Absent, they are INDEPENDENT — and
/// that is not a refusal, it is the other topology: each upstream's messages make their own rows,
/// so the ancestry is decided per row and becomes a CHOICE among them.
#[test]
fn a_declaration_that_designates_none_fans_in_instead() {
  let model = operator(&syn::parse_quote! {
    #[ingraph(upstream(node = "media::Frame"), upstream(node = "asr::Segment"))]
    struct Caption { #[ingraph(id)] id: Uuid7, text: String }
  })
  .expect("no designation is the other mode, not an error");
  let fanned = model
    .upstreams
    .as_ref()
    .and_then(Upstreams::fanned)
    .expect("the mode reaches the model");
  assert_eq!(
    fanned
      .kinds
      .iter()
      .map(|kind| kind.variant.to_string())
      .collect::<Vec<_>>(),
    ["Frame", "Segment"],
    "the variant's word is read off the path's last segment, never declared"
  );
  let lineage = model.lineage.as_ref().expect("a fan-in has an ancestry");
  assert!(
    matches!(lineage.shape, Shape::Kinds(_)) && lineage.path().is_empty(),
    "and it is a choice rather than a path"
  );
  assert_eq!(
    model.key.path.len(),
    1,
    "the key leads with that choice and nothing else"
  );
  assert_eq!(model.key.path[0].name, fanned_lineage_column());
  assert_eq!(
    model.key.path[0].source,
    fanned_lineage(&EmissionPrefix::default())
  );
}

/// The variant's word is the DISCRIMINANT everywhere it is spelled, so two upstreams cannot share
/// one — and the refusal names both paths rather than leaving `E0428` inside the emitted enum.
#[test]
fn two_upstreams_cannot_share_a_variant_word() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "asr::Segment"), upstream(node = "vad::Segment"))]
    struct Caption { #[ingraph(id)] id: Uuid7 }
  });
  assert!(
    names(&messages, "both end in `Segment`") && names(&messages, "`asr::Segment`"),
    "{messages:?}"
  );
}

/// A fan-in's ancestry is decided per ROW, so a `lineage(fields(…))` beside it names a path this
/// node does not have — and the refusal says which word makes the upstreams join instead.
#[test]
fn a_fan_in_has_no_path_to_declare() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A"), upstream(node = "b::B"), lineage(fields(media_id)))]
    struct Caption { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
  });
  assert!(
    names(&messages, "its ancestry decided per ROW")
      && names(&messages, "Designate one upstream with `key`"),
    "{messages:?}"
  );
}

/// A fan-in that PERSISTS names the half of the split layout that has not arrived, and the half is
/// the READ rather than the storage — which `ingraph`'s own descriptor, DDL and write lane carry.
///
/// The sentence is the whole of what this refusal is worth, so it is asserted here as well as in
/// `tests/refusals/`: a wait is worth what it tells the author to do instead, and two authorities
/// about one claim is the pattern `tests/fusions/` already keeps.
#[test]
fn a_fan_in_that_persists_waits_on_the_read_and_says_which_one() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(sqlite, upstream(node = "a::A"), upstream(node = "b::B"))]
    struct Caption { #[ingraph(id)] id: Uuid7 }
  });
  assert!(
    names(
      &messages,
      "the READ that raises a common row back into a record"
    ) && names(&messages, "a choice has no empty state to decode into")
      && names(&messages, "Designate one upstream with `key`"),
    "{messages:?}"
  );
}

/// The same declaration with NO rows is accepted, which is what makes the wait about storage rather
/// than about the topology: a node fanning in is the ordinary case and always was.
#[test]
fn a_fan_in_that_stores_nothing_is_not_waiting_on_anything() {
  operator(&syn::parse_quote! {
    #[ingraph(upstream(node = "a::A"), upstream(node = "b::B"))]
    struct Caption { #[ingraph(id)] id: Uuid7 }
  })
  .expect("a node with no rows has no layout to wait for");
}

/// A lineage is ONE path, so it descends from one upstream — and the second designation names the
/// first, because which of the two is wrong is the author's to decide.
#[test]
fn two_designated_parents_are_refused_naming_the_first() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(
      upstream(node = "a::A", key),
      upstream(node = "b::B", key),
      lineage(fields(media_id))
    )]
    struct Caption { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
  });
  assert!(
    names(&messages, "two upstreams are designated `key`") && names(&messages, "`a::A` already"),
    "{messages:?}"
  );
}

/// `key` says *this entry* and nothing else, so a value or a block beside it has nothing left to
/// name.
#[test]
fn the_designation_is_written_bare() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", key = "media"), lineage(fields(media_id)))]
    struct Caption { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
  });
  assert!(names(&messages, "`key` is a DESIGNATION"), "{messages:?}");
}

/// One node, one spelling of its edge. The two words differ in exactly what merging them would
/// hide: whether the declaration claims an identity.
#[test]
fn a_node_does_not_name_its_upstreams_twice() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(subscribe = "a::A", upstream(node = "a::A", key), lineage(fields(media_id)))]
    struct Caption { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
  });
  assert!(
    names(&messages, "names its upstreams twice"),
    "{messages:?}"
  );
}

/// The designation buys the EQUATION, and the equation is written against the lineage columns — so
/// a fusion with no `lineage(…)` block has designated a parent it cannot be checked against.
#[test]
fn a_fusion_declares_the_lineage_it_mirrors() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", key))]
    struct Caption { #[ingraph(id)] id: Uuid7 }
  });
  assert!(
    names(&messages, "has no lineage to check against"),
    "{messages:?}"
  );
}

/// ONE upstream is a fusion too. What `upstream(…)` adds over `subscribe` is the designation, and a
/// node with one parent wants the same equation a three-parent one does.
#[test]
fn one_upstream_may_still_designate_its_key_parent() {
  let model = operator(&syn::parse_quote! {
    #[ingraph(upstream(node = "media::Frame", key), lineage(fields(media_id)))]
    struct Caption { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
  })
  .expect("one designated upstream is a fusion");
  let fusion = model
    .upstreams
    .as_ref()
    .and_then(Upstreams::fused)
    .expect("the designation reaches the model");
  assert_eq!(fusion.upstreams().count(), 1);
  assert!(fusion.others.is_empty());
  assert_eq!(
    fusion
      .mirrors
      .iter()
      .map(|mirror| (mirror.column.to_string(), mirror.from.to_string()))
      .collect::<Vec<_>>(),
    [("media_id".to_owned(), "media_id".to_owned())],
    "a same-name mirror costs no words"
  );
}

/// The mapping word, and the two names it keeps apart: the column as the LINEAGE type spells it,
/// and the field of the parent's key it equals.
#[test]
fn a_diverging_mirror_names_the_parent_field_it_equals() {
  let model = operator(&syn::parse_quote! {
    #[ingraph(
      upstream(node = "media::Frame", key),
      upstream(node = "asr::Segment"),
      lineage(fields(media, frame(source = "id")))
    )]
    struct Caption {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(lineage(rename = "media_id"))] media: Uuid7,
      frame: Uuid7,
    }
  })
  .expect("a fusion over two upstreams");
  let fusion = model
    .upstreams
    .as_ref()
    .and_then(Upstreams::fused)
    .expect("the designation reaches the model");
  assert_eq!(
    fusion
      .others
      .iter()
      .map(|path| quote::ToTokens::to_token_stream(path).to_string())
      .collect::<Vec<_>>(),
    ["asr :: Segment"],
    "the upstream that is not the parent is still an upstream"
  );
  assert_eq!(
    fusion
      .mirrors
      .iter()
      .map(|mirror| (mirror.column.to_string(), mirror.from.to_string()))
      .collect::<Vec<_>>(),
    [
      ("media_id".to_owned(), "media".to_owned()),
      ("frame".to_owned(), "id".to_owned()),
    ],
    "the column is the RENAMED one, and the mapping is onto the parent's own field"
  );
}

/// The mapping word maps onto a PARENT's key, so a node with no parent has nothing to map onto —
/// and the refusal says what a lineage is instead rather than calling the word unknown.
#[test]
fn a_mirror_without_a_designated_parent_is_refused_by_name() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(lineage(fields(media(source = "id"))))]
    struct Caption { #[ingraph(id)] id: Uuid7, media: Uuid7 }
  });
  assert!(
    names(&messages, "has no designated parent to map onto")
      && names(&messages, "its lineage is its own columns"),
    "{messages:?}"
  );
}

/// The flat spelling reads as a rename of the lineage column, which this block already has a word
/// for — so it is refused naming that word rather than accepted as a second way to say `source`.
#[test]
fn the_mapping_word_is_written_inside_the_field() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(upstream(node = "a::A", key), lineage(fields(media = "id")))]
    struct Caption { #[ingraph(id)] id: Uuid7, media: Uuid7 }
  });
  assert!(
    names(
      &messages,
      "the parent key's field it mirrors is written inside it"
    ),
    "{messages:?}"
  );
}

/// One entry names one upstream, and the value is a PATH — a string that is not one is refused here
/// rather than pasted into an expansion to fail somewhere downstream.
#[test]
fn the_edge_is_one_path_declared_once() {
  let e = operator(&syn::parse_quote! {
    #[ingraph(subscribe = "a::A", subscribe = "b::B")]
    struct Attribution { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err()
  .to_string();
  assert!(e.contains("`subscribe` is declared more than once"), "{e}");
  let e = operator(&syn::parse_quote! {
    #[ingraph(subscribe = "not a path")]
    struct Attribution { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err()
  .to_string();
  assert!(e.contains("names the upstream node, as a type path"), "{e}");
}

/// The identity half of the grammar is the NODE's rather than the record's: an operator writes the
/// same `lineage(…)`, the same `id` and the same scoped renames, and reaches the same key.
#[test]
fn an_operator_declares_its_key_exactly_as_a_record_does() {
  let m = operator(&syn::parse_quote! {
    #[ingraph(lineage(fields(media_id)), key(rename = "TurnAddress"))]
    struct SpeakerTurn {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(copy)] media_id: Uuid7,
      speaker: String,
    }
  })
  .expect("an operator carries a key");
  assert_eq!(
    m.kind,
    NodeKind::Operator,
    "the derive it was written under"
  );
  assert_eq!(m.key.name, "TurnAddress");
  assert_eq!(lineage_names(&m), ["media_id"]);
  assert!(m.persist.is_none(), "and it stores nothing");
}

/// The one storage block a record takes is the one an operator does not, and the refusal names the
/// derive that does. It is not a MIGRATION like its three neighbours: rows have their derive
/// already, so the sentence stops at `Record` rather than at *when it arrives*.
#[test]
fn refuses_rows_on_a_node_that_stores_none() {
  let e = operator(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct SpeakerTurn { #[ingraph(id)] id: Uuid7, #[ingraph(string)] speaker: String }
  })
  .unwrap_err()
  .to_string();
  assert!(
    e.contains("an operator stores no rows")
      && e.contains("a node whose messages land in a database is a `record`"),
    "{e}"
  );
}

/// A field's row words on such a node are told the same thing rather than told the record's block is
/// missing. The missing-block sentence ended in *the block that names the databases*, and there is
/// no block to add here — reporting it would be the second problem derived from the first that
/// [`stored_in`](crate::parse) already refuses to report.
///
/// The word written used to be a bare `persist` marker, which participation's inversion deleted. Two
/// words are left that say something about a row, and each says something FALSE on a rowless node
/// rather than nothing: `persist(…)` refines a column there are none of, and `skip` answers a
/// question this declaration never asks. So both are asserted, where one marker used to be.
#[test]
fn a_row_word_on_a_node_that_stores_none_is_refused_in_the_same_words() {
  let e: Vec<String> = operator(&syn::parse_quote! {
    struct SpeakerTurn {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(string, rename = "who")] speaker: String,
      #[ingraph(skip)] cache: Vec<u8>,
    }
  })
  .unwrap_err()
  .into_iter()
  .map(|e| e.to_string())
  .collect();
  assert!(
    names(
      &e,
      "`speaker` refines a stored column and an operator has no rows"
    ),
    "{e:?}"
  );
  assert!(
    names(
      &e,
      "`cache` declares that no row holds it and an operator has no rows"
    ),
    "{e:?}"
  );
  assert!(
    !names(&e, "declares no `persist(…)` block"),
    "and not the missing-block sentence too: {e:?}"
  );
}

/// The wire face crosses the storage axis rather than riding it, so the node that has none is the
/// family's BASE rather than every node with no rows.
///
/// The rule used to read *the wire face rides the rows, so a node with none has none*, and the
/// sentence said a read populates a wire field from a stored column. The rowless tier that publishes
/// its ADDRESS broke that equation: an entity mints an identity, dresses it, and holds no table
/// anywhere. So the block is refused on an operator alone, and the sentence sends its author one
/// rung up rather than to a store.
#[test]
fn refuses_a_wire_face_on_the_node_family_s_base() {
  let e = operator(&syn::parse_quote! {
    #[ingraph(graphql(async_graphql))]
    struct SpeakerTurn { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err()
  .to_string();
  assert!(
    e.contains("an operator publishes nothing")
      && e.contains("the rowless tier that publishes its address is an `entity`"),
    "{e}"
  );

  under(
    &syn::parse_quote! {
      #[ingraph(graphql(async_graphql, plural = "turns"))]
      struct SpeakerTurn { #[ingraph(id)] id: Uuid7 }
    },
    NodeKind::Entity,
  )
  .expect("and one rung up the same block is the tier's whole point");
}

/// And the three that ARE migrations keep their sentence and change only who it is told to — one
/// law, spoken to the node in front of the author.
#[test]
fn the_storage_refusals_name_the_node_they_were_written_on() {
  let e = operator(&syn::parse_quote! {
    #[ingraph(fulltext(tantivy))]
    struct SpeakerTurn { #[ingraph(id)] id: Uuid7 }
  })
  .unwrap_err()
  .to_string();
  assert!(
    e.contains("an operator owns no full-text index")
      && e.contains("on a type whose `upstream(…)` names this operator")
      && e.contains("an operator's is none at all"),
    "{e}"
  );
}

/// An operator with no `id` is refused in ITS OWN words — the sentence a record gets, carrying the
/// noun and the article this node takes.
///
/// The rule relaxes for a node that SUBSCRIBES, whose key is the upstream's; nothing subscribes
/// yet, so today every operator mints its own identity.
#[test]
fn an_operator_mints_its_own_id() {
  let e = operator(&syn::parse_quote! { struct SpeakerTurn { speaker: String } })
    .unwrap_err()
    .to_string();
  assert!(
    e.contains("an operator needs exactly one `#[ingraph(id)]` field"),
    "{e}"
  );
}

/// The SHAPE refusals take the node's own noun too — down to the MACRO named in the one sentence
/// that quotes it, which is the message a reader checks their attribute line against.
#[test]
fn the_shape_refusals_speak_the_derive_that_was_written() {
  let e = operator(&syn::parse_quote! { enum SpeakerTurn { A } })
    .unwrap_err()
    .to_string();
  assert!(
    e.contains("`#[ingraph::operator]` supports structs only"),
    "{e}"
  );
  let e = operator(&syn::parse_quote! { struct SpeakerTurn<T> { #[ingraph(id)] id: T } })
    .unwrap_err()
    .to_string();
  assert!(e.contains("generic operators are not supported"), "{e}");
}

/// The forward word, in both of its forms, reaching the model as a TYPE PATH — so an alias in it is
/// the compiler's business and never this layer's.
#[test]
fn a_ref_reaches_the_model_as_the_path_it_names() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct VideoTrack {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(ref = "media::Media")] media: MediaId,
      #[ingraph(ref(type = "crate::media::Video"))] video: VideoId,
      bit_rate: u64,
    }
  })
  .expect("both forms of the forward word");
  let target = |name: &str| {
    rendered(
      &field(&m, name)
        .reference
        .as_ref()
        .unwrap_or_else(|| panic!("`{name}` declares a `ref`"))
        .target,
    )
  };
  assert_eq!(target("media"), "media::Media", "the shorthand");
  assert_eq!(target("video"), "crate::media::Video", "the full block");
  assert!(
    field(&m, "bit_rate").reference.is_none(),
    "and a field writing neither refers to nothing"
  );
}

/// WHERE the referring value sits is the declaration's word, never the field's spelled type: three
/// words put it inside, and a field writing none carries it.
#[test]
fn the_declarations_word_says_where_the_referring_value_sits() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite)]
    struct Video {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(ref = "Media")] media: MediaId,
      #[ingraph(optional, ref = "Keyframe")] cover: MaybeCover,
      #[ingraph(repeated, ref = "Scene")] scenes: Scenes,
      #[ingraph(list(scalar), ref = "Take")] takes: Takes,
    }
  })
  .expect("the three container words beside a bare one");
  let through = |name: &str| field(&m, name).reference.as_ref().expect("a `ref`").through;
  assert_eq!(through("media"), Through::Value);
  assert_eq!(through("cover"), Through::Held, "`optional`");
  assert_eq!(through("scenes"), Through::Held, "`repeated`");
  assert_eq!(through("takes"), Through::Held, "a collection label");
}

/// A relation needs a record, so every spelling that names none reaches ONE refusal — and it shows
/// both forms rather than the one that happened to be written.
#[test]
fn refuses_a_ref_that_names_no_record() {
  for written in [
    quote::quote!(ref = ""),
    quote::quote!(ref),
    quote::quote!(ref()),
  ] {
    let e = refused(syn::parse_quote! {
      struct S { #[ingraph(id)] id: Uuid7, #[ingraph(#written)] media: MediaId }
    });
    assert!(
      e.contains("`ref` names the record a field refers to")
        && e.contains("ref(type = \"path::to::Type\")"),
      "{e}"
    );
  }
}

/// One column addresses one record.
#[test]
fn refuses_a_repeated_ref() {
  let e = refused(syn::parse_quote! {
    struct S {
      #[ingraph(id)] id: Uuid7,
      #[ingraph(ref = "Media", ref = "Video")] media: MediaId,
    }
  });
  assert!(
    e.contains("`ref` is declared more than once on this field"),
    "{e}"
  );
}

/// The reverse block, in both of its forms, reaching the model with the name it calls the position
/// by and the record that points back.
#[test]
fn a_derived_block_reaches_the_model_as_its_positions() {
  let m = parse(&syn::parse_quote! {
    #[ingraph(sqlite, derived(
      tracks = "media::VideoTrack",
      covers(type = "media::Cover", field = "video_id"),
    ))]
    struct Video { #[ingraph(id)] id: Uuid7 }
  })
  .expect("both forms of the reverse block");
  let named: Vec<String> = m
    .derived
    .iter()
    .map(|entry| entry.name.to_string())
    .collect();
  assert_eq!(
    named,
    ["tracks", "covers"],
    "in the order they were written"
  );
  assert_eq!(rendered(&m.derived[0].source), "media::VideoTrack");
  assert!(m.derived[0].field.is_none(), "the shorthand names no field");
  assert_eq!(
    m.derived[1]
      .field
      .as_ref()
      .map(syn::LitStr::value)
      .as_deref(),
    Some("video_id"),
    "and the full form does"
  );
}

/// A record nothing points at is spelled by omitting the block.
#[test]
fn refuses_a_derived_block_naming_no_position() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, derived())]
    struct Video { #[ingraph(id)] id: Uuid7 }
  });
  assert!(
    e.contains("`derived(…)` names the records that point back at this one, and it names none"),
    "{e}"
  );
}

/// A reverse position has NO Rust field, so a position and a field sharing a name are two things
/// under one name on one face.
#[test]
fn refuses_a_derived_position_that_takes_a_fields_name() {
  let e = refused(syn::parse_quote! {
    #[ingraph(sqlite, derived(tracks = "VideoTrack"))]
    struct Video { #[ingraph(id)] id: Uuid7, tracks: u32 }
  });
  assert!(
    e.contains("`tracks` is already a field of this record")
      && e.contains("One namespace per face"),
    "{e}"
  );
}

/// One position, one name — and the entry a reader cannot read at all is answered with both forms.
#[test]
fn refuses_a_reverse_position_this_grammar_cannot_read() {
  let e = refusals(syn::parse_quote! {
    #[ingraph(derived(tracks = "VideoTrack", tracks = "Clip", covers(field = "x"), takes(rename = "y")))]
    struct Video { #[ingraph(id)] id: Uuid7 }
  });
  for rule in [
    "`tracks` is declared more than once in `derived(…)`",
    "a reverse position is `<name> = \"path::to::Source\"`",
    "unknown entry in a reverse position",
  ] {
    assert!(names(&e, rule), "missing `{rule}` in: {e:?}");
  }
}

/// The `subscribe(…)` CONTAINER, read into the fan-in it declares.
///
/// Three shapes in one declaration, because that is what the container exists for: two upstreams
/// joined by key, one arriving independently, and one taking a named product of a multi-product
/// upstream. The order is the declaration's, because the emitted enum's variants are.
#[test]
fn the_subscribe_container_reads_a_mixed_fan_in() {
  let model = operator(&syn::parse_quote! {
    #[ingraph(subscribe(
      upstream(node = "media::Frame", key),
      upstream(node = "asr::Segment", key),
      upstream(node = "media::Scene"),
      upstream(node = "vision::Detector", out = "Boxes"),
    ))]
    struct Caption { #[ingraph(id)] id: Uuid7 }
  })
  .expect("a mixed container is legal");
  let fan_in = model
    .subscriptions
    .as_ref()
    .expect("the container was read");
  assert!(fan_in.is_sum(), "four upstreams are a sum");
  assert_eq!(
    fan_in
      .upstreams
      .iter()
      .map(|source| source.variant.to_string())
      .collect::<Vec<_>>(),
    ["Frame", "Segment", "Scene", "Boxes"],
    "the variant is the upstream's last segment, or the product's own word where one was named"
  );
  assert_eq!(
    fan_in
      .keyed()
      .map(|source| rendered(&source.node))
      .collect::<Vec<_>>(),
    ["media::Frame", "asr::Segment"],
    "`key` joins THE group, in declaration order"
  );
  assert_eq!(
    fan_in
      .straight()
      .map(|source| source.variant.to_string())
      .collect::<Vec<_>>(),
    ["Scene", "Boxes"],
  );
  assert_eq!(
    fan_in.upstreams[3]
      .out
      .as_ref()
      .map(ToString::to_string)
      .as_deref(),
    Some("Boxes"),
  );
}

/// ONE straight source is today's world: one upstream, one message type, and no sum to emit.
#[test]
fn one_straight_source_is_not_a_sum() {
  let model = operator(&syn::parse_quote! {
    #[ingraph(subscribe(upstream(node = "media::Frame")))]
    struct Caption { #[ingraph(id)] id: Uuid7 }
  })
  .expect("a one-entry container is legal");
  assert!(
    !model
      .subscriptions
      .as_ref()
      .expect("the container was read")
      .is_sum(),
    "one upstream arriving on its own needs no enum around it"
  );
}

/// A keyed group of ANY size is a sum, because what arrives is a pair rather than a message.
#[test]
fn a_keyed_group_is_a_sum_at_any_size() {
  let model = operator(&syn::parse_quote! {
    #[ingraph(subscribe(upstream(node = "media::Frame", key)))]
    struct Caption { #[ingraph(id)] id: Uuid7 }
  })
  .expect("a keyed entry is legal");
  assert!(
    model
      .subscriptions
      .as_ref()
      .expect("the container was read")
      .is_sum()
  );
}

/// One node, one fan-in — whichever of the two spellings it was written in.
#[test]
fn a_node_declares_its_fan_in_once() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(subscribe = "a::A", subscribe(upstream(node = "b::B")))]
    struct Caption { #[ingraph(id)] id: Uuid7 }
  });
  assert!(
    names(&messages, "`subscribe` is declared more than once"),
    "{messages:?}"
  );
}

/// The container and the top-level entries are two declarations about one edge set.
#[test]
fn the_container_does_not_stand_beside_the_identity_entries() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(subscribe(upstream(node = "a::A")), upstream(node = "a::A", key), lineage(fields(media_id)))]
    struct Caption { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
  });
  assert!(
    names(&messages, "names its upstreams twice"),
    "{messages:?}"
  );
}

/// Two edges that would take one name, refused where the declaration can still be edited.
#[test]
fn two_edges_cannot_share_a_variant_name() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(subscribe(upstream(node = "asr::Segment"), upstream(node = "dia::Segment")))]
    struct Caption { #[ingraph(id)] id: Uuid7 }
  });
  assert!(
    names(&messages, "both come out as `Segment`") && names(&messages, "`name = \"…\"` word"),
    "{messages:?}"
  );
}

/// Two products of ONE upstream are two edges, kept apart by the words the declaration wrote.
#[test]
fn two_products_of_one_upstream_are_named_by_their_products() {
  let model = operator(&syn::parse_quote! {
    #[ingraph(subscribe(
      upstream(node = "vision::Detector", out = "Boxes"),
      upstream(node = "vision::Detector", out = "Masks"),
    ))]
    struct Caption { #[ingraph(id)] id: Uuid7 }
  })
  .expect("two products of one upstream are two edges");
  assert_eq!(
    model
      .subscriptions
      .expect("the container was read")
      .upstreams
      .iter()
      .map(|source| source.variant.to_string())
      .collect::<Vec<_>>(),
    ["Boxes", "Masks"],
  );
}

/// Every word inside a container entry, and every way one can be written wrongly.
#[test]
fn the_container_entry_takes_three_words_and_refuses_the_rest() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(subscribe(
      upstream(key = "media"),
      upstream(node = "a::A", listen(channel)),
      lineage(fields(media_id)),
    ))]
    struct Caption { #[ingraph(id)] id: Uuid7, media_id: Uuid7 }
  });
  for rule in [
    "`key` is written bare",
    "`upstream(…)` needs `node = \"path::To::Upstream\"`",
    "unknown entry in `upstream(…)`",
    "unknown entry in `subscribe(…)`",
  ] {
    assert!(names(&messages, rule), "missing `{rule}` in: {messages:?}");
  }
}

/// A container with nothing in it is a fan-in with no arms — spelled by omitting the word.
#[test]
fn an_empty_container_is_refused_by_name() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(subscribe())]
    struct Caption { #[ingraph(id)] id: Uuid7 }
  });
  assert!(
    names(&messages, "`subscribe(…)` holds at least one"),
    "{messages:?}"
  );
}

/// `emits` is the node's own product list, read into the sum its `Out` becomes.
#[test]
fn emits_declares_the_products_in_order() {
  let model = operator(&syn::parse_quote! {
    #[ingraph(emits = ["Caption", "Summary"])]
    struct Describe { #[ingraph(id)] id: Uuid7 }
  })
  .expect("a product list is legal");
  let products = model.products.as_ref().expect("the list was read");
  assert!(products.is_sum());
  assert_eq!(
    products
      .products
      .iter()
      .map(|product| product.variant.to_string())
      .collect::<Vec<_>>(),
    ["Caption", "Summary"],
  );
}

/// One product is NOT a sum: the node's `Out` is that type, and today's world is unchanged.
#[test]
fn one_declared_product_is_not_a_sum() {
  let model = operator(&syn::parse_quote! {
    #[ingraph(emits = "Caption")]
    struct Describe { #[ingraph(id)] id: Uuid7 }
  })
  .expect("naming the one product is legal");
  assert!(!model.products.expect("the list was read").is_sum());
}

/// Every way a product list can be written wrongly.
#[test]
fn the_product_list_refuses_what_it_cannot_name() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(emits = ["Caption", "media::Caption", "1 + 1"])]
    struct Describe { #[ingraph(id)] id: Uuid7 }
  });
  for rule in ["both end in `Caption`", "so each value is a type path"] {
    assert!(names(&messages, rule), "missing `{rule}` in: {messages:?}");
  }

  let messages = refusals(syn::parse_quote! {
    #[ingraph(emits = [])]
    struct Describe { #[ingraph(id)] id: Uuid7 }
  });
  assert!(
    names(&messages, "`emits` names at least one product"),
    "{messages:?}"
  );
}

/// The keyed group's own word is spoken for wherever a group exists.
#[test]
fn a_straight_source_cannot_take_the_groups_word() {
  let messages = refusals(syn::parse_quote! {
    #[ingraph(subscribe(upstream(node = "a::A", key), upstream(node = "b::Paired")))]
    struct Caption { #[ingraph(id)] id: Uuid7 }
  });
  assert!(
    names(&messages, "is the variant that group takes"),
    "{messages:?}"
  );

  let model = operator(&syn::parse_quote! {
    #[ingraph(subscribe(upstream(node = "a::A"), upstream(node = "b::Paired")))]
    struct Caption { #[ingraph(id)] id: Uuid7 }
  })
  .expect("with no group, the word is nobody's");
  assert_eq!(
    model
      .subscriptions
      .expect("the container was read")
      .upstreams
      .iter()
      .map(|source| source.variant.to_string())
      .collect::<Vec<_>>(),
    ["A", PAIRED],
  );
}