dora-message 1.2.0-rc.2

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

use crate::{
    config::{ByteSize, Input, NodeRunConfig},
    id::{DataId, NodeId, OperatorId},
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::{
    collections::{BTreeMap, BTreeSet},
    fmt,
    path::PathBuf,
};

/// Wire framing requested for an output via `output_framing`.
///
/// Accepted for dora 1.x schema compatibility only: neither value changes
/// anything. Every output is encoded as Arrow IPC regardless of this
/// setting.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum OutputFraming {
    /// The default.
    #[default]
    Raw,
    /// Arrow IPC stream format.
    ArrowIpc,
}

/// Source identifier for shell-based nodes.
pub const SHELL_SOURCE: &str = "shell";
/// Set the [`Node::path`] field to this value to treat the node as a
/// [_dynamic node_](https://docs.rs/dora-node-api/latest/dora_node_api/).
pub const DYNAMIC_SOURCE: &str = "dynamic";

/// # Dataflow Specification
///
/// The main configuration structure for defining a Dora dataflow. Dataflows are
/// specified through YAML files that describe the nodes, their connections, and
/// execution parameters.
///
/// ## Structure
///
/// A dataflow consists of:
/// - **Nodes**: The computational units that process data
/// - **Deployment**: Optional deployment configuration
/// - **Debug options**: Optional development and debugging settings
///
/// ## Example
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use dora_message::descriptor::Descriptor;
/// let yaml = r#"
/// nodes:
///   - id: webcam
///     operator:
///       python: webcam.py
///       inputs:
///         tick: dora/timer/millis/100
///       outputs:
///         - image
///   - id: plot
///     operator:
///       python: plot.py
///       inputs:
///         image: webcam/image
/// "#;
/// let descriptor: Descriptor = serde_yaml::from_str(yaml)?;
/// assert_eq!(descriptor.nodes.len(), 2);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(title = "dora-rs specification")]
// Same rationale as `Node`: keeps a new *dataflow-level* key a minor release.
// This is where `exit_when_nodes_finish`, `health_check_interval`, `type_rules`
// and `strict_types` landed, so it grows at least as often as `Node` does.
// Construct with `Descriptor::new`; the fields remain `pub`.
#[non_exhaustive]
pub struct Descriptor {
    /// List of nodes in the dataflow
    ///
    /// This is the most important field of the dataflow specification.
    /// Each node must be identified by a unique `id`:
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: foo
    ///     path: path/to/the/executable
    ///     # ... (see below)
    ///   - id: bar
    ///     path: path/to/another/executable
    ///     # ... (see below)
    /// ```
    ///
    /// For each node, you need to specify the `path` of the executable or script that Dora should run when starting the node.
    /// Most of the other node fields are optional, but you typically want to specify at least some `inputs` and/or `outputs`.
    pub nodes: Vec<Node>,

    /// Deployment configuration (optional).
    pub deploy: Option<Deploy>,

    /// Debug options (optional).
    #[serde(default)]
    // An empty key is YAML `null`, which deserializes to the default.
    #[schemars(with = "Option<Debug>")]
    pub debug: Debug,

    /// How often the daemon checks node health (in seconds).
    ///
    /// Defaults to 5.0 seconds if not specified. Lower values detect hung nodes
    /// faster but add more overhead.
    #[serde(default)]
    pub health_check_interval: Option<f64>,

    /// Enable strict type checking: type warnings become errors during build.
    ///
    /// Can also be enabled via `--strict-types` CLI flag on `dora build`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strict_types: Option<bool>,

    /// Finish the dataflow once every node has, treating
    /// `dora/timer/...` inputs as a clock rather than as work.
    ///
    /// A timer input has no upstream node, so it never closes. By default
    /// a node consuming one is therefore never told its inputs are done
    /// and the graph cannot end on its own, even after every node doing
    /// real work has exited (dora-rs/dora#2920).
    ///
    /// Off by default: for a long-lived dataflow the timer is precisely
    /// what keeps it alive. Nodes with no data inputs at all (timer-only
    /// sources, or no inputs) are unaffected either way -- they have no
    /// dependency that could finish, so they are treated as sources.
    ///
    /// Set by `dora run --exit-when-nodes-finish` and `dora start
    /// --exit-when-nodes-finish`, and settable directly in YAML. It lives
    /// on the descriptor rather than on the wire so that it survives the
    /// events a dataflow outlives: auto-recovery re-spawn, coordinator
    /// restart with state reconstruction, and `dora restart`.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// exit_when_nodes_finish: true
    /// nodes:
    ///   - id: worker
    ///     path: ./worker
    ///     inputs:
    ///       tick: dora/timer/millis/100
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_when_nodes_finish: Option<bool>,

    /// Custom type compatibility rules.
    ///
    /// Each rule declares that a source type can be implicitly converted to
    /// a target type. These supplement the built-in widening rules.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// type_rules:
    ///   - from: myproject/SensorV1
    ///     to: myproject/SensorV2
    /// ```
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    // An empty key is YAML `null`, which deserializes to the default.
    #[schemars(with = "Option<Vec<TypeRuleDef>>")]
    pub type_rules: Vec<TypeRuleDef>,

    /// Global environment variables inherited by every node.
    ///
    /// Each node's own `env` map takes precedence on key conflicts, so nodes
    /// can override a global default without repeating shared values like
    /// `RUST_LOG`, `OTEL_EXPORTER_OTLP_ENDPOINT`, or `CUDA_VISIBLE_DEVICES`.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// env:
    ///   RUST_LOG: info
    ///   OTEL_EXPORTER_OTLP_ENDPOINT: http://collector:4317
    /// nodes:
    ///   - id: verbose-node
    ///     path: path/to/node
    ///     env:
    ///       RUST_LOG: debug  # overrides the global RUST_LOG for this node
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub env: Option<BTreeMap<String, EnvValue>>,
}

// Wire descriptors must remain readable by peers whose strict `Node` schema
// predates `path_fallback`. Control requests carry it separately; daemon spawn
// requests already carry it in the permissive resolved `CustomNode`.
pub(crate) fn serialize_without_path_fallback<S>(
    descriptor: &Descriptor,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    let mut descriptor = descriptor.clone();
    for node in &mut descriptor.nodes {
        node.path_fallback = None;
    }
    descriptor.serialize(serializer)
}

impl Descriptor {
    /// Fallback commands keyed by expanded node id, for the control protocol.
    pub fn path_fallbacks(&self) -> BTreeMap<NodeId, String> {
        self.nodes
            .iter()
            .filter_map(|node| {
                node.path_fallback
                    .as_ref()
                    .map(|name| (node.id.clone(), name.clone()))
            })
            .collect()
    }

    /// A dataflow of `nodes` with every dataflow-level option left at its
    /// default (the state a YAML file with only a `nodes:` key deserializes
    /// to).
    ///
    /// `Descriptor` is `#[non_exhaustive]`, so other crates cannot build one
    /// with a struct literal. Start here and assign the options you need — the
    /// fields are all still `pub`.
    pub fn new(nodes: Vec<Node>) -> Self {
        Self {
            nodes,
            deploy: None,
            debug: Default::default(),
            health_check_interval: None,
            strict_types: None,
            exit_when_nodes_finish: None,
            type_rules: Default::default(),
            env: None,
        }
    }
}

/// A type compatibility rule declared in the dataflow YAML.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
// See the note on `Node`: `type_rules:` is a dataflow-level YAML surface, so a
// per-rule option added later (a direction flag, a coercion mode) must stay a
// minor release. Construct with `TypeRuleDef::new`; the fields remain `pub`.
#[non_exhaustive]
pub struct TypeRuleDef {
    /// Source type URN
    pub from: String,
    /// Target type URN
    pub to: String,
}

impl TypeRuleDef {
    /// A rule declaring that `from` is compatible with `to`.
    ///
    /// `TypeRuleDef` is `#[non_exhaustive]`, so other crates cannot build one
    /// with a struct literal. Start here and assign any further options — the
    /// fields are all still `pub`.
    pub fn new(from: String, to: String) -> Self {
        Self { from, to }
    }
}

/// Specifies when a node should be restarted.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
// The descriptor *enums* — this one, `OutputFraming`, `DistributeStrategy`,
// `NodeSource`, `GitRepoRev`, `EnvValue`, `OperatorSource`, `PythonSourceDef`,
// the four `Ros2*` enums and `config::QueuePolicy` — are deliberately NOT
// `#[non_exhaustive]`, unlike the descriptor structs.
//
// The cost of that is real and known: adding a variant (`restart-policy:
// unless-stopped`, a third `output_framing`, an rsync `distribute` strategy) is
// `enum_variant_added` — a semver-major break — so it cannot land until 2.0.
//
// It is deliberate because the alternative is worse here. `#[non_exhaustive]`
// forces a `_ =>` arm in every downstream match. Marking all of them stops the
// build with 11 such matches in `dora-core` and the ROS2 bridge alone, before
// it even reaches the ones in `dora-daemon` and `dora-cli` — restart decisions,
// git-ref resolution, lockfile cache keys, operator-runtime dispatch, ROS2
// transport selection. Those crates ship in lockstep with this one, so today a
// new variant is a compile error naming every site that must handle it; behind
// a catch-all it becomes a silent wrong answer (a new `GitRepoRev` colliding in
// the build lockfile key, a new `RestartPolicy` reading as "never restart").
// Exhaustive matching is the thing actually preventing those bugs, and no
// external consumer gets a comparable guarantee back.
//
// The structs have no such tension: a new field breaks only struct literals,
// which the `::new` constructors already replace.
pub enum RestartPolicy {
    /// Never restart the node (default)
    #[default]
    Never,
    /// Restart the node if it exits with a non-zero exit code.
    OnFailure,
    /// Always restart the node when it exits, regardless of exit code.
    ///
    /// The node will not be restarted on the following conditions:
    ///
    /// - The node was stopped by the user (e.g., via `dora stop`).
    /// - All inputs to the node have been closed and the node finished with a non-zero exit code.
    Always,
}

/// Deployment configuration for distributing nodes across machines.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
// Same rationale as `Node`: keeps a new deployment key a minor release.
// Every field has a meaningful default, so `Deploy::default()` is the
// construction entry point rather than a bespoke `new`; the fields remain
// `pub`.
#[non_exhaustive]
pub struct Deploy {
    /// Target machine for deployment
    pub machine: Option<String>,
    /// Working directory for the deployment
    pub working_dir: Option<PathBuf>,
    /// Labels for label-based scheduling (e.g. `gpu: "true"`, `arch: arm64`).
    /// The coordinator matches these against daemon labels reported at registration.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    // An empty key is YAML `null`, which deserializes to the default.
    #[schemars(with = "Option<BTreeMap<String, String>>")]
    pub labels: BTreeMap<String, String>,
    /// How built binaries are distributed to remote daemons.
    #[serde(default)]
    pub distribute: DistributeStrategy,
}

/// Strategy for distributing built binaries to daemons.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum DistributeStrategy {
    /// Each daemon builds from source (current/default behavior).
    #[default]
    Local,
    /// Reserved for SCP distribution. Currently uses local builds.
    Scp,
    /// Reserved for HTTP distribution. Currently uses local builds.
    Http,
}

/// Debug options for dataflow development and troubleshooting.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
// See the note on `Node`: `debug:` is a dataflow-level YAML surface and a
// second debug option must stay a minor release. Every field has a meaningful
// default, so `Debug::default()` is the construction entry point; the fields
// remain `pub`.
#[non_exhaustive]
pub struct Debug {
    /// When true, daemons mirror every node output to the coordinator WebSocket
    /// so that `dora topic echo`, `dora topic hz`, and `dora topic info` can
    /// inspect runtime messages.
    #[serde(default)]
    pub enable_debug_inspection: bool,
}

/// # Dora Node Configuration
///
/// A node represents a computational unit in a Dora dataflow. Each node runs as a
/// separate process and can communicate with other nodes through inputs and outputs.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
// Adding a descriptor key must stay a *minor* release. Without this, every new
// per-node field is `constructible_struct_adds_field` — a semver-major break
// for `dora-message` — which turns routine feature work into a "land it before
// the next major or wait" scramble. `Node::new` is the construction entry point
// for other crates; the fields stay `pub`, so they are still freely readable
// and assignable. The *wire-protocol* enums in this crate (`daemon_to_node.rs`,
// `node_to_daemon.rs`, `daemon_to_coordinator.rs`, `daemon_to_daemon.rs`) were
// marked for the same reason in #3151, and `RunDataflowOptions` in the daemon
// is the existing struct-shaped precedent. The descriptor *enums* are a
// separate axis and are not covered — see the note on `RestartPolicy`.
//
// The construction advice lives here and on `Node::new`, not in the `///`
// doc: that doc is the description schemars writes into `dora-schema.json`,
// which YAML editors show to dataflow authors, and rustdoc already flags
// `#[non_exhaustive]` types on its own.
#[non_exhaustive]
pub struct Node {
    /// Unique node identifier.
    ///
    /// Node IDs may only contain ASCII letters, digits, `_`, `.` and `-`
    /// (no `/`, no whitespace), with the following further limitations:
    ///
    /// - They must not be empty or start with `.`.
    /// - They must not be the reserved id `dora`.
    ///
    /// Each node must have an ID field.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: camera_node
    ///   - id: some_other_node
    /// ```
    pub id: NodeId,

    /// Human-readable node name for documentation.
    ///
    /// This optional field can be used to define a more descriptive name in addition to a short
    /// [`id`](Self::id).
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: camera_node
    ///     name: "Camera Input Handler"
    pub name: Option<String>,

    /// Detailed description of the node's functionality.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: camera_node
    ///     description: "Captures video frames from webcam"
    /// ```
    pub description: Option<String>,

    /// Path to executable or script that should be run.
    ///
    /// Specifies the path of the executable or script that Dora should run when starting the
    /// dataflow.
    /// This can point to a normal executable (e.g. when using a compiled language such as Rust) or
    /// a Python script.
    ///
    /// Dora will automatically append a `.exe` extension on Windows systems when the specified
    /// file name has no extension.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: rust-example
    ///     path: target/release/rust-node
    ///   - id: python-example
    ///     path: ./receive_data.py
    /// ```
    ///
    /// ## URL as Path
    ///
    /// The `path` field can also point to a URL instead of a local path.
    /// In this case, Dora will download the given file when starting the dataflow.
    ///
    /// Note that this is quite an old feature and using this functionality is **not recommended**
    /// anymore. Instead, we recommend using a [`git`][Self::git] and/or [`build`](Self::build)
    /// key.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,

    /// SHA-256 checksum the `path` download must match, verified after fetch
    /// and on cache reuse (spec §8.2/§8.4). Set internally when a `hub:`
    /// reference resolves to a prebuilt binary artifact; rarely set by hand.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_sha256: Option<String>,

    /// Command-line arguments passed to the executable.
    ///
    /// The command-line arguments that should be passed to the executable/script specified in `path`.
    /// The arguments should be separated by space.
    /// This field is optional and defaults to an empty argument list.
    ///
    /// ## Example
    /// ```yaml
    /// nodes:
    ///   - id: example
    ///     path: example-node
    ///     args: -v --some-flag foo
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub args: Option<String>,

    /// Environment variables for node builds and execution.
    ///
    /// Key-value map of environment variables that should be set for both the
    /// [`build`](Self::build) operation and the node execution (i.e. when the node is spawned
    /// through [`path`](Self::path)).
    ///
    /// Supports strings, numbers, and booleans.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: example-node
    ///     path: path/to/node
    ///     env:
    ///       DEBUG: true
    ///       PORT: 8080
    ///       API_KEY: "secret-key"
    /// ```
    pub env: Option<BTreeMap<String, EnvValue>>,

    /// Multiple operators running in a shared runtime process.
    ///
    /// Operators are an experimental, lightweight alternative to nodes.
    /// Instead of running as a separate process, operators are linked into a runtime process.
    /// This allows running multiple operators to share a single address space (not supported for
    /// Python currently).
    ///
    /// Operators are defined as part of the node list, as children of a runtime node.
    /// A runtime node is a special node that specifies no [`path`](Self::path) field, but contains
    /// an `operators` field instead.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: runtime-node
    ///     operators:
    ///       - id: processor
    ///         python: process.py
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operators: Option<RuntimeNode>,

    /// Single operator configuration.
    ///
    /// This is a convenience field for defining runtime nodes that contain only a single operator.
    /// This field is an alternative to the [`operators`](Self::operators) field, which can be used
    /// if there is only a single operator defined for the runtime node.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: runtime-node
    ///     operator:
    ///       id: processor
    ///       python: script.py
    ///       outputs: [data]
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operator: Option<SingleOperatorDefinition>,

    /// ROS2 bridge configuration (unstable).
    ///
    /// Declares this node as a ROS2 bridge that automatically subscribes to or
    /// publishes on ROS2 topics. No custom code is needed -- the framework spawns
    /// a bridge binary that converts between ROS2 DDS messages and Dora's Arrow
    /// format.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: camera_bridge
    ///     ros2:
    ///       topic: /camera/image_raw
    ///       message_type: sensor_msgs/Image
    ///       direction: subscribe
    ///     outputs:
    ///       - image
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ros2: Option<Ros2BridgeConfig>,

    /// Output data identifiers produced by this node.
    ///
    /// List of output identifiers that the node sends.
    /// Must contain all `output_id` values that the node uses when sending output, e.g. through the
    /// [`send_output`](https://docs.rs/dora-node-api/latest/dora_node_api/struct.DoraNode.html#method.send_output)
    /// function.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: example-node
    ///     outputs:
    ///       - processed_image
    ///       - metadata
    /// ```
    #[serde(default)]
    // An empty `outputs:` is YAML `null`, which deserializes to an empty set.
    #[schemars(with = "Option<BTreeSet<DataId>>")]
    pub outputs: BTreeSet<DataId>,

    /// Optional type annotations for outputs.
    ///
    /// Maps output identifiers to type URNs (e.g. `std/media/v1/Image`).
    /// Only annotated outputs are type-checked; unannotated outputs remain dynamic.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    // An empty key is YAML `null`, which deserializes to the default.
    #[schemars(with = "Option<BTreeMap<DataId, String>>")]
    pub output_types: BTreeMap<DataId, String>,

    /// Per-output framing overrides. Accepted for 1.x schema compatibility
    /// but ignored: every output is encoded as Arrow IPC whatever its entry
    /// here says (see [`OutputFraming`]).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    // An empty key is YAML `null`, which deserializes to the default.
    #[schemars(with = "Option<BTreeMap<DataId, OutputFraming>>")]
    pub output_framing: BTreeMap<DataId, OutputFraming>,

    /// Input data connections from other nodes.
    ///
    /// Defines the inputs that this node is subscribing to.
    ///
    /// The `inputs` field should be a key-value map of the following format:
    ///
    /// `input_id: source_node_id/source_node_output_id`
    ///
    /// The components are defined as follows:
    ///
    ///   - `input_id` is the local identifier that should be used for this input.
    ///
    ///     This will map to the `id` field of
    ///     [`Event::Input`](https://docs.rs/dora-node-api/latest/dora_node_api/enum.Event.html#variant.Input)
    ///     events sent to the node event loop.
    ///   - `source_node_id` should be the `id` field of the node that sends the output that we want
    ///     to subscribe to
    ///   - `source_node_output_id` should be the identifier of the output that that we want
    ///     to subscribe to
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: example-node
    ///     outputs:
    ///       - one
    ///       - two
    ///   - id: receiver
    ///     inputs:
    ///         my_input: example-node/two
    /// ```
    #[serde(default)]
    // Like `outputs`: an empty `inputs:` is `null`, which deserializes to an empty map.
    #[schemars(with = "Option<BTreeMap<DataId, Input>>")]
    pub inputs: BTreeMap<DataId, Input>,

    /// Optional type annotations for inputs.
    ///
    /// Maps input identifiers to expected type URNs. Used by `dora validate`
    /// to check that upstream output types match expectations.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    // An empty key is YAML `null`, which deserializes to the default.
    #[schemars(with = "Option<BTreeMap<DataId, String>>")]
    pub input_types: BTreeMap<DataId, String>,

    /// Required metadata keys per output.
    ///
    /// Maps output identifiers to lists of required metadata key names.
    /// These are checked at build/validate time.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// output_metadata:
    ///   response: [request_id]
    /// ```
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    // An empty key is YAML `null`, which deserializes to the default.
    #[schemars(with = "Option<BTreeMap<DataId, Vec<String>>>")]
    pub output_metadata: BTreeMap<DataId, Vec<String>>,

    /// Communication pattern shorthand (e.g. `service-server`).
    ///
    /// Automatically implies required metadata keys on all outputs.
    /// See `pattern_metadata_keys()` for supported patterns.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,

    /// Redirect stdout/stderr to a data output.
    ///
    /// This field can be used to send all stdout and stderr output of the node as a Dora output.
    /// Each output line is sent as a separate message.
    ///
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: example
    ///     send_stdout_as: stdout_output
    ///   - id: logger
    ///     inputs:
    ///         example_output: example/stdout_output
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_stdout_as: Option<String>,

    /// Redirect structured log entries to a data output as JSON strings.
    ///
    /// Unlike `send_stdout_as` which sends raw stdout lines, this sends only
    /// parsed structured log entries (with level, timestamp, message, fields).
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: sensor
    ///     path: ./sensor
    ///     send_logs_as: logs
    ///     outputs:
    ///       - data
    ///       - logs
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_logs_as: Option<String>,

    /// Minimum log level for this node (error, warn, info, debug, trace, stdout).
    ///
    /// Logs below this level are suppressed from file output, coordinator
    /// forwarding, and `send_logs_as` routing.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: noisy_sensor
    ///     path: ./sensor
    ///     min_log_level: info
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_log_level: Option<String>,

    /// Maximum log file size before rotation (e.g. "50MB", "1GB").
    ///
    /// When the JSONL log file exceeds this size, it is rotated. Old files
    /// are renamed with numeric suffixes (`.1.jsonl`, `.2.jsonl`, etc.) and
    /// the oldest are deleted once 5 rotated files exist.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: sensor
    ///     path: ./sensor
    ///     max_log_size: "100MB"
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_log_size: Option<String>,
    /// Maximum number of rotated log files to keep (default: 5, range: 0-100)
    ///
    /// `0` keeps the active log only, rotating the previous one away.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(range(max = 100))]
    pub max_rotated_files: Option<u32>,

    /// Build commands executed during `dora build`. Each line runs separately.
    ///
    /// The `build` key specifies the command that should be invoked for building the node.
    /// The key expects a single- or multi-line string.
    ///
    /// Each line is run as a separate command.
    /// Spaces are used to separate arguments.
    ///
    /// Note that all the environment variables specified in the [`env`](Self::env) field are also
    /// applied to the build commands.
    ///
    /// ## Special treatment of `pip`
    ///
    /// Build lines that start with `pip` or `pip3` are treated in a special way:
    /// If the `--uv` argument is passed to the `dora build` command, all `pip`/`pip3` commands are
    /// run through the [`uv` package manager](https://docs.astral.sh/uv/).
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    /// - id: build-example
    ///   build: cargo build -p receive_data --release
    ///   path: target/release/receive_data
    /// - id: multi-line-example
    ///   build: |
    ///       pip install requirements.txt
    ///       pip install -e some/local/package
    ///   path: package
    /// ```
    ///
    /// In the above example, the `pip` commands will be replaced by `uv pip` when run through
    /// `dora build --uv`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build: Option<String>,

    /// Git repository URL for downloading nodes.
    ///
    /// The `git` key allows downloading nodes (i.e. their source code) from git repositories.
    /// This can be especially useful for distributed dataflows.
    ///
    /// When a `git` key is specified, `dora build` automatically clones the specified repository
    /// (or reuse an existing clone).
    /// Then it checks out the specified [`branch`](Self::branch), [`tag`](Self::tag), or
    /// [`rev`](Self::rev), or the default branch if none of them are specified.
    /// Afterwards it runs the [`build`](Self::build) command if specified.
    ///
    /// Note that the git clone directory is set as working directory for both the
    /// [`build`](Self::build) command and the specified [`path`](Self::path).
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: rust-node
    ///     git: https://github.com/dora-rs/dora.git
    ///     build: cargo build -p rust-dataflow-example-node
    ///     path: target/debug/rust-dataflow-example-node
    /// ```
    ///
    /// In the above example, `dora build` will first clone the specified `git` repository and then
    /// run the specified `build` inside the local clone directory.
    /// When `dora run` or `dora start` is invoked, the working directory will be the git clone
    /// directory too. So a relative `path` will start from the clone directory.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub git: Option<String>,

    /// Hub package reference.
    ///
    /// **Outside the 1.0 stability guarantee.** This field, the way it is
    /// resolved, and the `HubProvenance` recorded in the lockfile may change
    /// or be removed in a minor release. `dora build` and `dora validate`
    /// print a warning whenever a dataflow uses it.
    ///
    /// The reason is readiness rather than scope: stabilizing `hub:` would
    /// promise a typed-contract guarantee that no package in the catalog
    /// currently delivers. The path to stabilization is the node-typing
    /// workstream, not more code here — see `docs/plan-node-hub.md` §14 (P3.5).
    ///
    /// References a node published in the Dora Hub index:
    /// `[<namespace>/]<name>@<semver-requirement>`. A bare name is shorthand
    /// for the official `dora-rs/` namespace.
    ///
    /// `dora build` resolves the reference against the index to a pinned
    /// commit and the node is fetched/built through the same machinery as a
    /// [`git`](Self::git) node; the package manifest supplies the
    /// entrypoint, build command, and typed contracts. Mutually exclusive
    /// with `path`, `git`, and `build`.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: detector
    ///     hub: dora-yolo@^0.5
    ///     inputs:
    ///       image: camera/image
    ///     outputs:
    ///       - bbox
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hub: Option<String>,

    /// Git branch to checkout after cloning.
    ///
    /// The `branch` field is only allowed in combination with the [`git`](#git) field.
    /// It specifies the branch that should be checked out after cloning.
    /// Only one of `branch`, `tag`, or `rev` can be specified.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: rust-node
    ///     git: https://github.com/dora-rs/dora.git
    ///     branch: some-branch-name
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,

    /// Git tag to checkout after cloning.
    ///
    /// The `tag` field is only allowed in combination with the [`git`](#git) field.
    /// It specifies the git tag that should be checked out after cloning.
    /// Only one of `branch`, `tag`, or `rev` can be specified.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: rust-node
    ///     git: https://github.com/dora-rs/dora.git
    ///     tag: v0.1.0
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tag: Option<String>,

    /// Git revision (e.g. commit hash) to checkout after cloning.
    ///
    /// The `rev` field is only allowed in combination with the [`git`](#git) field.
    /// It specifies the git revision (e.g. a commit hash) that should be checked out after cloning.
    /// Only one of `branch`, `tag`, or `rev` can be specified.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: rust-node
    ///     git: https://github.com/dora-rs/dora.git
    ///     rev: 64ab0d7c
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rev: Option<String>,

    /// Whether this node should be restarted on exit or error.
    ///
    /// Defaults to `RestartPolicy::Never`.
    #[serde(default)]
    pub restart_policy: RestartPolicy,

    /// Size of the zenoh shared memory pool for zero-copy output publishing.
    ///
    /// Accepts an integer (raw bytes) or a string with a unit suffix
    /// (`KB`, `MB`, `GB`, case-insensitive). If unset, the
    /// `DORA_NODE_SHM_POOL_SIZE` env var is used, falling back to a
    /// built-in default.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: camera-node
    ///     shared_memory_pool_size: 128MB
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shared_memory_pool_size: Option<ByteSize>,

    /// Maximum number of restart attempts. 0 means unlimited.
    ///
    /// When combined with `restart_window`, this limits restarts within the window period.
    /// For example, `max_restarts: 5` with `restart_window: 300` means "5 restarts per 5 minutes".
    #[serde(default)]
    pub max_restarts: u32,

    /// Initial delay in seconds before restarting. Doubles each attempt (exponential backoff).
    ///
    /// For example, with `restart_delay: 1.0`, delays will be 1s, 2s, 4s, 8s, ...
    /// Use `max_restart_delay` to cap the backoff.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub restart_delay: Option<f64>,

    /// Maximum delay in seconds for exponential backoff.
    ///
    /// Caps the exponentially growing `restart_delay`. For example, with
    /// `restart_delay: 1.0` and `max_restart_delay: 30.0`, delays grow as
    /// 1s, 2s, 4s, 8s, 16s, 30s, 30s, ...
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_restart_delay: Option<f64>,

    /// Time window in seconds for counting restarts.
    ///
    /// When set, the restart counter resets after this period of time elapses since the
    /// first restart in the current window. This enables "N restarts within M seconds" semantics.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub restart_window: Option<f64>,

    /// Health check timeout in seconds.
    ///
    /// When set, the daemon monitors this node for activity **once it has
    /// connected** (i.e. subscribed to events during `Node::init`). If the
    /// connected node then does not communicate with the daemon within this
    /// timeout, it is killed and the restart policy is evaluated.
    ///
    /// This bounds post-connection liveness only, not startup time: a node
    /// still in a slow cold start has not connected yet and is never killed by
    /// this watchdog. A node that hangs before it ever subscribes is therefore
    /// not reaped here either.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub health_check_timeout: Option<f64>,

    /// Per-node finish-drain grace period in seconds.
    ///
    /// Overrides the global `DORA_FINISH_DRAIN_GRACE_SECS` for this node only.
    /// When all other nodes in a dataflow have finished, the daemon waits this
    /// long after the node's last input closes before force-stopping it.
    ///
    /// Set to a large value (e.g. `3600.0`) for nodes that need significant
    /// post-input compute time (ML training, large-batch inference, checkpoint
    /// writes) to prevent premature SIGKILL while the computation is in progress.
    ///
    /// When unset, the global grace period applies (default 120s, controlled
    /// by `DORA_FINISH_DRAIN_GRACE_SECS`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub finish_grace_secs: Option<f64>,

    /// Path to a module definition file (e.g. `nav_module.yml`).
    ///
    /// A module is a reusable sub-dataflow: a group of nodes with declared
    /// inputs and outputs. At build time the module is expanded inline —
    /// internal node IDs are prefixed with `{module_id}.` and all wiring is
    /// rewritten so the runtime sees only flat nodes.
    ///
    /// A module node has no source or per-node runtime configuration of its own,
    /// so only `module`, `inputs`, `params`, `env`, `build`, and `deploy` are
    /// meaningful on it. Every other node field is rejected at expansion time
    /// rather than silently discarded -- both the source/kind fields (`path`,
    /// `args`, `path_sha256`, `git`, `hub`, `branch`, `tag`, `rev`, `operators`,
    /// `operator`, `ros2`) and per-node runtime fields (`outputs`,
    /// `output_types`, `cpu_affinity`, `restart_policy`, ...). The same rule
    /// applies at every nesting level.
    ///
    /// `env`, `build`, `deploy`, and `params` *are* accepted: they propagate
    /// into the module's inner nodes.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: nav_stack
    ///     module: modules/navigation_module.yml
    ///     inputs:
    ///       goal_pose: localization/goal
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub module: Option<String>,

    /// Parameters passed to a module for compile-time substitution.
    ///
    /// Only meaningful when `module` is set. Values are substituted into
    /// inner node `args` fields (using `${_param.name}` syntax) and can be
    /// injected into inner node `env` maps.
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: nav_stack
    ///     module: modules/navigation_module.yml
    ///     params:
    ///       speed: "2.0"
    ///       mode: turbo
    /// ```
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    // An empty key is YAML `null`, which deserializes to the default.
    #[schemars(with = "Option<BTreeMap<String, String>>")]
    pub params: BTreeMap<String, String>,

    /// CPU cores to pin this node's process to (Linux only, ignored on other platforms).
    ///
    /// ## Example
    ///
    /// ```yaml
    /// nodes:
    ///   - id: fast_node
    ///     path: ./fast_node
    ///     cpu_affinity: [0, 1]
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cpu_affinity: Option<Vec<usize>>,

    /// Machine deployment configuration.
    pub deploy: Option<Deploy>,

    /// Startup connection deadline in seconds.
    ///
    /// If the node process fails to connect (subscribe to events) within this
    /// many seconds after process spawn, the daemon kills the process and
    /// evaluates the `restart_policy`.
    ///
    /// Evaluated on each `health_check_interval` tick (default 5s).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub startup_timeout: Option<f64>,

    /// What to run when nothing exists at `path`, looked up like a top-level
    /// `path` (working directory, uv environment, then `$PATH`; variables
    /// are not expanded). Internal: module expansion sets it when a module
    /// node's `path` is a single name without an extension, such as
    /// `dora-echo`: `path` points next to the module file, and this keeps
    /// the name as written. One written in a dataflow, module or node file is
    /// rejected, so it is not part of the YAML schema.
    // Appended last so existing fields keep their wire-format order.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(skip)]
    #[doc(hidden)]
    pub path_fallback: Option<String>,
}

impl Node {
    /// A node with the given ID and every other field left at its descriptor
    /// default (the state a YAML node with only an `id:` key deserializes to).
    ///
    /// `Node` is `#[non_exhaustive]`, so other crates cannot build one with a
    /// struct literal. Start here and assign the fields you need — they are all
    /// still `pub`:
    ///
    /// ```
    /// use dora_message::descriptor::Node;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut node = Node::new("camera".parse()?);
    /// node.path = Some("./camera".to_owned());
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(id: NodeId) -> Self {
        Self {
            id,
            name: None,
            description: None,
            path: None,
            path_sha256: None,
            args: None,
            env: None,
            operators: None,
            operator: None,
            ros2: None,
            outputs: Default::default(),
            output_types: Default::default(),
            output_framing: Default::default(),
            inputs: Default::default(),
            input_types: Default::default(),
            shared_memory_pool_size: None,
            output_metadata: Default::default(),
            pattern: None,
            send_stdout_as: None,
            send_logs_as: None,
            min_log_level: None,
            max_log_size: None,
            max_rotated_files: None,
            build: None,
            git: None,
            hub: None,
            branch: None,
            tag: None,
            rev: None,
            restart_policy: Default::default(),
            max_restarts: 0,
            restart_delay: None,
            max_restart_delay: None,
            restart_window: None,
            health_check_timeout: None,
            finish_grace_secs: None,
            module: None,
            params: Default::default(),
            cpu_affinity: None,
            deploy: None,
            startup_timeout: None,
            path_fallback: None,
        }
    }
}

/// A [`Node`] after alias resolution and defaulting, as the daemon runs it.
#[allow(missing_docs)]
#[derive(Debug, Clone, Serialize, Deserialize)]
// Same rationale as `Node`: keeps a new per-node key a minor release. This is
// where keys that are not custom-node-specific land — `cpu_affinity` and
// `deploy` are threaded `Node` -> `ResolvedNode` without passing through
// `CustomNode`. Construct with `ResolvedNode::new`; the fields remain `pub`.
// Resolution itself goes through `ResolvedNode::from_node`, the in-crate
// literal that keeps a new field a compile error.
#[non_exhaustive]
pub struct ResolvedNode {
    pub id: NodeId,
    pub name: Option<String>,
    pub description: Option<String>,
    pub env: Option<BTreeMap<String, EnvValue>>,

    #[serde(default)]
    pub cpu_affinity: Option<Vec<usize>>,

    #[serde(default)]
    pub deploy: Option<Deploy>,

    #[serde(flatten)]
    pub kind: CoreNodeKind,
}

#[allow(missing_docs)]
impl ResolvedNode {
    /// A resolved node with the given ID and kind, and every other field left
    /// at its default.
    ///
    /// `ResolvedNode` is `#[non_exhaustive]`, so other crates cannot build one
    /// with a struct literal. Start here and assign the fields you need — they
    /// are all still `pub`.
    pub fn new(id: NodeId, kind: CoreNodeKind) -> Self {
        Self {
            id,
            name: None,
            description: None,
            env: None,
            cpu_affinity: None,
            deploy: None,
            kind,
        }
    }

    /// The resolved node for `node`'s node-level keys — `id`, `name`,
    /// `description`, `env`, `cpu_affinity`, `deploy` — around an already
    /// resolved `kind`. `env` is carried as declared; merging the
    /// dataflow-level `env` into it is the caller's job.
    ///
    /// The kind-level keys are dropped: for a custom node
    /// [`CustomNode::from_node`] has already moved them out, and a runtime
    /// node's live in its `operators`.
    ///
    /// This is a struct literal on purpose. `ResolvedNode` is
    /// `#[non_exhaustive]`, so a literal only compiles here, inside the
    /// defining crate — exactly where the compiler still insists that every
    /// field is accounted for. A field added to `ResolvedNode` is a build
    /// error on this line, not a key that resolution silently leaves at its
    /// default.
    pub fn from_node(node: Node, kind: CoreNodeKind) -> Self {
        Self {
            id: node.id,
            name: node.name,
            description: node.description,
            env: node.env,
            cpu_affinity: node.cpu_affinity,
            deploy: node.deploy,
            kind,
        }
    }

    pub fn has_git_source(&self) -> bool {
        self.kind
            .as_custom()
            .map(|n| n.source.is_git())
            .unwrap_or_default()
    }
}

#[allow(missing_docs)]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[allow(clippy::large_enum_variant)]
pub enum CoreNodeKind {
    /// Dora runtime node
    #[serde(rename = "operators")]
    Runtime(RuntimeNode),
    Custom(CustomNode),
}

#[allow(missing_docs)]
impl CoreNodeKind {
    pub fn as_custom(&self) -> Option<&CustomNode> {
        match self {
            CoreNodeKind::Runtime(_) => None,
            CoreNodeKind::Custom(custom_node) => Some(custom_node),
        }
    }
}

#[allow(missing_docs)]
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(transparent)]
pub struct RuntimeNode {
    /// List of operators running in this runtime
    pub operators: Vec<OperatorDefinition>,
}

#[allow(missing_docs)]
#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone)]
pub struct OperatorDefinition {
    /// Unique operator identifier within the runtime
    pub id: OperatorId,
    #[serde(flatten)]
    pub config: OperatorConfig,
}

#[allow(missing_docs)]
#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone)]
// Same rationale as `Node`: keeps a new operator-level descriptor key a minor
// release. No constructor yet because nothing constructs one outside this crate
// — every instance comes from deserialization. Adding a constructor later is
// itself a minor change, so only the `#[non_exhaustive]` half is time-critical;
// open an issue if you need to build one programmatically.
#[non_exhaustive]
pub struct SingleOperatorDefinition {
    /// Operator identifier (optional for single operators)
    pub id: Option<OperatorId>,
    #[serde(flatten)]
    pub config: OperatorConfig,
}

#[allow(missing_docs)]
#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone)]
// Same rationale as `Node`: keeps a new operator-level descriptor key a minor
// release. No constructor yet because nothing constructs one outside this crate
// — every instance comes from deserialization. Adding a constructor later is
// itself a minor change, so only the `#[non_exhaustive]` half is time-critical;
// open an issue if you need to build one programmatically.
//
// Kept as a `//` comment deliberately: a `///` doc here is `#[serde(flatten)]`ed
// by schemars onto `OperatorDefinition`'s entry in `dora-schema.json`, which
// YAML editors show to dataflow authors.
#[non_exhaustive]
pub struct OperatorConfig {
    /// Human-readable operator name
    pub name: Option<String>,
    /// Detailed description of the operator
    pub description: Option<String>,

    /// Input data connections
    // Unlike on `Node`, an empty key here is rejected: `OperatorConfig` is
    // `#[serde(flatten)]`ed, and flattened fields don't turn `null` into an
    // empty collection. So the schema keeps requiring an object/array.
    #[serde(default)]
    pub inputs: BTreeMap<DataId, Input>,
    /// Output data identifiers
    #[serde(default)]
    pub outputs: BTreeSet<DataId>,
    /// Optional type annotations for outputs
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub output_types: BTreeMap<DataId, String>,

    /// Per-output framing overrides. Ignored: every output is encoded as
    /// Arrow IPC (see [`OutputFraming`]).
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub output_framing: BTreeMap<DataId, OutputFraming>,

    /// Optional type annotations for inputs
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub input_types: BTreeMap<DataId, String>,

    /// Required metadata keys per output
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub output_metadata: BTreeMap<DataId, Vec<String>>,

    /// Communication pattern shorthand (e.g. `service-server`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,

    /// Operator source configuration (Python, shared library, etc.)
    #[serde(flatten)]
    pub source: OperatorSource,

    /// Build commands for this operator
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build: Option<String>,
    /// Redirect stdout to data output
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_stdout_as: Option<String>,
    /// Redirect structured log entries to a data output as JSON strings
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_logs_as: Option<String>,
    /// Minimum log level for this operator
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_log_level: Option<String>,
    /// Maximum log file size before rotation (e.g. "50MB", "1GB")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_log_size: Option<String>,
    /// Maximum number of rotated log files to keep (default: 5, range: 0-100)
    ///
    /// `0` keeps the active log only, rotating the previous one away.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(range(max = 100))]
    pub max_rotated_files: Option<u32>,
}

#[allow(missing_docs)]
#[derive(Debug, Serialize, Deserialize, JsonSchema, Clone)]
#[serde(rename_all = "kebab-case")]
pub enum OperatorSource {
    SharedLibrary(String),
    Python(PythonSource),
    #[schemars(skip)]
    Wasm(String),
}
#[allow(missing_docs)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(from = "PythonSourceDef", into = "PythonSourceDef")]
pub struct PythonSource {
    pub source: String,
    pub conda_env: Option<String>,
}

#[allow(missing_docs)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum PythonSourceDef {
    SourceOnly(String),
    WithOptions {
        source: String,
        conda_env: Option<String>,
    },
}

impl From<PythonSource> for PythonSourceDef {
    fn from(input: PythonSource) -> Self {
        match input {
            PythonSource {
                source,
                conda_env: None,
            } => Self::SourceOnly(source),
            PythonSource { source, conda_env } => Self::WithOptions { source, conda_env },
        }
    }
}

impl From<PythonSourceDef> for PythonSource {
    fn from(value: PythonSourceDef) -> Self {
        match value {
            PythonSourceDef::SourceOnly(source) => Self {
                source,
                conda_env: None,
            },
            PythonSourceDef::WithOptions { source, conda_env } => Self { source, conda_env },
        }
    }
}

/// Built-in runtime name for shared-library operators.
pub const RUNTIME_SHARED_LIBRARY: &str = "shared-library";
/// Built-in runtime name for Python operators.
pub const RUNTIME_PYTHON: &str = "python";
/// Built-in runtime name for WebAssembly operators.
pub const RUNTIME_WASM: &str = "wasm";

impl OperatorSource {
    /// The name of the runtime that hosts operators declared with this source.
    ///
    /// This mapping is the single source of truth for "which runtime hosts this
    /// operator": the daemon's spawn logic and the CLI's build hashing key on
    /// the name rather than matching each variant.
    pub fn runtime_name(&self) -> &'static str {
        match self {
            OperatorSource::SharedLibrary(_) => RUNTIME_SHARED_LIBRARY,
            OperatorSource::Python(_) => RUNTIME_PYTHON,
            OperatorSource::Wasm(_) => RUNTIME_WASM,
        }
    }
}

#[allow(missing_docs)]
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
// See the note on `Node`: keeps a new resolved-node field a minor release.
// Construct with `CustomNode::new`; the fields remain `pub`. Resolution goes
// through `CustomNode::from_node`, the in-crate literal that keeps a new field
// a compile error rather than a silently dropped descriptor key.
#[non_exhaustive]
pub struct CustomNode {
    /// Path of the source code
    ///
    /// If you want to use a specific `conda` environment.
    /// Provide the python path within the source.
    ///
    /// source: /home/peter/miniconda3/bin/python
    ///
    /// args: some_node.py
    ///
    /// Source can match any executable in PATH.
    pub path: String,
    pub source: NodeSource,
    /// SHA-256 the `path` download must match (set for hub binary artifacts,
    /// spec §8.2). When present the daemon fetches `path` as a verified URL
    /// download regardless of confinement — the checksum is the trust anchor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_sha256: Option<String>,
    /// Args for the executable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub args: Option<String>,
    /// Environment variables injected during resolution.
    ///
    /// Not user-writable: [`Node::env`] is the YAML surface. Resolution folds
    /// it into this field, and the ROS2 bridge desugaring uses it to pass
    /// `DORA_ROS2_BRIDGE_CONFIG` to the spawned bridge binary.
    pub envs: Option<BTreeMap<String, EnvValue>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build: Option<String>,
    /// Send stdout and stderr to another node
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_stdout_as: Option<String>,
    /// Redirect structured log entries to a data output as JSON strings
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_logs_as: Option<String>,
    /// Minimum log level for this node
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_log_level: Option<String>,
    /// Maximum log file size before rotation (e.g. "50MB", "1GB")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_log_size: Option<String>,
    /// Maximum number of rotated log files to keep (default: 5, range: 0-100)
    ///
    /// `0` keeps the active log only, rotating the previous one away.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(range(max = 100))]
    pub max_rotated_files: Option<u32>,

    #[serde(default)]
    pub restart_policy: RestartPolicy,

    /// Maximum number of restart attempts. 0 means unlimited.
    #[serde(default)]
    pub max_restarts: u32,

    /// Initial delay in seconds before restarting (exponential backoff).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub restart_delay: Option<f64>,

    /// Maximum delay in seconds for exponential backoff.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_restart_delay: Option<f64>,

    /// Time window in seconds for counting restarts.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub restart_window: Option<f64>,

    /// Health check timeout in seconds.
    ///
    /// When set, the daemon monitors this node for activity **once it has
    /// connected** (i.e. subscribed to events during `Node::init`). If the
    /// connected node then does not communicate with the daemon within this
    /// timeout, it is killed and the restart policy is evaluated.
    ///
    /// This bounds post-connection liveness only, not startup time: a node
    /// still in a slow cold start has not connected yet and is never killed by
    /// this watchdog. A node that hangs before it ever subscribes is therefore
    /// not reaped here either.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub health_check_timeout: Option<f64>,

    /// Per-node finish-drain grace period in seconds.
    ///
    /// Overrides the global `DORA_FINISH_DRAIN_GRACE_SECS` for this node only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub finish_grace_secs: Option<f64>,

    #[serde(flatten)]
    pub run_config: NodeRunConfig,

    /// Startup connection deadline in seconds.
    ///
    /// If the node process fails to connect (subscribe to events) within this
    /// many seconds after process spawn, the daemon kills the process and
    /// evaluates the `restart_policy`.
    ///
    /// Evaluated on each `health_check_interval` tick (default 5s).
    // Appended last so existing fields keep their wire-format order.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub startup_timeout: Option<f64>,
    /// What to run when nothing exists at `path`, resolved like a top-level
    /// `path` (the name a module node's `path:` was written as).
    // Appended last so existing fields keep their wire-format order.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_fallback: Option<String>,
}

impl CustomNode {
    /// A local-source node at `path` with every other field left at its
    /// default.
    ///
    /// `CustomNode` is `#[non_exhaustive]`, so other crates cannot build one
    /// with a struct literal. Start here and assign the fields you need — they
    /// are all still `pub`.
    pub fn new(path: String) -> Self {
        Self {
            path,
            source: NodeSource::Local,
            path_sha256: None,
            args: None,
            envs: None,
            build: None,
            send_stdout_as: None,
            send_logs_as: None,
            min_log_level: None,
            max_log_size: None,
            max_rotated_files: None,
            restart_policy: Default::default(),
            max_restarts: 0,
            restart_delay: None,
            max_restart_delay: None,
            restart_window: None,
            health_check_timeout: None,
            finish_grace_secs: None,
            run_config: NodeRunConfig::default(),
            startup_timeout: None,
            path_fallback: None,
        }
    }

    /// Move the custom-node keys out of `node` into a `CustomNode` at `path`.
    ///
    /// Every key that all custom-node kinds resolve identically is taken from
    /// `node`, leaving its `Option`s empty and its collections cleared. What
    /// stays behind are the node-level keys — `id`, `name`, `description`,
    /// `env`, `cpu_affinity`, `deploy` — for [`ResolvedNode::from_node`] to
    /// consume next, plus the kind-selection keys (`git`, `hub`, `operators`,
    /// `ros2`, …) that classification has already read.
    ///
    /// `source` and `envs` stay at their defaults: they are the two keys whose
    /// value depends on the node kind, so the caller sets them — `source` from
    /// classification for a `path:` node, `envs` for the ROS2 bridge, whose
    /// `path` is its fixed binary.
    ///
    /// This is a struct literal on purpose. `CustomNode` and `NodeRunConfig`
    /// are `#[non_exhaustive]`, so a literal only compiles here, inside the
    /// defining crate — exactly where the compiler still insists that every
    /// field is accounted for. A key added to either struct is a build error
    /// on this line, not a descriptor key that parses and is then silently
    /// dropped. `dora-core`'s `every_custom_node_field_is_carried_through`
    /// checks the values on top.
    pub fn from_node(node: &mut Node, path: String) -> Self {
        Self {
            path,
            source: NodeSource::Local,
            path_sha256: node.path_sha256.take(),
            args: node.args.take(),
            envs: None,
            build: node.build.take(),
            send_stdout_as: node.send_stdout_as.take(),
            send_logs_as: node.send_logs_as.take(),
            min_log_level: node.min_log_level.take(),
            max_log_size: node.max_log_size.take(),
            max_rotated_files: node.max_rotated_files.take(),
            restart_policy: node.restart_policy,
            max_restarts: node.max_restarts,
            restart_delay: node.restart_delay.take(),
            max_restart_delay: node.max_restart_delay.take(),
            restart_window: node.restart_window.take(),
            health_check_timeout: node.health_check_timeout.take(),
            finish_grace_secs: node.finish_grace_secs.take(),
            run_config: NodeRunConfig {
                inputs: std::mem::take(&mut node.inputs),
                outputs: std::mem::take(&mut node.outputs),
                output_types: std::mem::take(&mut node.output_types),
                output_framing: std::mem::take(&mut node.output_framing),
                input_types: std::mem::take(&mut node.input_types),
                shared_memory_pool_size: node.shared_memory_pool_size.take(),
            },
            startup_timeout: node.startup_timeout.take(),
            path_fallback: node.path_fallback.take(),
        }
    }
}

#[allow(missing_docs)]
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub enum NodeSource {
    Local,
    GitBranch {
        repo: String,
        rev: Option<GitRepoRev>,
    },
}

#[allow(missing_docs)]
impl NodeSource {
    pub fn is_git(&self) -> bool {
        matches!(self, Self::GitBranch { .. })
    }
}

#[allow(missing_docs)]
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub enum GitRepoRev {
    Branch(String),
    Tag(String),
    Rev(String),
}

// The value of an `env:` entry. (A plain comment, not a doc comment:
// schemars would publish a doc comment as the `EnvValue` description in
// `dora-schema.json`.)
//
// A native YAML/JSON bool or number keeps its type, except an integer
// in `i64::MAX + 1 ..= u64::MAX`, which keeps its exact digits as a string.
// An integer outside `i64::MIN ..= u64::MAX` is a parse error in YAML, but
// serde_json hands it over as an `f64`, so a JSON descriptor still rounds it
// (the CLI -> coordinator -> daemon hops are unaffected: by then such a value
// is already a string). Quote it to keep it exact. A string has its
// `$VAR` / `${VAR}` references expanded and is then typed as a bool or
// number only when that is lossless, i.e. when the typed value prints
// back as exactly the same text. `"8080"` and `${PORT}` (= 8080) still
// become `Integer(8080)`, as in every 1.x release, but `"1.10"`, `"007"`
// and `"1e3"` stay strings instead of reaching the node as `1.1`, `7` and
// `1000`.
//
// The expansion happens on every decode, and the descriptor is decoded
// once per hop (CLI -> coordinator -> daemon -> node, the coordinator's
// persisted store, the CLI's hub session file, and any future one). So a
// string is serialized with each `$` written as `$$`, which the next decode
// turns back into `$`: the value the CLI expanded reaches the node verbatim
// instead of being expanded again against the receiving host's environment
// (#3947). Released 1.x peers decode that the same way.
//
// Escaping here, unconditionally, rather than only at the specific places
// that happen to send a `Descriptor` across a hop today, is deliberate:
// every encode is then safe by construction, and a new hop added later does
// not need to remember to opt in. The cost is that the three places that
// serialize an already-decoded `Descriptor` straight to user code and never
// decode it back — the Python node's `dataflow_descriptor()`, a Python
// operator's `self.dataflow_descriptor`, the C++ `dataflow_descriptor_json`
// — see the escaped form too. Each of those undoes it with
// `descriptor_for_display` below rather than this type gaining an unescaped
// mode (#4067).
#[allow(missing_docs)]
#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
#[serde(untagged)]
pub enum EnvValue {
    Bool(bool),
    Integer(i64),
    Float(f64),
    #[serde(serialize_with = "serialize_escaping_dollars")]
    String(String),
}

/// `s` with each `$` written as `$$`, which is what `$` expands from, so the
/// next decode restores `s`.
fn serialize_escaping_dollars<S: serde::Serializer>(
    s: &str,
    serializer: S,
) -> Result<S::Ok, S::Error> {
    if s.contains('$') {
        serializer.serialize_str(&s.replace('$', "$$"))
    } else {
        serializer.serialize_str(s)
    }
}

/// `descriptor` as the three introspection points hand it to user code:
/// `Node.dataflow_descriptor()` (Python), a Python operator's
/// `self.dataflow_descriptor`, and the C++ `dataflow_descriptor_json`.
///
/// Serializing a `Descriptor` directly always escapes `$` as `$$` in every
/// `env` string (see the comment on `EnvValue`), because the same
/// `Serialize` impl is also how a `Descriptor` crosses a dora-to-dora wire
/// hop. These three callers serialize the same, already-decoded
/// `Descriptor` with no decode step after to undo that, so without this
/// they would show the wire form instead of the real value (#4067). This
/// walks only the two places `env` actually appears — `descriptor.env` and
/// each node's `env` — rather than unescaping the whole serialized tree,
/// so an unrelated string that happens to contain `$$` (a `build:` command,
/// a description, ...) is left alone.
///
/// Returns the serialize error rather than unwrapping it: these callers run
/// at an FFI boundary (the C++ `dataflow_descriptor_json`, pyo3), where a
/// panic is undefined behaviour, and the originals already returned a
/// fallible result here.
pub fn descriptor_for_display(
    descriptor: &Descriptor,
) -> Result<serde_json::Value, serde_json::Error> {
    let mut value = serde_json::to_value(descriptor)?;
    if let Some(env) = value.get_mut("env") {
        unescape_json_env_map(env);
    }
    if let Some(nodes) = value
        .get_mut("nodes")
        .and_then(|nodes| nodes.as_array_mut())
    {
        for node in nodes {
            if let Some(env) = node.get_mut("env") {
                unescape_json_env_map(env);
            }
        }
    }
    Ok(value)
}

/// Undoes [`serialize_escaping_dollars`] on every string value of a JSON
/// object already known to be one `env:` map, in place.
fn unescape_json_env_map(env: &mut serde_json::Value) {
    if let Some(map) = env.as_object_mut() {
        for value in map.values_mut() {
            if let serde_json::Value::String(s) = value {
                *s = s.replace("$$", "$");
            }
        }
    }
}

thread_local! {
    static MODULE_DIR: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}

/// Decode a module from the original YAML, resolving `$MODULE_DIR` in its
/// environment strings alongside ordinary host variables.
#[doc(hidden)]
pub fn deserialize_module_yaml<'de, T: Deserialize<'de>>(
    yaml: &'de [u8],
    module_dir: &str,
) -> Result<T, serde_yaml::Error> {
    // Serde's nested EnvValue visitor has no context parameter. Confine the
    // override to this synchronous decode, including nesting and unwinding.
    struct Restore(Option<String>);
    impl Drop for Restore {
        fn drop(&mut self) {
            MODULE_DIR.replace(self.0.take());
        }
    }
    let _restore = Restore(MODULE_DIR.replace(Some(module_dir.to_owned())));
    serde_yaml::from_slice(yaml)
}

fn expand_env_value<'de, D: serde::Deserializer<'de>>(de: D) -> Result<String, D::Error> {
    let raw = String::deserialize(de)?;
    MODULE_DIR.with_borrow(|dir| {
        shellexpand::env_with_context(&raw, |name| {
            if name == "MODULE_DIR"
                && let Some(dir) = dir
            {
                return Ok(Some(dir.clone()));
            }
            std::env::var(name).map(Some)
        })
        .map(|value| value.into_owned())
        .map_err(serde::de::Error::custom)
    })
}

impl<'de> Deserialize<'de> for EnvValue {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum Raw {
            Bool(bool),
            Integer(i64),
            // Before `Float`, which would round it to the nearest `f64`.
            Unsigned(u64),
            Float(f64),
            #[serde(deserialize_with = "expand_env_value")]
            String(String),
        }
        Ok(match Raw::deserialize(deserializer)? {
            Raw::Bool(b) => EnvValue::Bool(b),
            Raw::Integer(i) => EnvValue::Integer(i),
            // Above `i64::MAX`, so `Integer` cannot hold it: keep its digits.
            Raw::Unsigned(u) => EnvValue::String(u.to_string()),
            Raw::Float(f) if f.is_finite() => EnvValue::Float(f),
            // A non-finite native float (`.inf`, `.nan`, or a literal such as
            // `1e400` that overflows): JSON has no encoding for it (serde_json
            // writes `null`), so a `Float` would not survive the CLI ->
            // coordinator hop. Keep the text that `Float` prints as (`inf`,
            // `-inf`, `NaN`), i.e. what the node's env var would have held.
            Raw::Float(f) => EnvValue::String(f.to_string()),
            Raw::String(s) => EnvValue::from_string_lossless(s),
        })
    }
}

impl EnvValue {
    /// Type `s` as a bool or number if that prints back as exactly `s`,
    /// and keep it a string otherwise. `inf` and `NaN` stay strings: JSON
    /// has no encoding for a non-finite float (serde_json writes `null`),
    /// so the descriptor would not survive the coordinator -> daemon hop.
    fn from_string_lossless(s: String) -> Self {
        let typed = if let Ok(b) = s.parse() {
            EnvValue::Bool(b)
        } else if let Ok(i) = s.parse() {
            EnvValue::Integer(i)
        } else if let Ok(f) = s.parse::<f64>()
            && f.is_finite()
        {
            EnvValue::Float(f)
        } else {
            return EnvValue::String(s);
        };
        if typed.to_string() == s {
            typed
        } else {
            EnvValue::String(s)
        }
    }
}

impl fmt::Display for EnvValue {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            EnvValue::Bool(bool) => fmt.write_str(&bool.to_string()),
            EnvValue::Integer(i64) => fmt.write_str(&i64.to_string()),
            EnvValue::Float(f64) => fmt.write_str(&f64.to_string()),
            EnvValue::String(str) => fmt.write_str(str),
        }
    }
}

/// ROS2 bridge configuration for declarative ROS2 bridging.
///
/// This allows nodes to interact with ROS2 topics, services, and actions
/// without writing any custom code. The framework spawns a bridge binary that
/// handles the ROS2 DDS communication and Arrow data conversion.
///
/// Exactly one of `topic`, `topics`, `service`, or `action` must be set.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Ros2BridgeConfig {
    /// Native transport used to communicate with the ROS2 graph.
    ///
    /// Defaults to the existing DDS implementation.
    #[serde(default)]
    pub transport: Ros2TransportConfig,

    /// ROS2 topic name (e.g. "/camera/image_raw").
    /// Mutually exclusive with `topics`, `service`, `action`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub topic: Option<String>,

    /// ROS2 message type (e.g. "sensor_msgs/Image").
    /// Required when `topic` is set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message_type: Option<String>,

    /// Direction: subscribe (ROS2 -> Dora) or publish (Dora -> ROS2).
    /// Defaults to subscribe. Only used with `topic`/`topics`.
    #[serde(default)]
    pub direction: Ros2Direction,

    /// Multiple topics on a single ROS2 node context.
    /// Mutually exclusive with `topic`, `service`, `action`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub topics: Option<Vec<Ros2TopicConfig>>,

    /// ROS2 service name (e.g. "/add_two_ints").
    /// Mutually exclusive with `topic`, `topics`, `action`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service: Option<String>,

    /// ROS2 service type (e.g. "example_interfaces/AddTwoInts").
    /// Required when `service` is set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service_type: Option<String>,

    /// ROS2 action name (e.g. "/navigate").
    /// Mutually exclusive with `topic`, `topics`, `service`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub action: Option<String>,

    /// ROS2 action type (e.g. "nav2_msgs/NavigateToPose").
    /// Required when `action` is set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub action_type: Option<String>,

    /// Role: client or server. Required for `service` and `action`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub role: Option<Ros2Role>,

    /// QoS policies applied to all topics (can be overridden per-topic).
    #[serde(default)]
    // An empty key is YAML `null`, which deserializes to the default.
    #[schemars(with = "Option<Ros2QosConfig>")]
    pub qos: Ros2QosConfig,

    /// ROS2 namespace (default: "/").
    #[serde(default = "default_ros2_namespace")]
    pub namespace: String,

    /// ROS2 node name. Defaults to the dora node id.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub node_name: Option<String>,
}

impl Default for Ros2BridgeConfig {
    fn default() -> Self {
        Self {
            transport: Ros2TransportConfig::default(),
            topic: None,
            message_type: None,
            direction: Ros2Direction::default(),
            topics: None,
            service: None,
            service_type: None,
            action: None,
            action_type: None,
            role: None,
            qos: Ros2QosConfig::default(),
            namespace: default_ros2_namespace(),
            node_name: None,
        }
    }
}

/// Native transport used by a ROS2 bridge context.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Ros2TransportConfig {
    /// The existing `ros2-client` and RustDDS transport.
    #[default]
    Dds,
    /// Direct interoperability with `rmw_zenoh_cpp` peers.
    Zenoh {
        /// Wire-compatibility profile used by the target ROS2 distribution.
        compatibility: RmwZenohCompatibility,
        /// Optional Zenoh session configuration path.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        config_uri: Option<PathBuf>,
    },
}

/// Wire-compatibility profile for the `rmw_zenoh_cpp` protocol.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RmwZenohCompatibility {
    /// ROS2 Humble, whose endpoint identity uses `TypeHashNotSupported`.
    Humble,
    /// ROS2 distributions whose endpoint identity uses REP-2016 type hashes.
    Rep2016,
}

/// Role of a ROS2 service or action bridge node.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Ros2Role {
    /// Client: sends requests/goals, receives responses/results.
    Client,
    /// Server: receives requests, sends responses.
    Server,
}

fn default_ros2_namespace() -> String {
    "/".to_string()
}

/// Configuration for a single ROS2 topic in multi-topic mode.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Ros2TopicConfig {
    /// ROS2 topic name.
    pub topic: String,

    /// ROS2 message type (e.g. "geometry_msgs/Twist").
    pub message_type: String,

    /// Direction: subscribe or publish.
    #[serde(default)]
    pub direction: Ros2Direction,

    /// Maps to an dora output id (for subscribe direction).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output: Option<String>,

    /// Maps to an dora input id (for publish direction).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input: Option<String>,

    /// Per-topic QoS override.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub qos: Option<Ros2QosConfig>,
}

/// Strip the leading `/` of a ROS2 topic name, then map any remaining `/` to
/// `_` (e.g. `/robot/scan` -> `robot_scan`).
///
/// ```
/// use dora_message::descriptor::derive_port_id;
///
/// assert_eq!(derive_port_id("/robot/scan"), "robot_scan");
/// assert_eq!(derive_port_id("scan"), "scan");
/// ```
pub fn derive_port_id(topic: &str) -> String {
    topic.trim_start_matches('/').replace('/', "_")
}

impl Ros2TopicConfig {
    /// The dora output a `subscribe` topic feeds: the explicit `output:`
    /// mapping, or the topic-derived id when that is unset.
    ///
    /// Both the descriptor validator (`dora-core`) and the ros2 bridge node
    /// depend on producing the *same* id — the validator rejects configs whose
    /// port is not declared precisely because the bridge would otherwise
    /// silently drop the data — so the rule lives here in the shared message
    /// crate rather than being duplicated at each call site.
    pub fn output_port_id(&self) -> String {
        self.output
            .clone()
            .unwrap_or_else(|| derive_port_id(&self.topic))
    }

    /// The dora input a `publish` topic consumes; the counterpart of
    /// [`Self::output_port_id`].
    pub fn input_port_id(&self) -> String {
        self.input
            .clone()
            .unwrap_or_else(|| derive_port_id(&self.topic))
    }
}

/// The dora port a **single-topic** (`topic:`) ros2 bridge binds to, or `None`
/// when `declared_ports` leaves the choice ambiguous.
///
/// Single-topic mode has no explicit `output:`/`input:` field, so the port comes
/// from the node's declaration — `docs/ros2-bridge.md`: "In single-topic mode,
/// the node's declared `outputs` or `inputs` are used directly". Preferring the
/// topic-derived id when it *is* declared keeps a node that declares an extra
/// port (a `send_stdout_as` output, say) resolvable instead of ambiguous.
///
/// Both the descriptor resolver, which bakes the resolved id into the bridge
/// config, and the validator, which rejects the ambiguous case, call this — a
/// wrong choice here binds the bridge to a port nothing is wired to and drops
/// every message silently.
///
/// ```
/// use dora_message::descriptor::single_topic_port_id;
///
/// // The topic-derived id is preferred when the node declares it...
/// assert_eq!(
///     single_topic_port_id("/robot/scan", &["robot_scan", "status"]),
///     Some("robot_scan".to_string()),
/// );
/// // ...otherwise a node that declares a single port resolves to that port...
/// assert_eq!(
///     single_topic_port_id("/robot/scan", &["lidar"]),
///     Some("lidar".to_string()),
/// );
/// // ...but several non-matching ports leave the choice ambiguous.
/// assert_eq!(single_topic_port_id("/robot/scan", &["a", "b"]), None);
/// ```
pub fn single_topic_port_id(topic: &str, declared_ports: &[&str]) -> Option<String> {
    let derived = derive_port_id(topic);
    if declared_ports.contains(&derived.as_str()) {
        return Some(derived);
    }
    match declared_ports {
        [sole_port] => Some((*sole_port).to_owned()),
        _ => None,
    }
}

/// Direction of ROS2 bridge communication.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Ros2Direction {
    /// Subscribe: receive from ROS2, forward to dora outputs.
    #[default]
    Subscribe,
    /// Publish: receive from dora inputs, publish to ROS2.
    Publish,
}

/// ROS2 Quality of Service configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Ros2QosConfig {
    /// Use reliable transport (default: false = best effort).
    #[serde(default)]
    pub reliable: bool,

    /// Durability: "volatile" (default), "transient_local".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub durability: Option<String>,

    /// Liveliness: "automatic" (default), "manual_by_participant", "manual_by_topic".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub liveliness: Option<String>,

    /// Lease duration in seconds (default: infinity).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lease_duration: Option<f64>,

    /// Max blocking time in seconds for reliable transport.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_blocking_time: Option<f64>,

    /// History depth for KeepLast policy (default: 1).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub keep_last: Option<i32>,

    /// Use KeepAll history policy instead of KeepLast.
    #[serde(default)]
    pub keep_all: bool,
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A quoted `env:` value must reach the node verbatim. The derived
    /// untagged enum parsed strings into the first matching variant, so
    /// `"1.10"` became `1.1` and `"007"` became `7`.
    #[test]
    fn env_value_keeps_quoted_strings_verbatim() {
        for quoted in [
            "1.10",
            "007",
            "+5",
            "1e3",
            "1.0",
            "12345678901234567890",
            "inf",
            "-inf",
            "NaN",
        ] {
            let yaml = format!("\"{quoted}\"");
            let value: EnvValue = serde_yaml::from_str(&yaml).unwrap();
            assert_eq!(value, EnvValue::String(quoted.into()), "yaml {yaml}");

            // ...and survives the JSON hops CLI -> coordinator -> daemon.
            let json = serde_json::to_string(&value).unwrap();
            let value: EnvValue = serde_json::from_str(&json).unwrap();
            assert_eq!(value.to_string(), quoted, "json {json}");
        }
    }

    /// Strings that type losslessly keep the bool/number type every 1.x
    /// release gave them, so `dataflow_descriptor()` consumers see no change.
    #[test]
    fn env_value_types_lossless_strings() {
        let parse = |yaml: &str| serde_yaml::from_str::<EnvValue>(yaml).unwrap();
        assert_eq!(parse("\"true\""), EnvValue::Bool(true));
        assert_eq!(parse("\"8080\""), EnvValue::Integer(8080));
        assert_eq!(parse("\"-3\""), EnvValue::Integer(-3));
        assert_eq!(parse("\"1.5\""), EnvValue::Float(1.5));
    }

    #[test]
    fn env_value_keeps_native_types() {
        let parse = |yaml: &str| serde_yaml::from_str::<EnvValue>(yaml).unwrap();
        assert_eq!(parse("true"), EnvValue::Bool(true));
        assert_eq!(parse("8080"), EnvValue::Integer(8080));
        assert_eq!(parse("-3"), EnvValue::Integer(-3));
        assert_eq!(parse("1.5"), EnvValue::Float(1.5));
        assert_eq!(parse("hello"), EnvValue::String("hello".into()));
    }

    /// A native YAML `.inf` / `.nan` has no JSON encoding (serde_json
    /// writes `null`), so as a `Float` it made the coordinator reject the
    /// whole `dora start`. It must stay the string the node would have seen
    /// and survive the JSON hops CLI -> coordinator -> daemon.
    #[test]
    fn env_value_keeps_non_finite_native_floats_as_strings() {
        for (yaml, text) in [(".inf", "inf"), ("-.inf", "-inf"), (".nan", "NaN")] {
            let value: EnvValue = serde_yaml::from_str(yaml).unwrap();
            assert_eq!(value, EnvValue::String(text.into()), "yaml {yaml}");

            let json = serde_json::to_string(&value).unwrap();
            let value: EnvValue = serde_json::from_str(&json).unwrap();
            assert_eq!(value.to_string(), text, "json {json}");
        }
    }

    /// A native integer above `i64::MAX` reaches the node with its exact
    /// digits, not rounded through `f64` (`12345678901234567890` used to
    /// arrive as `12345678901234567000`).
    #[test]
    fn env_value_keeps_large_native_integers_exact() {
        for text in [
            "9223372036854775808",
            "12345678901234567890",
            "18446744073709551615",
        ] {
            let value: EnvValue = serde_yaml::from_str(text).unwrap();
            assert_eq!(value.to_string(), text, "yaml {text}");

            let json = serde_json::to_string(&value).unwrap();
            let value: EnvValue = serde_json::from_str(&json).unwrap();
            assert_eq!(value.to_string(), text, "json {json}");
        }
    }

    /// Strings still expand `$VAR` references, quoted or not, and the result
    /// is typed by the same lossless rule.
    #[test]
    fn env_value_expands_variables_in_strings() {
        let parse = |yaml: &str| serde_yaml::from_str::<EnvValue>(yaml).unwrap();
        for unquoted in [false, true] {
            let q = if unquoted { "" } else { "\"" };
            let parse_ref = |default: &str| {
                parse(&format!(
                    "{q}${{DORA_TEST_ENV_VALUE_UNSET_VAR:-{default}}}{q}"
                ))
            };
            assert_eq!(parse_ref("1.10"), EnvValue::String("1.10".into()));
            assert_eq!(parse_ref("8080"), EnvValue::Integer(8080));
            assert_eq!(parse_ref("true"), EnvValue::Bool(true));
        }
        assert_eq!(
            parse("\"v${DORA_TEST_ENV_VALUE_UNSET_VAR:-2}\""),
            EnvValue::String("v2".into())
        );
        assert!(serde_yaml::from_str::<EnvValue>("\"$DORA_TEST_ENV_VALUE_UNSET_VAR\"").is_err());
    }

    /// A string whose expansion contains `$` must not be expanded again by
    /// the next decode, which runs in the coordinator, the daemon and the
    /// node against *their* environments (#3947). `$${...}` is how a value
    /// containing `${...}` gets into memory without a CLI-side variable;
    /// `DORA_TEST_ENV_VALUE_UNSET_VAR` is unset, so a second expansion would
    /// fail the decode instead of passing by accident.
    #[test]
    fn env_value_is_not_expanded_again_after_a_round_trip() {
        let yaml = "env:\n  X: $${DORA_TEST_ENV_VALUE_UNSET_VAR}\n  \
                    PW: p$$ssw0rd\n  TAIL: cost$$\nnodes: []\n";
        let descriptor: Descriptor = serde_yaml::from_str(yaml).unwrap();
        let expected = BTreeMap::from([
            (
                "X".to_string(),
                EnvValue::String("${DORA_TEST_ENV_VALUE_UNSET_VAR}".into()),
            ),
            ("PW".to_string(), EnvValue::String("p$ssw0rd".into())),
            ("TAIL".to_string(), EnvValue::String("cost$".into())),
        ]);
        assert_eq!(descriptor.env.as_ref(), Some(&expected));

        // Every hop: CLI -> coordinator -> daemon -> node over JSON.
        let mut current = descriptor;
        for hop in 0..3 {
            let json = serde_json::to_string(&current).unwrap();
            current = serde_json::from_str(&json)
                .unwrap_or_else(|e| panic!("JSON hop {hop} failed: {e}\n{json}"));
            assert_eq!(current.env.as_ref(), Some(&expected), "JSON hop {hop}");
        }
        // The YAML session file the CLI writes and rereads for `hub:` dataflows.
        let yaml = serde_yaml::to_string(&current).unwrap();
        let reread: Descriptor = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(reread.env.as_ref(), Some(&expected), "YAML\n{yaml}");
    }

    /// Strings without `$` and typed values keep the plain encoding, so the
    /// common case stays byte-identical to what 1.x peers send.
    #[test]
    fn env_value_serializes_without_dollar_unchanged() {
        let json = |v: EnvValue| serde_json::to_string(&v).unwrap();
        assert_eq!(json(EnvValue::String("hello".into())), "\"hello\"");
        assert_eq!(json(EnvValue::String("1.10".into())), "\"1.10\"");
        assert_eq!(json(EnvValue::Integer(8080)), "8080");
        assert_eq!(json(EnvValue::Float(1.5)), "1.5");
        assert_eq!(json(EnvValue::Bool(true)), "true");
        assert_eq!(json(EnvValue::String("a$b".into())), "\"a$$b\"");
    }

    /// `Node.dataflow_descriptor()` (Python), a Python operator's
    /// `self.dataflow_descriptor`, and the C++ `dataflow_descriptor_json`
    /// all serialize an already-decoded `Descriptor` directly, with no
    /// further decode step to undo the wire escape — `descriptor_for_display`
    /// is what each of them must go through instead of a bare
    /// `serde_json::to_value`/`pythonize` call (#4067).
    #[test]
    fn descriptor_for_display_shows_the_raw_value() {
        let mut node = Node::new("n".parse().unwrap());
        node.env = Some(BTreeMap::from([(
            "K".to_string(),
            EnvValue::String("a$b".into()),
        )]));
        let mut descriptor = Descriptor::new(vec![node]);
        descriptor.env = Some(BTreeMap::from([(
            "PRICE".to_string(),
            EnvValue::String("50$ off".into()),
        )]));

        // A bare serialize still shows the wire-escaped form.
        let wire = serde_json::to_value(&descriptor).unwrap();
        assert_eq!(wire["env"]["PRICE"], "50$$ off");
        assert_eq!(wire["nodes"][0]["env"]["K"], "a$$b");

        // `descriptor_for_display` undoes it, at both `env` locations.
        let display = descriptor_for_display(&descriptor).unwrap();
        assert_eq!(display["env"]["PRICE"], "50$ off");
        assert_eq!(display["nodes"][0]["env"]["K"], "a$b");
    }

    /// `descriptor_for_display` targets only `env`/`nodes[].env`, so a `$$`
    /// elsewhere in the descriptor (a path, a description, ...) that has
    /// nothing to do with the escape must survive unchanged.
    #[test]
    fn descriptor_for_display_leaves_unrelated_dollar_signs_alone() {
        let mut node = Node::new("n".parse().unwrap());
        node.path = Some("echo $$ not an env escape".into());
        let descriptor = Descriptor::new(vec![node]);
        let display = descriptor_for_display(&descriptor).unwrap();
        assert_eq!(display["nodes"][0]["path"], "echo $$ not an env escape");
    }

    /// Assert that `constructed` serializes to exactly what `yaml`
    /// deserializes to — that a hand-written constructor agrees with the
    /// per-field `#[serde(default)]`s.
    ///
    /// The two are independent sources of the same defaults, and both are
    /// used in production: the daemon builds dynamically registered nodes
    /// through `Node::new` (`Daemon::handle_add_node`) and declared nodes
    /// through serde, so a divergence — say a field that later grows a
    /// `#[serde(default = "…")]` custom default — would silently give the two
    /// kinds different configuration.
    fn assert_matches_yaml_defaults<T: Serialize + serde::de::DeserializeOwned>(
        yaml: &str,
        constructed: T,
        what: &str,
    ) {
        let from_yaml: T = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(
            serde_yaml::to_value(&from_yaml).unwrap(),
            serde_yaml::to_value(&constructed).unwrap(),
            "`{what}` drifted from the defaults serde applies"
        );
    }

    /// `Node::new` must agree with what serde produces for a YAML node that
    /// sets nothing but `id`.
    #[test]
    fn node_new_matches_yaml_defaults() {
        assert_matches_yaml_defaults(
            "id: some-node\n",
            Node::new("some-node".to_owned().into()),
            "Node::new",
        );
    }

    /// The same contract for the other constructors this crate hands out.
    ///
    /// `Descriptor::new` is what the coordinator's `AddNode` resolution and the
    /// daemon's bench support build from; `Deploy::default()` and
    /// `Debug::default()` are the documented entry points for `deploy:` and
    /// `debug:`; `NodeRunConfig::default()` is the runtime node's I/O config in
    /// the daemon while custom nodes deserialize theirs.
    ///
    /// `CustomNode::new` is not covered here: `source` and `envs` have no serde
    /// default, so there is no "nothing set" YAML for it. Its guard is
    /// `CustomNode::from_node` — a struct literal in this crate, so a new field
    /// is a compile error — plus
    /// `dora_core::descriptor::tests::every_custom_node_field_is_carried_through`
    /// for the values.
    #[test]
    fn constructors_match_yaml_defaults() {
        assert_matches_yaml_defaults(
            "nodes: []\n",
            Descriptor::new(Vec::new()),
            "Descriptor::new",
        );
        assert_matches_yaml_defaults("{}\n", Deploy::default(), "Deploy::default");
        assert_matches_yaml_defaults("{}\n", Debug::default(), "Debug::default");
        assert_matches_yaml_defaults("{}\n", NodeRunConfig::default(), "NodeRunConfig::default");
        assert_matches_yaml_defaults(
            "from: a\nto: b\n",
            TypeRuleDef::new("a".to_owned(), "b".to_owned()),
            "TypeRuleDef::new",
        );
    }

    #[test]
    fn ros2_transport_defaults_to_dds() {
        let config: Ros2BridgeConfig =
            serde_yaml::from_str("topic: /chatter\nmessage_type: std_msgs/String\n").unwrap();
        assert!(matches!(config.transport, Ros2TransportConfig::Dds));
    }

    #[test]
    fn ros2_transport_parses_humble_zenoh() {
        let config: Ros2BridgeConfig = serde_yaml::from_str(
            "transport:\n  kind: zenoh\n  compatibility: humble\n  config_uri: /tmp/rmw.json5\n\
             topic: /chatter\nmessage_type: std_msgs/String\n",
        )
        .unwrap();
        assert_eq!(
            config.transport,
            Ros2TransportConfig::Zenoh {
                compatibility: RmwZenohCompatibility::Humble,
                config_uri: Some("/tmp/rmw.json5".into()),
            }
        );
    }

    #[test]
    fn ros2_transport_rejects_unknown_zenoh_compatibility() {
        let error = serde_yaml::from_str::<Ros2BridgeConfig>(
            "transport:\n  kind: zenoh\n  compatibility: automatic\n\
             topic: /chatter\nmessage_type: std_msgs/String\n",
        )
        .unwrap_err();
        assert!(error.to_string().contains("unknown variant `automatic`"));
    }

    #[test]
    fn single_topic_port_uses_the_sole_declared_port() {
        // `docs/ros2-bridge.md`: single-topic mode uses the declared port
        // directly, so `/turtle1/pose` binds to `pose` and not to the
        // topic-derived `turtle1_pose`.
        assert_eq!(
            single_topic_port_id("/turtle1/pose", &["pose"]),
            Some("pose".to_owned())
        );
    }

    #[test]
    fn single_topic_port_prefers_a_declared_topic_derived_id() {
        // A second declared port (here a `send_stdout_as` output) would make the
        // choice ambiguous, but the topic-derived id is itself declared.
        assert_eq!(
            single_topic_port_id("/turtle1/pose", &["log", "turtle1_pose"]),
            Some("turtle1_pose".to_owned())
        );
    }

    #[test]
    fn single_topic_port_is_ambiguous_with_several_unrelated_ports() {
        assert_eq!(
            single_topic_port_id("/turtle1/pose", &["pose", "log"]),
            None
        );
    }

    #[test]
    fn single_topic_port_needs_a_declared_port() {
        assert_eq!(single_topic_port_id("/turtle1/pose", &[]), None);
    }

    #[test]
    fn output_framing_defaults_to_raw() {
        let yaml = r#"
nodes:
  - id: test
    path: test.py
    outputs:
      - data
"#;
        let desc: Descriptor = serde_yaml::from_str(yaml).unwrap();
        assert!(desc.nodes[0].output_framing.is_empty());
    }

    #[test]
    fn output_framing_parses_arrow_ipc() {
        let yaml = r#"
nodes:
  - id: test
    path: test.py
    outputs:
      - data
    output_framing:
      data: arrow-ipc
"#;
        let desc: Descriptor = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(
            desc.nodes[0].output_framing.get::<DataId>(&"data".into()),
            Some(&OutputFraming::ArrowIpc)
        );
    }

    #[test]
    fn cpu_affinity_parses() {
        let yaml = r#"
nodes:
  - id: test
    path: test.py
    cpu_affinity: [0, 2, 4]
"#;
        let desc: Descriptor = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(desc.nodes[0].cpu_affinity, Some(vec![0, 2, 4]));
    }

    #[test]
    fn cpu_affinity_defaults_to_none() {
        let yaml = r#"
nodes:
  - id: test
    path: test.py
"#;
        let desc: Descriptor = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(desc.nodes[0].cpu_affinity, None);
    }

    #[test]
    fn debug_flag_accepts_new_name() {
        let yaml = r#"
nodes:
  - id: test
    path: test.py
debug:
  enable_debug_inspection: true
"#;
        let desc: Descriptor = serde_yaml::from_str(yaml).unwrap();
        assert!(desc.debug.enable_debug_inspection);
    }

    #[test]
    fn removed_unstable_key_prefix_is_rejected_not_ignored() {
        // `_unstable_deploy` / `_unstable_debug` lost their prefix for 1.0.
        // Both must *error*, never deserialize to the default: a dataflow that
        // still says `_unstable_deploy` would otherwise run every node on the
        // local daemon while looking like it pinned them to machines, and a
        // stale `_unstable_debug` would leave `dora topic echo` silently
        // empty. `deny_unknown_fields` on `Descriptor` is what makes these
        // diagnosable, so this test guards that attribute as much as the
        // rename.
        for (key, block) in [
            ("_unstable_deploy", "_unstable_deploy:\n  machine: m1\n"),
            (
                "_unstable_debug",
                "_unstable_debug:\n  enable_debug_inspection: true\n",
            ),
        ] {
            let yaml = format!("nodes:\n  - id: test\n    path: test.py\n{block}");
            let err = serde_yaml::from_str::<Descriptor>(&yaml)
                .expect_err("the pre-1.0 `_unstable_` key must be rejected");
            assert!(
                err.to_string().contains(key),
                "error should name `{key}`, got: {err}"
            );
        }
    }

    #[test]
    fn debug_flag_rejects_the_removed_legacy_alias() {
        // The `publish_all_messages_to_zenoh` alias was removed for 1.0. It
        // must *error* rather than deserialize to the default: silently
        // ignoring it would leave debug inspection off while the dataflow
        // looks like it enabled it, and `dora topic echo` would return
        // nothing with no explanation. `deny_unknown_fields` on `Debug` is
        // what turns that into a diagnosable failure.
        let yaml = r#"
nodes:
  - id: test
    path: test.py
debug:
  publish_all_messages_to_zenoh: true
"#;
        let err = serde_yaml::from_str::<Descriptor>(yaml)
            .expect_err("removed alias must be rejected, not silently ignored");
        assert!(
            err.to_string().contains("publish_all_messages_to_zenoh"),
            "error should name the offending field, got: {err}"
        );
    }

    #[test]
    fn operator_source_shared_library_names_its_runtime() {
        let cfg: OperatorConfig = serde_yaml::from_str("shared-library: build/op").unwrap();
        assert!(matches!(&cfg.source, OperatorSource::SharedLibrary(s) if s == "build/op"));
        assert_eq!(cfg.source.runtime_name(), RUNTIME_SHARED_LIBRARY);
        assert_eq!(cfg.source.runtime_name(), "shared-library");
    }

    #[test]
    fn operator_source_python_source_only_names_its_runtime() {
        let cfg: OperatorConfig = serde_yaml::from_str("python: op.py").unwrap();
        assert!(matches!(&cfg.source, OperatorSource::Python(py) if py.source == "op.py"));
        assert_eq!(cfg.source.runtime_name(), RUNTIME_PYTHON);
    }

    #[test]
    fn operator_source_python_with_conda_env_names_its_runtime() {
        let cfg: OperatorConfig =
            serde_yaml::from_str("python:\n  source: op.py\n  conda_env: my-env").unwrap();
        match &cfg.source {
            OperatorSource::Python(py) => {
                assert_eq!(py.source, "op.py");
                assert_eq!(py.conda_env.as_deref(), Some("my-env"));
            }
            other => panic!("expected python source, got {other:?}"),
        }
        assert_eq!(cfg.source.runtime_name(), RUNTIME_PYTHON);
    }

    #[test]
    fn operator_source_wasm_names_its_runtime() {
        let cfg: OperatorConfig = serde_yaml::from_str("wasm: op.wasm").unwrap();
        assert!(matches!(&cfg.source, OperatorSource::Wasm(s) if s == "op.wasm"));
        assert_eq!(cfg.source.runtime_name(), RUNTIME_WASM);
    }

    /// The runtime a node is spawned with must survive a descriptor round-trip:
    /// the daemon re-parses the serialized descriptor before spawning.
    #[test]
    fn operator_source_runtime_survives_a_serde_roundtrip() {
        for yaml in ["shared-library: build/op", "python: op.py", "wasm: op.wasm"] {
            let cfg: OperatorConfig = serde_yaml::from_str(yaml).unwrap();
            let serialized = serde_yaml::to_string(&cfg).unwrap();
            let reparsed: OperatorConfig = serde_yaml::from_str(&serialized).unwrap();
            assert_eq!(cfg.source.runtime_name(), reparsed.source.runtime_name());
        }
    }

    /// The schema must agree with the parser on every empty key. An empty
    /// key is YAML `null`, which serde maps to the field's default wherever
    /// the field has one, so the schema has to accept `null` exactly there.
    ///
    /// Every property of every struct a dataflow spells out as a YAML mapping
    /// is checked at a real location. A struct definition this test doesn't
    /// know about fails it, so a new field or struct cannot drift unseen.
    #[test]
    fn empty_keys_schema_matches_parser() {
        fn schema_accepts_null(property: &serde_json::Value) -> bool {
            property["type"]
                .as_array()
                .is_some_and(|t| t.contains(&"null".into()))
                || property["anyOf"]
                    .as_array()
                    .is_some_and(|v| v.iter().any(|s| s["type"] == "null"))
        }
        /// The properties of a definition, including those of its variants.
        fn properties(
            definition: &serde_json::Value,
        ) -> serde_json::Map<String, serde_json::Value> {
            let mut properties = serde_json::Map::new();
            let variants = ["oneOf", "anyOf"]
                .iter()
                .filter_map(|k| definition[k].as_array())
                .flatten();
            for variant in std::iter::once(definition).chain(variants) {
                if let Some(p) = variant["properties"].as_object() {
                    properties.extend(p.clone());
                }
            }
            properties
        }

        let schema = serde_json::to_value(schemars::schema_for!(Descriptor)).unwrap();
        let node = "nodes:\n  - id: a\n    path: x\n";
        let ros2 =
            "nodes:\n  - id: a\n    ros2:\n      topic: /x\n      message_type: std_msgs/String\n";
        // (definition, a dataflow with `{key}` where the empty key goes, keys
        // that dataflow already sets). `""` is the dataflow itself.
        let locations: &[(&str, String, &[&str])] = &[
            ("", format!("{node}{{key}}:\n"), &["nodes"]),
            ("Node", format!("{node}    {{key}}:\n"), &["id", "path"]),
            ("Debug", format!("{node}debug:\n  {{key}}:\n"), &[]),
            ("Deploy", format!("{node}    deploy:\n      {{key}}:\n"), &[]),
            (
                "Input",
                format!("{node}    inputs:\n      i:\n        source: b/o\n        {{key}}:\n"),
                &["source"],
            ),
            (
                "PythonSource",
                "nodes:\n  - id: a\n    operator:\n      python:\n        source: x.py\n        {key}:\n"
                    .to_owned(),
                &["source"],
            ),
            (
                "Ros2BridgeConfig",
                format!("{ros2}      {{key}}:\n"),
                &["topic", "message_type"],
            ),
            ("Ros2QosConfig", format!("{ros2}      qos:\n        {{key}}:\n"), &[]),
            (
                "Ros2TopicConfig",
                "nodes:\n  - id: a\n    ros2:\n      topics:\n        - topic: /x\n          message_type: std_msgs/String\n          {key}:\n"
                    .to_owned(),
                &["topic", "message_type"],
            ),
            (
                "Ros2TransportConfig",
                format!("{ros2}      transport:\n        kind: zenoh\n        compatibility: humble\n        {{key}}:\n"),
                &["kind", "compatibility"],
            ),
        ];
        // serde_yaml reads `null` into a plain `String` as "", not as the
        // field's default (`namespace` would be "" instead of "/"), so the
        // schema rejects an empty key there on purpose.
        let null_is_not_the_default = [("Ros2BridgeConfig", "namespace")];

        for (definition, template, preset) in locations {
            let def = if definition.is_empty() {
                &schema
            } else {
                &schema["$defs"][definition]
            };
            let without_key: String = template
                .lines()
                .filter(|l| !l.contains("{key}"))
                .map(|l| format!("{l}\n"))
                .collect();
            serde_yaml::from_str::<Descriptor>(&without_key)
                .unwrap_or_else(|e| panic!("template for `{definition}` must parse: {e}"));
            for (key, property) in properties(def) {
                if preset.contains(&key.as_str()) {
                    continue;
                }
                let yaml = template.replace("{key}", &key);
                let parses = serde_yaml::from_str::<Descriptor>(&yaml).is_ok();
                let expected = parses && !null_is_not_the_default.contains(&(definition, &key));
                assert_eq!(schema_accepts_null(&property), expected, "{yaml}{property}");
            }
        }

        // Not written as YAML mappings, so there is no empty key to check:
        // input mappings and their parts are strings (`node/output`,
        // `dora/timer/millis/100`, `dora/logs/...`).
        // `TypeRuleDef`: both fields are required strings, and an empty one
        // reads as "" (like `namespace`), so the schema rejects it on purpose.
        // Operators are checked below.
        let not_walked = [
            "InputMapping",
            "UserInputMapping",
            "LogSubscriptionFilter",
            "Duration",
            "TypeRuleDef",
            "OperatorDefinition",
            "SingleOperatorDefinition",
        ];
        for (name, def) in schema["$defs"].as_object().unwrap() {
            if properties(def).is_empty() || not_walked.contains(&name.as_str()) {
                continue;
            }
            assert!(
                locations.iter().any(|(d, ..)| d == name),
                "new struct `{name}` in the schema: add a location for it to this test"
            );
        }

        // Operators are `#[serde(flatten)]`ed, and flattened fields don't
        // map `null` to a default, so there the schema must reject it.
        let operators = "nodes:\n  - id: a\n    operators:\n      - id: op\n        python: x.py\n        inputs:\n";
        let operator = "nodes:\n  - id: a\n    operator:\n      python: x.py\n      outputs:\n";
        for yaml in [operators, operator] {
            assert!(serde_yaml::from_str::<Descriptor>(yaml).is_err(), "{yaml}");
        }
        for definition in ["OperatorDefinition", "SingleOperatorDefinition"] {
            for key in ["inputs", "outputs", "input_types", "output_types"] {
                let property = &schema["$defs"][definition]["properties"][key];
                assert!(
                    !schema_accepts_null(property),
                    "{definition}.{key}: {property}"
                );
            }
        }
    }
}