ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
//! The field-fragment tier's emission, over models built BY HAND — `crate::tests`' rule, one tier
//! over.

use quote::ToTokens as _;

use super::{FieldsModel, FragmentField};
use crate::model::{Column, Projection};

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

fn column(name: &str, ty: &str, project: Projection) -> FragmentField {
  FragmentField {
    column: Column {
      name: ident(name),
      source: ident(name),
      ty: syn::parse_str(ty).expect("a type"),
      project,
    },
    docs: Vec::new(),
    build: crate::construct::Build::default(),
    flatten: false,
    condition: crate::model::Condition::always(),
    skip: None,
    stored_name: None,
    wire_name: None,
    derived: Vec::new(),
    write: None,
    read: None,
  }
}

/// The same column with ONE derived column hung off it — `record(derived(…))`, the word that adds a
/// column the write computes and the read never fetches.
fn deriving(name: &str, ty: &str, column: &str, from: &str, derived: &str) -> FragmentField {
  FragmentField {
    derived: vec![super::Derived {
      column: crate::name::RustSafeName::new(column, proc_macro2::Span::call_site()),
      from: syn::parse_str(from).expect("a path"),
      ty: syn::parse_str(derived).expect("a type"),
    }],
    ..self::column(name, ty, Projection::Copied)
  }
}

/// The same column with a WRITE-path transform on it — `record(write = "…")`, the function a value
/// crosses the storage boundary through on its way in.
fn writing(name: &str, ty: &str, write: &str) -> FragmentField {
  FragmentField {
    write: Some(syn::parse_str(write).expect("a path")),
    ..column(name, ty, Projection::Borrowed)
  }
}

/// The same column with `persist(flatten)` on it — the INNER MOUNT that lends no name.
fn flattened(name: &str, ty: &str) -> FragmentField {
  FragmentField {
    flatten: true,
    ..column(name, ty, Projection::Borrowed)
  }
}

/// A two-field value: one handed back by value beside its borrow, one borrowed only.
fn dimensions() -> FieldsModel {
  FieldsModel {
    fragment: ident("Dimensions"),
    vis: syn::Visibility::Public(syn::token::Pub::default()),
    krate: syn::parse_quote!(::ingraph),
    remote: None,
    fields: vec![
      column("width", "u32", Projection::Copied),
      column("label", "String", Projection::Borrowed),
    ],
    construction: crate::construct::Construction::default(),
    cursor: None,
    filter: None,
    delegates: Vec::new(),
    // BOTH host kinds, so the model these tests are written over emits every face — the assertions
    // below are about what each face SAYS, and a per-test activation would put the fork under every
    // one of them. The fork itself is asserted by the two tests that name it.
    record: Some(super::RecordHost {
      databases: Vec::new(),
      write: None,
      read: None,
    }),
    entity: true,
    // …and the WIRE face with them, for the same reason: the assertions below read what each face
    // SAYS, and the fork itself is asserted by the tests that name it.
    wire: Some(super::WireFace {
      object: None,
      filter: None,
    }),
  }
}

/// ONE dialect at a head with nothing mounted at it — the entry every test but the mount's writes.
fn built(kind: crate::model::DatabaseKind) -> super::BuiltFor {
  super::BuiltFor {
    kind,
    comparison: None,
    cursor: None,
  }
}

/// THE SAME two fields, restated as a MANIFEST — the fragment WRAPS a type another crate owns.
///
/// Deliberately the same names, types and projections as [`dimensions`], so every difference the
/// rewrite tests read below is the MODE's rather than the model's.
fn wrapped() -> FieldsModel {
  FieldsModel {
    remote: Some(syn::parse_quote!(upstream::Dimensions)),
    ..dimensions()
  }
}

fn emission(model: &FieldsModel) -> syn::File {
  syn::parse2(model.emit()).expect("the emission is a parsable file")
}

/// Every item the emission declares, descending into the const the impl lives in.
fn items(file: &syn::File) -> Vec<&syn::Item> {
  let mut found = Vec::new();
  for item in &file.items {
    found.push(item);
    if let syn::Item::Const(anonymous) = item
      && let syn::Expr::Block(block) = &*anonymous.expr
    {
      for statement in &block.block.stmts {
        if let syn::Stmt::Item(inner) = statement {
          found.push(inner);
        }
      }
    }
  }
  found
}

/// Every trait the expansion names, as one flat list of `Trait for Self` strings.
fn bound(file: &syn::File) -> Vec<String> {
  items(file)
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Impl(item) => Some(item),
      _ => None,
    })
    .filter_map(|item| {
      let (path, _) = item.trait_.as_ref()?;
      Some(
        format!(
          "{} for {}",
          path.to_token_stream(),
          item.self_ty.to_token_stream()
        )
        .replace(' ', ""),
      )
    })
    .collect()
}

/// The tier's traits are the WIDTH, the two MARKER rows and the COMPARISON's five — and the node
/// families are still absent.
///
/// Asserted as a closed COUNT beside the named ones, because what would break the tier is a face
/// arriving that nobody asked for, and a test that only read the expected impls would pass beside
/// it. The absences are asserted by name for the same reason: they are the tier's definition, and a
/// binding that appeared here would be the ladder collapsing rather than a new feature.
#[test]
fn the_traits_are_the_width_the_markers_and_the_comparison() {
  let file = emission(&dimensions());
  let bound = bound(&file);
  for expected in [
    "::ingraph::__private::column::ColumnKindforDimensions",
    "::ingraph::__private::marker::CompositeFilterMarkerforDimensions",
    "::ingraph::__private::marker::DefaultMarkerforDimensions",
    "::ingraph::__private::graphql::ToGraphqlOutputforDimensions",
    // The predicate's own EMPTINESS answer, which the composed door emits outside the binding
    // gate: *is anything set* is the same question on every backend. TWO of them here, this
    // fixture activating both host kinds — one predicate per face.
    "::ingraph::__private::graphql::GraphqlFilterforDimensionsFilter",
    "::ingraph::__private::graphql::GraphqlFilterforDimensionsColumnFilter",
  ] {
    assert!(bound.iter().any(|row| row == expected), "{bound:?}");
  }
  for face in ["ComplexComparison", "CompositeComparison"] {
    assert!(
      bound
        .iter()
        .any(|row| row.contains(face) && row.contains("forDimensionsComparison")),
      "the comparison wears {face}: {bound:?}"
    );
  }
  // The PAIR, at a parameter: this fixture writes the bare `record`, so its crossing and its empty
  // predicate are one impl each over every backend rather than one per named dialect. Both are
  // ungated for the same reason the map row above is — a dialect-generic impl names no driver.
  for face in [
    "::core::default::DefaultforDimensionsComparison<__INGRAPH_DB__>",
    "::ingraph::__private::comparison::TryFromFilter<DimensionsColumnFilter>\
     forDimensionsComparison<__INGRAPH_DB__>",
  ] {
    assert!(
      bound.iter().any(|row| row == face),
      "the bare word's pair is dialect-generic: {bound:?}"
    );
  }
  // The map row is on the STORED face and on it alone: what a predicate lowers into is a storage
  // fact, and the full face has no lowering to state.
  assert!(
    bound
      .iter()
      .any(|row| row.contains("ToDatabaseComparison<Dimensions")
        && row.contains("forDimensionsColumnFilter")),
    "the map row crosses the STORED filter into the comparison: {bound:?}"
  );
  assert!(
    !bound
      .iter()
      .any(|row| row.contains("ToDatabaseComparison<Dimensions")
        && row.contains("forDimensionsFilter")),
    "and the full face states no lowering: {bound:?}"
  );
  // THE TIER'S DEFINITION, restated as absences. A fragment bears no identity and holds no rows, so
  // none of these can arrive without the ladder having lost its bottom rung.
  for absent in ["Identifiable", "Transformer", "Graphql", "Record"] {
    assert!(
      !bound.iter().any(|row| row.starts_with(absent)),
      "a fragment binds no {absent}: {bound:?}"
    );
  }
  // The `#[Object]` block and the predicate's three INPUT faces are not counted here and cannot be:
  // both ride `if_async_graphql!`, so what the walk sees is a MACRO CALL rather than an impl. That
  // they are gated at all is the assertion below.
  // The DECLARED WORD rides beside the width, and it is one impl over every dialect for the
  // width's own reason: a shape carries no `Db`, so the LENGTH of a fragment's word list is a
  // dialect-free `const` even where the values are the parameter's.
  assert!(
    bound
      .iter()
      .any(|row| row == "::ingraph::__private::column::StoredAs<__INGRAPH_DB__>forDimensions"),
    "the declared word is stated: {bound:?}"
  );
  // …and the ORDER LEAF word beside it, which is one impl over every dialect for the same reason a
  // width is: what a level of this fragment compares is the fragment, whatever database asks. It is
  // a WORD rather than a row — `DeclaredLeaves` carries no items — so a fragment that is never a
  // page boundary pays nothing for it, the `Clone` a boundary costs riding the blanket the word is
  // the key to.
  assert!(
    bound
      .iter()
      .any(|row| row == "::ingraph::__private::column::DeclaredLeavesforDimensions"),
    "the fragment says its columns mean the sequence it declares them in: {bound:?}"
  );
  // THE SAMENESS ROW, beside the width and the leaf word — the face a holder's emitted row folds
  // where it used to derive `PartialEq` over its declared field types, so a fragment is a column a
  // record can compare without its author having derived anything.
  assert!(
    bound
      .iter()
      .any(|row| row == "::ingraph::__private::column::ColumnEqforDimensions"),
    "the fragment says when two of it are one column value: {bound:?}"
  );
  assert_eq!(bound.len(), 14, "and nothing else: {bound:?}");
}

/// The OBJECT rides the binding gate and the CROSSING does not, which is the split every wire face
/// in this tree takes: plain Rust is emitted plainly, and only what names `async_graphql` asks
/// whether `ingraph` was built with it.
#[test]
fn the_object_is_gated_and_the_crossing_is_not() {
  let rendered = prettyplease::unparse(&emission(&dimensions())).replace(' ', "");
  assert!(
    rendered.contains("gate::if_async_graphql!"),
    "the object rides the gate: {rendered}"
  );
  assert!(
    rendered.contains("async_graphql::Object"),
    "and what it carries is the object: {rendered}"
  );
  // LAYER 3 on every field, renamed or not — the `__async_graphql_` prefix is what took the
  // camelCase fallback away from the library, so the fallback is SPELLED.
  assert!(rendered.contains(r#"graphql(name="width")"#), "{rendered}");
  // THREE gates on this fixture, and the split is the same one everywhere in this tree: each
  // predicate's three INPUT faces ride one — and a declaration activating both host kinds has two
  // predicates — the object rides the last, and what stays outside them all is the plain Rust: the
  // crossing, and each filter's own emptiness answer.
  assert_eq!(
    rendered.matches("gate::if_async_graphql!").count(),
    3,
    "one input face per predicate, and the object: {rendered}"
  );
  // The OBJECT's gate is the last one emitted, and the crossing is already declared before it.
  let (before, _) = rendered
    .rsplit_once("gate::if_async_graphql!")
    .expect("the gate");
  assert!(
    before.contains("ToGraphqlOutputforDimensions"),
    "the crossing is ungated: {before}"
  );
  assert!(
    before.contains("GraphqlFilterforDimensionsFilter"),
    "and so is the emptiness answer: {before}"
  );
}

/// The two types it mints are the two FACES, and neither is a node's.
///
/// A fragment still mints no key, no lineage and no row — what it now mints is the predicate a
/// holder's filter carries at the field that holds one, and the comparison that predicate crosses
/// into. Both are the record family's own names for the same shapes.
#[test]
fn the_types_it_mints_are_the_filter_and_the_comparison() {
  let file = emission(&dimensions());
  let minted: Vec<String> = items(&file)
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Struct(item) => Some(item.ident.to_string()),
      syn::Item::Enum(item) => Some(item.ident.to_string()),
      _ => None,
    })
    .collect();
  assert_eq!(
    minted,
    [
      "DimensionsFilter",
      "DimensionsColumnFilter",
      "DimensionsComparison"
    ]
  );
  // AT TOP LEVEL, not inside the anonymous const: a type a holder cannot name is a face it cannot
  // carry, and the whole point of these two is that a holder's own emission projects through them.
  let top: Vec<String> = file
    .items
    .iter()
    .filter_map(|item| match item {
      syn::Item::Struct(item) => Some(item.ident.to_string()),
      _ => None,
    })
    .collect();
  assert_eq!(
    top,
    [
      "DimensionsFilter",
      "DimensionsColumnFilter",
      "DimensionsComparison"
    ]
  );
}

/// EVERY field takes the mutator pair, which is the one place the shape differs from a record's and
/// is a consequence rather than a choice: a record withholds them from the fields that bear
/// identity, and a fragment has no such field.
#[test]
fn every_field_carries_its_mutators() {
  assert_eq!(
    own_methods(&emission(&dimensions())),
    [
      "width",
      "width_ref",
      "set_width",
      "with_width",
      "label_ref",
      "set_label",
      "with_label",
    ],
    "the copy field's extra accessor, and both mutators on each"
  );
}

/// The methods on the FRAGMENT'S OWN inherent impl, in emission order.
///
/// Keyed on the self type rather than on being the only inherent impl there is: the filter and the
/// comparison have inherent impls of their own, and their members are their units' business.
fn own_methods(file: &syn::File) -> Vec<String> {
  items(file)
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Impl(item)
        if item.trait_.is_none() && item.self_ty.to_token_stream().to_string() == "Dimensions" =>
      {
        Some(item)
      }
      _ => None,
    })
    .flat_map(|item| &item.items)
    .filter_map(|item| match item {
      syn::ImplItem::Fn(method) => Some(method.sig.ident.to_string()),
      _ => None,
    })
    .collect()
}

/// The emitted-method walk answers the same names, which is what lets a front end refuse a
/// collision before the expansion lands two of one name in a scope its author cannot edit.
#[test]
fn the_walk_names_exactly_the_methods_the_emission_declares() {
  let model = dimensions();
  let walked: Vec<String> = model
    .emitted_methods()
    .iter()
    .map(|emitted| emitted.name.to_string())
    .collect();
  assert_eq!(
    walked,
    [
      "width",
      "width_ref",
      "set_width",
      "with_width",
      "label_ref",
      "set_label",
      "with_label",
    ]
  );
}

/// Visibility is MIRRORED, for a record's reason: nobody can widen a type they did not declare.
#[test]
fn the_methods_take_the_declarations_own_visibility() {
  let mut model = dimensions();
  model.vis = syn::Visibility::Inherited;
  let rendered = prettyplease::unparse(&emission(&model));
  assert!(
    !rendered.contains("pub "),
    "a private value's methods are private: {rendered}"
  );
  assert!(
    prettyplease::unparse(&emission(&dimensions())).contains("pub const fn width("),
    "and a public one's are public"
  );
}
/// **A REWRITE KEEPS EVERY FACE AND ADDS THE WRAPPER'S OWN.** The four projections a holder asks
/// through are unmoved — a manifest states a name and a type exactly as a held field does — and
/// what joins them is the reference family, which is what makes a wrapper usable where the wrapped
/// type was.
///
/// A CLOSED count again, and a second one rather than a loosening of the first: the two modes emit
/// different sets, and a test that admitted either would assert neither. The absences are the same
/// four and are asserted for the same reason — wrapping a foreign type does not put a fragment on
/// the node ladder.
#[test]
fn a_rewrite_keeps_every_face_and_adds_the_reference_family() {
  let bound = bound(&emission(&wrapped()));
  for face in [
    "::ingraph::__private::column::ColumnKindforDimensions",
    "::ingraph::__private::column::ColumnEqforDimensions",
    "::ingraph::__private::marker::CompositeFilterMarkerforDimensions",
    "::ingraph::__private::marker::DefaultMarkerforDimensions",
    "::ingraph::__private::graphql::ToGraphqlOutputforDimensions",
    "::ingraph::__private::graphql::GraphqlFilterforDimensionsFilter",
    "::ingraph::__private::graphql::GraphqlFilterforDimensionsColumnFilter",
  ] {
    assert!(bound.iter().any(|row| row == face), "{bound:?}");
  }
  for wrapper in [
    "::core::convert::AsRef<upstream::Dimensions>forDimensions",
    "::core::convert::AsMut<upstream::Dimensions>forDimensions",
    "::core::ops::DerefforDimensions",
    "::core::ops::DerefMutforDimensions",
    "::core::borrow::Borrow<upstream::Dimensions>forDimensions",
    "::core::borrow::BorrowMut<upstream::Dimensions>forDimensions",
    "::core::convert::From<upstream::Dimensions>forDimensions",
    "::core::convert::From<Dimensions>forupstream::Dimensions",
  ] {
    assert!(bound.iter().any(|row| row == wrapper), "{bound:?}");
  }
  // The BRIDGE's blanket impl, which is the one row here that is not about either type by name.
  assert!(
    bound
      .iter()
      .any(|row| row.starts_with("__IngraphRemoteBridge")),
    "the crossing marker is declared: {bound:?}"
  );
  // The PAIR is the MODE's business too — a manifest's columns are read off a declared name and a
  // declared type exactly as a held field's are, so the bare word's dialect-generic pair arrives
  // here unchanged. This is the FOUR FACES claim at the one face the pair belongs to.
  for face in [
    "::core::default::DefaultforDimensionsComparison<__INGRAPH_DB__>",
    "::ingraph::__private::comparison::TryFromFilter<DimensionsColumnFilter>\
     forDimensionsComparison<__INGRAPH_DB__>",
  ] {
    assert!(bound.iter().any(|row| row == face), "{bound:?}");
  }
  for absent in ["Identifiable", "Transformer", "Graphql", "Record"] {
    assert!(
      !bound.iter().any(|row| row.starts_with(absent)),
      "a wrapping fragment binds no {absent}: {bound:?}"
    );
  }
  assert_eq!(bound.len(), 23, "and nothing else: {bound:?}");
}

/// **NO IDENTITY SEAT** — one reader per manifest field, and not one member beside it.
///
/// Three absences and one presence, and each is the mode's rather than this walk's: no `_ref`,
/// because a crossed value is owned and there is nothing to borrow; no `set_`/`with_`, because a
/// remote's fields are its own; no `const`, because the body calls a foreign accessor. The `copy`
/// word on `width` decides none of it, which is the point of asserting over a model whose
/// projections are the held fixture's.
#[test]
fn a_rewrite_reads_every_field_by_crossing_and_nothing_else() {
  let file = emission(&wrapped());
  assert_eq!(
    own_methods(&file),
    ["width", "label"],
    "one reader per manifest field, in declared order"
  );
  let rendered = prettyplease::unparse(&file);
  assert!(
    rendered.contains("pub fn width(&self) -> u32 {\n            __ingraph_cross(self.0.width())"),
    "the read is the remote's own accessor, crossed: {rendered}"
  );
  assert!(
    !rendered.contains("pub const fn width("),
    "a foreign accessor is not this emission's to declare `const`: {rendered}"
  );
}

/// A manifest field's own documentation MIGRATES onto its reader — the rewrite deletes the field it
/// was written on, and the reader is where that field's meaning is still answerable.
///
/// The rung above already keeps this promise; the assertion is here because the tier's model
/// carries the docs of its own, and a seat nothing reads is a promise rather than a rule.
#[test]
fn a_manifest_fields_docs_ride_its_reader() {
  let mut model = wrapped();
  model.fields[1].docs = vec![syn::parse_quote!(#[doc = " The label, as the upstream spells it."])];
  let rendered = prettyplease::unparse(&emission(&model));
  assert!(
    rendered.contains("The label, as the upstream spells it."),
    "the sentence the author wrote survives the item that carried it: {rendered}"
  );
}

/// **THE WIRE ARM HOLDS ITS VALUE, and both arms end at the same map.**
///
/// A held field is a place, so its resolver returns `<Ty as ToGraphqlOutput>::Output<'_>` and every
/// arm of that map works. A manifest field is not: the value comes back from `self.0.label()` by
/// value, so the only reference available is one to a temporary. Measured at async-graphql 7.2 —
/// `E0515: cannot return value referencing temporary value` for the borrowing arms, and
/// `E0716: temporary value dropped while borrowed` at `Output<'static>`.
///
/// So the wrapped arm returns `ingraph::Crossed<Ty>`, which takes the value by MOVE and projects out
/// of its own field at resolve time. The obligation is `ToGraphqlOutput` on BOTH arms — where
/// returning the declared type bare had moved the wrapped one onto `async_graphql::OutputType` — and
/// the SDL name is the projection's on both. See [`FieldsModel::wire`](super::FieldsModel::wire),
/// which carries the whole measurement.
#[test]
fn the_wrapped_wire_arm_holds_its_value_and_crosses_out_of_it() {
  // WHITESPACE-FREE, because the two arms are compared inside a macro call and `prettyplease`
  // breaks a macro's token stream at widths that have nothing to do with what is being asserted.
  let dense = |model: &FieldsModel| {
    prettyplease::unparse(&emission(model))
      .split_whitespace()
      .collect::<String>()
  };
  let held = dense(&dimensions());
  assert!(
    held.contains("asyncfn__async_graphql_label(&self)-><Stringas"),
    "a held field crosses: {held}"
  );
  let wrapped = dense(&wrapped());
  assert!(
    wrapped.contains(
      "asyncfn__async_graphql_label(&self)->::ingraph::__private::graphql::Crossed<String>{::\
       ingraph::__private::graphql::Crossed(Self::label(self))}"
    ),
    "a manifest field is HELD and crossed out of: {wrapped}"
  );
  assert!(
    !wrapped.contains("asyncfn__async_graphql_label(&self)->String{"),
    "and never handed back bare, which is what put it on the library's own map: {wrapped}"
  );
}

/// The emitted-method walk forks where the emission forks, so a front end refusing a collision is
/// reading the names really declared rather than a second copy of the rule.
#[test]
fn the_walk_names_exactly_the_readers_the_rewrite_declares() {
  let model = wrapped();
  let walked: Vec<String> = model
    .emitted_methods()
    .iter()
    .map(|emitted| emitted.name.to_string())
    .collect();
  assert_eq!(walked, own_methods(&emission(&model)));
  assert_eq!(walked, ["width", "label"]);
}

/// The tokens the emission really writes, with every space removed.
///
/// WHITESPACE-FREE, for the reason the wire assertion's own local copy is: `prettyplease` breaks a
/// token stream at widths that have nothing to do with what is being asserted, and half of what is
/// read below sits inside a macro call.
fn dense_of(model: &FieldsModel) -> String {
  prettyplease::unparse(&emission(model))
    .split_whitespace()
    .collect::<String>()
}

/// ONE emitted struct, by name, rendered dense — its SHAPE, with the doc comment taken off.
///
/// The doc is the one thing the two predicate faces are meant to differ in beyond their names: each
/// says which reading of the shared sentence applies to it. Comparing shapes is what makes the
/// *modulo the rename* claim below a claim about the emission rather than about prose.
fn minted(file: &syn::File, name: &str) -> String {
  let mut item = items(file)
    .into_iter()
    .find_map(|item| match item {
      syn::Item::Struct(item) if item.ident == name => Some(item.clone()),
      _ => None,
    })
    .unwrap_or_else(|| panic!("`{name}` is minted"));
  item.attrs.retain(|attr| !attr.path().is_ident("doc"));
  item.to_token_stream().to_string().replace(' ', "")
}

/// Every struct the emission mints, in emission order.
fn structs(file: &syn::File) -> Vec<String> {
  items(file)
    .into_iter()
    .filter_map(|item| match item {
      syn::Item::Struct(item) => Some(item.ident.to_string()),
      _ => None,
    })
    .collect()
}

/// **ONE ACTIVATION, ONE TYPE — seated at both marker rows.**
///
/// The zero-cost half of the ruling, asserted from both ends. A record-hosted declaration mints the
/// STORED face and nothing else; an entity-hosted one mints the FULL face and nothing else; and each
/// names its one type at both seats, so a holder of the kind the declaration did not activate
/// resolves to the predicate there is rather than to a face nobody emitted.
#[test]
fn a_single_activation_mints_one_predicate_and_seats_it_at_both_rows() {
  let stored = FieldsModel {
    entity: false,
    ..dimensions()
  };
  assert_eq!(
    structs(&emission(&stored)),
    ["DimensionsColumnFilter", "DimensionsComparison"]
  );
  assert!(
    dense_of(&stored).contains(
      "CompositeFilterMarkerforDimensions{typeFilter=DimensionsColumnFilter;typeColumnFilter=DimensionsColumnFilter;}"
    ),
    "the stored face takes both seats"
  );

  let projected = FieldsModel {
    record: None,
    ..dimensions()
  };
  assert_eq!(
    structs(&emission(&projected)),
    ["DimensionsFilter"],
    "an entity-hosted fragment mints the full face and no storage answer at all"
  );
  assert!(
    dense_of(&projected).contains(
      "CompositeFilterMarkerforDimensions{typeFilter=DimensionsFilter;typeColumnFilter=DimensionsFilter;}"
    ),
    "and the full face takes both seats"
  );
}

/// **THE TWO FACES ARE ONE WALK**, so a declaration that skips nothing gets two structs differing by
/// the word `Column` and by nothing else.
///
/// The delta is measured rather than asserted by eye: insert `Column` at the two places it belongs —
/// the type's own name and the projection's associated item — and the two renderings are equal. That
/// is the whole cost of the second face on the fragments the corpus already had.
#[test]
fn the_two_faces_differ_by_the_word_column_and_nothing_else() {
  let file = emission(&dimensions());
  let full = minted(&file, "DimensionsFilter");
  let stored = minted(&file, "DimensionsColumnFilter").replace("ColumnFilter", "Filter");
  assert_eq!(full, stored);
}

/// **AND WHERE A FIELD IS SKIPPED THEY PART**, which is the ruling itself: the stored face has no
/// slot for a column no database holds, and the full face keeps every declared field.
#[test]
fn the_stored_face_drops_a_skipped_field_and_the_full_face_keeps_it() {
  use crate::model::Fill;

  let mut model = dimensions();
  model.fields[1].skip = Some(Fill {
    at: proc_macro2::Span::call_site(),
    named: None,
  });
  let file = emission(&model);
  assert!(
    minted(&file, "DimensionsFilter").contains("label:"),
    "memory is the data, so a rowless host may ask about it"
  );
  assert!(
    !minted(&file, "DimensionsColumnFilter").contains("label:"),
    "and a row-holding host may not: what it would compare is a raise's fill"
  );
}

/// **THE STORAGE FACE RIDES THE FAMILY GATE**, which is what keeps a build compiling no SQL family
/// from naming a trait it has not got — and a build compiling two from getting the impls twice.
///
/// Both rows are inside `if_sqlx!`, so the trait walk above cannot see them: what it sees is a MACRO
/// CALL. That is exactly why the closed count in
/// [`the_traits_are_the_width_the_markers_and_the_comparison`] did not move when they arrived.
#[test]
fn the_bind_and_the_read_are_behind_the_sqlx_gate() {
  let emitted = dense_of(&dimensions());
  for face in ["Carrier", "Assemble"] {
    assert!(
      emitted.contains(face),
      "the {face} row is emitted: {emitted}"
    );
  }
  let file = emission(&dimensions());
  for row in bound(&file) {
    assert!(
      !row.contains("Carrier") && !row.contains("Assemble"),
      "and neither is a bare impl the walk can see: {row}"
    );
  }
}

/// **N BINDS AND THE COMMAS BETWEEN THEM**, one per declared field — and the comma is written
/// BEFORE every part but the first, so a two-field fragment pushes exactly one.
#[test]
fn the_bind_pushes_one_placeholder_per_column_with_its_own_separator() {
  let emitted = dense_of(&dimensions());
  assert_eq!(
    emitted.matches("::push_bind(&self.").count(),
    2,
    "one bind per field: {emitted}"
  );
  assert_eq!(
    emitted.matches("push(__ingraph_qb,\",\")").count(),
    1,
    "and one comma between the two: {emitted}"
  );
}

/// **THE NAMES ARE ONE `const`, AND BOTH READERS INDEX IT.** A second spelling of a column's name is
/// the drift this arrangement exists to make unspellable.
#[test]
fn the_width_and_the_read_name_the_columns_from_one_list() {
  let emitted = dense_of(&dimensions());
  assert!(
    emitted.contains(
      "const__INGRAPH_FRAGMENT_FIELDS:&[&'static::ingraph::__private::field::FieldName]=&[\
       ::ingraph::__private::field::FieldName::new(\"width\"),\
       ::ingraph::__private::field::FieldName::new(\"label\"),]"
    ),
    "the one list: {emitted}"
  );
  assert!(
    emitted.contains("ColumnName::of(__INGRAPH_FRAGMENT_FIELDS[0usize],)"),
    "the width indexes it: {emitted}"
  );
  assert!(
    emitted.contains("__INGRAPH_FRAGMENT_FIELDS[0usize],__ingraph_under)?"),
    "and so does the read: {emitted}"
  );
  assert!(
    !emitted.contains("FieldName::new(\"width\"),__ingraph_under"),
    "so no read spells a name of its own: {emitted}"
  );
}

/// **AN OWN FRAGMENT IS RAISED LITERALLY**, and a WRAPPED one through the construction protocol —
/// one seam, two answers, and the second is the record rung's own saddle rather than a copy.
#[test]
fn the_raise_is_a_literal_for_a_held_fragment_and_a_call_for_a_wrapped_one() {
  assert!(
    dense_of(&dimensions()).contains("Ok(Self{width,label,})"),
    "the struct literal"
  );
  let wrapped = dense_of(&wrapped());
  assert!(
    wrapped.contains(
      "Ok(Self(upstream::Dimensions::new(__ingraph_cross(width),__ingraph_cross(label))))"
    ),
    "the default law: every column a positional argument to `new`, crossed: {wrapped}"
  );
}

/// **NO CURSOR WORD, NO CURSOR ROW** — the one face here that is an assertion rather than a
/// consequence, and its absence is what a fragment declaring nothing gets.
#[test]
fn a_wordless_fragment_is_no_position_in_an_order() {
  assert!(!dense_of(&dimensions()).contains("CursorValue"));
  let keyed = FieldsModel {
    cursor: Some(Vec::new()),
    ..dimensions()
  };
  let emitted = dense_of(&keyed);
  assert!(emitted.contains("CursorValueforDimensions"), "{emitted}");
  assert_eq!(
    emitted.matches("write_member(&self.").count(),
    2,
    "one framed member per key column: {emitted}"
  );
  assert_eq!(
    emitted.matches("read_member(&mut__ingraph_rest,)?").count(),
    2,
    "and one read back: {emitted}"
  );
  assert!(
    emitted.contains("is_empty(__ingraph_rest)"),
    "with a trailing byte refused: {emitted}"
  );
}

/// **A LISTED KEY IS THE SAME KEY** — the list is a PIN, so the emission it produces is token for
/// token the bare word's.
///
/// That is the whole claim the pin rests on: if the two could differ, the list would be a second way
/// to say something rather than a check on the first.
#[test]
fn a_pinned_key_emits_what_the_bare_word_emits() {
  let bare = FieldsModel {
    cursor: Some(Vec::new()),
    ..dimensions()
  };
  let pinned = FieldsModel {
    cursor: Some(vec![ident("width"), ident("label")]),
    ..dimensions()
  };
  assert_eq!(dense_of(&bare), dense_of(&pinned));
}

/// **THE NESTING FIXTURE** — one fragment holding two, one seat lending its name and one flattened.
///
/// The shape a real consumer has: a detection is a box plus a classification, and which of the two
/// wears a prefix is a layout decision rather than a fact about either type.
fn detection() -> FieldsModel {
  FieldsModel {
    fragment: ident("ObjectDetection"),
    fields: vec![
      column("bounds", "BoundingBox", Projection::Borrowed),
      flattened("classification", "Classification"),
    ],
    ..dimensions()
  }
}

/// **THE WIDTH IS THE FIELD'S OWN TYPE ANSWERING, AND `flatten` PICKS THE OTHER SPELLING.**
///
/// Nothing here counts a nested fragment's columns or joins its names: `shape::<BoundingBox>` is the
/// same token a scalar field writes, and the descent is the `ColumnShape` tree's.
#[test]
fn an_inner_mount_lends_its_name_unless_it_was_flattened() {
  let emitted = dense_of(&detection());
  assert!(
    emitted.contains("column::shape::<BoundingBox,>(::ingraph::__private::column::ColumnName::of("),
    "the nested seat lends its name: {emitted}"
  );
  assert!(
    emitted.contains("column::flattened::<Classification>()"),
    "and the flattened one lends none: {emitted}"
  );
}

/// **AND THE READ IS THE SAME FORK, ONE FUNCTION APART** — the decode of a flattened mount takes the
/// path unchanged, which is what makes it the exact twin of the column list rather than a second rule
/// that agrees today.
#[test]
fn a_flattened_mount_reads_at_the_fragments_own_path() {
  let emitted = dense_of(&detection());
  assert!(
    emitted.contains("assembled(__ingraph_row,__INGRAPH_FRAGMENT_FIELDS[0usize],__ingraph_under)?"),
    "the nested seat descends a segment: {emitted}"
  );
  assert!(
    emitted.contains("assembled_flattened(__ingraph_row,__ingraph_under)?"),
    "and the flattened one does not: {emitted}"
  );
  assert!(
    !emitted.contains("__INGRAPH_FRAGMENT_FIELDS[1usize]"),
    "so nothing indexes the name it did not lend: {emitted}"
  );
}

/// **THE PREDICATE FORKS AT THE SAME SEAM** — one conjunct per field, and the flattened one is
/// applied at the address it was handed rather than one segment below it.
#[test]
fn a_flattened_mount_renders_at_the_address_it_was_handed() {
  let emitted = dense_of(&detection());
  assert!(
    emitted
      .contains("At::frame(__ingraph_at,::ingraph::__private::field::FieldName::new(\"bounds\"),)"),
    "the nested seat pushes its frame: {emitted}"
  );
  assert_eq!(
    emitted.matches("At::frame(").count(),
    1,
    "and the flattened one pushes none: {emitted}"
  );
  assert!(
    emitted.contains("apply(&self.classification,__ingraph_at,__ingraph_builder)?"),
    "so it renders where the whole fragment was applied: {emitted}"
  );
}

/// **ONLY A FLATTENING FRAGMENT PAYS THE FENCE**, which is the `where`-clause discipline kept: a
/// `const` assertion is evaluated where it is written, so one per fragment would demand every field's
/// `ColumnKind` row at the declaration instead of at the record that stores it.
#[test]
fn the_rendered_names_are_fenced_only_where_a_field_was_flattened() {
  let plain = dense_of(&dimensions());
  assert!(
    !plain.contains("distinct("),
    "a fragment that flattens nothing cannot collide: {plain}"
  );
  let emitted = dense_of(&detection());
  assert_eq!(
    emitted.matches("distinct(<ObjectDetectionas").count(),
    2,
    "one assertion per field, over the impl's own const: {emitted}"
  );
  assert!(
    emitted.contains("wouldrender`classification`intoacolumn"),
    "and the one that fires names the field: {emitted}"
  );
}

/// **A KEY MEMBER IS ONE COLUMN**, asserted at the declaration — the refusal a nested cursor-bearing
/// fragment would otherwise walk straight past, its `CursorValue` row being present.
#[test]
fn every_key_member_is_asserted_to_span_one_column() {
  let keyed = FieldsModel {
    cursor: Some(Vec::new()),
    ..detection()
  };
  let emitted = dense_of(&keyed);
  assert_eq!(
    emitted.matches("::SEGMENTS.is_empty(),\"`").count(),
    2,
    "one width assertion per key member: {emitted}"
  );
  assert!(
    emitted
      .contains("<BoundingBoxas::ingraph::__private::column::ColumnKind>::SEGMENTS.is_empty()"),
    "each over the member's own type: {emitted}"
  );
  assert!(
    !dense_of(&detection()).contains("SEGMENTS.is_empty()"),
    "and a fragment with no key asserts nothing about a width"
  );
}

/// **THE PAIR IS THE DIALECT LIST SPENT**, and the list being EMPTY spends it at a parameter.
///
/// The two rows a wire-faced holder asks a composite column for — the value-level crossing and the
/// empty predicate — are written at a CONCRETE backend wherever the declaration named one, so which
/// backends they are written at is the declaration's to say. `record(sqlite, postgres)` says it, and
/// gets one pair per entry, each behind that backend's gate. The bare `record` names none and gets
/// ONE pair over a parameter, which is a different emission rather than an absent one: see
/// [`the_bare_word_emits_the_pair_at_a_parameter`].
///
/// The two are EXCLUSIVE, and the reason is coherence: `impl<DB> … for XComparison<DB>` overlaps
/// `impl … for XComparison<Sqlite>`, so a declaration takes one arm or the other.
#[test]
fn the_comparison_pair_is_emitted_per_declared_dialect_and_nowhere_else() {
  use crate::model::DatabaseKind;

  let named = FieldsModel {
    record: Some(super::RecordHost {
      databases: vec![built(DatabaseKind::Sqlite), built(DatabaseKind::Postgres)],
      write: None,
      read: None,
    }),
    ..dimensions()
  };
  let emitted = dense_of(&named);
  assert_eq!(
    emitted
      .matches("TryFromFilter<DimensionsColumnFilter>")
      .count(),
    2,
    "one crossing per declared dialect: {emitted}"
  );
  assert_eq!(
    emitted
      .matches("::core::default::Defaultfor DimensionsComparison<")
      .count(),
    0,
    "the empty predicate is written at a concrete backend rather than generically"
  );
  for (gate, backend) in [
    ("if_sqlite!", "sqlx::Sqlite"),
    ("if_postgres!", "sqlx::Postgres"),
  ] {
    let dense = gate.replace(' ', "");
    assert!(
      emitted.contains(&dense),
      "each pair rides its own backend's gate: {emitted}"
    );
    assert!(
      emitted.contains(&backend.replace(' ', "")),
      "and names that backend concretely: {emitted}"
    );
  }
}

/// **THE BARE WORD'S PAIR IS ONE IMPL OVER EVERY BACKEND**, and its clause is the union of its
/// members' rows.
///
/// The declaration names no dialect, so there is no concrete backend to write the pair at and no
/// gate for it to ride. What stands in for both is the crossing being reached through
/// `ToCrossedComparison`'s methods rather than through the comparison's projection: the body names
/// no comparison type at all, and each member's obligation is a predicate whose SELF TYPE is that
/// member's filter.
#[test]
fn the_bare_word_emits_the_pair_at_a_parameter() {
  let emitted = dense_of(&dimensions());

  for row in [
    "::ingraph::__private::comparison::TryFromFilter<DimensionsColumnFilter>\
     forDimensionsComparison<__INGRAPH_DB__>where",
    "impl<__INGRAPH_DB__>::core::default::DefaultforDimensionsComparison<__INGRAPH_DB__>where",
  ] {
    assert!(
      emitted.contains(row),
      "one pair over the parameter: {emitted}"
    );
  }
  // The two rows, at the members' own kinds — the union, one predicate per member.
  for member in ["u32", "String"] {
    assert!(
      emitted.contains(&format!(
        "as::ingraph::__private::comparison::ToCrossedComparison<{member},__INGRAPH_DB__,>>::cross"
      )),
      "each member crosses through its own kind's row: {emitted}"
    );
    assert!(
      emitted.contains(&format!(
        "as::ingraph::__private::comparison::ToCrossedComparison<{member},__INGRAPH_DB__,>>::empty"
      )),
      "and answers the empty predicate through the same one: {emitted}"
    );
  }
  // No gate and no concrete backend: a dialect-generic impl names no driver.
  for absent in [
    "if_sqlite!",
    "if_postgres!",
    "sqlx::Sqlite",
    "sqlx::Postgres",
  ] {
    assert!(
      !emitted.contains(&absent.replace(' ', "")),
      "the generic arm names no dialect: {absent} in {emitted}"
    );
  }
  // And the projection is nowhere in the BODY — that is the whole of what buys the parameter.
  assert!(
    !emitted.contains("as::ingraph::__private::comparison::TryFromFilter<<<u32"),
    "the body reaches no comparison through its projection: {emitted}"
  );
}

/// The union is DEDUPLICATED: two members of one type ask one question.
///
/// A `where` clause is a set, and a predicate written twice says nothing the once did. The count is
/// asserted rather than the presence, because the failure this guards against is a clause that grows
/// with the field list rather than with the kind list.
#[test]
fn the_generic_clause_states_one_row_per_kind_and_not_per_field() {
  let mut model = dimensions();
  model
    .fields
    .push(column("height", "u32", Projection::Copied));
  let emitted = dense_of(&model);

  let row =
    "::ColumnFilter:::ingraph::__private::comparison::ToCrossedComparison<u32,__INGRAPH_DB__,>,";
  assert_eq!(
    emitted.matches(row).count(),
    2,
    "TWO clauses carry the row — the crossing's and the empty predicate's — and neither repeats it \
     for the second `u32` field: {emitted}"
  );
  // The BODY still walks every field, which is what makes the dedup a fact about the clause alone.
  for member in ["width", "height", "label"] {
    assert!(
      emitted.contains(&format!("__ingraph_filter.{member}")),
      "every member is still crossed: {emitted}"
    );
  }
}

/// A NAMED dialect keeps today's emission, byte for byte — the generic arm is reached only by the
/// bare word.
///
/// The claim the whole knife rests on: a declaration that already had the pair must not have moved.
/// Asserted as an ABSENCE of the new seam anywhere in the named emission, beside the concrete arm's
/// own assertions above, because the two arms are exclusive and a declaration carrying both would be
/// `E0119` inside an expansion its author cannot edit.
#[test]
fn a_named_dialect_never_reaches_the_generic_arm() {
  use crate::model::DatabaseKind;

  let named = FieldsModel {
    record: Some(super::RecordHost {
      databases: vec![built(DatabaseKind::Sqlite)],
      write: None,
      read: None,
    }),
    ..dimensions()
  };
  let emitted = dense_of(&named);

  assert!(
    !emitted.contains("ToCrossedComparison"),
    "a named dialect discharges its members' rows rather than carrying them: {emitted}"
  );
  assert!(
    !emitted.contains("impl<__INGRAPH_DB__>::ingraph::__private::comparison::TryFromFilter<"),
    "and writes its crossing at the backend rather than at the parameter: {emitted}"
  );
  assert_eq!(
    emitted
      .matches("impl<__INGRAPH_DB__>::core::default::Default")
      .count(),
    0,
    "including the empty predicate: {emitted}"
  );
}

/// **A `#[cfg]` FIELD LEAVES BOTH WALKS**, in either arm — the leg that crosses it and the argument
/// that hands it to the constructor.
///
/// A function parameter and a call argument are both attribute positions, so `unit::comparison`'s
/// `new` really loses an argument where its column is gone and this pair has to lose the same one.
/// Written otherwise it is `E0061` at the constructor and `E0609` at the filter's member, inside an
/// expansion its author cannot edit — measured on `ingraph`'s own `fragment_condition_wire` lane,
/// which writes the bare `record` and so had no pair to be wrong until the parameter arm existed.
#[test]
fn a_conditional_member_leaves_the_crossing_and_the_constructor() {
  use crate::model::{Condition, DatabaseKind};

  let mut model = dimensions();
  model.fields[1].condition = Condition::of(vec![syn::parse_quote!(#[cfg(any())])], Vec::new());

  for (arm, emitted) in [
    ("the parameter", dense_of(&model)),
    (
      "the backend",
      dense_of(&FieldsModel {
        record: Some(super::RecordHost {
          databases: vec![built(DatabaseKind::Sqlite)],
          write: None,
          read: None,
        }),
        ..model.clone()
      }),
    ),
  ] {
    assert!(
      emitted.contains("#[cfg(any())]letlabel=match__ingraph_filter.label"),
      "{arm}: the conditional member's leg rides its own gate: {emitted}"
    );
    assert!(
      emitted.contains("Self::new(width,#[cfg(any())]label"),
      // The trailing comma differs between the arms and says nothing: the concrete pair rides a
      // `gate!` macro call, whose token stream prettyplease prints verbatim.
      "{arm}: and so does the argument that hands it over: {emitted}"
    );
  }

  // The UNCONDITIONAL declaration is untouched, which is what keeps every existing expansion byte
  // for byte what it was: an empty gate renders no tokens at all.
  let plain = dense_of(&dimensions());
  assert!(
    plain.contains("Self::new(width,label)"),
    "no gate, no change: {plain}"
  );
}

/// A MOUNTED filter takes the generic crossing with it and leaves the generic empty predicate,
/// which is the concrete arm's own split at the parameter.
#[test]
fn the_swap_reaches_the_generic_arm_the_same_way() {
  let mounted = FieldsModel {
    filter: Some(syn::parse_quote!(faces::DimensionsWhere)),
    ..dimensions()
  };
  let emitted = dense_of(&mounted);

  assert!(
    !emitted.contains("TryFromFilter<DimensionsColumnFilter>"),
    "the author's predicate brings its own crossing: {emitted}"
  );
  assert!(
    emitted.contains("impl<__INGRAPH_DB__>::core::default::DefaultforDimensionsComparison"),
    "and the empty predicate stays, being a fact about the comparison: {emitted}"
  );
}

/// The pair walks the PARTICIPATING subset, so a `record(skip)`ped field is neither crossed nor
/// counted into the empty predicate.
///
/// The crossing zips the filter's slots against the comparison's members, and `skip` takes a field
/// out of both — a leg for it would name a filter member that is not there.
#[test]
fn the_pair_walks_the_participation_and_not_the_declaration() {
  use crate::model::{DatabaseKind, Fill};

  let mut model = FieldsModel {
    record: Some(super::RecordHost {
      databases: vec![built(DatabaseKind::Sqlite)],
      write: None,
      read: None,
    }),
    ..dimensions()
  };
  model.fields[1].skip = Some(Fill {
    at: proc_macro2::Span::call_site(),
    named: None,
  });
  let emitted = dense_of(&model);
  assert!(
    emitted.contains("__ingraph_filter.width"),
    "the column that stays is crossed: {emitted}"
  );
  assert!(
    !emitted.contains("__ingraph_filter.label"),
    "and the one with no column anywhere is not: {emitted}"
  );
}

/// **THE SWAP TAKES FOUR EMISSIONS WITH IT**, and leaves the fifth.
///
/// `filter = "…"` says the predicate over this value is the AUTHOR's, so the generated one is not
/// emitted at all — no struct, no input face — and neither is what it would have LOWERED into: the
/// `ToDatabaseComparison` map row and the value-level crossing are facts about a predicate, and this
/// declaration no longer owns one. What stays is the EMPTY predicate, which is a fact about the
/// COMPARISON — still this emission's, and the row an author's own lowering points at.
#[test]
fn a_mounted_filter_replaces_the_generated_one_and_what_it_lowered_into() {
  use crate::model::DatabaseKind;

  let mounted = FieldsModel {
    filter: Some(syn::parse_quote!(faces::DimensionsWhere)),
    record: Some(super::RecordHost {
      databases: vec![built(DatabaseKind::Sqlite)],
      write: None,
      read: None,
    }),
    ..dimensions()
  };
  let emitted = dense_of(&mounted);

  for generated in ["structDimensionsFilter", "structDimensionsColumnFilter"] {
    assert!(
      !emitted.contains(generated),
      "NEITHER generated predicate is declared — one word, one predicate: {emitted}"
    );
  }
  assert!(
    !emitted.contains("ToDatabaseComparison<Dimensions,DB>forDimensionsColumnFilter"),
    "nor the map row that said what it compares: {emitted}"
  );
  assert!(
    !emitted.contains("TryFromFilter<DimensionsColumnFilter>"),
    "nor the value-level crossing beside it: {emitted}"
  );
  assert!(
    !emitted.contains("InputObjectType"),
    "and the input face a generated predicate registers is gone with the struct: {emitted}"
  );

  assert!(
    emitted.contains(
      "CompositeFilterMarkerforDimensions{typeFilter=faces::DimensionsWhere;typeColumnFilter=faces::DimensionsWhere;}"
    ),
    "the marker row names the author's type at BOTH seats, which is the swap being a swap: \
     {emitted}"
  );
  assert!(
    emitted.contains("DefaultMarkerforDimensions"),
    "and the reading is unmoved, which is why no holder learns a word: {emitted}"
  );
  assert!(
    emitted.contains("::core::default::DefaultforDimensionsComparison<"),
    "the EMPTY predicate is a fact about the comparison and stays: {emitted}"
  );
}

/// The obligations a mounted predicate owes are spent at the DECLARATION, and the input one only
/// where the declaration published a face for a client to name it through.
#[test]
fn a_mounted_filter_owes_what_a_holder_holds_at_its_own_span() {
  let mounted = FieldsModel {
    filter: Some(syn::parse_quote!(faces::DimensionsWhere)),
    ..dimensions()
  };
  let emitted = dense_of(&mounted);
  assert!(emitted.contains("trait__IngraphMountedFilter"), "{emitted}");
  assert!(
    emitted.contains("trait__IngraphMountedInput"),
    "the wire obligation rides the wire activation: {emitted}"
  );

  let quiet = FieldsModel {
    wire: None,
    ..mounted
  };
  let emitted = dense_of(&quiet);
  assert!(
    emitted.contains("trait__IngraphMountedFilter"),
    "a holder HOLDS the predicate whatever this declaration publishes: {emitted}"
  );
  assert!(
    !emitted.contains("trait__IngraphMountedInput"),
    "but a declaration with no face asks its predicate for none either: {emitted}"
  );
}

/// A wrapping fragment with a delegate FAN — the forwarding methods on its inherent impl, and the
/// lifted entries on its object beside the columns.
fn delegating() -> FieldsModel {
  FieldsModel {
    delegates: vec![
      crate::delegate::Delegate {
        signature: syn::parse_quote!(fn label(&self) -> String),
        exclusive: false,
        wire: vec![crate::delegate::DelegateSkin {
          kind: crate::model::GraphqlKind::AsyncGraphql,
          rename: None,
        }],
        on_self: None,
      },
      crate::delegate::Delegate {
        signature: syn::parse_quote!(fn pixels(&self) -> u64),
        exclusive: false,
        wire: vec![crate::delegate::DelegateSkin {
          kind: crate::model::GraphqlKind::AsyncGraphql,
          rename: Some(syn::parse_quote!("pixelCount")),
        }],
        on_self: None,
      },
      crate::delegate::Delegate {
        signature: syn::parse_quote!(fn halve(&mut self)),
        exclusive: true,
        wire: Vec::new(),
        on_self: None,
      },
    ],
    ..wrapped()
  }
}

/// **AN ENTRY FORWARDS ONTO THE WRAPPED VALUE**, and the receiver decides which borrow of it the
/// body takes — never a materialisation, this tier HOLDING what a mirror has to rebuild.
#[test]
fn a_delegate_forwards_onto_the_value_the_wrapper_holds() {
  let emitted = delegating().emit().to_string();
  assert!(
    emitted.contains("fn label (& self) -> String { (& self . 0) . label () }"),
    "{emitted}"
  );
  assert!(
    emitted.contains("fn halve (& mut self) { (& mut self . 0) . halve () }"),
    "an exclusive receiver mutates in place, at no conversion: {emitted}"
  );
}

/// **A LIFTED ENTRY IS A FIELD OF THE OBJECT**, riding `Crossed` because its value is MANUFACTURED —
/// and reached by a fully qualified call, because a wrapper DEREFS.
#[test]
fn a_lifted_delegate_rides_the_holding_adapter() {
  let emitted = delegating().emit().to_string();
  assert!(
    emitted.contains(r#"# [graphql (name = "label")]"#),
    "{emitted}"
  );
  assert!(
    emitted.contains(r#"# [graphql (name = "pixelCount")]"#),
    "and `rename` moves the word a client writes: {emitted}"
  );
  assert!(
    emitted.contains(
      "Crossed < u64 > { :: ingraph :: __private :: graphql :: Crossed (Self :: pixels (self)) }"
    ),
    "the manufactured value moves into the adapter, reached fully qualified: {emitted}"
  );
  assert!(
    !emitted.contains(r#"# [graphql (name = "halve")]"#),
    "an exclusive receiver is never lifted: {emitted}"
  );
}

/// The seat is EMPTY on an ordinary declaration, and costs it nothing: the front end refuses every
/// entry on a fragment that wraps nothing, so this walk never sees one.
#[test]
fn a_fragment_with_no_seat_pays_nothing_for_it() {
  let emitted = dimensions().emit().to_string();
  assert!(!emitted.contains("Crossed <"), "{emitted}");
}

/// **AN ORDINARY FRAGMENT'S ENTRY MINTS NO METHOD, AND LIFTS THROUGH `Self`.**
///
/// The seat asks nothing about where a method came from — clause ⑨'s letter, and what the emission
/// forks on is the MODE rather than the acceptance. A wrapper needs the forwarding method, its
/// wrapped value's being reachable only through `Deref`; a fragment that wraps nothing already HAS
/// the method, on the author's own `impl`, and a same-named one emitted beside it would be that
/// method calling itself. So the entry's whole content here is the field of the object, and
/// `Self::label(self)` is where method resolution — and an `E0599` for a name nothing answers to —
/// happens.
#[test]
fn an_own_fragments_delegate_is_lifted_and_never_forwarded() {
  let own = FieldsModel {
    delegates: vec![crate::delegate::Delegate {
      signature: syn::parse_quote!(fn label(&self) -> String),
      exclusive: false,
      wire: vec![crate::delegate::DelegateSkin {
        kind: crate::model::GraphqlKind::AsyncGraphql,
        rename: None,
      }],
      on_self: None,
    }],
    ..dimensions()
  };
  let emitted = own.emit().to_string();

  assert!(
    emitted.contains(r#"# [graphql (name = "label")]"#),
    "the entry is a field of the object: {emitted}"
  );
  assert!(
    emitted.contains(
      "Crossed < String > { :: ingraph :: __private :: graphql :: Crossed (Self :: label (self)) }"
    ),
    "reached through `Self`, which is where resolution answers: {emitted}"
  );
  assert!(
    !emitted.contains("fn label (& self) -> String { (& self . 0)"),
    "and NO forwarding method is minted — the method is already the author's: {emitted}"
  );

  let wrapper = FieldsModel {
    remote: Some(syn::parse_quote!(upstream::Dimensions)),
    ..own
  };
  assert!(
    wrapper
      .emit()
      .to_string()
      .contains("fn label (& self) -> String { (& self . 0) . label () }"),
    "where a wrapper needs one, it is minted — the same entry, the other mode"
  );
}

/// **`on = self` PUTS A WRAPPER'S ENTRY IN THE ORDINARY MODE'S POSITION** — nothing minted, the
/// lifted half unchanged.
///
/// The mint calls the method on the WRAPPED value, which is wrong for exactly one case: a method the
/// author wrote on the wrapper. There it is `E0599` at the body, or `E0592` against the author's own
/// inherent one — so the word takes the entry out of this walk and leaves everything else alone. The
/// lifted body is `Self::m(self)` either way, which is why the waiver costs the wire face nothing.
#[test]
fn a_waived_entry_mints_no_forwarding_half() {
  let waived = FieldsModel {
    delegates: vec![crate::delegate::Delegate {
      signature: syn::parse_quote!(fn label(&self) -> String),
      exclusive: false,
      wire: vec![crate::delegate::DelegateSkin {
        kind: crate::model::GraphqlKind::AsyncGraphql,
        rename: None,
      }],
      on_self: Some(ident("self")),
    }],
    ..wrapped()
  };
  let emitted = waived.emit().to_string();

  assert!(
    !emitted.contains("(& self . 0) . label ()"),
    "the forwarding half is not emitted: {emitted}"
  );
  assert!(
    emitted.contains(
      "Crossed < String > { :: ingraph :: __private :: graphql :: Crossed (Self :: label (self)) }"
    ),
    "and the LIFTED half is untouched, reaching the author's method through `Self`: {emitted}"
  );
}

/// **THE WAIVER IS PER ENTRY**, so a shorthand one beside it is minted exactly as before.
///
/// The delta is the whole assertion: one model, one entry moved, and every other byte of the
/// rewrite's inherent impl the same.
#[test]
fn a_waiver_moves_one_entry_and_no_other() {
  let before = delegating().emit().to_string();
  let mut model = delegating();
  model.delegates[0].on_self = Some(ident("self"));
  let after = model.emit().to_string();

  assert!(
    before.contains("fn label (& self) -> String { (& self . 0) . label () }"),
    "{before}"
  );
  assert!(!after.contains("(& self . 0) . label ()"), "{after}");
  assert!(
    after.contains("fn halve (& mut self) { (& mut self . 0) . halve () }"),
    "the entry beside it is minted unchanged: {after}"
  );
  assert!(
    after.contains("Crossed (Self :: pixels (self))"),
    "and so is every lifted half: {after}"
  );
}

/// A two-field value with a derived column hung off the first — the layout the emission below is
/// read against.
fn spanned() -> FieldsModel {
  FieldsModel {
    fragment: ident("Span"),
    fields: vec![
      deriving("pts", "i64", "nanos", "Span::nanos", "i64"),
      column("label", "String", Projection::Borrowed),
    ],
    ..dimensions()
  }
}

/// **THE LAYOUT PUTS A DERIVED COLUMN AFTER ITS SOURCE**, and every face that walks columns walks
/// the same list.
///
/// The names const, the width and the bind are the three readers, and the assertion reads all three
/// off one rendering: a position rule stated in one place and spent in three is the arrangement that
/// makes a drift between them unspellable.
#[test]
fn a_derived_column_follows_its_source_in_the_layout() {
  let dense = dense_of(&spanned());
  assert!(
    dense.contains(r#"FieldName::new("pts"),::ingraph::__private::field::FieldName::new("nanos"),::ingraph::__private::field::FieldName::new("label"),]"#),
    "the names const carries the derived column between its source and the field after it: {dense}"
  );
  assert!(
    dense.contains(
      "column::derived::<Span,i64,>(Span::nanos,::ingraph::__private::column::ColumnName::of(__INGRAPH_FRAGMENT_FIELDS[1usize],),)"
    ),
    "and the width names it through `derived`, which is `shape` with the function as a parameter it \
     never calls: {dense}"
  );
}

/// **THE WRITE COMPUTES IT AND THE READ NEVER FETCHES IT** — the two halves of the storage face,
/// read off one emission.
#[test]
fn the_bind_carries_a_derived_column_and_the_raise_does_not() {
  let dense = dense_of(&spanned());
  assert!(
    dense.contains("push_bind(&Span::nanos(self),__ingraph_qb);"),
    "the bind pushes what the function returns, at the position the layout gave it: {dense}"
  );
  assert!(
    dense.contains("letlabel:String=::ingraph::__private::column::assembled(__ingraph_row,__INGRAPH_FRAGMENT_FIELDS[2usize],__ingraph_under)?;"),
    "the read indexes the LAYOUT's positions, so the field after a derived column still fetches its \
     own name: {dense}"
  );
  assert!(
    !dense.contains("Span::nanos(__ingraph_row"),
    "and nothing reads the derived column back — the value is rebuilt from its sources: {dense}"
  );
  assert!(
    dense.contains(
      "i64:::ingraph::__private::column::Assemble<'__ingraph,__INGRAPH_ROW__>,String:::ingraph::__private::column::Assemble<'__ingraph,__INGRAPH_ROW__>,"
    ),
    "the READ's clause owes a row for the declared types alone: {dense}"
  );
}

/// **THE STORED FACE OFFERS THE DERIVED COLUMN AND THE FULL FACE DOES NOT**, which is the dual-face
/// ruling read at the one column that exists only in a row.
#[test]
fn only_the_stored_face_has_a_slot_for_a_derived_column() {
  let file = emission(&spanned());
  assert!(
    minted(&file, "SpanColumnFilter").contains("nanos"),
    "a row-holding host may ask about it, which is what the word is for"
  );
  assert!(
    !minted(&file, "SpanFilter").contains("nanos"),
    "a rowless host holds the value, and there is no derived column in a value"
  );
}

/// **A DERIVED COLUMN RIDES ITS SOURCE'S PREDICATE**, in every list a predicate contracts.
///
/// The function reads the field, so a build whose `#[cfg]` removed the field has no function to
/// call: one gate, one pair of columns. What that costs is arithmetic — the layout's positions are a
/// running sum over the predicates, and a derived column is a real entry in it — so the assertion
/// reads the emitted `const`s rather than the ordinals a macro can see.
#[test]
fn a_derived_column_carries_the_condition_of_the_field_it_follows() {
  let gate: syn::Attribute = syn::parse_quote!(#[cfg(feature = "nanos")]);
  let mut model = spanned();
  model.fields[0].condition = crate::model::Condition::of(vec![gate], Vec::new());
  let dense = dense_of(&model);
  assert!(
    dense.contains(r#"FieldName::new("pts"),#[cfg(feature="nanos")]::ingraph::__private::field::FieldName::new("nanos"),"#),
    "the gate reaches the source's name entry and the derived one alike: {dense}"
  );
  assert!(
    dense.contains(
      r#"#[cfg(feature="nanos")]::ingraph::__private::column::derived::<Span,i64,>(Span::nanos,"#
    ),
    "and the segment it mints: {dense}"
  );
  assert!(
    dense.contains("#[cfg(feature=\"nanos\")]{if__INGRAPH_AT_1>0{"),
    "the bind asks the PLACE rather than the declaration ordinal, and the derived column has a \
     place of its own: {dense}"
  );
  assert!(
    dense.contains("__INGRAPH_AT_2:::core::primitive::usize=__INGRAPH_AT_1+"),
    "so the field after a gated pair is two positions along when the predicate holds and none when \
     it does not: {dense}"
  );
}

// -------------------------------------------------------------------------------------------------
// THE TRANSFORM SEATS — `record(write = "…")` and `record(read = "…")`
// -------------------------------------------------------------------------------------------------

/// A two-field value whose first field crosses the STORAGE BOUNDARY through a transform.
///
/// Bare `record`, so the crossing arm it reaches is the dialect-GENERIC one. The concrete arm is
/// read off [`canonical_at_sqlite`], and the two are asserted separately because the whole content
/// of the seat is that they spend the SAME function.
fn canonical() -> FieldsModel {
  FieldsModel {
    fragment: ident("Track"),
    fields: vec![
      writing("frame_rate", "Rate", "Rate::reduced"),
      column("codec", "String", Projection::Borrowed),
    ],
    ..dimensions()
  }
}

/// The same declaration at a NAMED dialect, which is what buys the concrete pair.
fn canonical_at_sqlite() -> FieldsModel {
  use crate::model::DatabaseKind;

  FieldsModel {
    record: Some(super::RecordHost {
      databases: vec![built(DatabaseKind::Sqlite)],
      write: None,
      read: None,
    }),
    ..canonical()
  }
}

/// **ONE FUNCTION, TWO SITES** — the bind writes through it and the crossing's query operand crosses
/// through it, in the arm a bare `record` reaches.
///
/// This is the whole seat in one assertion. A value stored canonical and asked in the declared
/// spelling is a row the client cannot find, so the two sites are not two decisions: the emission
/// spells one path and spends it twice, and the assertion reads both spends off one rendering.
#[test]
fn the_write_reaches_the_bind_and_the_generic_crossing() {
  let dense = dense_of(&canonical());
  assert!(
    dense.contains("push_bind(&__INGRAPH_FRAGMENT_WRITE_0(&self.frame_rate),__ingraph_qb);"),
    "the BIND writes what the function returns, which is what makes the column canonical: {dense}"
  );
  assert!(
    dense.contains("graphql::TryMapFilter<Rate,Rate,>>::try_map_filter(__ingraph_held,"),
    "and the QUERY OPERAND is mapped through the seam a declared converter already crosses: {dense}"
  );
  assert!(
    dense.contains("::Ok(__INGRAPH_FRAGMENT_WRITE_0(&__ingraph_operand)),)"),
    "through the same path the bind spends, which is the whole of the two-site agreement: {dense}"
  );
  assert!(
    dense.contains("push_bind(&self.codec,__ingraph_qb);")
      && !dense.contains("TryMapFilter<String"),
    "the field that wrote no word binds what it holds and crosses at the identity: {dense}"
  );
  assert_eq!(
    dense.matches("__INGRAPH_FRAGMENT_WRITE_0").count(),
    3,
    "THREE spellings and no more: the pin's own definition, and the two sites that read it. A \
     fourth would be a face nobody ruled on, and a second would be a site left unspent: {dense}"
  );
}

/// **THE CONCRETE ARM SPENDS IT TOO**, which is what the two-site agreement means across the fork.
///
/// A declaration that names a dialect takes the other pair — one impl at that backend rather than
/// one over a parameter — and an operand map written into only one of them would make the seat's
/// promise depend on a word about dialects that has nothing to do with it.
#[test]
fn the_write_reaches_the_concrete_crossing_too() {
  let dense = dense_of(&canonical_at_sqlite());
  assert!(
    dense.contains("push_bind(&__INGRAPH_FRAGMENT_WRITE_0(&self.frame_rate),__ingraph_qb);"),
    "the bind is the layout's, so it does not move when a dialect is named: {dense}"
  );
  assert!(
    dense.contains("TryMapFilter<Rate,Rate>>::try_map_filter(__ingraph_held,"),
    "and the concrete pair maps the operand through the same path: {dense}"
  );
  assert!(
    dense.contains("::Ok(__INGRAPH_FRAGMENT_WRITE_0(&__ingraph_operand)),)"),
    "naming the declaration's own function and no other: {dense}"
  );
  assert_eq!(
    dense.matches("__INGRAPH_FRAGMENT_WRITE_0").count(),
    3,
    "the same three at the other arm — one definition, two readers, whichever pair the dialect \
     word selected: {dense}"
  );
}

/// **THE PIN NAMES THE FUNCTION WITHOUT CALLING IT**, in a `const` no feature gates away.
///
/// Every face a `write` reaches sits behind the SQL family's gate, so a build compiling none of it
/// would otherwise accept a path that resolves to nothing. The `const` is what makes a declaration's
/// refusal a fact about the declaration rather than about a feature set.
#[test]
fn a_transform_is_pinned_where_no_feature_reaches_it() {
  let dense = dense_of(&canonical());
  assert!(
    dense.contains("const__INGRAPH_FRAGMENT_WRITE_0:fn(&Rate)->Rate=Rate::reduced;"),
    "the pin is the const's own TYPE, which is `E0308` on a wrong signature and `E0433` on a path \
     naming nothing — at the string the author wrote: {dense}"
  );
  let gated = {
    let gate: syn::Attribute = syn::parse_quote!(#[cfg(feature = "rates")]);
    let mut model = canonical();
    model.fields[0].condition = crate::model::Condition::of(vec![gate], Vec::new());
    dense_of(&model)
  };
  assert!(
    gated.contains(
      "#[cfg(feature=\"rates\")]const__INGRAPH_FRAGMENT_WRITE_0:fn(&Rate)->Rate=Rate::reduced;"
    ),
    "and it rides the field's own predicate, because a build that removed the field removed the \
     transform with it: {gated}"
  );
}

/// **THE READ MIRROR WRAPS THE FETCH AND REACHES NOTHING ELSE.**
///
/// A filter operand is a client's value travelling INTO storage, which is the write's direction, so
/// the mirror has exactly one site: the column coming back.
#[test]
fn the_read_wraps_the_fetch_alone() {
  let mut model = canonical();
  model.fields[0].read = Some(syn::parse_str("Rate::spelled").expect("a path"));
  let dense = dense_of(&model);
  assert!(
    dense.contains(
      "letframe_rate:Rate=__INGRAPH_FRAGMENT_READ_0(&::ingraph::__private::column::assembled(\
       __ingraph_row,__INGRAPH_FRAGMENT_FIELDS[0usize],__ingraph_under)?);"
    ),
    "the fetch is what the mirror is applied to, and the annotation still fixes the row: {dense}"
  );
  assert!(
    !dense.contains("__INGRAPH_FRAGMENT_READ_0(&__ingraph_operand)"),
    "and no operand crosses through it — a query travels the WRITE's direction: {dense}"
  );
  assert!(
    dense.contains("const__INGRAPH_FRAGMENT_READ_0:fn(&Rate)->Rate=Rate::spelled;"),
    "the mirror is pinned to the same shape as its twin: {dense}"
  );
}

/// **A DERIVED COLUMN IS NOT WRITTEN THROUGH ITS SOURCE'S TRANSFORM**, and its function sees the
/// value as DECLARED.
///
/// The rule is forced rather than chosen. `write` is a `fn(&T) -> T` over the field's own type and
/// `from` is a `fn(&Self) -> U` over the whole value, so the two are different types wherever `U`
/// differs from `T` — and there is no `Self` with one field replaced for `from` to read instead,
/// short of rebuilding the value through a `Clone` this tier never asked for. A declaration wanting
/// the canonical form computes it inside `from`, which holds the whole value.
#[test]
fn a_derived_column_stands_outside_its_sources_transform() {
  let mut model = canonical();
  model.fields[0].derived = vec![super::Derived {
    column: crate::name::RustSafeName::new("rate_hz", proc_macro2::Span::call_site()),
    from: syn::parse_str("Track::rate_hz").expect("a path"),
    ty: syn::parse_str("f64").expect("a type"),
  }];
  let dense = dense_of(&model);
  assert!(
    dense.contains("push_bind(&__INGRAPH_FRAGMENT_WRITE_0(&self.frame_rate),__ingraph_qb);"),
    "the source field still writes through its own transform: {dense}"
  );
  assert!(
    dense.contains("push_bind(&Track::rate_hz(self),__ingraph_qb);"),
    "and the derived column binds what its own function returns, off the value as declared: {dense}"
  );
  assert!(
    !dense.contains("__INGRAPH_FRAGMENT_WRITE_0(&Track::rate_hz")
      && !dense.contains("Track::rate_hz(&__INGRAPH_FRAGMENT_WRITE_0"),
    "neither wrapping the other, which the types already refuse wherever they differ: {dense}"
  );
  assert!(
    !dense.contains("TryMapFilter<f64,f64>"),
    "and the derived column's own slot crosses at the identity, having no word of its own: {dense}"
  );
}

/// **A DECLARATION THAT WROTE NEITHER WORD EXPANDS AS IT DID**, asserted as byte identity rather
/// than by reading for absences.
#[test]
fn a_fragment_with_no_transform_expands_token_for_token() {
  let plain = FieldsModel {
    fields: vec![
      column("frame_rate", "Rate", Projection::Borrowed),
      column("codec", "String", Projection::Borrowed),
    ],
    ..canonical()
  };
  let mut cleared = canonical();
  cleared.fields[0].write = None;
  assert_eq!(
    dense_of(&cleared),
    dense_of(&plain),
    "the seat costs nothing where nothing was written"
  );
}

/// **THE WHOLE-VALUE SEAT'S MODEL** — two columns whose canonical form reads BOTH of them.
///
/// A ratio rather than a rate, and the difference is the point: `Rate` is ONE column of a text type
/// and its reduction is a `fn(&Rate) -> Rate` the FIELD seat can already spell. Reducing a ratio held
/// as `(num, den)` divides both halves by a factor of the PAIR, so no `fn(&u32) -> u32` exists to
/// hang on either column — which is the gap the head seat is for.
fn reduced() -> FieldsModel {
  FieldsModel {
    fragment: ident("Ratio"),
    fields: vec![
      column("num", "u32", Projection::Copied),
      column("den", "u32", Projection::Copied),
    ],
    record: Some(super::RecordHost {
      databases: Vec::new(),
      write: Some(syn::parse_str("Ratio::reduced").expect("a path")),
      read: None,
    }),
    ..dimensions()
  }
}

/// **ONE FUNCTION, TWO SITES** — the bind and the cursor's write, off one binding apiece.
///
/// This is the whole seat. Both faces carry the value ACROSS the storage boundary and both must
/// carry the same one: a keyset boundary written from the declared spelling resumes against columns
/// holding the canonical one, so a page repeats rows or drops them. The pin is what makes that an
/// arrangement rather than a habit — one definition, and each site spells it.
#[test]
fn the_head_write_reaches_the_bind_and_the_cursor() {
  let keyed = FieldsModel {
    cursor: Some(Vec::new()),
    ..reduced()
  };
  let dense = dense_of(&keyed);
  assert!(
    dense.contains("const__INGRAPH_FRAGMENT_HEAD_WRITE:fn(&Ratio)->Ratio=Ratio::reduced;"),
    "the pin is `fn(&Self) -> Self`, which is `E0308` on a wrong signature and `E0433` on a path \
     naming nothing — at the string the author wrote: {dense}"
  );
  assert_eq!(
    dense
      .matches(
        "let__ingraph_whole:Self=__INGRAPH_FRAGMENT_HEAD_WRITE(self);\
         #[allow(unused_variables)]let__ingraph_whole:&Self=&__ingraph_whole;"
      )
      .count(),
    2,
    "ONE call per site and not one per column: a reduction computes a gcd, and nothing promises a \
     household's own method is cheap: {dense}"
  );
  assert!(
    dense.contains("push_bind(&__ingraph_whole.num,__ingraph_qb);")
      && dense.contains("push_bind(&__ingraph_whole.den,__ingraph_qb);"),
    "the BIND reads every column off the transformed whole: {dense}"
  );
  assert!(
    dense.contains("write_member(&__ingraph_whole.num,__ingraph_out,)")
      && dense.contains("write_member(&__ingraph_whole.den,__ingraph_out,)"),
    "and so does the CURSOR's write, which is the site a one-site seat would have left lying: \
     {dense}"
  );
  assert_eq!(
    dense.matches("__INGRAPH_FRAGMENT_HEAD_WRITE").count(),
    3,
    "THREE spellings and no more: the pin's own definition, and the two sites that read it. A \
     fourth would be a face nobody ruled on, and a second would be a site left unspent: {dense}"
  );
}

/// **A FRAGMENT THAT IS NO PAGING POSITION HAS ONE SITE**, and the count says so rather than
/// pretending to two.
///
/// The seat's promise is *every place this emission carries the whole value across the boundary*,
/// and a declaration that wrote no `cursor` has exactly one such place. Two spellings is then the
/// honest count rather than a regression from three.
#[test]
fn the_head_write_reaches_whatever_sites_the_declaration_has() {
  let dense = dense_of(&reduced());
  assert!(
    !dense.contains("CursorValue"),
    "no `cursor` word, no keyset row: {dense}"
  );
  assert_eq!(
    dense.matches("__INGRAPH_FRAGMENT_HEAD_WRITE").count(),
    2,
    "the definition and the bind, which is the whole list here: {dense}"
  );
}

/// **THE CROSSING IS NOT A SITE**, and this is the measurement that says so rather than an absence
/// nobody looked for.
///
/// A fragment's predicate is one `Option<component filter>` per COLUMN, and both crossing arms
/// consume it member by member — there is no whole `Self` in `try_from_filter` for a
/// `fn(&Self) -> Self` to be applied to, and no per-column action to push the word down into: under
/// a reduction `num = 2` is not `num = 1`, it is *`num = 2/g` where `g` divides the pair*, which is
/// a relation over two columns rather than a function of one. So the emitted crossing is the one it
/// always was, and a declaration whose clients must ask in DOMAIN terms mounts `filter = "…"` with
/// `record(<db>(comparison = "…"))` — the seat pair built for exactly that.
#[test]
fn the_head_write_leaves_the_crossing_where_it_stands() {
  let at_sqlite = FieldsModel {
    record: Some(super::RecordHost {
      databases: vec![built(crate::model::DatabaseKind::Sqlite)],
      write: Some(syn::parse_str("Ratio::reduced").expect("a path")),
      read: None,
    }),
    ..reduced()
  };
  for dense in [dense_of(&reduced()), dense_of(&at_sqlite)] {
    assert!(
      dense.contains("TryFromFilter<RatioColumnFilter>"),
      "the crossing is still emitted: {dense}"
    );
    assert!(
      !dense.contains("__INGRAPH_FRAGMENT_HEAD_WRITE(&__ingraph_operand)")
        && !dense.contains("TryMapFilter<Ratio,Ratio"),
      "and nothing in it spends the head word — there is no operand of the fragment's own type for \
       a whole-value function to touch, at either arm: {dense}"
    );
  }
}

/// **THE MIRROR RUNS LAST, ON THE VALUE THE COLUMNS REBUILT** — at the raise and at the cursor's
/// read alike.
///
/// A `fn(&Self) -> Self` needs a `Self`, and the earliest one a read has is the one the struct
/// literal just produced. That puts the head word AFTER every column's own `read`, which is the
/// exact inverse of the write path — where the head runs FIRST and each column's `write` runs on
/// what it returned. A pair spent in one order going in and the other coming out is what makes a
/// round trip a round trip.
#[test]
fn the_head_read_runs_last_on_the_value_the_columns_rebuilt() {
  let mut model = FieldsModel {
    cursor: Some(Vec::new()),
    ..reduced()
  };
  let host = model.record.as_mut().expect("the activation");
  host.read = Some(syn::parse_str("Ratio::spread").expect("a path"));
  let dense = dense_of(&model);
  assert!(
    dense.contains("const__INGRAPH_FRAGMENT_HEAD_READ:fn(&Ratio)->Ratio=Ratio::spread;"),
    "the mirror is pinned to the same shape as its twin: {dense}"
  );
  assert_eq!(
    dense
      .matches("__INGRAPH_FRAGMENT_HEAD_READ(&Self{num,den")
      .count(),
    2,
    "and it wraps the BUILT value at both read sites — the row's raise and the cursor's: {dense}"
  );
  assert!(
    !dense.contains("__INGRAPH_FRAGMENT_HEAD_READ(&__ingraph_operand)"),
    "no operand crosses through it — a query travels the WRITE's direction: {dense}"
  );
  assert_eq!(
    dense.matches("__INGRAPH_FRAGMENT_HEAD_READ").count(),
    3,
    "one definition, two readers, exactly as the write half counts: {dense}"
  );
}

/// **THE MIRROR WRAPS WHATEVER THE RAISE PRODUCED**, which is what makes it one rule across the two
/// build modes.
///
/// An own fragment is built by a struct literal and a WRAPPED one by somebody else's constructor,
/// and the word sits outside both rather than inside either. That is also where the fallible road's
/// answer comes from without a word of its own: a `fallible` protocol's terminal step carries its
/// `?` INSIDE the built expression, so a refused row leaves the raise before there is a value at all
/// and the mirror never runs on one.
#[test]
fn the_head_read_wraps_the_construction_protocol_too() {
  let mut model = FieldsModel {
    remote: Some(syn::parse_quote!(upstream::Ratio)),
    ..reduced()
  };
  model.record.as_mut().expect("the activation").read =
    Some(syn::parse_str("Ratio::spread").expect("a path"));
  let dense = dense_of(&model);
  assert!(
    dense.contains("__INGRAPH_FRAGMENT_HEAD_READ(&Self(upstream::Ratio::new("),
    "the mirror is applied to the value the protocol built, not to the columns it was built from: \
     {dense}"
  );
}

/// **A DERIVED COLUMN READS THE VALUE AS DECLARED**, even under a head write.
///
/// `from` is the author's own `fn(&Self) -> U` and the head word is a different function of the same
/// argument, so the two are independent declarations rather than a pipeline. The choice between them
/// is forced by which direction is RECOVERABLE: a `from` handed the value as declared can call the
/// head function itself, and one handed the transformed value can never get the declared spelling
/// back. It is the field seat's own ruling, one level up and for the same reason.
#[test]
fn a_derived_column_reads_the_value_as_declared_under_a_head_write() {
  let mut model = reduced();
  model.fields[0].derived = vec![super::Derived {
    column: crate::name::RustSafeName::new("spelled", proc_macro2::Span::call_site()),
    from: syn::parse_str("Ratio::spelled").expect("a path"),
    ty: syn::parse_str("String").expect("a type"),
  }];
  let dense = dense_of(&model);
  assert!(
    dense.contains("push_bind(&__ingraph_whole.num,__ingraph_qb);"),
    "the declared column still binds off the transformed whole: {dense}"
  );
  assert!(
    dense.contains("push_bind(&Ratio::spelled(self),__ingraph_qb);"),
    "and the derived column's function reads `self` — the value AS DECLARED: {dense}"
  );
  assert!(
    !dense.contains("Ratio::spelled(__ingraph_whole)"),
    "never the transformed one, which is the reading that could not be undone: {dense}"
  );
}

/// **THE TWO SEATS COMPOSE, HEAD FIRST** — a fragment carrying both words spends both, in the one
/// order the types admit.
///
/// The head word is `fn(&Self) -> Self` and a field's is `fn(&T) -> T`, so the only composition that
/// type-checks is the head's output feeding the field's input: the whole value is canonicalised, and
/// then each column that named its own function crosses through it. Neither word is refused for the
/// other's presence — they answer different questions, one about the value and one about a column.
#[test]
fn a_field_transform_composes_under_the_head_one() {
  let mut model = reduced();
  model.fields[1].write = Some(syn::parse_str("positive").expect("a path"));
  let dense = dense_of(&model);
  assert!(
    dense.contains("push_bind(&__ingraph_whole.num,__ingraph_qb);"),
    "the column with no word of its own binds the transformed whole's value: {dense}"
  );
  assert!(
    dense.contains("push_bind(&__INGRAPH_FRAGMENT_WRITE_1(&__ingraph_whole.den),__ingraph_qb);"),
    "and the column that wrote one crosses through it AFTER the head word, which is the only \
     order `fn(&Self) -> Self` and `fn(&T) -> T` compose in: {dense}"
  );
}

/// **A DECLARATION THAT WROTE NEITHER HEAD WORD EXPANDS AS IT DID**, asserted as byte identity.
#[test]
fn a_fragment_with_no_head_transform_expands_token_for_token() {
  let mut cleared = reduced();
  cleared.record.as_mut().expect("the activation").write = None;
  let plain = FieldsModel {
    fragment: ident("Ratio"),
    fields: vec![
      column("num", "u32", Projection::Copied),
      column("den", "u32", Projection::Copied),
    ],
    ..dimensions()
  };
  assert_eq!(
    dense_of(&cleared),
    dense_of(&plain),
    "the seat costs nothing where nothing was written"
  );
}

/// **THE MOUNT LANDS IN THE MAP ROW AT ITS OWN DIALECT**, and the unmounted dialect beside it keeps
/// the product.
///
/// The seat replaces the per-field product at ONE database, which is the whole of what a whole-value
/// operator needs: `overlaps` is one predicate over two columns and has no field to hang on. So the
/// row `ToDatabaseComparison<Dimensions, Sqlite>` names the author's type, the row at Postgres names
/// `DimensionsComparison<Postgres>`, and both are written at a CONCRETE backend behind that
/// backend's gate — the parameter arm cannot stand beside either, `impl<DB> … for F` overlapping
/// `impl … for F` at any one dialect.
#[test]
fn a_mounted_lowering_replaces_the_product_at_that_dialect_alone() {
  use crate::model::DatabaseKind;

  let mounted = FieldsModel {
    record: Some(super::RecordHost {
      databases: vec![
        super::BuiltFor {
          kind: DatabaseKind::Sqlite,
          comparison: Some(syn::parse_quote!(lowering::SqlDimensionsComparison)),
          cursor: None,
        },
        built(DatabaseKind::Postgres),
      ],
      write: None,
      read: None,
    }),
    ..dimensions()
  };
  let emitted = dense_of(&mounted);

  assert!(
    emitted.contains(
      "ToDatabaseComparison<Dimensions,::ingraph::__private::sqlx::Sqlite>\
       forDimensionsColumnFilter{typeComparison=lowering::SqlDimensionsComparison;}"
    ),
    "the mounted type IS what the predicate lowers into at that dialect: {emitted}"
  );
  assert!(
    emitted.contains(
      "ToDatabaseComparison<Dimensions,::ingraph::__private::sqlx::Postgres>\
       forDimensionsColumnFilter{typeComparison=DimensionsComparison<::ingraph::__private::sqlx::Postgres>;}"
    ),
    "and a dialect with no mount keeps the framework's per-field product: {emitted}"
  );
  assert!(
    !emitted.contains("ToDatabaseComparison<Dimensions,__INGRAPH_DB__"),
    "the parameter arm cannot stand beside either — it overlaps both: {emitted}"
  );
  assert!(
    emitted.contains("__IngraphMountedComparison0"),
    "and the mount is audited at the dialect it was named at: {emitted}"
  );
  assert!(
    !emitted.contains("__IngraphMountedComparison1"),
    "one witness per MOUNT, not per dialect: {emitted}"
  );
  // The PRODUCT is still minted at the mounted dialect, which is what a mount delegates to when it
  // wants the component walk under its own vocabulary.
  assert!(
    emitted.contains(
      "TryFromFilter<DimensionsColumnFilter>forDimensionsComparison<::ingraph::__private::sqlx::Sqlite>"
    ),
    "the product it replaces is still emitted and still nameable: {emitted}"
  );
}

/// **THE TWO HALVES COMPOSE**, and the row that joins them is the one artifact neither word writes.
///
/// `filter = "…"` mounts the author's WIRE predicate and takes the map row with it — what a
/// predicate lowers into is a fact about the predicate. `<db>(comparison = "…")` mounts the author's
/// LOWERING. Written together they name both ends of one row, so the framework writes it: the
/// author's filter, at this dialect, lowering into the author's comparison. At a dialect with no
/// mount there is no such row to write and the author keeps writing their own.
#[test]
fn a_mounted_filter_and_a_mounted_lowering_meet_in_the_row_between_them() {
  use crate::model::DatabaseKind;

  let both = FieldsModel {
    filter: Some(syn::parse_quote!(faces::DimensionsWhere)),
    record: Some(super::RecordHost {
      databases: vec![
        super::BuiltFor {
          kind: DatabaseKind::Sqlite,
          comparison: Some(syn::parse_quote!(lowering::SqlDimensionsComparison)),
          cursor: None,
        },
        built(DatabaseKind::Postgres),
      ],
      write: None,
      read: None,
    }),
    ..dimensions()
  };
  let emitted = dense_of(&both);

  assert!(
    emitted.contains(
      "ToDatabaseComparison<Dimensions,::ingraph::__private::sqlx::Sqlite>\
       forfaces::DimensionsWhere{typeComparison=lowering::SqlDimensionsComparison;}"
    ),
    "the author's filter lowers into the author's comparison, joined here: {emitted}"
  );
  assert!(
    !emitted.contains("ToDatabaseComparison<Dimensions,::ingraph::__private::sqlx::Postgres>"),
    "and the unmounted dialect writes no row at all — a generated comparison is a crossing only \
     the author's predicate can state: {emitted}"
  );
  assert!(
    emitted.contains("TryFromFilter<faces::DimensionsWhere>"),
    "the audit asks the mount for a crossing from the AUTHOR's predicate: {emitted}"
  );
}

/// **A DECLARATION THAT MOUNTED NOTHING EXPANDS AS IT DID**, asserted as byte identity.
#[test]
fn a_fragment_with_no_mounted_lowering_expands_token_for_token() {
  use crate::model::DatabaseKind;

  let named = FieldsModel {
    record: Some(super::RecordHost {
      databases: vec![built(DatabaseKind::Sqlite)],
      write: None,
      read: None,
    }),
    ..dimensions()
  };
  let mut cleared = named.clone();
  cleared
    .record
    .as_mut()
    .expect("the activation")
    .databases
    .iter_mut()
    .for_each(|one| one.comparison = None);
  assert_eq!(
    dense_of(&cleared),
    dense_of(&named),
    "the seat costs nothing where nothing was mounted"
  );
}

/// **THE MOUNTED CODEC'S MODEL** — a Rate-shaped pair with a hand codec at SQLite, a bare PostgreSQL
/// beside it, and the head's canonicalisation over both.
///
/// The head words are here rather than in a second fixture because the two seats meet in these rows
/// and the meeting is the assertion: a codec spells the value in BYTES, and which value gets spelled
/// is still the head's.
fn coded() -> FieldsModel {
  use crate::model::DatabaseKind;

  FieldsModel {
    cursor: Some(Vec::new()),
    record: Some(super::RecordHost {
      databases: vec![
        super::BuiltFor {
          kind: DatabaseKind::Sqlite,
          comparison: None,
          cursor: Some(syn::parse_quote!(codecs::RateCursor)),
        },
        built(DatabaseKind::Postgres),
      ],
      write: Some(syn::parse_str("Ratio::reduced").expect("a path")),
      read: Some(syn::parse_str("Ratio::spread").expect("a path")),
    }),
    ..reduced()
  }
}

/// **A MOUNT FORKS THE ROW PER DIALECT**, and the mixed state is the ordinary one.
///
/// SQLite spends the household's codec; PostgreSQL, named and unmounted, rides the framed default —
/// both in one declaration, each walking its own pages. And the dialect-FREE row is gone: a value
/// whose bytes are the engine's has no single `CursorValue`, which is the fork being total rather
/// than additive.
#[test]
fn a_mounted_codec_forks_the_row_per_dialect() {
  let dense = dense_of(&coded());

  assert!(
    dense.contains(
      "impl::ingraph::__private::cursor::DialectCursor<::ingraph::__private::cursor::dialect::Sqlite,>forRatio{"
    ),
    "SQLite gets a row of its own: {dense}"
  );
  assert!(
    dense.contains(
      "<codecs::RateCursoras::ingraph::__private::cursor::CursorCodec<Self,>>::encode(\
       __ingraph_whole,__ingraph_out);"
    ),
    "and it spends the codec, handed the value the head word returned: {dense}"
  );
  assert!(
    dense.contains(
      "let__ingraph_decoded:Self=<codecs::RateCursoras::ingraph::__private::cursor::\
       CursorCodec<Self,>>::decode(__ingraph_bytes)?;"
    ) && dense.contains("Some(__INGRAPH_FRAGMENT_HEAD_READ(&__ingraph_decoded),)"),
    "its read is the dual, with the domain mirror one call further on: {dense}"
  );
  assert!(
    dense.contains(
      "impl::ingraph::__private::cursor::DialectCursor<::ingraph::__private::cursor::dialect::Postgres,>forRatio"
    ) && dense.contains("write_member(&__ingraph_whole.num,__ingraph_out,);"),
    "PostgreSQL was NAMED and mounted nothing, so it rides the framed walk — a mixed declaration is \
     ordinary: {dense}"
  );
  assert!(
    !dense.contains("::ingraph::__private::cursor::CursorValueforRatio"),
    "and the dialect-free row is GONE: a value whose bytes are the engine's cannot also claim one \
     form everywhere, which is `E0119` and is the fork being total: {dense}"
  );
  assert!(
    dense.contains("SEGMENTS.is_empty()"),
    "the WIDTH refusal stays: it is about the SQL keyset's column order, which a byte form has no \
     bearing on: {dense}"
  );
}

/// **THE CLAUSE PARTS WITH THE BODY** — a framed row owes each member's own row, a mounted one owes
/// nothing.
///
/// Dropping the clause is what lets a household page past a value whose components have no
/// `CursorValue` at all, which is half of why a hand kit existed.
#[test]
fn only_the_framed_row_owes_the_members_their_own_codecs() {
  let dense = dense_of(&coded());
  let sqlite = dense
    .split("DialectCursor<::ingraph::__private::cursor::dialect::Sqlite,>forRatio")
    .nth(1)
    .expect("the SQLite row");
  assert!(
    !sqlite.starts_with("where"),
    "the mounted row calls no member's row, so it demands none: {sqlite}"
  );
  let postgres = dense
    .split("DialectCursor<::ingraph::__private::cursor::dialect::Postgres,>forRatio")
    .nth(1)
    .expect("the PostgreSQL row");
  assert!(
    postgres.starts_with("whereu32:::ingraph::__private::cursor::CursorValue"),
    "and the framed one states exactly what its walk spends: {postgres}"
  );
}

/// **NOTHING HERE IS GATED**, because the seam names a MARKER rather than a driver.
///
/// The comparison pair rides its dialect's feature gate — it names `sqlx::Sqlite`, which a build
/// that compiled SQLite out does not have. A cursor's bytes name no driver at all, so a
/// declaration's cursor rows and the refusals about them read the same in every feature set. It is
/// also what keeps the record's own cursor sum writable: `SqlOrdering::Value: CursorValue` is stated
/// at a generic `DB` and checked in every build, so a gated codec row would be `E0277` on the sum in
/// any build missing that dialect — measured, on `record(sqlite, postgres)` in a `sqlite`-only
/// crate.
#[test]
fn the_cursor_seam_names_a_marker_and_rides_no_gate() {
  let dense = dense_of(&coded());
  // Read off the ROWS themselves rather than the whole expansion: the comparison pair beside them
  // names a backend and is gated, which is that seat's own correct answer.
  for dialect in ["Sqlite", "Postgres"] {
    let head = format!("cursor::DialectCursor<::ingraph::__private::cursor::dialect::{dialect},>");
    let at = dense
      .find(&head)
      .unwrap_or_else(|| panic!("the {dialect} row: {dense}"));
    let before = &dense[..at];
    assert!(
      before.ends_with("#[automatically_derived]impl::ingraph::__private::"),
      "the row stands on its own, with no gate wrapped round it: …{}",
      &before[before.len().saturating_sub(120)..]
    );
  }
  assert!(
    !dense.contains("DialectCursor<::ingraph::__private::sqlx::"),
    "and no driver is named in them — `cursor::dialect::…` is the key: {dense}"
  );
}

/// **THE MOUNT IS AUDITED AT THE STRING ITS OWN AUTHOR WROTE**, once per dialect that named a codec.
#[test]
fn a_mounted_codec_is_audited_at_every_dialect_that_named_it() {
  use crate::model::DatabaseKind;

  let dense = dense_of(&coded());
  assert!(
    dense.contains("trait__IngraphMountedCursor0")
      && dense.contains("__ingraph_mounted::<codecs::RateCursor>")
      && dense.contains("mountsasits`sqlite`cursorcodec,anditdoesnotanswerthatseat"),
    "one witness, spent at the author's path, in the seat's own words: {dense}"
  );
  assert!(
    !dense.contains("__IngraphMountedCursor1"),
    "and none for the dialect that mounted nothing: {dense}"
  );

  let differing = FieldsModel {
    record: Some(super::RecordHost {
      databases: vec![
        super::BuiltFor {
          kind: DatabaseKind::Sqlite,
          comparison: None,
          cursor: Some(syn::parse_quote!(codecs::RateSqlite)),
        },
        super::BuiltFor {
          kind: DatabaseKind::Postgres,
          comparison: None,
          cursor: Some(syn::parse_quote!(codecs::RatePostgres)),
        },
      ],
      write: None,
      read: None,
    }),
    ..coded()
  };
  let dense = dense_of(&differing);
  assert!(
    dense.contains("__ingraph_mounted::<codecs::RateSqlite>")
      && dense.contains("__ingraph_mounted::<codecs::RatePostgres>"),
    "DIFFERING codecs are the ordinary case, and each is audited on its own: {dense}"
  );
  assert!(
    dense.contains("mountsasits`sqlite`cursorcodec")
      && dense.contains("mountsasits`postgres`cursorcodec"),
    "each naming the dialect it was written at: {dense}"
  );
}

/// **A FRAGMENT THAT MOUNTS NOTHING EXPANDS TOKEN FOR TOKEN** — the framed default is the incumbent,
/// and the seat costs a declaration without it nothing at all.
#[test]
fn a_fragment_with_no_codec_keeps_the_framed_default() {
  let framed = FieldsModel {
    record: Some(super::RecordHost {
      databases: vec![built(crate::model::DatabaseKind::Sqlite)],
      write: Some(syn::parse_str("Ratio::reduced").expect("a path")),
      read: Some(syn::parse_str("Ratio::spread").expect("a path")),
    }),
    ..coded()
  };
  let dense = dense_of(&framed);
  assert!(
    dense.contains("impl::ingraph::__private::cursor::CursorValueforRatio")
      && dense.contains("write_member(&__ingraph_whole.num,__ingraph_out,)")
      && dense.contains("write_member(&__ingraph_whole.den,__ingraph_out,)"),
    "ONE dialect-free row, framed — which the blanket answers at every dialect: {dense}"
  );
  assert!(
    !dense.contains("DialectCursor") && !dense.contains("__IngraphMountedCursor"),
    "and nothing of the seat is emitted beside it — no row, no call, no witness: {dense}"
  );
  assert!(
    dense.contains("whereu32:::ingraph::__private::cursor::CursorValue"),
    "the clause the framed walk owes is still stated: {dense}"
  );
}