ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
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
//! The wire faces, read back out of a built schema — the SDL is the only place a registration's
//! effect is visible, and it is what a schema owner reviews.

use async_graphql::{EmptyMutation, EmptySubscription, Object, Schema};

use crate::{
  BooleanFilter, BytesFilter, ConfidenceFilter, Count, EnumFilter, FieldName, GraphqlFilter,
  ListFilter, Nullable, OrderDirection, QuantifiedFilter, Radians, ScalarFilter, Score, SetFilter,
  TextFilter, Timestamp,
};

/// An operand standing in for a DECLARER's vocabulary — the position `#[derive(ingraph::Enum)]`
/// fills out there.
///
/// Written with async-graphql's own `Enum` derive, which is legal HERE and is not the point of the
/// fixture: what is under test is `EnumFilter<T>`'s generic wire face, and that row asks one thing of
/// its operand — that it crosses the wire. Where the face comes from is the declaring crate's
/// business, which is the openness the bound states.
#[derive(Debug, Clone, Copy, PartialEq, Eq, async_graphql::Enum)]
enum Probe {
  Near,
  Far,
}

/// A SECOND vocabulary, named and never mounted. It exists for the injectivity pin below: the filter
/// name is a function of the operand's own schema name, so two operands give two names, and showing
/// that needs a second operand rather than a second schema.
#[derive(Debug, Clone, Copy, PartialEq, Eq, async_graphql::Enum)]
enum Signal {
  Lit,
}

/// A THIRD vocabulary, and the one deliberately left OUT of the input crossing below — it stands
/// where an element with no honest literal form stands.
///
/// A WIDE collection of it is unspellable: [`ListFilter`]'s face asks its element for
/// [`ToGraphqlInput`](crate::ToGraphqlInput), and this type has no such row, so
/// `ListFilter<Trace, EnumFilter<Trace>>` cannot reach a schema at all.
/// [`QuantifiedFilter`](crate::QuantifiedFilter) over the same element does — its face asks the
/// element for nothing — and that is the claim the kind's own note makes, shown here where a schema
/// can be read back.
///
/// It still needs [`InputType`](async_graphql::InputType), and that is the ELEMENT'S FILTER's demand
/// rather than the collection's: `EnumFilter<T>` reads `T` off the wire inside its own operators.
/// Nothing about the quantified collection is what asks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, async_graphql::Enum)]
enum Trace {
  Seen,
}

/// The INPUT CROSSING both fixtures owe, and what a declaring crate writes for its own vocabulary —
/// emitted by `#[derive(ingraph::Enum)]` there, hand-written here because these two are written with
/// async-graphql's own derive.
///
/// A COLLECTION face asks its element for this rather than for `InputType`: the six list slots and
/// `hasElement` put the ELEMENT'S CROSSING on the wire, which is what lets `u128` reach a schema and
/// stops `Vec<u8>` reaching one that lies. A vocabulary needs no carrier — its wire form IS the type
/// — and still owes the row, because the bound asks every element alike.
macro_rules! crosses_as_itself {
  ($($ty:ty),+ $(,)?) => {
    $(
      impl crate::ToGraphqlInput for $ty {
        type Input = Self;
        type Error = core::convert::Infallible;

        fn cross(input: Self) -> Result<Self, core::convert::Infallible> {
          Ok(input)
        }

        fn carry(operand: &Self) -> Self {
          *operand
        }
      }
    )+
  };
}

crosses_as_itself!(Probe, Signal);

/// One resolver per registered filter, each taking the bare face and the nullable one — an input
/// object reaches a schema only by being named in an argument, so this fixture IS the inventory.
struct Query;

macro_rules! probe_fields {
  ($( $field:ident : $filter:ty ),+ $(,)?) => {
    #[Object]
    impl Query {
      $(
        async fn $field(&self, bare: $filter, nullable: Nullable<$filter>) -> bool {
          GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
        }
      )+
    }
  };
}

probe_fields! {
  boolean: BooleanFilter,
  int8: ScalarFilter<i8>,
  int16: ScalarFilter<i16>,
  int32: ScalarFilter<i32>,
  int64: ScalarFilter<i64>,
  uint8: ScalarFilter<u8>,
  uint16: ScalarFilter<u16>,
  uint32: ScalarFilter<u32>,
  uint64: ScalarFilter<u64>,
  float32: ScalarFilter<f32>,
  float64: ScalarFilter<f64>,
  non_zero_int32: ScalarFilter<core::num::NonZeroI32>,
  score: ConfidenceFilter,
  timestamp: ScalarFilter<Timestamp>,
  // The CARDINALITY operand. It reaches the schema through the two collection kinds' `count` field
  // as well, so this row is what registers its NULLABLE twin — nothing declares a nullable
  // cardinality, and the pairing discipline below is asserted from the SDL rather than from the
  // macro.
  count: ScalarFilter<usize>,
  // **THE DECLARED CARDINALITY, MOUNTED BESIDE THE PROTOCOL ONE**, which is the whole point of the
  // row: `Count` is a named type of this crate's and would wear `CountFilter` under the household
  // register, and the line above already holds that name. So its reading takes `CardinalityFilter`,
  // and this fixture is where the two are shown COEXISTING — a schema carrying both is what
  // `Registry::create_type` would have panicked on had they shared a name.
  cardinality: ScalarFilter<Count>,
  // The two operands with no scalar ANYWHERE until this round — async-graphql's integers stop at 64
  // bits — crossing through the carriers `graphql::scalar` mints. A `u128` column reached no schema
  // at all before these two rows.
  int128: ScalarFilter<i128>,
  uint128: ScalarFilter<u128>,
  // The BLOB, whose operand had a face and the wrong one: `Vec<u8>` renders as `[Int!]` through
  // async-graphql's blanket, so the carrier crosses it as hex instead.
  bytes: BytesFilter<Vec<u8>>,
  string: TextFilter<String>,
  boolean_list: ListFilter<bool>,
  int8_list: ListFilter<i8>,
  int16_list: ListFilter<i16>,
  int32_list: ListFilter<i32>,
  int64_list: ListFilter<i64>,
  uint16_list: ListFilter<u16>,
  uint32_list: ListFilter<u32>,
  uint64_list: ListFilter<u64>,
  float32_list: ListFilter<f32>,
  float64_list: ListFilter<f64>,
  boolean_set: SetFilter<bool>,
  int8_set: SetFilter<i8>,
  int16_set: SetFilter<i16>,
  int32_set: SetFilter<i32>,
  int64_set: SetFilter<i64>,
  uint16_set: SetFilter<u16>,
  uint32_set: SetFilter<u32>,
  uint64_set: SetFilter<u64>,
  float32_set: SetFilter<f32>,
  float64_set: SetFilter<f64>,
  // The framework's own text collection, and the row the wall was missing: a `Vec<String>` column
  // resolves to `ListFilter<String, TextFilter<String>>`, which is two types a declaring crate is
  // foreign to, so only this crate could ever have supplied the face.
  string_list: ListFilter<String>,
  string_set: SetFilter<String>,
  // The DECLARER's kind, and the only row here whose face is written over a PARAMETER: one generic
  // impl serves every enum a declaring crate declares, so this probe registers a face nothing in this
  // crate has a table row for. Its operand is the only one in the fixture this crate does not own.
  probe: EnumFilter<Probe>,
  // The narrow collection's ELEMENT filter, mounted at a scalar seat of its own so that its nullable
  // twin is registered too — the pairing discipline is asserted over the whole inventory, and an
  // element filter reachable ONLY through a collection's `any` field would have no twin.
  trace: EnumFilter<Trace>,
  // The two rows the WALL said belonged to a declarer and nobody could write: a collection whose
  // ELEMENT is a declarer's own vocabulary. `ListFilter<Tag, …>` is a foreign type parameterised by
  // a local one, so `impl InputType for ListFilter<Tag, …>` in a declaring crate is `E0117` and RFC
  // 2451 does not reach it — the face had to be one generic row HERE, and this is that row asked of
  // an operand this crate does not own.
  probe_list: ListFilter<Probe, EnumFilter<Probe>>,
  probe_set: SetFilter<Probe, EnumFilter<Probe>>,
  // The NARROW collection, over the one element in this fixture with no input crossing. Neither wide
  // kind can be written at this element — their faces demand the crossing — so this row is the whole
  // of what the third collection kind buys, and the SDL below is where it is read.
  trace_quantified: QuantifiedFilter<Trace, EnumFilter<Trace>>,
}

fn sdl() -> String {
  Schema::build(Query, EmptyMutation, EmptySubscription)
    .finish()
    .sdl()
}

/// The `input` type names one line of SDL each, in the registry's own order (alphabetical — it
/// stores types in a `BTreeMap`).
fn input_names(sdl: &str) -> Vec<&str> {
  sdl
    .lines()
    .filter_map(|line| line.strip_prefix("input "))
    .filter_map(|line| line.strip_suffix(" {"))
    .collect()
}

/// The registration inventory, spelled out. A `ScalarWire`, `TextWire` or `BytesWire` row added to
/// or removed from `Builtin` changes this list and nothing else, so the list is where the schema's
/// surface is reviewed rather than inferred from the readings.
///
/// `UInt8ListFilter` is the absence to notice: `u8`'s row reads a `Vec` of it as a VALUE here, so
/// `ListFilter<u8>` is a type no field's default resolves to and an input object for it would be
/// unreachable. `legacy/ingraph` has the row because there a `Vec<u8>` is a list of small integers.
/// `UInt8SetFilter` is absent for the same reason, which is what keeps the two collection lists the
/// same list.
///
/// `CountFilter` is `ScalarFilter<usize>`, and it is ONE entry however many collection kinds are
/// registered: a cardinality does not depend on the element, so the `count` field of every list and
/// set input object names this one type. It is also the one row whose name states a ROLE rather than
/// the operand's width — see the registration for why a `usize` has no width to state.
///
/// **`CardinalityFilter` STANDS BESIDE IT, and the two being here together is the measurement.**
/// `ScalarFilter<Count>` is a DECLARED column's operand — `Count` being the type `counting` answers
/// — and under the household register it would wear `CountFilter`, which the row above holds. Two
/// Rust types under one GraphQL name is what `Registry::create_type` panics on, so the reading takes
/// the other true word for the same thing; this schema builds, which is that argument checked rather
/// than asserted.
#[test]
fn every_registration_reaches_the_schema() {
  const EXPECTED: &[&str] = &[
    "BooleanFilter",
    "BooleanListFilter",
    "BooleanSetFilter",
    "CardinalityFilter",
    "ConfidenceFilter",
    "CountFilter",
    "F32Filter",
    "F32ListFilter",
    "F32SetFilter",
    "F64Filter",
    "F64ListFilter",
    "F64SetFilter",
    "I128Filter",
    "I16Filter",
    "I16ListFilter",
    "I16SetFilter",
    "I32Filter",
    "I32ListFilter",
    "I32SetFilter",
    "I64Filter",
    "I64ListFilter",
    "I64SetFilter",
    "I8Filter",
    "I8ListFilter",
    "I8SetFilter",
    "NonZeroI32Filter",
    "NullableBooleanFilter",
    "NullableBooleanListFilter",
    "NullableBooleanSetFilter",
    "NullableCardinalityFilter",
    "NullableConfidenceFilter",
    "NullableCountFilter",
    "NullableF32Filter",
    "NullableF32ListFilter",
    "NullableF32SetFilter",
    "NullableF64Filter",
    "NullableF64ListFilter",
    "NullableF64SetFilter",
    "NullableI128Filter",
    "NullableI16Filter",
    "NullableI16ListFilter",
    "NullableI16SetFilter",
    "NullableI32Filter",
    "NullableI32ListFilter",
    "NullableI32SetFilter",
    "NullableI64Filter",
    "NullableI64ListFilter",
    "NullableI64SetFilter",
    "NullableI8Filter",
    "NullableI8ListFilter",
    "NullableI8SetFilter",
    "NullableNonZeroI32Filter",
    "NullableProbeFilter",
    "NullableProbeListFilter",
    "NullableProbeSetFilter",
    "NullableStringFilter",
    "NullableStringListFilter",
    "NullableStringSetFilter",
    "NullableTimestampFilter",
    "NullableTraceFilter",
    "NullableTraceQuantifiedFilter",
    "NullableU128Filter",
    "NullableU16Filter",
    "NullableU16ListFilter",
    "NullableU16SetFilter",
    "NullableU32Filter",
    "NullableU32ListFilter",
    "NullableU32SetFilter",
    "NullableU64Filter",
    "NullableU64ListFilter",
    "NullableU64SetFilter",
    "NullableU8Filter",
    "NullableU8VectorFilter",
    "ProbeFilter",
    "ProbeListFilter",
    "ProbeSetFilter",
    "StringFilter",
    "StringListFilter",
    "StringSetFilter",
    "TimestampFilter",
    "TraceFilter",
    "TraceQuantifiedFilter",
    "U128Filter",
    "U16Filter",
    "U16ListFilter",
    "U16SetFilter",
    "U32Filter",
    "U32ListFilter",
    "U32SetFilter",
    "U64Filter",
    "U64ListFilter",
    "U64SetFilter",
    "U8Filter",
    "U8VectorFilter",
  ];

  assert_eq!(input_names(&sdl()), EXPECTED);
}

/// The pairing discipline, asserted from the schema rather than from the macro: every bare input
/// object has its `Nullable` twin. `filter_input_object!` has no arm that emits one alone, and this
/// is what would notice an arm being added.
#[test]
fn no_bare_input_object_is_missing_its_nullable_twin() {
  let sdl = sdl();
  let names = input_names(&sdl);
  for bare in names.iter().filter(|n| !n.starts_with("Nullable")) {
    let twin = format!("Nullable{bare}");
    assert!(names.contains(&twin.as_str()), "{twin} is not registered");
  }
}

/// The field lists, verbatim, for one input object per kind — the operator names, their order and
/// their wire types, which is everything a client writes against.
///
/// `NonZeroI32Filter` is here for what it does NOT say: its body is `I32Filter`'s to the letter —
/// the width crosses on `i32`'s own roster scalar since 2026-08-25 — and the refusal of zero is
/// invisible to introspection either way, a GraphQL scalar having no place to state a hole in its
/// domain. What carries it is the input object's NAME and the refusal a client is handed at the
/// crossing. The two blocks are asserted separately so that stays on the record.
#[test]
fn the_input_objects_render_their_operators() {
  let sdl = sdl();

  // Four fields, and the four that are ABSENT are the ordering family — which is the whole of this
  // kind's narrowing relative to the eight `legacy/ingraph` renders under the name this one vacated.
  //
  // The NAME AND THE OPERANDS ARE BOTH THE STANDARD ONE'S, which is the 2026-08-18 amendment read
  // where a client meets it: `bool` is not a roster row — GraphQL's `Boolean` already says
  // everything there is to say about the operand — so the kind publishes the canonical name over
  // the canonical scalar and there is nothing lowercase anywhere on this line.
  assert!(sdl.contains(
    "input BooleanFilter {\n\teq: Boolean\n\tne: Boolean\n\tin: [Boolean!]\n\tnotIn: \
     [Boolean!]\n}\n"
  ));

  // `i32` where these operators read `Int` before the SCALAR SUITE — the width is in the operand
  // now and not only in the input object's name.
  const I32: &str = "\teq: i32\n\tne: i32\n\tgt: i32\n\tgte: i32\n\tlt: i32\n\tlte: i32\n\tin: \
                     [i32!]\n\tnotIn: [i32!]\n";
  assert!(sdl.contains(&format!("input I32Filter {{\n{I32}}}\n")));
  // **THE `NonZero` FAMILY MOVED ONTO THE SUITE**, ruled 2026-08-25, and this is where it shows: the
  // body is now `I32Filter`'s to the letter, so the WIDTH is on the wire and the only difference
  // between the two input objects is the NAME — which is the one thing that can carry the zero
  // refusal, async-graphql's introspection having no place to state a domain hole. The operands read
  // `Int` until that ruling, so the schema stated neither the width nor the refusal.
  assert!(sdl.contains(&format!("input NonZeroI32Filter {{\n{I32}}}\n")));
  // The null test is the nullable face's whole difference, and it comes LAST — the bare face's
  // fields in their declared order, then `isNull`.
  assert!(sdl.contains(&format!(
    "input NullableI32Filter {{\n{I32}\tisNull: Boolean\n}}\n"
  )));

  // The four ordering fields are on the wire for every element type, including where the compiled
  // backend cannot answer them: a schema is rendered without naming a dialect, and a wire face that
  // varied with a Cargo feature would change a client's schema when a server was rebuilt.
  //
  // The three set operators are ABSENT, and their absence is the split reaching the schema: a client
  // that sent `encloses` against a `Vec<T>` column was relying on an ordered collection being read
  // as a set.
  // `any` renders as the ELEMENT's own input object rather than as a shape of this kind's: a
  // collection of `Int64` asks about one member in the vocabulary an `Int64` column is asked in, so
  // the two are the same registration read twice. `count` renders as `CountFilter` for every element
  // type, because a cardinality does not depend on the element.
  assert!(sdl.contains(
    "input I64ListFilter {\n\teq: [i64!]\n\tne: [i64!]\n\tgt: [i64!]\n\tgte: [i64!]\n\tlt: \
     [i64!]\n\tlte: [i64!]\n\thasElement: i64\n\tany: I64Filter\n\tcount: CountFilter\n}\n"
  ));

  // The other half of the split, and the two lists together are the whole of what a client can now
  // say about a collection: `eq`/`ne` are in both under different MEANINGS, `hasElement` is in both
  // under one, and each kind carries the operators the other has no answer for.
  assert!(sdl.contains(
    "input I64SetFilter {\n\teq: [i64!]\n\tne: [i64!]\n\tencloses: [i64!]\n\tenclosedBy: \
     [i64!]\n\toverlaps: [i64!]\n\thasElement: i64\n\tany: I64Filter\n\tcount: \
     CountFilter\n}\n"
  ));

  // The cardinality's own face, and the whole of what it tells a client: the eight operators a
  // number takes, each rendering as `Int`. The NAME is where the operand is stated, and what it
  // states is a ROLE — a `usize` has no portable width for the roster's first law to name, and
  // registering one under a width would make the same schema mean two things on two targets.
  //
  // It is `Int` and STAYS `Int` after the SCALAR SUITE, which is the L17 floor holding: a
  // cardinality is the framework's OWN vocabulary — the same class as `first`, `depth`, `ordinal`
  // and `rank` — and the suite is for the widths a DECLARATION names. With the `NonZero` family
  // moved onto the suite, this is the LAST input object in the whole inventory whose operands read
  // the standard scalar without a field having named the `Std` reading.
  const INT: &str = "\teq: Int\n\tne: Int\n\tgt: Int\n\tgte: Int\n\tlt: Int\n\tlte: Int\n\tin: \
                     [Int!]\n\tnotIn: [Int!]\n";
  assert!(sdl.contains(&format!("input CountFilter {{\n{INT}}}\n")));

  assert!(sdl.contains(
    "input StringFilter {\n\teq: String\n\tne: String\n\tgt: String\n\tgte: String\n\tlt: \
     String\n\tlte: String\n\tcontains: String\n\tcontainsNocase: String\n\tnotContains: \
     String\n\tnotContainsNocase: String\n\tstartsWith: String\n\tstartsWithNocase: \
     String\n\tnotStartsWith: String\n\tnotStartsWithNocase: String\n\tendsWith: \
     String\n\tendsWithNocase: String\n\tnotEndsWith: String\n\tnotEndsWithNocase: String\n\tin: \
     [String!]\n\tnotIn: [String!]\n}\n"
  ));
}

/// **EXACTLY TWO FIELDS, AND THE ELEMENT IS ON THE WIRE NOWHERE** — the narrow collection's face,
/// read back whole so that a slot arriving would red this line rather than pass unnoticed.
///
/// The two names are the two the wide kinds share, rendering exactly as they render there: `any` is
/// the ELEMENT's own input object, so the vocabulary a member is asked in is the member's, and
/// `count` is `CountFilter` for every element type there is.
///
/// The seven that are ABSENT are the seven whose operand is an element — six whole-collection
/// operators and `hasElement` — and their absence is the whole kind. It is also why the element type
/// under this face has no crossing at all: [`Trace`] is the fixture vocabulary with no
/// [`ToGraphqlInput`](crate::ToGraphqlInput) row, so a wide collection of it would not compile, let
/// alone render.
///
/// The nullable twin is asserted beside it because the pairing discipline is asserted for every
/// registration, and a new kind is exactly where a twin would go missing.
#[test]
fn the_quantified_face_publishes_the_two_quantifiers_and_nothing_else() {
  let sdl = sdl();

  const QUANTIFIERS: &str = "\tany: TraceFilter\n\tcount: CountFilter\n";
  assert!(
    sdl.contains(&format!(
      "input TraceQuantifiedFilter {{\n{QUANTIFIERS}}}\n"
    )),
    "{sdl}"
  );
  assert!(
    sdl.contains(&format!(
      "input NullableTraceQuantifiedFilter {{\n{QUANTIFIERS}\tisNull: Boolean\n}}\n"
    )),
    "{sdl}"
  );

  // The NAME is the element's FILTER with the family word on it, which is what keeps it injective —
  // and it is a name of its OWN rather than a shorter `TraceListFilter` with fields left out, so no
  // client reading a wire name can be reading two different field lists.
  assert!(!sdl.contains("input TraceListFilter"), "{sdl}");
  assert!(!sdl.contains("input TraceSetFilter"), "{sdl}");
}

/// **THE TWO SLOTS SURVIVE A ROUND TRIP**, and an OBJECT is the only thing the face reads.
///
/// `parse` and `to_value` are one claim rather than two: the value written back is fed to the parser
/// and has to come back the same filter, which is the property a client depends on when a server
/// echoes a stored query.
///
/// The BARE-VALUE shorthand is refused, and that is the shorthand law's third road rather than a gap
/// — this kind has no single operator a bare value could be the `eq` of, exactly as a composite
/// filter has none. Its `any` is a whole nested predicate and its `count` a whole scalar filter, so
/// there is nothing for a scalar literal to mean.
#[test]
fn the_quantified_face_round_trips_its_two_slots() {
  use async_graphql::{InputType, Name, Number, Value, indexmap::IndexMap};

  type Face = QuantifiedFilter<Trace, EnumFilter<Trace>>;

  let filter = Face::new()
    .with_any(EnumFilter::new().with_eq(Trace::Seen))
    .with_count(ScalarFilter::new().with_gte(2));

  let written = InputType::to_value(&filter);
  let Value::Object(object) = written.clone() else {
    panic!("a filter writes back as an object: {written:?}");
  };
  assert!(object.contains_key(&Name::new("any")), "{object:?}");
  assert!(object.contains_key(&Name::new("count")), "{object:?}");
  assert_eq!(object.len(), 2, "{object:?}");

  assert_eq!(
    Face::parse(Some(written)).expect("what the face wrote, the face reads"),
    filter
  );

  // An ABSENT operator comes back absent rather than as an empty one — the distinction the whole
  // `Option` slot discipline exists for.
  let empty = Face::parse(Some(Value::Object(IndexMap::new()))).expect("an empty object parses");
  assert_eq!(empty, Face::new());
  assert!(GraphqlFilter::is_empty(&empty));

  // Rule ③ of the shorthand law, at a position with no `eq` to be the shorthand FOR.
  assert!(Face::parse(Some(Value::Number(Number::from(7)))).is_err());
  assert!(Face::parse(None).is_err());
}

/// The nullable face is FLAT and shares the bare face's parser: one object carrying `isNull` beside
/// the operators, never `{ inner: { … }, null: … }`. `parse` reads `isNull` off the object and hands
/// the SAME object to the inner filter, which ignores keys it does not know.
///
/// The operand is written as a STRING here, and `i64` reads one at every magnitude — the LIBERAL
/// half of the hybrid encoding, visible at the level a client writes at. (What comes BACK at a value
/// this small is a JSON number, the bound being 2^53 − 1; `tests/hybrid_encoding.rs` owns that
/// fork.) The Rust slot still holds a bare `7`, which is the other half of the same fact: the
/// wrapper is the binding's and the filter never sees it.
#[test]
fn the_nullable_face_parses_one_flat_object() {
  use async_graphql::{InputType, Name, Value, indexmap::IndexMap};

  let mut obj = IndexMap::new();
  obj.insert(Name::new("gte"), Value::String(String::from("7")));
  obj.insert(Name::new("isNull"), Value::Boolean(false));

  let parsed = <Nullable<ScalarFilter<i64>> as InputType>::parse(Some(Value::Object(obj.clone())))
    .expect("a flat object with a known operator and the null test parses");
  assert_eq!(
    parsed,
    Nullable::new(ScalarFilter::new().with_gte(7)).with_null(false)
  );

  // The bare face reads the same object and simply never looks at `isNull`.
  let bare = <ScalarFilter<i64> as InputType>::parse(Some(Value::Object(obj)))
    .expect("the inner filter ignores the key it does not declare");
  assert_eq!(bare, ScalarFilter::new().with_gte(7));

  // `to_value` renders every slot, set or not, so the round trip is total rather than sparse. The
  // operand comes back as a NUMBER though it was written as a string, which is the hybrid encoding's
  // own asymmetry: the DECODE takes either form at any magnitude and the ENCODE answers one form per
  // value — the number below 2^53 − 1, the digits above it. Seven is below.
  let Value::Object(rendered) = InputType::to_value(&parsed) else {
    panic!("an input object renders as an object");
  };
  assert_eq!(rendered.get("gte"), Some(&Value::Number(7.into())));
  assert_eq!(rendered.get("isNull"), Some(&Value::Boolean(false)));
  assert_eq!(rendered.get("eq"), Some(&Value::Null));
}

/// The boolean kind's membership pair, crossed both ways — the slots whose wire names (`in`,
/// `notIn`) differ from the Rust ones and whose operand is a LIST over a two-valued domain.
///
/// `notIn: []` is the row carrying the argument for having them at all. An empty membership operand
/// asks for no rows, and it is what a client's computed set arrives as when the computation came out
/// empty; it parses to a SET slot holding an empty list, not to an absent one, and renders back as a
/// list rather than as `null`. That distinction is the one `eq`/`ne` cannot express, so a client with
/// two slots to aim at would have to notice the empty case and emit a different document.
#[test]
fn the_boolean_membership_operands_cross_the_wire() {
  use async_graphql::{InputType, Name, Value, indexmap::IndexMap};

  let mut obj = IndexMap::new();
  obj.insert(Name::new("in"), Value::List(vec![Value::Boolean(true)]));
  obj.insert(Name::new("notIn"), Value::List(Vec::new()));

  let parsed = <BooleanFilter as InputType>::parse(Some(Value::Object(obj)))
    .expect("both membership operands parse");
  assert_eq!(
    parsed,
    BooleanFilter::new().with_in_([true]).with_not_in([])
  );
  assert!(!GraphqlFilter::is_empty(&parsed));

  let Value::Object(rendered) = InputType::to_value(&parsed) else {
    panic!("an input object renders as an object");
  };
  assert_eq!(
    rendered.get("in"),
    Some(&Value::List(vec![Value::Boolean(true)]))
  );
  assert_eq!(rendered.get("notIn"), Some(&Value::List(Vec::new())));
  // …and the slots nobody set are `null`, which is what tells the two apart on the way back.
  assert_eq!(rendered.get("eq"), Some(&Value::Null));
}

/// **THE CONFIDENCE PUBLISHES ONE FILTER AND NO SCALAR OF ITS OWN**, and this is the golden the
/// retirement is accepted on.
///
/// `Score`, `ScoreF64`, `ScoreF16` and `ScoreF128` were four SDL scalars over four widths of one
/// type, and four input objects under them carrying one vocabulary word for word. Both halves are
/// gone, and each half went for its own reason:
///
/// - **the SCALARS**, because a named scalar has to say something the roster does not, and what
///   these said was the INTERVAL — a constructor's promise rather than a grammar, statable only in
///   prose a client could act on nowhere. A confidence RETURNS as `f32` now, which is the same wire
///   form under the name every other single-precision column in the schema already uses.
/// - **the FILTERS**, because `Registry::create_type` panics on one GraphQL name held by two Rust
///   types, so four widths of one kind could not share a name however identical their field lists
///   were. A NON-GENERIC filter has one Rust type and therefore one name.
///
/// What arrives in their place is ONE input object and ONE scalar that is not a width:
/// `ConfidenceOperand`, the wide door, whose operands carry no width at all.
///
/// The `Float` row pins an ABSENCE and not a refusal, and it is kept from the retired golden:
/// async-graphql omits the five system scalars from every SDL export
/// (`registry::export_sdl::SYSTEM_SCALARS`), so a row that aliased onto `Float` would produce no
/// duplicate line to catch — it would delete a line instead, which is what the first assertions are
/// for.
#[test]
fn the_confidence_publishes_one_filter_and_returns_its_width() {
  struct ConfidenceQuery;

  #[Object]
  impl ConfidenceQuery {
    // The RETURN goes through the crossing, which is what an emitted resolver does and what the
    // retirement makes visible: `Confidence<S>` has no `OutputType` of its own any more, so the row
    // that renders it is `ToGraphqlOutput`'s and the form is the width's own roster carrier.
    async fn confidence(
      &self,
      bare: ConfidenceFilter,
      nullable: Nullable<ConfidenceFilter>,
    ) -> crate::F32 {
      let answered = if GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable) {
        Score::ZERO
      } else {
        Score::ONE
      };
      <Score as crate::ToGraphqlOutput>::to_graphql_output(&answered)
    }
  }

  let sdl = Schema::build(ConfidenceQuery, EmptyMutation, EmptySubscription)
    .finish()
    .sdl();

  assert_eq!(
    input_names(&sdl),
    ["ConfidenceFilter", "NullableConfidenceFilter"]
  );

  // The four retired names are gone from the schema WHOLE — scalar and filter alike — and the
  // assertion is written over the family word rather than over four literals, so a fifth width
  // reviving the scheme would be caught by the same line.
  assert_eq!(sdl.matches("Score").count(), 0);
  assert_eq!(sdl.matches("scalar Float").count(), 0);

  // What a confidence column RETURNS is its width's own roster scalar, which is the row the
  // retirement moved onto — and the schema declares that scalar exactly once.
  assert!(
    sdl.contains("confidence(bare: ConfidenceFilter!, nullable: NullableConfidenceFilter!): f32!")
  );
  assert_eq!(sdl.matches("scalar f32\n").count(), 1);

  // SIX WORDS, and the two membership slots are absent from the type rather than refused at a
  // crossing. The operand is the same at every one of them, because it carries no width.
  const OPERATORS: &str = "\teq: ConfidenceOperand\n\tne: ConfidenceOperand\n\tgt: \
                           ConfidenceOperand\n\tgte: ConfidenceOperand\n\tlt: \
                           ConfidenceOperand\n\tlte: ConfidenceOperand\n";
  assert!(sdl.contains(&format!("input ConfidenceFilter {{\n{OPERATORS}}}\n")));
  assert!(sdl.contains(&format!(
    "input NullableConfidenceFilter {{\n{OPERATORS}\tisNull: Boolean\n}}\n"
  )));
  assert_eq!(sdl.matches("\tin: [").count(), 0, "no membership slot");

  // The WIDE DOOR states its own two spellings in the schema, which is where the interval's
  // enforcement is now visible to a client: the operand scalar says what it takes and what it
  // refuses, where the retired scalars said it four times over four names.
  assert_eq!(sdl.matches("scalar ConfidenceOperand").count(), 1);
  assert!(sdl.contains("[0.0, 1.0]"));
  assert!(sdl.contains("never clamped"));
}

/// **[`Radians`] publishes NO scalar of its own, and its FILTER wears its own name** — the
/// [`Count`]/`CardinalityFilter` shape one width over, checked here against a live schema rather
/// than assumed: a value crosses as the roster's bare `f32`, and the input object is `RadiansFilter`
/// rather than `F32Filter`, which is what keeps a schema holding both a plain `f32` column and a
/// `Radians` one from asking `Registry::create_type` to seat two Rust types under one name.
///
/// Unlike [`ConfidenceFilter`], the body is the ORDINARY eight-operator [`ScalarFilter`] shape — the
/// same body `I32Filter` renders in [`the_input_objects_render_their_operators`], over `f32` rather
/// than `i32` — because there is no interval here for `in`/`notIn` to be dishonest about.
#[test]
fn the_radians_filter_publishes_its_own_name_and_crosses_as_f32() {
  struct RadiansQuery;

  #[Object]
  impl RadiansQuery {
    async fn roll(
      &self,
      bare: ScalarFilter<Radians<f32>>,
      nullable: Nullable<ScalarFilter<Radians<f32>>>,
    ) -> crate::F32 {
      let answered = if GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable) {
        Radians::new(0.0_f32)
      } else {
        Radians::new(1.0_f32)
      };
      <Radians<f32> as crate::ToGraphqlOutput>::to_graphql_output(&answered)
    }
  }

  let sdl = Schema::build(RadiansQuery, EmptyMutation, EmptySubscription)
    .finish()
    .sdl();

  assert_eq!(
    input_names(&sdl),
    ["NullableRadiansFilter", "RadiansFilter"]
  );

  // No scalar named for the type itself — it crosses on the roster's own `f32`, exactly once.
  assert_eq!(sdl.matches("scalar Radians").count(), 0);
  assert_eq!(sdl.matches("scalar f32\n").count(), 1);
  assert!(sdl.contains("roll(bare: RadiansFilter!, nullable: NullableRadiansFilter!): f32!"));

  // The ordinary eight-operator body, over `f32` rather than a bespoke widthless operand.
  const OPERATORS: &str = "\teq: f32\n\tne: f32\n\tgt: f32\n\tgte: f32\n\tlt: f32\n\tlte: \
                           f32\n\tin: [f32!]\n\tnotIn: [f32!]\n";
  assert!(sdl.contains(&format!("input RadiansFilter {{\n{OPERATORS}}}\n")));
  assert!(sdl.contains(&format!(
    "input NullableRadiansFilter {{\n{OPERATORS}\tisNull: Boolean\n}}\n"
  )));
}

/// **THE WIDE DOOR AT THE WIRE** — the parse table, asserted through async-graphql's own
/// `ScalarType` rather than through the constructors, because the two legs and their refusals are
/// what a CLIENT meets.
///
/// The operand's notion of validity is the constructors' and nothing else: a threshold outside the
/// interval is an input-coercion ERROR, never a clamped value. A clamp would answer
/// `confidence: { gte: 1.5 }` with the rows matching `1.0` and say nothing about the substitution,
/// which is the failure an agentic consumer cannot detect.
///
/// `is_valid` is asserted beside `parse` over the same table because the two are asked at different
/// times — validation walks the document, coercion reads the operand — and async-graphql's default
/// `is_valid` answers `true` for everything, so a scalar that narrows only in `parse` ships a
/// validator that admits what its parser will reject.
#[test]
fn the_operand_refuses_what_a_confidence_is_not() {
  use async_graphql::{Number, ScalarType, Value};

  use crate::ConfidenceOperand;

  for (operand, accepted) in [
    (1.5, false),
    (-0.1, false),
    (0.0, true),
    (1.0, true),
    (0.25, true),
  ] {
    let value = Value::Number(Number::from_f64(operand).expect("the operand is finite"));
    assert_eq!(
      <ConfidenceOperand as ScalarType>::parse(value.clone()).is_ok(),
      accepted,
      "{operand} parses"
    );
    assert_eq!(
      <ConfidenceOperand as ScalarType>::is_valid(&value),
      accepted,
      "{operand} validates"
    );
  }

  // An INTEGER operand is a confidence too. `1` and `1.0` are the same number to a client, and a
  // generated one emitting the shorter spelling should not be told it sent the wrong type.
  assert!(<ConfidenceOperand as ScalarType>::parse(Value::Number(1.into())).is_ok());
  assert!(<ConfidenceOperand as ScalarType>::parse(Value::Number(2.into())).is_err());

  // THE TEXT LEG, which is the half the retired scalars had at ONE width and this door has at every
  // one: a string is a decimal literal, kept exactly, and refused for its spelling and for its range
  // separately.
  assert!(<ConfidenceOperand as ScalarType>::parse(Value::String("0.5".into())).is_ok());
  assert!(<ConfidenceOperand as ScalarType>::parse(Value::String("1.5".into())).is_err());
  assert!(<ConfidenceOperand as ScalarType>::parse(Value::String("half".into())).is_err());

  // `NaN` never reaches `parse` as a NUMBER at all — a JSON number refuses to hold one — so the leg
  // that has a spelling for it is the text one, and that is where the refusal has to be real.
  assert!(Number::from_f64(f64::NAN).is_none());
  assert!(<ConfidenceOperand as ScalarType>::parse(Value::String("NaN".into())).is_err());
  assert!(!<ConfidenceOperand as ScalarType>::is_valid(
    &Value::String("NaN".into())
  ));

  // The round trip is over the SPELLING the operand arrived in, which is what keeps the text leg
  // exact: an exact base-ten threshold handed back as a double is handed back as a value that is
  // not it.
  for value in [
    Value::Number(Number::from_f64(0.82).expect("finite")),
    Value::String("0.82".into()),
  ] {
    let operand = <ConfidenceOperand as ScalarType>::parse(value.clone()).expect("it parses");
    assert_eq!(ScalarType::to_value(&operand), value);
  }
}

/// The framework's own instant declares its own scalar, and the name is free: async-graphql 7.2
/// claims `Date`, `Time`, `DateTime`, `ZonedDateTime` and `Duration` for jiff's five types and no
/// `Timestamp` among them. So this is the second registration whose BOTH halves are this crate's —
/// [`ConfidenceOperand`](crate::ConfidenceOperand) is the other — and unlike the `Duration` pair
/// there is no shadowing to reason about.
///
/// `@specifiedBy` is asserted because it is the schema's whole statement of the operand GRAMMAR, the
/// reason the four jiff filters' URLs are asserted below; reading it takes `sdl_with_options`, since
/// `Schema::sdl()` leaves `include_specified_by` off.
///
/// The `DateTime` row pins an ABSENCE: naming this scalar after the one async-graphql already holds
/// for `jiff::Timestamp` would put one GraphQL name on two Rust types, which async-graphql drops in
/// SILENCE for scalars (see `a_second_duration_scalar_is_dropped_rather_than_refused`). Nothing would
/// fail; the SDL would simply describe one of them.
#[test]
fn the_timestamp_scalar_declares_itself_and_is_not_a_date_time() {
  use async_graphql::registry::SDLExportOptions;

  struct InstantQuery;

  #[Object]
  impl InstantQuery {
    async fn at(
      &self,
      bare: ScalarFilter<Timestamp>,
      nullable: Nullable<ScalarFilter<Timestamp>>,
    ) -> Timestamp {
      if GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable) {
        Timestamp::UNIX_EPOCH
      } else {
        Timestamp::MAX
      }
    }
  }

  let sdl = Schema::build(InstantQuery, EmptyMutation, EmptySubscription)
    .finish()
    .sdl_with_options(SDLExportOptions::new().include_specified_by());

  assert_eq!(
    input_names(&sdl),
    ["NullableTimestampFilter", "TimestampFilter"]
  );
  assert!(sdl.contains(
    "\nscalar Timestamp @specifiedBy(url: \"https://datatracker.ietf.org/doc/html/rfc3339\")\n"
  ));
  assert_eq!(sdl.matches("scalar DateTime").count(), 0);

  const OPERATORS: &str = "\teq: Timestamp\n\tne: Timestamp\n\tgt: Timestamp\n\tgte: \
                           Timestamp\n\tlt: Timestamp\n\tlte: Timestamp\n\tin: \
                           [Timestamp!]\n\tnotIn: [Timestamp!]\n";
  assert!(sdl.contains(&format!("input TimestampFilter {{\n{OPERATORS}}}\n")));
  assert!(sdl.contains(&format!(
    "input NullableTimestampFilter {{\n{OPERATORS}\tisNull: Boolean\n}}\n"
  )));

  // Every operand in this schema is a `Timestamp`, and the whole point of the scalar is that none of
  // them is a number — an integer says nothing about its own unit, so a wire that offered one would
  // leave the two ends agreeing by convention.
  assert_eq!(sdl.matches("Int").count(), 0);

  // The grammar and the range reach the schema and not only the rustdoc, which is the wide door's
  // own reason: an opaque scalar says nothing at all unless the schema does.
  assert!(sdl.contains("RFC 3339"));
  assert!(sdl.contains("never a bare integer"));
  assert!(sdl.contains("±9999 years"));
}

/// The operands cross as RFC 3339 TEXT, and the round trip is exact to the nanosecond in both
/// directions — nine digits out, the same nine back.
///
/// `is_valid` is asserted beside `parse` over one table, for the wide door's reason: the two are
/// asked at different times and async-graphql's default `is_valid` answers `true` for everything, so
/// a scalar that narrows in `parse` alone ships a validator admitting what its parser rejects.
#[test]
fn timestamp_operands_cross_the_wire_as_rfc_3339_text() {
  use async_graphql::{Number, ScalarType, Value};

  const NANOS: &str = "2026-08-09T21:14:03.123456789Z";

  let instant: Timestamp = NANOS
    .parse()
    .expect("nine digits of fraction is an instant");
  let rendered = ScalarType::to_value(&instant);
  assert_eq!(rendered, Value::String(NANOS.into()));
  assert_eq!(
    <Timestamp as ScalarType>::parse(rendered).expect("its own rendering parses"),
    instant
  );

  // An OFFSET spelling names the same instant and is normalised to it — the value is the moment,
  // never the notation it arrived in.
  let east =
    <Timestamp as ScalarType>::parse(Value::String("2026-08-09T21:14:03.123456789+09:00".into()))
      .expect("an offset spelling is an instant");
  assert_eq!(
    east,
    "2026-08-09T12:14:03.123456789Z"
      .parse::<Timestamp>()
      .expect("the same instant in UTC")
  );

  // NEVER a bare integer, in either half. Seconds since the epoch is the form a client is likeliest
  // to try, and the answer is a type error rather than a guess about which unit was meant.
  let epoch_seconds = Value::Number(Number::from(1_786_310_043));
  assert!(<Timestamp as ScalarType>::parse(epoch_seconds.clone()).is_err());
  assert!(!<Timestamp as ScalarType>::is_valid(&epoch_seconds));

  // Garbage refuses BY NAME, in both senses. async-graphql names the SCALAR it was coercing to, and
  // jiff's own text names the COMPONENT it went looking for — kept rather than re-worded, which is
  // the whole reason `parse` carries the error instead of answering `expected_type`:
  //
  //   Failed to parse "Timestamp": failed to find offset component, which is required for parsing a
  //   timestamp
  let refusal = <Timestamp as ScalarType>::parse(Value::String("2026-08-09T21:14:03".into()))
    .expect_err("a civil datetime is not an instant")
    .into_server_error(async_graphql::Pos::default());
  assert!(
    refusal.message.contains("failed to find offset component"),
    "{}",
    refusal.message
  );
  assert!(refusal.message.contains("Timestamp"), "{}", refusal.message);

  // The two halves agree over one table, garbage and good alike.
  for (operand, accepted) in [
    ("2026-08-09T21:14:03Z", true),
    ("2026-08-09T21:14:03.123456789Z", true),
    ("2026-08-09T21:14:03+09:00", true),
    ("2026-08-09T21:14:03", false),
    ("2026-08-09", false),
    ("not a time", false),
    ("", false),
  ] {
    let value = Value::String(operand.into());
    assert_eq!(
      <Timestamp as ScalarType>::parse(value.clone()).is_ok(),
      accepted,
      "{operand} parses"
    );
    assert_eq!(
      <Timestamp as ScalarType>::is_valid(&value),
      accepted,
      "{operand} validates"
    );
  }
}

/// `smol_str::SmolStr` owns the canonical `TextFilter` name, and its operands render as
/// async-graphql's own `SmolStr` scalar rather than as `String` — the one place a registered operand
/// is not a built-in scalar, and the reason the feature carries a weak `async-graphql?/smol_str`
/// edge.
#[cfg(feature = "smol_str")]
#[test]
fn the_smol_str_text_filter_owns_the_canonical_name() {
  struct TextQuery;

  #[Object]
  impl TextQuery {
    async fn text(
      &self,
      bare: TextFilter<smol_str::SmolStr>,
      nullable: Nullable<TextFilter<smol_str::SmolStr>>,
    ) -> bool {
      GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
    }
  }

  let sdl = Schema::build(TextQuery, EmptyMutation, EmptySubscription)
    .finish()
    .sdl();

  assert_eq!(input_names(&sdl), ["NullableTextFilter", "TextFilter"]);
  assert!(sdl.contains("scalar SmolStr"));
  assert!(sdl.contains("input TextFilter {\n\teq: SmolStr\n\tne: SmolStr\n"));
  assert!(sdl.contains("\tin: [SmolStr!]\n\tnotIn: [SmolStr!]\n\tisNull: Boolean\n}\n"));
}

/// The four temporal filters, and the four scalars async-graphql already owns for their operands —
/// which is why the input objects are named after the SCALAR (`DateTimeFilter`, not
/// `TimestampFilter`) and why the feature carries a weak `async-graphql?/jiff` edge.
///
/// The `@specifiedBy` URLs are asserted because they are the schema's whole statement of the operand
/// GRAMMAR: `DateTime` is RFC 3339 and `ZonedDateTime` is RFC 8536, and a client reading `eq:
/// DateTime` has nothing else to go on. `Date` and `Time` carry none — async-graphql formats those
/// two with `%Y-%m-%d` and `%H:%M:%S%.f` and points at no document.
///
/// Reading them takes `sdl_with_options`: `Schema::sdl()` leaves `include_specified_by` off, so the
/// default export DECLARES `directive @specifiedBy` and then applies it to nothing. Every other test
/// here uses the plain `sdl()` because no other registration has a URL to lose.
#[cfg(feature = "jiff")]
#[test]
fn the_jiff_filters_render_the_scalars_async_graphql_owns() {
  use async_graphql::registry::SDLExportOptions;
  use jiff::{
    Timestamp, Zoned,
    civil::{Date, Time},
  };

  struct TemporalQuery;

  #[Object]
  impl TemporalQuery {
    async fn instant(
      &self,
      bare: ScalarFilter<Timestamp>,
      nullable: Nullable<ScalarFilter<Timestamp>>,
    ) -> bool {
      GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
    }

    async fn day(&self, bare: ScalarFilter<Date>, nullable: Nullable<ScalarFilter<Date>>) -> bool {
      GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
    }

    async fn clock(
      &self,
      bare: ScalarFilter<Time>,
      nullable: Nullable<ScalarFilter<Time>>,
    ) -> bool {
      GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
    }

    async fn zoned(
      &self,
      bare: ScalarFilter<Zoned>,
      nullable: Nullable<ScalarFilter<Zoned>>,
    ) -> bool {
      GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
    }
  }

  let sdl = Schema::build(TemporalQuery, EmptyMutation, EmptySubscription)
    .finish()
    .sdl_with_options(SDLExportOptions::new().include_specified_by());

  assert_eq!(
    input_names(&sdl),
    [
      "DateFilter",
      "DateTimeFilter",
      "NullableDateFilter",
      "NullableDateTimeFilter",
      "NullableTimeFilter",
      "NullableZonedDateTimeFilter",
      "TimeFilter",
      "ZonedDateTimeFilter",
    ]
  );

  const OPERATORS: &str = "\teq: %S%\n\tne: %S%\n\tgt: %S%\n\tgte: %S%\n\tlt: %S%\n\tlte: \
                           %S%\n\tin: [%S%!]\n\tnotIn: [%S%!]\n";
  for (input, scalar) in [
    ("DateTimeFilter", "DateTime"),
    ("DateFilter", "Date"),
    ("TimeFilter", "Time"),
    ("ZonedDateTimeFilter", "ZonedDateTime"),
  ] {
    let operators = OPERATORS.replace("%S%", scalar);
    assert!(
      sdl.contains(&format!("input {input} {{\n{operators}}}\n")),
      "{input}"
    );
    assert!(
      sdl.contains(&format!(
        "input Nullable{input} {{\n{operators}\tisNull: Boolean\n}}\n"
      )),
      "Nullable{input}"
    );
  }

  assert!(sdl.contains(
    "\nscalar DateTime @specifiedBy(url: \"https://datatracker.ietf.org/doc/html/rfc3339\")\n"
  ));
  assert!(sdl.contains(
    "\nscalar ZonedDateTime @specifiedBy(url: \"https://datatracker.ietf.org/doc/html/rfc8536\")\n"
  ));
  // Not anchored on a leading newline: the registry is a `BTreeMap`, so `Date` sorts to the top of
  // this schema and has nothing in front of it.
  assert!(sdl.contains("scalar Date\n"));
  assert!(sdl.contains("scalar Time\n"));
}

/// **THE TWO TEMPORAL FILTERS THIS CRATE MINTS THE SCALAR FOR**, and the two names that had to dodge
/// the four above.
///
/// async-graphql 7.2's `jiff` module carries five `#[Scalar]` impls and neither a civil datetime nor
/// a zone offset is among them, so each crosses through a carrier of this crate's — which is what
/// makes these two the only temporal rows whose SCALAR NAME is chosen here rather than inherited.
///
/// `LocalDateTime` rather than `DateTime`, because that word is already `jiff::Timestamp`'s and a
/// schema cannot hold two; `UtcOffset` rather than `Offset`, because an unqualified one reads as a
/// pagination cursor's in a schema that paginates. Both carry a `@specifiedBy` URL, which is the
/// schema's whole statement of the operand grammar to a client reading `eq: UtcOffset`.
#[cfg(feature = "jiff")]
#[test]
fn the_two_minted_temporal_filters_render_the_scalars_this_crate_names() {
  use async_graphql::registry::SDLExportOptions;
  use jiff::{civil::DateTime, tz::Offset};

  struct MintedQuery;

  #[Object]
  impl MintedQuery {
    async fn local(
      &self,
      bare: ScalarFilter<DateTime>,
      nullable: Nullable<ScalarFilter<DateTime>>,
    ) -> bool {
      GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
    }

    async fn offset(
      &self,
      bare: ScalarFilter<Offset>,
      nullable: Nullable<ScalarFilter<Offset>>,
    ) -> bool {
      GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
    }
  }

  let sdl = Schema::build(MintedQuery, EmptyMutation, EmptySubscription)
    .finish()
    .sdl_with_options(SDLExportOptions::new().include_specified_by());

  assert_eq!(
    input_names(&sdl),
    [
      "LocalDateTimeFilter",
      "NullableLocalDateTimeFilter",
      "NullableUtcOffsetFilter",
      "UtcOffsetFilter",
    ]
  );

  const OPERATORS: &str = "\teq: %S%\n\tne: %S%\n\tgt: %S%\n\tgte: %S%\n\tlt: %S%\n\tlte: \
                           %S%\n\tin: [%S%!]\n\tnotIn: [%S%!]\n";
  for (input, scalar) in [
    ("LocalDateTimeFilter", "LocalDateTime"),
    ("UtcOffsetFilter", "UtcOffset"),
  ] {
    let operators = OPERATORS.replace("%S%", scalar);
    assert!(
      sdl.contains(&format!("input {input} {{\n{operators}}}\n")),
      "{input}"
    );
    assert!(
      sdl.contains(&format!(
        "input Nullable{input} {{\n{operators}\tisNull: Boolean\n}}\n"
      )),
      "Nullable{input}"
    );
  }

  assert!(sdl.contains(
    "\nscalar LocalDateTime @specifiedBy(url: \"https://en.wikipedia.org/wiki/ISO_8601\")\n"
  ));
  assert!(sdl.contains(
    "\nscalar UtcOffset @specifiedBy(url: \"https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC\")\n"
  ));
  assert!(
    !sdl.contains("scalar DateTime"),
    "the minted name does not collide with async-graphql's own"
  );
}

/// `Duration` is a GraphQL name three types claim — async-graphql's `chrono::Duration` and
/// `jiff::Span`, and this crate's own scalar for `jiff::SignedDuration` — and the two a build of
/// THIS crate can reach are both on here, now under ONE feature rather than two: `jiff` brings
/// async-graphql's `Span` scalar through the weak edge and the duration kind's scalar through the
/// registration. The schema is unaffected, because async-graphql builds its registry by WALKING the
/// schema and `jiff::Span` has no `to_filter!` row for a field to resolve through: an unreferenced
/// `ScalarType` impl is never registered, so defining all three costs nothing.
#[cfg(feature = "jiff")]
#[test]
fn an_unreferenced_scalar_leaves_the_duration_name_to_its_owner() {
  use jiff::Timestamp;

  use crate::DurationFilter;

  struct MixedQuery;

  #[Object]
  impl MixedQuery {
    async fn instant(&self, filter: ScalarFilter<Timestamp>) -> bool {
      GraphqlFilter::is_empty(&filter)
    }

    async fn elapsed(&self, filter: DurationFilter) -> bool {
      GraphqlFilter::is_empty(&filter)
    }
  }

  let sdl = Schema::build(MixedQuery, EmptyMutation, EmptySubscription)
    .finish()
    .sdl();

  assert_eq!(input_names(&sdl), ["DateTimeFilter", "DurationFilter"]);
  assert_eq!(sdl.matches("scalar Duration\n").count(), 1);
  // The one `Duration` is this crate's: only that one carries a description, and it is the grammar
  // this crate documented.
  assert!(sdl.contains("`ns` is a unit"));
}

/// …and what a schema that DOES name a second `Duration`-flavoured type gets, which is not the
/// refusal a name clash usually gets: nothing at all.
///
/// `Registry::create_type` panics on one GraphQL name held by two Rust types — but only when the
/// entry already present reports a `rust_typename`, and `MetaType::rust_typename` returns `None` for
/// the `Scalar` variant (it is `Some` for the five named composite kinds). So a scalar's second
/// claimant is dropped in silence, and the FIRST one to be walked keeps the entry: its description
/// and its `specifiedBy` then describe both types. Declaration ORDER decides which, and that is what
/// the two schemas below differ in.
///
/// Nothing is misparsed by it. `InputType::parse` is resolved on the Rust type, never looked up by
/// GraphQL name, so each argument still reads its own grammar; the loss is confined to what the SDL
/// SAYS — and both types render ISO 8601, so a surviving `specifiedBy` describes either of them. That
/// is why this is a note in the manifest rather than a reason to rename anything, but a schema owner
/// declaring a `Span` field alongside a duration column should know the introspected DESCRIPTION will
/// be one of the two, not both.
#[cfg(feature = "jiff")]
#[test]
fn a_second_duration_scalar_is_dropped_rather_than_refused() {
  use async_graphql::{InputType, Value, registry::SDLExportOptions};

  use crate::DurationFilter;

  struct SpanFirst;

  #[Object]
  impl SpanFirst {
    async fn span(&self, operand: Option<jiff::Span>) -> bool {
      operand.is_none()
    }

    async fn elapsed(&self, filter: DurationFilter) -> bool {
      GraphqlFilter::is_empty(&filter)
    }
  }

  struct FilterFirst;

  #[Object]
  impl FilterFirst {
    async fn elapsed(&self, filter: DurationFilter) -> bool {
      GraphqlFilter::is_empty(&filter)
    }

    async fn span(&self, operand: Option<jiff::Span>) -> bool {
      operand.is_none()
    }
  }

  // `include_specified_by`, because the `specifiedBy` URL is half of what the surviving entry says
  // about the type it did not come from — `Schema::sdl()` leaves the directive out entirely.
  let span_first = Schema::build(SpanFirst, EmptyMutation, EmptySubscription)
    .finish()
    .sdl_with_options(SDLExportOptions::new().include_specified_by());
  let filter_first = Schema::build(FilterFirst, EmptyMutation, EmptySubscription)
    .finish()
    .sdl_with_options(SDLExportOptions::new().include_specified_by());

  // One entry either way — no panic, and no second `Duration`.
  assert_eq!(span_first.matches("scalar Duration ").count(), 1);
  assert_eq!(filter_first.matches("scalar Duration ").count(), 1);

  // …and the description that survives is whichever registered first. jiff's `Span` scalar has none,
  // so this crate's grammar note vanishes from the schema that walks `span` first. The `specifiedBy`
  // survives either way and is the SAME URL from both claimants, which is what makes the loss a
  // description rather than a wrong statement.
  assert!(!span_first.contains("`ns` is a unit"));
  assert!(filter_first.contains("`ns` is a unit"));
  for sdl in [&span_first, &filter_first] {
    assert!(sdl.contains(
      "scalar Duration @specifiedBy(url: \"https://en.wikipedia.org/wiki/ISO_8601#Durations\")"
    ));
  }

  // The operands are unharmed in both, and each still reads through its OWN `InputType`. The two
  // grammars OVERLAP rather than differ — a `Span` reads jiff's friendly form as readily as this
  // filter does — and what separates them is which UNITS each admits: a `Span` carries calendar
  // units and the filter's operand cannot, so `P1M` is a value for one and an error for the other.
  // That is the same asymmetry the `Span` registration's refusal rests on, seen from the wire.
  let operand = |text: &str| {
    <DurationFilter as InputType>::parse(Some(Value::Object(
      [(async_graphql::Name::new("gte"), Value::String(text.into()))]
        .into_iter()
        .collect(),
    )))
  };
  for text in ["2h", "PT2H"] {
    assert!(operand(text).is_ok(), "{text}");
    assert!(
      <Option<jiff::Span> as InputType>::parse(Some(Value::String(text.into()))).is_ok(),
      "{text}"
    );
  }
  assert!(<Option<jiff::Span> as InputType>::parse(Some(Value::String("P1M".into()))).is_ok());
  assert!(operand("P1M").is_err());
}

/// `DurationFilter` is the one registration none of the four macros could serve — its wire face is
/// hand-written — so its SDL is asserted whole rather than by representative.
///
/// The scalar carries a DESCRIPTION where the twenty-three generated input objects carry none. An
/// opaque scalar is the one place a client has nothing else to read: `Int` says what it accepts by
/// being `Int`, and `Duration` says nothing at all unless the schema does.
#[cfg(feature = "jiff")]
#[test]
fn the_duration_filter_renders_its_own_wire_face() {
  use crate::DurationFilter;

  struct DurationQuery;

  #[Object]
  impl DurationQuery {
    async fn duration(&self, bare: DurationFilter, nullable: Nullable<DurationFilter>) -> bool {
      GraphqlFilter::is_empty(&bare) && GraphqlFilter::is_empty(&nullable)
    }
  }

  let sdl = Schema::build(DurationQuery, EmptyMutation, EmptySubscription)
    .finish()
    .sdl();

  assert_eq!(
    input_names(&sdl),
    ["DurationFilter", "NullableDurationFilter"]
  );

  const OPERATORS: &str = "\teq: Duration\n\tne: Duration\n\tgt: Duration\n\tgte: \
                           Duration\n\tlt: Duration\n\tlte: Duration\n\tin: [Duration!]\n\tnotIn: \
                           [Duration!]\n";
  assert!(sdl.contains(&format!("input DurationFilter {{\n{OPERATORS}}}\n")));
  assert!(sdl.contains(&format!(
    "input NullableDurationFilter {{\n{OPERATORS}\tisNull: Boolean\n}}\n"
  )));

  assert!(sdl.contains("\nscalar Duration\n"));
  // The two grammars, the sign, and — the half a client cannot discover by trying — the fact that
  // two of the accepted units are APPROXIMATIONS, with their definitions. All of it reaches the
  // schema and not only the rustdoc, because an opaque scalar is the one place a client has nothing
  // else to read.
  assert!(sdl.contains("`ns` is a unit"));
  assert!(sdl.contains("ISO 8601 is what comes back"));
  assert!(sdl.contains("SIGNED"));
  assert!(sdl.contains("APPROXIMATE"));
  assert!(sdl.contains("30.44 days"));
  assert!(sdl.contains("365.25 days"));
  assert!(sdl.contains("`M` is a MONTH and `m` is a minute"));
  assert!(sdl.contains("are refused"));
}

/// The operands cross as TEXT, and the crossing is jiff's grammar — BOTH of its grammars inbound,
/// and ISO 8601 alone outbound.
#[cfg(feature = "jiff")]
#[test]
fn duration_operands_cross_the_wire_as_jiff_text() {
  use async_graphql::{InputType, Name, Value, indexmap::IndexMap};
  use jiff::SignedDuration;

  use crate::DurationFilter;

  let mut obj = IndexMap::new();
  // The friendly form on one slot and ISO 8601 on another, in one object: a client is not made to
  // pick a grammar and hold to it.
  obj.insert(Name::new("gte"), Value::String("1h30min".into()));
  obj.insert(Name::new("lt"), Value::String("PT2H".into()));
  obj.insert(
    Name::new("in"),
    Value::List(vec![
      Value::String("500ms".into()),
      Value::String("-PT2S".into()),
    ]),
  );

  let parsed = <DurationFilter as InputType>::parse(Some(Value::Object(obj)))
    .expect("both an inline operand and a list operand parse");
  assert_eq!(
    parsed,
    DurationFilter::new()
      .with_gte(SignedDuration::from_secs(5400))
      .with_lt(SignedDuration::from_secs(7200))
      .with_in_([
        SignedDuration::from_millis(500),
        SignedDuration::from_secs(-2)
      ])
  );

  // Rendering is CANONICAL and single-grammar, so `1h30min` comes back as `PT1H30M` — the round trip
  // is over values, and the SIGN survives it.
  let Value::Object(rendered) = InputType::to_value(&parsed) else {
    panic!("an input object renders as an object");
  };
  assert_eq!(rendered.get("gte"), Some(&Value::String("PT1H30M".into())));
  assert_eq!(rendered.get("lt"), Some(&Value::String("PT2H".into())));
  assert_eq!(
    rendered.get("in"),
    Some(&Value::List(vec![
      Value::String("PT0.5S".into()),
      Value::String("-PT2S".into()),
    ]))
  );
  assert_eq!(rendered.get("eq"), Some(&Value::Null));

  // A unitless number is refused at the wire boundary, carrying jiff's own message.
  let mut bad = IndexMap::new();
  bad.insert(Name::new("lt"), Value::String("5400".into()));
  let error = <DurationFilter as InputType>::parse(Some(Value::Object(bad)))
    .expect_err("a bare number is not a duration")
    .into_server_error(async_graphql::Pos::default());
  assert!(
    error
      .message
      .contains("expected to find unit designator suffix"),
    "{}",
    error.message
  );

  // A CALENDAR unit crosses too, through the wide grammar's table — and it renders back in the one
  // grammar that comes out, so `1month` leaves as the hours the table defines it to be. That the
  // wire form is not the submitted form is the same fact `1h30min` already shows; what is new is
  // that the value is an APPROXIMATION, which the scalar's description states.
  let mut calendar = IndexMap::new();
  calendar.insert(Name::new("gt"), Value::String("1month".into()));
  let parsed = <DurationFilter as InputType>::parse(Some(Value::Object(calendar)))
    .expect("a month is 30.44 days here");
  let Value::Object(rendered) = InputType::to_value(&parsed) else {
    panic!("an input object renders as an object");
  };
  assert_eq!(
    rendered.get("gt"),
    Some(&Value::String("PT730H33M36S".into()))
  );

  // …and the ISO 8601 spelling of the same unit is still refused, because the fallback reads no ISO
  // 8601 at all. The message a client gets is jiff's own.
  let mut iso = IndexMap::new();
  iso.insert(Name::new("gt"), Value::String("P1M".into()));
  let error = <DurationFilter as InputType>::parse(Some(Value::Object(iso)))
    .expect_err("no parser reads an ISO 8601 month here")
    .into_server_error(async_graphql::Pos::default());
  assert!(
    error.message.contains("days or greater"),
    "{}",
    error.message
  );

  // The nullable face reads the same flat object and adds only the null test.
  let mut nullable = IndexMap::new();
  nullable.insert(Name::new("lte"), Value::String("2h".into()));
  nullable.insert(Name::new("isNull"), Value::Boolean(true));
  let parsed = <Nullable<DurationFilter> as InputType>::parse(Some(Value::Object(nullable)))
    .expect("the null test sits beside the operators");
  assert_eq!(
    parsed,
    Nullable::new(DurationFilter::new().with_lte(SignedDuration::from_secs(7200))).with_null(true)
  );
}

// ---------------------------------------------------------------------------------------------
// The three-layer naming law, measured against the derive the output object will carry.
// ---------------------------------------------------------------------------------------------

/// A [`MediaGraphqlOutput`] member whose own type is a composite — the ADDRESS half, mirroring what
/// `ingraph-codegen` emits as `<E>KeyOutput`.
///
/// It carries the same non-`pub` members the object above it does, so the measurement covers a
/// nested registration as well as a flat one: a derive that read its own type's fields and stopped
/// at a member's would have passed the flat case alone.
#[derive(async_graphql::SimpleObject, Debug, Clone)]
struct MediaKeyOutput {
  pub(crate) media_id: u64,
  pub(crate) id: u64,
}

/// The shape `ingraph-codegen` emits for `<E>GraphqlOutput`, mirrored here for [`MediaOrderBy`]'s
/// reason — the emitter cannot reach a schema — and measuring the one assumption the THREE-LAYER
/// NAMING LAW rests on: **`SimpleObject` does not require `pub` fields.**
///
/// | layer | what it is here | what moves it |
/// |---|---|---|
/// | 1 | the struct's MEMBERS — `title`, `bit_rate` | nothing; they are the domain names |
/// | 2 | the inherent accessors — `headline_ref`, `bit_rate_ref` | `output(field = "…")` |
/// | 3 | the SDL — `titleText`, `bitRate` | `#[graphql(name = "…")]`, and the backend's own camelCase where no word is written |
///
/// Layer 1 is `pub(crate)` because an emitted-to-emitted read spends the FIELD: same-crate
/// expansions are mutually visible there, where an accessor's name is a knob a declaration can move.
/// Had the derive demanded `pub`, the object's representation would have been its API and the
/// accessor face decorative — so this is measured rather than assumed, and it is measured on the
/// emitted shape rather than on a bare struct: nested composite member, no constructor, borrows for
/// a face.
///
/// **Fully PRIVATE members were measured too and are equally accepted** (async-graphql 7.2.1); the
/// spelling here is `pub(crate)` because that is what the law asks the emitter to write, and this is
/// the pin that notices the day a version demands more.
///
/// **Layer 3's attribute cannot precede layer 3's derive**, which is what keeps the emitter from
/// writing `#[graphql(name = "…")]` today. Measured: the same field attribute on a struct carrying
/// no `SimpleObject` is
///
/// ```text
/// error: cannot find attribute `graphql` in this scope
///    = note: `graphql` is an attribute that can be used by the derive macros `Description`,
///      `Enum`, `InputObject`, … and `Union`, you might be missing a `derive` attribute
/// ```
///
/// So the wire rename rides with the backend derive, in the round that binds every wire type to a
/// library at once; what the emitter carries meanwhile is the NAME, on
/// `ingraph-codegen`'s `model::Face::name`, which is where that round reads it from.
#[derive(async_graphql::SimpleObject, Debug, Clone)]
struct MediaGraphqlOutput {
  pub(crate) id: u64,
  pub(crate) key: MediaKeyOutput,
  // Renamed on the SCHEMA axis alone — layer 3 — so the member and the accessor are untouched.
  //
  // A `//` and not a `///`, for the reason the assertion below is byte-exact: a doc comment on a
  // field becomes that field's SDL DESCRIPTION, and the emitter writes none — its field members
  // carry no `#[doc]` at all, descriptions being `attrs(desc = …)`'s alone.
  #[graphql(name = "titleText")]
  pub(crate) title: String,
  pub(crate) bit_rate: u64,
}

impl MediaGraphqlOutput {
  /// The address, by reference — the fixed member every emitted output object carries.
  const fn key_ref(&self) -> &MediaKeyOutput {
    &self.key
  }

  /// The accessor an `output(field = "headline")` moves — layer 2, over a member layer 1 pins to
  /// `title`.
  const fn headline_ref(&self) -> &String {
    &self.title
  }

  /// …and the accessor a field naming no word gets, which is its member's own name.
  const fn bit_rate_ref(&self) -> &u64 {
    &self.bit_rate
  }
}

struct WireQuery;

#[Object]
impl WireQuery {
  async fn media(&self) -> MediaGraphqlOutput {
    MediaGraphqlOutput {
      id: 1,
      key: MediaKeyOutput { media_id: 2, id: 1 },
      title: "a reel".to_owned(),
      bit_rate: 320,
    }
  }
}

/// The three layers, read off one object at once: the SDL says `titleText`, the accessor says
/// `headline_ref`, and the member behind both is `title`.
///
/// The SDL is byte-exact because every line of it is a schema commitment, and the two unrenamed
/// members are in it for what they show about the DEFAULT: `bit_rate` reaches a client as `bitRate`
/// through the backend's own rename rule, so a schema name arrives without any word being written
/// and without any Rust ident moving.
#[test]
fn a_non_pub_member_registers_and_the_three_faces_are_three_names() {
  let sdl = Schema::build(WireQuery, EmptyMutation, EmptySubscription)
    .finish()
    .sdl();

  assert!(
    sdl.contains(
      "type MediaGraphqlOutput {\n\tid: Int!\n\tkey: MediaKeyOutput!\n\ttitleText: \
       String!\n\tbitRate: Int!\n}\n"
    ),
    "{sdl}"
  );
  assert!(
    sdl.contains("type MediaKeyOutput {\n\tmediaId: Int!\n\tid: Int!\n}\n"),
    "{sdl}"
  );
  // The name the WORD did not move is absent from the schema, which is the half a positive
  // assertion cannot make: `title` reaching a client would mean the attribute had been ignored.
  assert!(!sdl.contains("\ttitle: String!"), "{sdl}");

  let media = MediaGraphqlOutput {
    id: 1,
    key: MediaKeyOutput { media_id: 2, id: 1 },
    title: "a reel".to_owned(),
    bit_rate: 320,
  };
  assert_eq!(media.headline_ref(), "a reel");
  assert_eq!(*media.bit_rate_ref(), 320);
  assert_eq!(media.key_ref().media_id, 2);
}

// ---------------------------------------------------------------------------------------------
// The ordering vocabulary, and the shape a generated `*OrderBy` takes.
// ---------------------------------------------------------------------------------------------

/// The shape `ingraph-codegen` emits for `<E>OrderBy`, mirrored here because the emitter cannot
/// reach a schema: `ingraph-derive`'s fixtures have no `async-graphql` dev-dependency, and the
/// backend derive is held back to the round that binds every wire type to a library at once.
///
/// **This mirror is what makes the variant a WIRE fact.** `OneofObject` renders each variant as a
/// schema key in lower camel case — `CreatedAt` becomes `createdAt`, asserted byte-exact below — so
/// the variant is not an internal spelling a reader may treat as free. It is layer 3's input, and
/// that is why the emitter builds it from the RECORD FIELD: a variant taken from the first declared
/// database's column name put `<db>(rename)` into a client's query document, and two
/// deployments of one record then disagreed about the vocabulary. `ingraph-codegen`'s
/// `an_order_by_variant_is_the_record_field_whatever_storage_renamed` is the other half of that
/// claim; this is where the rendering it depends on is measured.
///
/// So what this file can hold is the CLAIM the emitted shape rests on — that a term's "exactly one
/// column" is enforced by the schema and never reaches a resolver — asserted over the framework's
/// own [`OrderDirection`] in the shape the emitter writes. The variant arity and the payload are
/// the load-bearing part: `OneofObject` refuses anything else, a struct with one
/// `Option<OrderDirection>` field per column included, so an emitter that wrote the obvious reading
/// of the SDL below would have produced a face the derive could never carry.
#[derive(async_graphql::OneofObject, Debug, Clone, Copy, PartialEq, Eq)]
enum MediaOrderBy {
  Title(OrderDirection),
  CreatedAt(OrderDirection),
}

impl MediaOrderBy {
  /// The per-database resolver's shape: the column, as the ordering seam's own type.
  const fn sqlite_column(self) -> &'static FieldName {
    match self {
      Self::Title(_) => FieldName::new("title"),
      Self::CreatedAt(_) => FieldName::new("created_at"),
    }
  }

  /// The half no database renames.
  const fn direction(self) -> OrderDirection {
    match self {
      Self::Title(direction) | Self::CreatedAt(direction) => direction,
    }
  }
}

/// How many times the ordering resolver was entered.
///
/// A refusal that leaves this at zero is the whole difference between a schema constraint and a
/// resolver's job: a resolver that had to check "exactly one" would be a check every future
/// resolver has to remember, and a client would learn about a malformed order from a runtime error
/// rather than from validation.
static ORDER_RESOLVER_ENTERED: core::sync::atomic::AtomicUsize =
  core::sync::atomic::AtomicUsize::new(0);

struct OrderQuery;

#[Object]
impl OrderQuery {
  /// A LIST of terms — ordered by the GraphQL specification, where an input object's fields are
  /// not.
  async fn medias(&self, order_by: Vec<MediaOrderBy>) -> String {
    ORDER_RESOLVER_ENTERED.fetch_add(1, core::sync::atomic::Ordering::SeqCst);
    order_by
      .into_iter()
      .map(|term| {
        // Through the deref, because a name is not `Display`: it is an identifier the rendering
        // backend quotes, and a type that formatted itself would be one `{}` away from reaching a
        // statement unquoted.
        let column: &str = term.sqlite_column();
        let direction = if term.direction().is_descending() {
          "DESC"
        } else {
          "ASC"
        };
        format!("{column} {direction}")
      })
      .collect::<Vec<_>>()
      .join(", ")
  }
}

fn order_sdl() -> String {
  Schema::build(OrderQuery, EmptyMutation, EmptySubscription)
    .finish()
    .sdl()
}

/// The direction vocabulary, whole: two values, in the wire spelling async-graphql's rename rule
/// gives them, and NO DESCRIPTION anywhere.
///
/// Byte-exact because every one of those is a schema commitment. `ASC` is not `asc`, and a client
/// reading `direction: OrderDirection` has the value list and nothing else.
///
/// # The descriptions LEFT, and this pin is what says so
///
/// It used to assert the two variant sentences as published text. They were `///` comments on this
/// crate's own type, and `async-graphql-derive`'s `Enum` lifts rustdoc unconditionally — so what
/// reached every client's schema was whatever this file's authors had written for Rust readers,
/// including, on the type itself, paragraphs naming polarsync and `crate::Id`.
///
/// That contradicts the emitter's own rule — descriptions come from `attrs(desc = …)` and nowhere
/// else — and the hand-written filter faces beside this one had always kept it, writing
/// `description: None` into the entry they build. `graphql::direction` states the repair; this is
/// where its wire consequence is measured.
#[test]
fn the_order_direction_renders_its_two_values_and_describes_neither() {
  assert!(
    order_sdl().contains("enum OrderDirection {\n\tASC\n\tDESC\n}\n"),
    "{}",
    order_sdl()
  );
  assert!(
    !order_sdl().contains("Smallest first"),
    "a Rust reader\'s sentence reached a client: {}",
    order_sdl()
  );
}

/// A term renders as a `@oneOf` INPUT OBJECT — one nullable field per column, typed as the
/// direction — and a query orders by a LIST of them.
///
/// The SDL is where the ruling is visible at all, so all three halves of it are pinned: the
/// directive on the type, the directive's own DECLARATION (async-graphql omits that line entirely
/// unless some input object is oneof, so its presence is what says the flag reached the registry),
/// and the argument's list spelling.
#[test]
fn an_order_by_term_is_a_oneof_input_object_and_a_query_takes_a_list_of_them() {
  let sdl = order_sdl();

  assert!(
    sdl.contains(
      "input MediaOrderBy @oneOf {\n\ttitle: OrderDirection\n\tcreatedAt: OrderDirection\n}\n"
    ),
    "{sdl}"
  );
  assert!(sdl.contains("directive @oneOf on INPUT_OBJECT\n"), "{sdl}");
  assert!(
    sdl.contains("medias(orderBy: [MediaOrderBy!]!): String!"),
    "{sdl}"
  );
}

/// **The reason this shape was chosen over two parallel lists:** "exactly one field" is enforced
/// when the document is VALIDATED, so a malformed term never reaches a resolver.
///
/// Zero fields and two fields are both refused, through a literal and through a variable alike, and
/// so is a single field explicitly set to `null` — with a message of its own, since "exactly one is
/// supplied" and "the one supplied is not null" are two conditions. The resolver's entry count is
/// what makes each of those a SCHEMA fact: a `0` after a refusal is a check nothing downstream has
/// to write, remember, or agree with.
///
/// The introspected flag is asserted beside them because it is what a client-side tooling chain
/// reads — the SDL directive and `__type(…).isOneOf` are two faces of the one registry entry, and a
/// generated client validates against the second.
#[test]
fn exactly_one_field_is_a_validation_rule_that_no_resolver_ever_sees() {
  use core::{
    pin::pin,
    sync::atomic::Ordering as Atomic,
    task::{Context as TaskContext, Poll, Waker},
  };

  use async_graphql::{Request, Variables};

  /// Drive a ready future to its value without a runtime — the shape `store::blob`'s tests use, and
  /// for the same reason: nothing here awaits I/O, so one poll and a `Waker` that is never woken is
  /// the whole of what a request needs.
  fn block_on<F: Future>(future: F) -> F::Output {
    let mut future = pin!(future);
    let mut cx = TaskContext::from_waker(Waker::noop());
    loop {
      if let Poll::Ready(value) = future.as_mut().poll(&mut cx) {
        return value;
      }
    }
  }

  /// One request, answered with what the resolver produced and how many times it was entered.
  fn ask(query: &str, variables: Option<Variables>) -> (Result<String, String>, usize) {
    ORDER_RESOLVER_ENTERED.store(0, Atomic::SeqCst);
    let mut request = Request::new(query);
    if let Some(variables) = variables {
      request = request.variables(variables);
    }
    let response = block_on(
      Schema::build(OrderQuery, EmptyMutation, EmptySubscription)
        .finish()
        .execute(request),
    );
    let entered = ORDER_RESOLVER_ENTERED.load(Atomic::SeqCst);
    let answer = match response.errors.first() {
      Some(error) => Err(error.message.clone()),
      None => Ok(response.data.to_string()),
    };
    (answer, entered)
  }

  // ONE field is the whole vocabulary of a well-formed term, and it arrives as the pair the
  // lowering will ask for: a column resolved per database, and the direction that column runs in.
  let (answer, entered) = ask(
    r#"{ medias(orderBy: [{ createdAt: DESC }, { title: ASC }]) }"#,
    None,
  );
  assert_eq!(
    answer,
    Ok(r#"{medias: "created_at DESC, title ASC"}"#.to_owned())
  );
  assert_eq!(entered, 1);

  // …and the LIST is what carries the sequence, which is the other half of the ruling: reversing
  // the two entries is a different order, where reversing an input object's fields is the same
  // value by specification.
  let (reversed, _) = ask(
    r#"{ medias(orderBy: [{ title: ASC }, { createdAt: DESC }]) }"#,
    None,
  );
  assert_eq!(
    reversed,
    Ok(r#"{medias: "title ASC, created_at DESC"}"#.to_owned())
  );

  const EXACTLY_ONE: &str = "Oneof input objects requires have exactly one field";
  const NOT_NULL: &str = "Oneof Input Objects require that exactly one field must be supplied and \
                          that field must not be null";

  for (label, query, variables, expected) in [
    (
      "two fields, spelled inline",
      r#"{ medias(orderBy: [{ title: DESC, createdAt: ASC }]) }"#,
      None,
      EXACTLY_ONE,
    ),
    (
      "no field at all",
      r#"{ medias(orderBy: [{}]) }"#,
      None,
      EXACTLY_ONE,
    ),
    (
      "one field, explicitly null",
      r#"{ medias(orderBy: [{ title: null }]) }"#,
      None,
      NOT_NULL,
    ),
    // A VARIABLE is the path a real client takes and it is coerced later than a literal, so it is
    // asserted rather than assumed to follow.
    (
      "two fields, through a variable",
      r#"query Q($order: [MediaOrderBy!]!) { medias(orderBy: $order) }"#,
      Some(Variables::from_value(async_graphql::value!({
        "order": [{ "title": "DESC", "createdAt": "ASC" }]
      }))),
      EXACTLY_ONE,
    ),
    (
      "no field at all, through a variable",
      r#"query Q($order: [MediaOrderBy!]!) { medias(orderBy: $order) }"#,
      Some(Variables::from_value(async_graphql::value!({
        "order": [{}]
      }))),
      EXACTLY_ONE,
    ),
  ] {
    let (answer, entered) = ask(query, variables);
    let message = answer.expect_err(label);
    assert!(message.contains(expected), "{label}: {message}");
    assert_eq!(entered, 0, "{label}: the resolver was entered anyway");
  }

  // The same registry entry, as a generated client reads it.
  let (introspected, _) = ask(r#"{ __type(name: "MediaOrderBy") { isOneOf } }"#, None);
  assert_eq!(introspected, Ok(r#"{__type: {isOneOf: true}}"#.to_owned()));
}

/// **The rows the wall was missing, the framework's own half.** A `Vec<String>` column resolves to
/// `ListFilter<String, TextFilter<String>>` and, until this row, reached no schema at all — a state
/// this module's own note used to describe as designed. Both types are foreign to a declaring crate,
/// so `impl InputType for ListFilter<String, …>` written there is `E0117` and only this crate could
/// ever have supplied the face.
///
/// `any` renders as the ELEMENT's own input object, which for a text element is `StringFilter` — so
/// a collection of text asks about one member in the vocabulary a text column is asked in, and the
/// row registers nothing new for it.
///
/// The composed names are the element's own running through the wrapper axes, which is the
/// derivation working rather than a second table: the element FILTER's name with its family suffix
/// off, and `Nullable` in front of that.
#[test]
fn the_text_collections_reach_a_schema() {
  let sdl = sdl();

  assert!(sdl.contains(
    "input StringListFilter {\n\teq: [String!]\n\tne: [String!]\n\tgt: [String!]\n\tgte: \
     [String!]\n\tlt: [String!]\n\tlte: [String!]\n\thasElement: String\n\tany: \
     StringFilter\n\tcount: CountFilter\n}\n"
  ));
  assert!(sdl.contains(
    "input StringSetFilter {\n\teq: [String!]\n\tne: [String!]\n\tencloses: \
     [String!]\n\tenclosedBy: [String!]\n\toverlaps: [String!]\n\thasElement: String\n\tany: \
     StringFilter\n\tcount: CountFilter\n}\n"
  ));
  // Their `Nullable` twins came with them, which is the pairing discipline: no arm of any
  // registration macro mints a bare face alone.
  assert!(sdl.contains("input NullableStringListFilter {"));
  assert!(sdl.contains("input NullableStringSetFilter {"));
}

/// **A 128-bit column reaches a schema at all**, which is the wall row that said NOBODY could supply
/// it: async-graphql's integer scalars stop at 64 bits and `impl ScalarType for u128` is `E0117` in
/// every crate but its own. The carrier is the way past it, and the operand crosses as a JSON NUMBER
/// inside the safe range and as DECIMAL TEXT beyond it.
///
/// The lexical form is the whole of what the row decides, and the SDL is where a client reads it:
/// `eq: u128` says nothing about the grammar, so the scalar's description carries BOTH forms and the
/// bound between them.
#[test]
fn a_128_bit_column_reaches_a_schema_under_its_own_grammar() {
  let sdl = sdl();

  const U128: &str = "\teq: u128\n\tne: u128\n\tgt: u128\n\tgte: u128\n\tlt: \
                      u128\n\tlte: u128\n\tin: [u128!]\n\tnotIn: [u128!]\n";
  assert!(sdl.contains(&format!("input U128Filter {{\n{U128}}}\n")));
  assert!(sdl.contains(&format!(
    "input NullableU128Filter {{\n{U128}\tisNull: Boolean\n}}\n"
  )));

  const I128: &str = "\teq: i128\n\tne: i128\n\tgt: i128\n\tgte: i128\n\tlt: \
                      i128\n\tlte: i128\n\tin: [i128!]\n\tnotIn: [i128!]\n";
  assert!(sdl.contains(&format!("input I128Filter {{\n{I128}}}\n")));

  // The two scalars, and the sentence that is the whole reason for the string form. An opaque scalar
  // is the one place a client has nothing else to read.
  //
  // The INPUT OBJECT keeps its name and the OPERAND changed, which is the suite's whole shape: a
  // filter name is a schema commitment the re-routing had no licence to rewrite.
  assert!(sdl.contains("scalar i128"), "{sdl}");
  assert!(sdl.contains("scalar u128"), "{sdl}");
  assert!(sdl.contains("decimal text"), "{sdl}");
  // The HYBRID grammar, which replaced *never a JSON number*: BOTH forms are described, because a
  // client reading `eq: u128` has to know that a small operand may be written either way and that a
  // large one may not.
  assert!(sdl.contains("HYBRID at 2^53 \u{2212} 1"), "{sdl}");
  assert!(sdl.contains("as a JSON number"), "{sdl}");
  assert!(!sdl.contains("never a JSON number"), "{sdl}");
}

/// **A blob reaches a schema as hex**, which is the other framework-only row — and the one where the
/// operand HAD a face and it was the wrong one: `Vec<u8>` renders as `[Int!]` through
/// async-graphql's blanket over `Vec<T>`, so a client would have asked about a thumbnail as a list
/// of small integers.
#[test]
fn a_blob_reaches_a_schema_as_hex() {
  let sdl = sdl();

  const BYTES: &str = "\teq: U8Vector\n\tne: U8Vector\n\tgt: U8Vector\n\tgte: U8Vector\n\tlt: \
                       U8Vector\n\tlte: U8Vector\n\tcontains: U8Vector\n\tnotContains: \
                       U8Vector\n\tin: [U8Vector!]\n\tnotIn: [U8Vector!]\n";
  assert!(sdl.contains(&format!("input U8VectorFilter {{\n{BYTES}}}\n")));
  assert!(sdl.contains(&format!(
    "input NullableU8VectorFilter {{\n{BYTES}\tisNull: Boolean\n}}\n"
  )));

  assert!(sdl.contains("scalar U8Vector"), "{sdl}");
  assert!(sdl.contains("two characters per byte"), "{sdl}");
  // The operand is NOT a list of integers, which is the face this row exists instead of.
  assert!(!sdl.contains("eq: [Int!]\n\tne: [Int!]\n\tgt: [Int!]\n\tgte: [Int!]\n\tlt: [Int!]\n\tlte: [Int!]\n\tcontains"), "{sdl}");
}

/// **The OUTPUT leg**, for the three operands whose Rust type may not carry a foreign trait.
///
/// One `#[Scalar]` impl writes `InputType` AND `OutputType`, so both legs have existed since each
/// carrier did — what was missing is REACHABILITY: a private carrier can be read into a filter and
/// cannot be returned by a resolver. These are public, so an output position can name them, and this
/// is that position.
///
/// `jiff::SignedDuration` is the row the wall listed as *ingraph — it mints the Duration scalar for
/// INPUT only*. It is the same scalar in both directions, under the same name.
#[cfg(feature = "jiff")]
#[test]
fn the_carriers_render_in_an_output_position() {
  use crate::{HexBytes, I128, JiffDuration, U128};

  struct OutputQuery;

  #[Object]
  impl OutputQuery {
    async fn elapsed(&self) -> JiffDuration {
      JiffDuration::from(jiff::SignedDuration::from_secs(5400))
    }

    async fn balance(&self) -> U128 {
      U128::from(u128::MAX)
    }

    async fn drift(&self) -> I128 {
      I128::from(i128::MIN)
    }

    async fn checksum(&self) -> HexBytes {
      HexBytes::from(vec![0x89, 0x50, 0x4e, 0x47])
    }
  }

  let schema = Schema::build(OutputQuery, EmptyMutation, EmptySubscription).finish();
  let sdl = schema.sdl();

  // The scalar's name, in an OUTPUT position and non-null — the field type a client generates
  // against.
  assert!(sdl.contains("elapsed: Duration!"), "{sdl}");
  assert!(sdl.contains("balance: u128!"), "{sdl}");
  assert!(sdl.contains("drift: i128!"), "{sdl}");
  assert!(sdl.contains("checksum: bytes!"), "{sdl}");

  // …and what actually crosses, which is the half an SDL cannot show. Driven with a `Waker` that is
  // never woken, as the order-decode test above is: nothing here awaits I/O, so polling to `Ready`
  // is the whole of what a request needs and no runtime has to be spun up for it.
  let answered = {
    use core::{
      future::Future,
      pin::pin,
      task::{Context as TaskContext, Poll, Waker},
    };

    let mut request = pin!(schema.execute("{ elapsed balance drift checksum }"));
    let mut cx = TaskContext::from_waker(Waker::noop());
    loop {
      if let Poll::Ready(response) = request.as_mut().poll(&mut cx) {
        break response;
      }
    }
  };
  assert!(answered.errors.is_empty(), "{:?}", answered.errors);
  assert_eq!(
    answered.data.to_string(),
    r#"{elapsed: "PT1H30M", balance: "340282366920938463463374607431768211455", drift: "-170141183460469231731687303715884105728", checksum: "89504e47"}"#
  );
}

/// **THE ENUM FILTER'S NAME IS DERIVED FROM ITS OPERAND**, which is what makes it unique without a
/// table to keep in step.
///
/// Every other registered filter is a row naming a LITERAL, and the argument that two rows never
/// claim one GraphQL name is made by eye across four macro invocations — `Registry::create_type`
/// panics when two Rust types claim one name, so the tables have to be right rather than merely
/// consistent. The enum kind has no table and could not have one: its operands are a DECLARER's
/// types, an open set.
///
/// So the uniqueness is re-made as a FUNCTION, and this is the pin for it: the filter's name is the
/// operand's own schema name with `Filter` after it, and the nullable twin is that name with
/// `Nullable` in front. Prefixing and suffixing preserve distinctness, so two operands async-graphql
/// already keeps distinct give two filters this crate keeps distinct — which is the whole of the
/// argument the literal tables make by hand.
///
/// What it does NOT rule out is a declared enum whose own schema name is one of this crate's operand
/// names: an enum called `i64` would claim `I64Filter`, which `ScalarFilter<i64>` holds. The
/// household register is what makes that a corner rather than a hazard — a declared enum takes
/// Pascal, and the roster's rows are lowercase — but it is a CONVENTION and not a guard, so the
/// collision stays representable. That
/// collision is async-graphql's own to report, and it reports it the way it reports any two Rust
/// types under one GraphQL name.
#[test]
fn the_enum_filters_name_follows_its_operand() {
  use async_graphql::InputType;

  assert_eq!(<EnumFilter<Probe> as InputType>::type_name(), "ProbeFilter");
  assert_eq!(
    <Nullable<EnumFilter<Probe>> as InputType>::type_name(),
    "NullableProbeFilter"
  );

  // A second operand, and a second pair of names — the injectivity, shown rather than argued.
  assert_eq!(
    <EnumFilter<Signal> as InputType>::type_name(),
    "SignalFilter"
  );
  assert_ne!(
    <EnumFilter<Probe> as InputType>::type_name(),
    <EnumFilter<Signal> as InputType>::type_name()
  );

  // And both are built from the ONE name the operand publishes, so a rename there moves both.
  assert_eq!(<Probe as InputType>::type_name(), "Probe");
}

/// **A collection face is named from its ELEMENT'S FILTER, and that source is forced rather than
/// chosen.**
///
/// The two collection kinds are written over their parameters now — one impl each, where there used
/// to be eleven hand-maintained rows apiece — so the uniqueness the tables argued for by eye has to
/// be re-made as a property of the derivation. It is, and the derivation's own input is the thing to
/// pin: the element's OWN schema name cannot serve, because async-graphql publishes every integer
/// width as `Int`. Named from the element, seven Rust types would claim `IntListFilter`.
///
/// Named from the element's FILTER, they do not: naming those is this crate's registry's own job,
/// and it does it injectively. Stripping the family suffix and appending the collection's recovers
/// exactly the words the tables used to spell — which `every_registration_reaches_the_schema` is
/// what checks, row for row.
#[test]
fn a_collection_filter_is_named_from_the_element_filter_because_the_element_cannot() {
  use async_graphql::InputType;

  // THE MEASUREMENT the derivation rests on: two widths, one scalar name.
  assert_eq!(<i8 as InputType>::type_name(), "Int");
  assert_eq!(<i64 as InputType>::type_name(), "Int");
  assert_eq!(
    <ScalarFilter<i8> as InputType>::type_name(),
    "I8Filter",
    "the FILTER is what distinguishes them"
  );

  // The rule, at a framework element and at a declarer's.
  assert_eq!(<ListFilter<i64> as InputType>::type_name(), "I64ListFilter");
  assert_eq!(<SetFilter<i64> as InputType>::type_name(), "I64SetFilter");
  assert_eq!(
    <ListFilter<Probe, EnumFilter<Probe>> as InputType>::type_name(),
    "ProbeListFilter"
  );
  assert_eq!(
    <Nullable<ListFilter<Probe, EnumFilter<Probe>>> as InputType>::type_name(),
    "NullableProbeListFilter"
  );

  // Injectivity, shown rather than argued: two distinct element filters, two distinct collection
  // names — prefixing and suffixing preserve distinctness, and the strip is injective on the set of
  // names that carry the suffix, which every filter this crate registers does.
  assert_ne!(
    <ListFilter<Probe, EnumFilter<Probe>> as InputType>::type_name(),
    <ListFilter<Signal, EnumFilter<Signal>> as InputType>::type_name()
  );
  assert_ne!(
    <ListFilter<i8> as InputType>::type_name(),
    <ListFilter<i64> as InputType>::type_name()
  );
  // A sequence and a set of ONE element are two names, which is what keeps the two kinds' faces
  // apart in a schema that carries both.
  assert_ne!(
    <ListFilter<i64> as InputType>::type_name(),
    <SetFilter<i64> as InputType>::type_name()
  );
}

/// **The enum kind's two faces render the operators a closed vocabulary has, and no others.**
///
/// Four fields — equality and membership — and NOT the ordering family: a vocabulary has no order,
/// and the four operators `ScalarFilter` carries would each need one. The `Nullable` twin is those
/// four plus the null test, flat, which is what every registered pair looks like.
#[test]
fn the_enum_input_objects_render_their_operators() {
  let sdl = sdl();
  assert!(
    sdl.contains(
      "input ProbeFilter {\n\teq: Probe\n\tne: Probe\n\tin: [Probe!]\n\tnotIn: [Probe!]\n}"
    ),
    "{sdl}"
  );
  assert!(
    sdl.contains(
      "input NullableProbeFilter {\n\teq: Probe\n\tne: Probe\n\tin: [Probe!]\n\tnotIn: [Probe!]\n\tisNull: Boolean\n}"
    ),
    "{sdl}"
  );
  // The operand itself reaches the schema through the filter that names it, which is what makes a
  // declared enum spellable at all.
  assert!(sdl.contains("enum Probe {\n\tNEAR\n\tFAR\n}"), "{sdl}");
}

/// **The nullable face parses ONE FLAT OBJECT**, and its operator fields are read by the bare face's
/// own parser — the arrangement the generated pairs have, held here over the generic one.
#[test]
fn the_nullable_enum_face_parses_one_flat_object() {
  use async_graphql::InputType;

  let parsed = <Nullable<EnumFilter<Probe>> as InputType>::parse(Some(async_graphql::value!({
    "eq": "NEAR",
    "isNull": false,
  })))
  .expect("a flat object carries both halves");
  assert_eq!(parsed.null(), Some(&false));
  assert_eq!(parsed.inner().eq(), Some(&Probe::Near));

  // And the round trip: what `to_value` renders parses back to the same filter.
  let rendered = InputType::to_value(&parsed);
  assert_eq!(
    <Nullable<EnumFilter<Probe>> as InputType>::parse(Some(rendered)).expect("the round trip"),
    parsed
  );
}

/// **FOUR WIDTHS, ONE FACE** — the golden the ConfidenceFilter reshape is accepted on, and the
/// direct successor of the four-faces-four-names one it replaces.
///
/// The widths did not change: a confidence still measures in `f32`, `f64` and — behind their cargo
/// features — `half::f16` and `rust_decimal::Decimal`. What changed is that the four no longer
/// PUBLISH four of anything. Every one of them names `ConfidenceFilter`, so the inventory below is
/// two entries however many widths a lane compiles, and a width that minted a face of its own would
/// show up here as a list that grew.
///
/// The RETURN is where the widths are still four, and that is the ruling's other half: each renders
/// under its own roster scalar, so a client reads the precision off the field and the threshold off
/// one operand.
#[test]
fn every_confidence_width_reaches_one_filter_and_its_own_roster_scalar() {
  use crate::Confidence;

  struct WidthQuery;

  #[Object]
  impl WidthQuery {
    async fn narrow(&self, filter: ConfidenceFilter) -> crate::F32 {
      let _ = GraphqlFilter::is_empty(&filter);
      <Score as crate::ToGraphqlOutput>::to_graphql_output(&Score::ONE)
    }

    async fn wide(&self, filter: ConfidenceFilter) -> crate::F64 {
      let _ = GraphqlFilter::is_empty(&filter);
      <Confidence<f64> as crate::ToGraphqlOutput>::to_graphql_output(&Confidence::ONE)
    }

    #[cfg(feature = "half")]
    async fn half(&self, filter: ConfidenceFilter) -> crate::F16 {
      let _ = GraphqlFilter::is_empty(&filter);
      <Confidence<half::f16> as crate::ToGraphqlOutput>::to_graphql_output(&Confidence::ONE)
    }

    #[cfg(feature = "rust_decimal")]
    async fn exact(&self, filter: ConfidenceFilter) -> crate::F128 {
      let _ = GraphqlFilter::is_empty(&filter);
      <Confidence<rust_decimal::Decimal> as crate::ToGraphqlOutput>::to_graphql_output(
        &Confidence::ONE,
      )
    }
  }

  let sdl = Schema::build(WidthQuery, EmptyMutation, EmptySubscription)
    .finish()
    .sdl();

  // ONE face for four widths, and it is the whole inventory. `Float` is still nowhere: no row
  // aliased onto the built-in on its way out of a named scalar.
  assert_eq!(input_names(&sdl), ["ConfidenceFilter"]);
  assert_eq!(sdl.matches("scalar Float").count(), 0);
  assert_eq!(sdl.matches("Score").count(), 0);

  // The RETURN, one roster scalar per width, each declared once. The two gated widths are the ones
  // the roster carries with no filter of their own — `f16` and `f128` — which is what a confidence
  // at those widths reaches the schema THROUGH.
  let mut returns = vec![("narrow", "f32"), ("wide", "f64")];
  if cfg!(feature = "half") {
    returns.push(("half", "f16"));
  }
  if cfg!(feature = "rust_decimal") {
    returns.push(("exact", "f128"));
  }
  for (field, scalar) in &returns {
    assert!(
      sdl.contains(&format!("{field}(filter: ConfidenceFilter!): {scalar}!")),
      "{field} returns {scalar}"
    );
    assert_eq!(
      sdl.matches(&format!("scalar {scalar}\n")).count(),
      1,
      "{scalar} is declared once"
    );
  }
}

/// The interval reaches the schema through the OPERAND now, which is the one place a client can act
/// on it — and it is one sentence rather than one per width.
///
/// An opaque scalar says nothing unless the schema does. What the retired `Score*` four said was
/// this, four times, on scalars whose other job was to name a precision; what says it here is the
/// door every threshold goes through, and the precision is said by the roster scalar the field
/// returns.
#[test]
fn the_interval_is_stated_once_at_the_wide_door() {
  struct DescribedQuery;

  #[Object]
  impl DescribedQuery {
    async fn wide(&self, filter: ConfidenceFilter) -> crate::F32 {
      let _ = GraphqlFilter::is_empty(&filter);
      <Score as crate::ToGraphqlOutput>::to_graphql_output(&Score::ONE)
    }
  }

  let sdl = Schema::build(DescribedQuery, EmptyMutation, EmptySubscription)
    .finish()
    .sdl();

  assert_eq!(sdl.matches("[0.0, 1.0]").count(), 1);
  assert!(sdl.contains("never clamped"));
}

/// **EVERY WIDTH READS ONE OPERAND AT ITS OWN PRECISION**, asserted at the LOWERING rather than at a
/// scalar, because that is where the width now enters.
///
/// This is the assertion the four retired scalars carried between them — each narrowed the wire's
/// double its own way, so a width wired to the wrong conversion would still pass a test written only
/// at `f32`. The claim survives the reshape whole; what moved is the seam it is made at.
#[test]
fn each_width_narrows_the_one_operand_its_own_way() {
  use crate::{Confidence, ConfidenceOperand, ScoreKind};

  // A tenth has no binary float that IS it, so the widths hold three different neighbours of it.
  let tenth = ConfidenceOperand::decimal("0.1").expect("0.1 is a confidence");

  assert_eq!(
    Confidence::<f32>::from_operand(&tenth)
      .expect("f32 holds it")
      .get(),
    0.1_f32
  );
  assert_eq!(
    Confidence::<f64>::from_operand(&tenth)
      .expect("f64 holds it")
      .get(),
    0.1_f64
  );
  #[cfg(feature = "half")]
  assert_eq!(
    Confidence::<half::f16>::from_operand(&tenth)
      .expect("f16 holds it")
      .get(),
    half::f16::from_f64(0.1)
  );
  #[cfg(feature = "rust_decimal")]
  assert_eq!(
    Confidence::<rust_decimal::Decimal>::from_operand(&tenth)
      .expect("a decimal holds it")
      .get(),
    rust_decimal::Decimal::from_str_exact("0.1").expect("0.1 is a decimal")
  );

  // The three NUMBER widths refuse what their constructors refuse, and the door refuses it first —
  // which is the reshape's own gain: an out-of-range threshold is one refusal at one scalar rather
  // than four refusals at four.
  for refused in [1.5, -0.1] {
    assert!(ConfidenceOperand::number(refused).is_err(), "{refused}");
  }
  for accepted in [0.0, 1.0] {
    let operand = ConfidenceOperand::number(accepted).expect("in range");
    assert!(Confidence::<f32>::from_operand(&operand).is_ok());
    assert!(Confidence::<f64>::from_operand(&operand).is_ok());
    #[cfg(feature = "half")]
    assert!(Confidence::<half::f16>::from_operand(&operand).is_ok());
  }

  // The `f64` width is the identity in both directions, so its round trip is over the value a
  // client wrote rather than over the value a narrowing left behind.
  let wide = ConfidenceOperand::number(0.1).expect("0.1 is a confidence");
  assert_eq!(
    Confidence::<f64>::from_operand(&wide)
      .expect("f64 holds its own double")
      .get(),
    0.1
  );
}

/// The decimal width's operand is TEXT and the number leg beside it reads a double, which is the
/// asymmetry the exact width exists for — carried whole from the retired `ScoreF128` golden, at the
/// seam that replaced it.
///
/// `0.1` has no double that IS it, so a client that wants what it MEANT writes the string. A string
/// is read EXACTLY: excess precision is refused rather than rounded away, which is what
/// `from_str_exact` buys over the rounding parse beside it.
#[cfg(feature = "rust_decimal")]
#[test]
fn the_decimal_width_reads_text_exactly_and_a_number_as_the_double() {
  use rust_decimal::Decimal;

  use crate::{Confidence, ConfidenceOperand, ScoreKind};

  let exact = Decimal::from_str_exact("0.1").expect("0.1 is a decimal");

  assert_eq!(
    Confidence::<Decimal>::from_operand(&ConfidenceOperand::decimal("0.1").expect("in range"))
      .expect("the text leg is exact")
      .get(),
    exact
  );
  assert_ne!(
    Confidence::<Decimal>::from_operand(&ConfidenceOperand::number(0.1).expect("in range"))
      .expect("the number leg carries the double")
      .get(),
    exact,
    "a JSON number carries the DOUBLE's own value, which is not a tenth"
  );

  // The RETURN side is text at every magnitude, which is `f128`'s own row and the reason a decimal
  // confidence publishes under it rather than under a float width.
  use async_graphql::{ScalarType, Value};

  let one = <Confidence<Decimal> as crate::ToGraphqlOutput>::to_graphql_output(&Confidence::ONE);
  assert_eq!(ScalarType::to_value(&one), Value::String("1".to_owned()));
}