oxide-batch-core 0.7.0

Internal OxideBatch implementation crate; use oxide-batch instead
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
//! Restart-relevant job-definition identity.

use std::collections::{BTreeMap, BTreeSet};
use std::error::Error;
use std::fmt;

use serde_json::json;
use sha2::{Digest, Sha256};

use crate::{ChunkSize, JobName, NodeId, StateSchemaId, StateSchemaVersion, StepName};

const MAX_TOKEN_BYTES: usize = 128;
/// The maximum number of nodes one plan may contain.
///
/// The bound is a framework capability rather than durable meaning: the
/// manifest reader enforces the ceiling of the running build, and raising it
/// in a later release must not change a fingerprint.
pub const MAX_NODES: usize = 1_024;
/// The maximum number of transitions one plan may contain.
///
/// The bound is a framework capability, on the same terms as [`MAX_NODES`].
pub const MAX_TRANSITIONS: usize = 4_096;
/// Maximum interceptors declared by one M7 repeat definition.
///
/// This capacity ceiling is not definition-fingerprint material.
pub const MAX_REPEAT_INTERCEPTORS: usize = 32;
/// Maximum nested M7 repeat-wrapper depth.
///
/// This capacity ceiling is not definition-fingerprint material.
pub const MAX_REPEAT_NESTING_DEPTH: usize = 8;
/// Maximum durable source nodes one compatible-upgrade edge may map.
pub const MAX_DEFINITION_UPGRADE_NODES: usize = MAX_NODES;
/// Maximum state-transform declarations one compatible-upgrade edge may carry.
pub const MAX_DEFINITION_UPGRADE_TRANSFORMS: usize = MAX_TRANSITIONS;
pub(crate) const MAX_MANIFEST_BYTES: usize = 64 * 1024;
/// The canonical manifest format for a one-step tasklet or chunk definition.
pub const MANIFEST_FORMAT_ONE_STEP: u16 = 1;
/// The canonical manifest format that captures a compiled flow graph.
pub const MANIFEST_FORMAT_FLOW: u16 = 2;
/// The canonical manifest format for bounded M4 local-scale plans.
pub const MANIFEST_FORMAT_LOCAL_SCALE: u16 = 3;
/// The canonical manifest format for bounded M7 composed flows, including
/// additive scoped-component definition identity.
pub const MANIFEST_FORMAT_ADVANCED_FLOW: u16 = 4;
/// The newest canonical manifest format this runtime can interpret.
pub(crate) const SUPPORTED_MANIFEST_FORMAT: u16 = MANIFEST_FORMAT_ADVANCED_FLOW;
const LEGACY_REVISION: &str = "__m1_repository_port_v1";
const LEGACY_MANIFEST: &[u8] =
    br#"{"format":1,"repository_port":"m1","revision":"__m1_repository_port_v1"}"#;

/// Validates one application-owned definition token.
///
/// # Errors
///
/// Rejects empty values, values longer than 128 UTF-8 bytes, surrounding
/// whitespace, and control characters.
pub fn validate_token(value: &str, kind: DefinitionTokenKind) -> Result<(), DefinitionError> {
    if value.is_empty() {
        return Err(DefinitionError::EmptyToken { kind });
    }
    if value.len() > MAX_TOKEN_BYTES {
        return Err(DefinitionError::TokenTooLong {
            kind,
            max_bytes: MAX_TOKEN_BYTES,
        });
    }
    if value.trim() != value {
        return Err(DefinitionError::SurroundingWhitespace { kind });
    }
    if value.chars().any(char::is_control) {
        return Err(DefinitionError::ControlCharacter { kind });
    }
    Ok(())
}

/// Declares one validated, application-owned definition token type.
///
/// The generated constructor calls [`validate_token`] and returns
/// [`DefinitionError`], both of which must be in scope where the macro is
/// invoked.
#[macro_export]
macro_rules! definition_token {
    ($name:ident, $kind:expr, $docs:literal) => {
        #[doc = $docs]
        #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
        pub struct $name(String);

        impl $name {
            /// Validates and constructs the token.
            ///
            /// # Errors
            ///
            /// Rejects empty values, values longer than 128 UTF-8 bytes,
            /// surrounding whitespace, and control characters.
            pub fn new(value: impl Into<String>) -> Result<Self, DefinitionError> {
                let value = value.into();
                validate_token(&value, $kind)?;
                Ok(Self(value))
            }

            /// Borrows the validated token.
            #[must_use]
            pub fn as_str(&self) -> &str {
                &self.0
            }
        }
    };
}

definition_token!(
    DefinitionRevision,
    DefinitionTokenKind::Revision,
    "An application-owned audit label for one restart-relevant definition."
);

/// Restart-relevant identity of one deterministic parameter incrementer.
///
/// The executable callback remains process-local. Only its reviewed kind and
/// revision enter a format-4 definition fingerprint.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParameterIncrementerIdentity {
    kind: DefinitionRevision,
    revision: DefinitionRevision,
}

impl ParameterIncrementerIdentity {
    /// Constructs an identity from already validated definition tokens.
    #[must_use]
    pub const fn new(kind: DefinitionRevision, revision: DefinitionRevision) -> Self {
        Self { kind, revision }
    }

    /// Borrows the reviewed incrementer kind.
    #[must_use]
    pub const fn kind(&self) -> &DefinitionRevision {
        &self.kind
    }

    /// Borrows the reviewed implementation revision.
    #[must_use]
    pub const fn revision(&self) -> &DefinitionRevision {
        &self.revision
    }
}
definition_token!(
    DefinitionArtifactId,
    DefinitionTokenKind::Artifact,
    "A bounded application-owned identity for the executable artifact that assembles one definition."
);
definition_token!(
    DefinitionUpgradeKey,
    DefinitionTokenKind::Upgrade,
    "An application-owned key for one directed definition compatibility edge."
);
definition_token!(
    DefinitionUpgradeRevision,
    DefinitionTokenKind::Upgrade,
    "A bounded application-owned revision for one deterministic compatible-upgrade implementation."
);
definition_token!(
    DefinitionStateTransformId,
    DefinitionTokenKind::Upgrade,
    "A stable bounded identity for one durable state family member transformed by a compatible upgrade."
);
definition_token!(
    RepeatId,
    DefinitionTokenKind::Repeat,
    "A stable logical identifier for one repeat definition."
);

/// One source-to-target durable step mapping for a compatible restart.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StepDefinitionUpgrade {
    source: StepName,
    target: StepName,
}

impl StepDefinitionUpgrade {
    /// Constructs one directed step mapping.
    #[must_use]
    pub const fn new(source: StepName, target: StepName) -> Self {
        Self { source, target }
    }

    /// Borrows the checkpoint-producing step name.
    #[must_use]
    pub const fn source(&self) -> &StepName {
        &self.source
    }

    /// Borrows the step name in the proposed definition.
    #[must_use]
    pub const fn target(&self) -> &StepName {
        &self.target
    }
}

/// Durable state family covered by one compatible-upgrade transform.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum DefinitionStateKind {
    /// A committed reader/checkpoint position.
    Checkpoint,
    /// Job- or step-owned execution context.
    ExecutionContext,
    /// Namespaced component-owned durable state.
    ComponentState,
    /// Value-free late-binding/source provenance.
    ScopeResolution,
    /// Current committed repeat state and decision.
    Repeat,
    /// Durable retry/skip/fault bookkeeping.
    FaultState,
}

impl DefinitionStateKind {
    /// Returns the stable durable encoding for this state family.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Checkpoint => "checkpoint",
            Self::ExecutionContext => "execution-context",
            Self::ComponentState => "component-state",
            Self::ScopeResolution => "scope-resolution",
            Self::Repeat => "repeat",
            Self::FaultState => "fault-state",
        }
    }
}

/// One durable source-to-target node mapping for a compatible restart.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DefinitionNodeUpgrade {
    source: NodeId,
    target: NodeId,
}

impl DefinitionNodeUpgrade {
    /// Constructs one explicit durable-node mapping.
    #[must_use]
    pub const fn new(source: NodeId, target: NodeId) -> Self {
        Self { source, target }
    }

    /// Borrows the source durable node.
    #[must_use]
    pub const fn source(&self) -> &NodeId {
        &self.source
    }

    /// Borrows the target durable node.
    #[must_use]
    pub const fn target(&self) -> &NodeId {
        &self.target
    }
}

/// Schema contract for one durable state transformation.
///
/// The actual pure transformer is runtime-owned and is deliberately absent
/// from durable metadata.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DefinitionStateTransform {
    source_node: NodeId,
    target_node: NodeId,
    kind: DefinitionStateKind,
    state_id: DefinitionStateTransformId,
    source_schema: StateSchemaId,
    source_version: StateSchemaVersion,
    target_schema: StateSchemaId,
    target_version: StateSchemaVersion,
    revision: DefinitionUpgradeRevision,
}

impl DefinitionStateTransform {
    /// Declares one explicit deterministic state transformation.
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    pub const fn new(
        source_node: NodeId,
        target_node: NodeId,
        kind: DefinitionStateKind,
        state_id: DefinitionStateTransformId,
        source_schema: StateSchemaId,
        source_version: StateSchemaVersion,
        target_schema: StateSchemaId,
        target_version: StateSchemaVersion,
        revision: DefinitionUpgradeRevision,
    ) -> Self {
        Self {
            source_node,
            target_node,
            kind,
            state_id,
            source_schema,
            source_version,
            target_schema,
            target_version,
            revision,
        }
    }

    /// Borrows the source durable node.
    #[must_use]
    pub const fn source_node(&self) -> &NodeId {
        &self.source_node
    }

    /// Borrows the target durable node.
    #[must_use]
    pub const fn target_node(&self) -> &NodeId {
        &self.target_node
    }

    /// Returns the durable state family.
    #[must_use]
    pub const fn kind(&self) -> DefinitionStateKind {
        self.kind
    }

    /// Borrows the stable identity of the state-family member.
    #[must_use]
    pub const fn state_id(&self) -> &DefinitionStateTransformId {
        &self.state_id
    }

    /// Borrows the source schema identifier.
    #[must_use]
    pub const fn source_schema(&self) -> &StateSchemaId {
        &self.source_schema
    }

    /// Returns the source schema version.
    #[must_use]
    pub const fn source_version(&self) -> StateSchemaVersion {
        self.source_version
    }

    /// Borrows the target schema identifier.
    #[must_use]
    pub const fn target_schema(&self) -> &StateSchemaId {
        &self.target_schema
    }

    /// Returns the target schema version.
    #[must_use]
    pub const fn target_version(&self) -> StateSchemaVersion {
        self.target_version
    }

    /// Borrows the deterministic transformer revision.
    #[must_use]
    pub const fn revision(&self) -> &DefinitionUpgradeRevision {
        &self.revision
    }
}

/// Process-local implementation of one declared state-transform revision.
///
/// The function is deliberately not serializable or durable. Registration
/// persists only the bounded revision/schema descriptor, while a compatible
/// restart must supply the exact live implementation again.
#[derive(Clone)]
pub struct DefinitionStateTransformer {
    revision: DefinitionUpgradeRevision,
    apply: fn(&[u8]) -> Result<Vec<u8>, DefinitionStateTransformError>,
}

impl DefinitionStateTransformer {
    /// Binds one deterministic payload transformer to its application revision.
    #[must_use]
    pub const fn new(
        revision: DefinitionUpgradeRevision,
        apply: fn(&[u8]) -> Result<Vec<u8>, DefinitionStateTransformError>,
    ) -> Self {
        Self { revision, apply }
    }

    /// Borrows the revision this implementation satisfies.
    #[must_use]
    pub const fn revision(&self) -> &DefinitionUpgradeRevision {
        &self.revision
    }

    /// Applies the process-local pure transform.
    ///
    /// # Errors
    ///
    /// Returns the application-provided redacted transform failure.
    pub fn apply(&self, payload: &[u8]) -> Result<Vec<u8>, DefinitionStateTransformError> {
        (self.apply)(payload)
    }
}

impl fmt::Debug for DefinitionStateTransformer {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DefinitionStateTransformer")
            .field("revision", &self.revision)
            .finish_non_exhaustive()
    }
}

/// Stable value-redacted failure from a compatible-upgrade transformer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DefinitionStateTransformError {
    /// Source bytes do not satisfy the transformer's declared contract.
    InvalidSource,
    /// The transformer could not produce the declared target state.
    TransformFailed,
}

impl fmt::Display for DefinitionStateTransformError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::InvalidSource => "definition-upgrade source state is invalid",
            Self::TransformFailed => "definition-upgrade state transform failed",
        })
    }
}

impl Error for DefinitionStateTransformError {}

/// One explicitly selected compatible-upgrade edge plus its live pure code.
///
/// Construction proves that every transform revision declared by the durable
/// edge has exactly one process-local implementation and that no undeclared
/// implementation is smuggled into the restart.
#[derive(Clone, Debug)]
pub struct DefinitionUpgradeExecution {
    upgrade: DefinitionUpgrade,
    transformers: BTreeMap<DefinitionUpgradeRevision, DefinitionStateTransformer>,
}

impl DefinitionUpgradeExecution {
    /// Validates one executable transformed edge.
    ///
    /// # Errors
    ///
    /// Rejects a legacy identity-only edge, duplicate implementations, a
    /// missing declared transform implementation, or an unused implementation.
    pub fn new(
        upgrade: DefinitionUpgrade,
        transformers: impl IntoIterator<Item = DefinitionStateTransformer>,
    ) -> Result<Self, DefinitionError> {
        if !upgrade.is_transformed() {
            return Err(DefinitionError::LegacyUpgradeExecution);
        }
        let mut implementations = BTreeMap::new();
        for transformer in transformers {
            if implementations
                .insert(transformer.revision().clone(), transformer)
                .is_some()
            {
                return Err(DefinitionError::DuplicateStateTransformer);
            }
        }
        let required = upgrade
            .transforms()
            .iter()
            .map(|transform| transform.revision().clone())
            .collect::<BTreeSet<_>>();
        let supplied = implementations.keys().cloned().collect::<BTreeSet<_>>();
        if required != supplied {
            return Err(DefinitionError::StateTransformerSetMismatch);
        }
        Ok(Self {
            upgrade,
            transformers: implementations,
        })
    }

    /// Borrows the exact durable edge selected by this execution.
    #[must_use]
    pub const fn upgrade(&self) -> &DefinitionUpgrade {
        &self.upgrade
    }

    /// Resolves the exact implementation declared by one transform descriptor.
    #[must_use]
    pub fn transformer(
        &self,
        transform: &DefinitionStateTransform,
    ) -> Option<&DefinitionStateTransformer> {
        self.transformers.get(transform.revision())
    }
}

/// One explicit, directed definition compatibility edge.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DefinitionUpgrade {
    key: DefinitionUpgradeKey,
    revision: Option<DefinitionUpgradeRevision>,
    from: DefinitionIdentity,
    to: DefinitionIdentity,
    step_mapping: BTreeMap<StepName, StepName>,
    node_mapping: BTreeMap<NodeId, NodeId>,
    transforms: Vec<DefinitionStateTransform>,
}

impl DefinitionUpgrade {
    /// Validates a direct, non-transitive compatibility edge.
    ///
    /// The M2 edge preserves checkpoint and context bytes unchanged, so
    /// applications may use it only when the mapped steps retain the same
    /// state schemas and semantics.
    ///
    /// # Errors
    ///
    /// Rejects self-edges, empty mappings, and mappings that reuse a target.
    pub fn new(
        key: DefinitionUpgradeKey,
        from: DefinitionIdentity,
        to: DefinitionIdentity,
        steps: impl IntoIterator<Item = StepDefinitionUpgrade>,
    ) -> Result<Self, DefinitionError> {
        if from.manifest_digest() == to.manifest_digest() {
            return Err(DefinitionError::UpgradeSelfEdge);
        }
        let mut step_mapping = BTreeMap::new();
        let mut targets = BTreeSet::new();
        for step in steps {
            if step_mapping
                .insert(step.source().clone(), step.target().clone())
                .is_some()
            {
                return Err(DefinitionError::DuplicateSourceStep);
            }
            if !targets.insert(step.target().clone()) {
                return Err(DefinitionError::DuplicateTargetStep);
            }
        }
        if step_mapping.is_empty() {
            return Err(DefinitionError::EmptyStepMapping);
        }
        Ok(Self {
            key,
            revision: None,
            from,
            to,
            step_mapping,
            node_mapping: BTreeMap::new(),
            transforms: Vec::new(),
        })
    }

    /// Validates the full transformed compatible-upgrade descriptor.
    ///
    /// Completeness against the source definition and committed durable state
    /// is checked by the restart path before lifecycle writes.
    ///
    /// # Errors
    ///
    /// Rejects self-edges, empty or non-injective node mappings, mappings or
    /// transform sets beyond their public bounds, duplicate transform
    /// identities, and transforms outside the declared node mapping.
    pub fn transformed(
        key: DefinitionUpgradeKey,
        revision: DefinitionUpgradeRevision,
        from: DefinitionIdentity,
        to: DefinitionIdentity,
        nodes: impl IntoIterator<Item = DefinitionNodeUpgrade>,
        transforms: impl IntoIterator<Item = DefinitionStateTransform>,
    ) -> Result<Self, DefinitionError> {
        if from.manifest_digest() == to.manifest_digest() {
            return Err(DefinitionError::UpgradeSelfEdge);
        }

        let mut node_mapping = BTreeMap::new();
        let mut targets = BTreeSet::new();
        for node in nodes {
            if node_mapping.len() >= MAX_DEFINITION_UPGRADE_NODES {
                return Err(DefinitionError::TooManyUpgradeNodes {
                    max: MAX_DEFINITION_UPGRADE_NODES,
                });
            }
            if node_mapping
                .insert(node.source().clone(), node.target().clone())
                .is_some()
            {
                return Err(DefinitionError::DuplicateSourceNode);
            }
            if !targets.insert(node.target().clone()) {
                return Err(DefinitionError::DuplicateTargetNode);
            }
        }
        if node_mapping.is_empty() {
            return Err(DefinitionError::EmptyStepMapping);
        }
        let source_nodes = definition_upgrade_source_nodes(&from)?;
        if node_mapping.keys().any(|node| !source_nodes.contains(node)) {
            return Err(DefinitionError::UnknownUpgradeSourceNode);
        }
        if source_nodes
            .iter()
            .any(|node| !node_mapping.contains_key(node))
        {
            return Err(DefinitionError::MissingUpgradeSourceNode);
        }
        let target_nodes = definition_upgrade_source_nodes(&to)?;
        if node_mapping
            .values()
            .any(|node| !target_nodes.contains(node))
        {
            return Err(DefinitionError::UnknownUpgradeTargetNode);
        }

        let transforms = transforms.into_iter().collect::<Vec<_>>();
        if transforms.len() > MAX_DEFINITION_UPGRADE_TRANSFORMS {
            return Err(DefinitionError::TooManyUpgradeTransforms {
                max: MAX_DEFINITION_UPGRADE_TRANSFORMS,
            });
        }

        let mut transform_keys = BTreeSet::new();
        for transform in &transforms {
            if node_mapping.get(transform.source_node()) != Some(transform.target_node()) {
                return Err(DefinitionError::StateTransformOutsideNodeMapping);
            }
            if !transform_keys.insert((
                transform.source_node().clone(),
                transform.kind(),
                transform.state_id().clone(),
            )) {
                return Err(DefinitionError::DuplicateStateTransform);
            }
        }
        validate_required_definition_state_transforms(&from, &to, &node_mapping, &transforms)?;

        Ok(Self {
            key,
            revision: Some(revision),
            from,
            to,
            step_mapping: BTreeMap::new(),
            node_mapping,
            transforms,
        })
    }

    /// Borrows the application-owned upgrade key.
    #[must_use]
    pub const fn key(&self) -> &DefinitionUpgradeKey {
        &self.key
    }

    /// Borrows the deterministic transformed-edge revision.
    ///
    /// None identifies the legacy M2 identity-only edge shape.
    #[must_use]
    pub const fn revision(&self) -> Option<&DefinitionUpgradeRevision> {
        self.revision.as_ref()
    }

    /// Borrows the checkpoint-producing definition.
    #[must_use]
    pub const fn from(&self) -> &DefinitionIdentity {
        &self.from
    }

    /// Borrows the proposed definition.
    #[must_use]
    pub const fn to(&self) -> &DefinitionIdentity {
        &self.to
    }

    /// Borrows the durable source-to-target step mapping.
    ///
    /// Durable adapters replay the mapping when they resolve a compatible
    /// restart, so the order is the validated declaration order.
    #[must_use]
    pub fn step_mapping(&self) -> &BTreeMap<StepName, StepName> {
        &self.step_mapping
    }

    /// Borrows the durable source-to-target node mapping.
    #[must_use]
    pub fn node_mapping(&self) -> &BTreeMap<NodeId, NodeId> {
        &self.node_mapping
    }

    /// Borrows deterministic state-transform declarations.
    #[must_use]
    pub fn transforms(&self) -> &[DefinitionStateTransform] {
        &self.transforms
    }

    /// Reports whether the edge carries the M7 transformed descriptor shape.
    #[must_use]
    pub const fn is_transformed(&self) -> bool {
        self.revision.is_some()
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct DefinitionDurableStateContract {
    kind: DefinitionStateKind,
    state_id: Option<String>,
    schema: StateSchemaId,
    version: StateSchemaVersion,
}

fn validate_required_definition_state_transforms(
    from: &DefinitionIdentity,
    to: &DefinitionIdentity,
    node_mapping: &BTreeMap<NodeId, NodeId>,
    transforms: &[DefinitionStateTransform],
) -> Result<(), DefinitionError> {
    for (source_node, target_node) in node_mapping {
        let source_contracts = definition_durable_state_contracts(from, source_node)?;
        let target_contracts = definition_durable_state_contracts(to, target_node)?;
        for source in source_contracts {
            let target = target_contracts
                .iter()
                .find(|candidate| {
                    candidate.kind == source.kind && candidate.state_id == source.state_id
                })
                .ok_or(DefinitionError::MissingTargetStateContract)?;
            let matching = transforms
                .iter()
                .filter(|transform| {
                    transform.source_node() == source_node
                        && transform.target_node() == target_node
                        && transform.kind() == source.kind
                        && source
                            .state_id
                            .as_deref()
                            .is_none_or(|state_id| transform.state_id().as_str() == state_id)
                })
                .collect::<Vec<_>>();
            if matching.len() > 1 {
                return Err(DefinitionError::DuplicateStateTransform);
            }
            let changed = source.schema != target.schema || source.version != target.version;
            let Some(transform) = matching.first().copied() else {
                if changed {
                    return Err(DefinitionError::MissingRequiredStateTransform);
                }
                continue;
            };
            if transform.source_schema() != &source.schema
                || transform.source_version() != source.version
                || transform.target_schema() != &target.schema
                || transform.target_version() != target.version
            {
                return Err(DefinitionError::StateTransformSchemaMismatch);
            }
        }
    }
    Ok(())
}

fn definition_durable_state_contracts(
    definition: &DefinitionIdentity,
    node_id: &NodeId,
) -> Result<Vec<DefinitionDurableStateContract>, DefinitionError> {
    let document: serde_json::Value = serde_json::from_slice(definition.canonical_manifest())
        .map_err(|_| DefinitionError::ManifestEncoding)?;
    if definition.manifest_format() == MANIFEST_FORMAT_ONE_STEP {
        let object = document
            .as_object()
            .ok_or(DefinitionError::ManifestEncoding)?;
        let step = object
            .get("step")
            .and_then(serde_json::Value::as_str)
            .ok_or(DefinitionError::ManifestEncoding)?;
        if step != node_id.as_str() {
            return Err(DefinitionError::UnknownUpgradeSourceNode);
        }
        return one_step_durable_state_contracts(object);
    }
    let node = find_definition_node(&document, node_id).ok_or(DefinitionError::ManifestEncoding)?;
    graph_node_durable_state_contracts(node)
}

fn one_step_durable_state_contracts(
    object: &serde_json::Map<String, serde_json::Value>,
) -> Result<Vec<DefinitionDurableStateContract>, DefinitionError> {
    if object.get("kind").and_then(serde_json::Value::as_str) != Some("chunk") {
        return Ok(Vec::new());
    }
    Ok(vec![
        schema_contract(
            DefinitionStateKind::Checkpoint,
            None,
            object
                .get("checkpoint")
                .ok_or(DefinitionError::ManifestEncoding)?,
            "schema",
        )?,
        schema_contract(
            DefinitionStateKind::ExecutionContext,
            None,
            object
                .get("context")
                .ok_or(DefinitionError::ManifestEncoding)?,
            "schema",
        )?,
    ])
}

fn graph_node_durable_state_contracts(
    node: &serde_json::Map<String, serde_json::Value>,
) -> Result<Vec<DefinitionDurableStateContract>, DefinitionError> {
    let mut contracts = Vec::new();
    match node.get("kind").and_then(serde_json::Value::as_str) {
        Some("step") => {
            let step = node
                .get("step")
                .and_then(serde_json::Value::as_object)
                .ok_or(DefinitionError::ManifestEncoding)?;
            if step.get("kind").and_then(serde_json::Value::as_str) == Some("chunk") {
                let declaration = step
                    .get("declaration")
                    .and_then(serde_json::Value::as_object)
                    .ok_or(DefinitionError::ManifestEncoding)?;
                contracts.push(schema_contract(
                    DefinitionStateKind::Checkpoint,
                    None,
                    declaration
                        .get("checkpoint")
                        .ok_or(DefinitionError::ManifestEncoding)?,
                    "schema",
                )?);
                contracts.push(schema_contract(
                    DefinitionStateKind::ExecutionContext,
                    None,
                    declaration
                        .get("context")
                        .ok_or(DefinitionError::ManifestEncoding)?,
                    "schema",
                )?);
            }
            if let Some(repeat) = node.get("repeat") {
                collect_repeat_state_contracts(repeat, &mut contracts)?;
            }
        }
        Some("custom_leaf") => {
            contracts.push(schema_contract(
                DefinitionStateKind::ExecutionContext,
                None,
                node.get("state_schema")
                    .ok_or(DefinitionError::ManifestEncoding)?,
                "id",
            )?);
        }
        _ => {}
    }
    Ok(contracts)
}

fn collect_repeat_state_contracts(
    repeat: &serde_json::Value,
    contracts: &mut Vec<DefinitionDurableStateContract>,
) -> Result<(), DefinitionError> {
    let object = repeat
        .as_object()
        .ok_or(DefinitionError::ManifestEncoding)?;
    let id = object
        .get("id")
        .and_then(serde_json::Value::as_str)
        .ok_or(DefinitionError::ManifestEncoding)?;
    contracts.push(schema_contract(
        DefinitionStateKind::Repeat,
        Some(id.to_owned()),
        object
            .get("state")
            .ok_or(DefinitionError::ManifestEncoding)?,
        "schema",
    )?);
    if let Some(nested) = object.get("nested") {
        collect_repeat_state_contracts(nested, contracts)?;
    }
    Ok(())
}

fn schema_contract(
    kind: DefinitionStateKind,
    state_id: Option<String>,
    value: &serde_json::Value,
    schema_key: &str,
) -> Result<DefinitionDurableStateContract, DefinitionError> {
    let object = value.as_object().ok_or(DefinitionError::ManifestEncoding)?;
    let schema = object
        .get(schema_key)
        .and_then(serde_json::Value::as_str)
        .ok_or(DefinitionError::ManifestEncoding)?;
    let version = object
        .get("version")
        .and_then(serde_json::Value::as_u64)
        .and_then(|value| u32::try_from(value).ok())
        .and_then(|value| StateSchemaVersion::new(value).ok())
        .ok_or(DefinitionError::ManifestEncoding)?;
    Ok(DefinitionDurableStateContract {
        kind,
        state_id,
        schema: StateSchemaId::new(schema).map_err(|_| DefinitionError::ManifestEncoding)?,
        version,
    })
}

fn find_definition_node<'a>(
    value: &'a serde_json::Value,
    node_id: &NodeId,
) -> Option<&'a serde_json::Map<String, serde_json::Value>> {
    match value {
        serde_json::Value::Object(object) => {
            let is_graph_node = matches!(
                object.get("kind").and_then(serde_json::Value::as_str),
                Some(
                    "step"
                        | "custom_leaf"
                        | "decision"
                        | "join"
                        | "split"
                        | "nested_flow"
                        | "nested_job"
                        | "partitioned_step"
                )
            );
            if is_graph_node
                && object.get("id").and_then(serde_json::Value::as_str) == Some(node_id.as_str())
            {
                return Some(object);
            }
            object
                .values()
                .find_map(|child| find_definition_node(child, node_id))
        }
        serde_json::Value::Array(values) => values
            .iter()
            .find_map(|child| find_definition_node(child, node_id)),
        _ => None,
    }
}

fn definition_upgrade_source_nodes(
    definition: &DefinitionIdentity,
) -> Result<BTreeSet<NodeId>, DefinitionError> {
    let document: serde_json::Value = serde_json::from_slice(definition.canonical_manifest())
        .map_err(|_| DefinitionError::ManifestEncoding)?;
    let object = document
        .as_object()
        .ok_or(DefinitionError::ManifestEncoding)?;
    if definition.manifest_format() == MANIFEST_FORMAT_ONE_STEP {
        let step = object
            .get("step")
            .and_then(serde_json::Value::as_str)
            .ok_or(DefinitionError::ManifestEncoding)?;
        return Ok(BTreeSet::from([NodeId::new(step)?]));
    }

    let nodes = object
        .get("nodes")
        .and_then(serde_json::Value::as_array)
        .ok_or(DefinitionError::ManifestEncoding)?;
    let mut result = BTreeSet::new();
    collect_upgrade_node_ids(nodes, &mut result)?;
    Ok(result)
}

fn collect_upgrade_node_ids(
    nodes: &[serde_json::Value],
    result: &mut BTreeSet<NodeId>,
) -> Result<(), DefinitionError> {
    for node in nodes {
        let object = node.as_object().ok_or(DefinitionError::ManifestEncoding)?;
        if let Some(id) = object.get("id").and_then(serde_json::Value::as_str) {
            result.insert(NodeId::new(id)?);
        }
        for key in ["members", "steps", "nodes"] {
            if let Some(children) = object.get(key).and_then(serde_json::Value::as_array) {
                collect_upgrade_node_ids(children, result)?;
            }
        }
        if let Some(branches) = object.get("branches").and_then(serde_json::Value::as_array) {
            for branch in branches {
                let branch = branch
                    .as_object()
                    .ok_or(DefinitionError::ManifestEncoding)?;
                for key in ["members", "steps", "nodes"] {
                    if let Some(children) = branch.get(key).and_then(serde_json::Value::as_array) {
                        collect_upgrade_node_ids(children, result)?;
                    }
                }
            }
        }
    }
    Ok(())
}

definition_token!(
    ComponentRevision,
    DefinitionTokenKind::Component,
    "An application-owned revision token for one opaque executable component."
);
definition_token!(
    ClassifierRevision,
    DefinitionTokenKind::Classifier,
    "An application-owned revision token for one bounded fault classifier."
);
definition_token!(
    ComponentStreamIdentity,
    DefinitionTokenKind::Component,
    "A stable, owner-scoped `ItemStream` namespace token.\n\nThis is the durable component-state namespace: it is never derived from a\ndisplay name, a memory address, or runtime object identity, and it\nparticipates in the restart-relevant chunk definition fingerprint alongside\nthe other component revisions."
);

/// Component revisions for a one-step chunk definition.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ChunkComponentRevisions {
    reader: ComponentRevision,
    processor: ComponentRevision,
    writer: ComponentRevision,
    checkpoint: ComponentRevision,
    restart: ChunkRestartContract,
    streams: BTreeMap<ComponentStreamIdentity, ComponentRevision>,
    completion_policy: Option<ComponentRevision>,
}

impl ChunkComponentRevisions {
    /// Constructs the four restart-relevant chunk component revisions.
    ///
    /// Registers no `ItemStream` namespaces and no completion-policy
    /// revision; use [`with_stream_revision`](Self::with_stream_revision) and
    /// [`with_completion_policy_revision`](Self::with_completion_policy_revision)
    /// to add them.
    #[must_use]
    pub const fn new(
        reader: ComponentRevision,
        processor: ComponentRevision,
        writer: ComponentRevision,
        checkpoint: ComponentRevision,
        restart: ChunkRestartContract,
    ) -> Self {
        Self {
            reader,
            processor,
            writer,
            checkpoint,
            restart,
            streams: BTreeMap::new(),
            completion_policy: None,
        }
    }

    /// Registers one `ItemStream` namespace's restart-relevant revision.
    ///
    /// Namespaces are kept in a deterministic (sorted, not insertion) order so
    /// the manifest and fingerprint never depend on registration order. A
    /// definition with no registered streams produces a manifest and
    /// fingerprint byte-for-byte identical to one built before this method
    /// existed.
    #[must_use]
    pub fn with_stream_revision(
        mut self,
        identity: ComponentStreamIdentity,
        revision: ComponentRevision,
    ) -> Self {
        self.streams.insert(identity, revision);
        self
    }

    /// Iterates registered `ItemStream` namespace revisions in deterministic
    /// (sorted) order.
    pub fn stream_revisions(
        &self,
    ) -> impl Iterator<Item = (&ComponentStreamIdentity, &ComponentRevision)> {
        self.streams.iter()
    }

    /// Records the restart-relevant revision of an installed
    /// [`crate::CompletionPolicy`](../../oxide_batch/trait.CompletionPolicy.html)
    /// (an early-completion policy supplementing the chunk's `ChunkSize`
    /// ceiling).
    ///
    /// A definition with no completion policy installed produces a manifest
    /// and fingerprint byte-for-byte identical to one built before this
    /// method existed.
    #[must_use]
    pub fn with_completion_policy_revision(mut self, revision: ComponentRevision) -> Self {
        self.completion_policy = Some(revision);
        self
    }

    /// Borrows the completion policy's restart-relevant revision, if one was
    /// registered.
    #[must_use]
    pub const fn completion_policy_revision(&self) -> Option<&ComponentRevision> {
        self.completion_policy.as_ref()
    }

    /// Returns the delivery mode declared by the restart contract.
    #[must_use]
    pub const fn delivery_mode(&self) -> ChunkDeliveryMode {
        self.restart.delivery_mode
    }

    /// Returns the shutdown policy of an already-open chunk.
    #[must_use]
    pub const fn in_flight_policy(&self) -> InFlightPolicy {
        self.restart.in_flight_policy
    }

    /// Borrows the revision of the component that reads items.
    #[must_use]
    pub const fn reader(&self) -> &ComponentRevision {
        &self.reader
    }

    /// Borrows the revision of the component that processes items.
    #[must_use]
    pub const fn processor(&self) -> &ComponentRevision {
        &self.processor
    }

    /// Borrows the revision of the component that writes items.
    #[must_use]
    pub const fn writer(&self) -> &ComponentRevision {
        &self.writer
    }

    /// Borrows the revision of the component that produces checkpoints.
    #[must_use]
    pub const fn checkpoint(&self) -> &ComponentRevision {
        &self.checkpoint
    }

    /// Borrows the declared checkpoint schema.
    #[must_use]
    pub const fn checkpoint_schema(&self) -> &StateSchemaId {
        &self.restart.checkpoint_schema
    }

    /// Returns the declared checkpoint schema version.
    #[must_use]
    pub const fn checkpoint_schema_version(&self) -> StateSchemaVersion {
        self.restart.checkpoint_schema_version
    }

    /// Borrows the declared execution-context schema.
    #[must_use]
    pub const fn context_schema(&self) -> &StateSchemaId {
        &self.restart.context_schema
    }

    /// Returns the declared execution-context schema version.
    #[must_use]
    pub const fn context_schema_version(&self) -> StateSchemaVersion {
        self.restart.context_schema_version
    }
}

/// The accepted shutdown behavior for an already-open chunk.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum InFlightPolicy {
    /// Complete and commit the open chunk, then stop at its boundary.
    #[default]
    FinishChunk,
    /// Roll back the open chunk and preserve the prior checkpoint.
    RollbackChunk,
}

/// Declared delivery boundary included in a chunk definition fingerprint.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ChunkDeliveryMode {
    /// Business writes and progress share one `PostgreSQL` transaction.
    AtomicSameResource,
    /// The resource may observe a duplicate after restart.
    AtLeastOnce,
}

impl ChunkDeliveryMode {
    /// Returns the stable name this mode is recorded under in a manifest.
    ///
    /// The name is durable: it is hashed into a definition fingerprint, so it
    /// is fixed for the life of the mode rather than a display string.
    #[must_use]
    pub const fn manifest_name(self) -> &'static str {
        match self {
            Self::AtomicSameResource => "atomic_same_resource",
            Self::AtLeastOnce => "at_least_once",
        }
    }
}

/// Restart-state schemas and delivery mode for a chunk definition.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ChunkRestartContract {
    checkpoint_schema: StateSchemaId,
    checkpoint_schema_version: StateSchemaVersion,
    context_schema: StateSchemaId,
    context_schema_version: StateSchemaVersion,
    delivery_mode: ChunkDeliveryMode,
    in_flight_policy: InFlightPolicy,
}

impl ChunkRestartContract {
    /// Constructs the restart-relevant state and delivery declaration.
    #[must_use]
    pub const fn new(
        checkpoint_schema: StateSchemaId,
        checkpoint_schema_version: StateSchemaVersion,
        context_schema: StateSchemaId,
        context_schema_version: StateSchemaVersion,
        delivery_mode: ChunkDeliveryMode,
    ) -> Self {
        Self {
            checkpoint_schema,
            checkpoint_schema_version,
            context_schema,
            context_schema_version,
            delivery_mode,
            in_flight_policy: InFlightPolicy::FinishChunk,
        }
    }

    /// Selects the restart-relevant open-chunk shutdown policy.
    #[must_use]
    pub const fn with_in_flight_policy(mut self, policy: InFlightPolicy) -> Self {
        self.in_flight_policy = policy;
        self
    }
}

/// Canonical restart-relevant identity persisted with every execution.
#[derive(Clone, Eq, PartialEq)]
pub struct DefinitionIdentity {
    job_name: Option<JobName>,
    revision: DefinitionRevision,
    manifest_format: u16,
    manifest_digest: [u8; 32],
    canonical_manifest: Box<[u8]>,
}

impl DefinitionIdentity {
    /// Builds the identity durable rows written before manifests carried one.
    ///
    /// The bytes are frozen: a durable row that predates manifest identity
    /// must keep resolving to exactly this value.
    #[must_use]
    pub fn legacy() -> Self {
        Self::from_canonical(
            None,
            DefinitionRevision(LEGACY_REVISION.to_owned()),
            LEGACY_MANIFEST.to_vec(),
            MANIFEST_FORMAT_ONE_STEP,
        )
    }

    /// Builds the canonical identity for a one-step tasklet definition.
    ///
    /// # Errors
    ///
    /// Returns [`DefinitionError::ManifestEncoding`] if the bounded canonical
    /// manifest cannot be encoded.
    pub fn tasklet(
        job_name: &JobName,
        step_name: &StepName,
        revision: DefinitionRevision,
        component_revision: &ComponentRevision,
    ) -> Result<Self, DefinitionError> {
        let manifest = json!({
            "component": {
                "tasklet": component_revision.as_str()
            },
            "delivery_mode": "best_effort",
            "format": MANIFEST_FORMAT_ONE_STEP,
            "job": job_name.as_str(),
            "kind": "tasklet",
            "restart_state": "none",
            "step": step_name.as_str(),
            "transaction_boundary": "tasklet_completion"
        });
        Self::encode(job_name.clone(), revision, &manifest)
    }

    /// Builds the canonical identity for a one-step chunk definition.
    ///
    /// # Errors
    ///
    /// Returns [`DefinitionError::ManifestEncoding`] if the bounded canonical
    /// manifest cannot be encoded.
    pub fn chunk(
        job_name: &JobName,
        step_name: &StepName,
        chunk_size: ChunkSize,
        revision: DefinitionRevision,
        components: &ChunkComponentRevisions,
    ) -> Result<Self, DefinitionError> {
        let mut manifest = json!({
            "chunk_size": chunk_size.get(),
            "components": {
                "checkpoint": components.checkpoint.as_str(),
                "processor": components.processor.as_str(),
                "reader": components.reader.as_str(),
                "writer": components.writer.as_str()
            },
            "context": {
                "schema": components.restart.context_schema.as_str(),
                "version": components.restart.context_schema_version.get()
            },
            "checkpoint": {
                "schema": components.restart.checkpoint_schema.as_str(),
                "version": components.restart.checkpoint_schema_version.get()
            },
            "delivery_mode": components.restart.delivery_mode.manifest_name(),
            "format": MANIFEST_FORMAT_ONE_STEP,
            "job": job_name.as_str(),
            "kind": "chunk",
            "step": step_name.as_str(),
            "transaction_boundary": "chunk"
        });
        if components.restart.in_flight_policy == InFlightPolicy::RollbackChunk
            && let Some(object) = manifest.as_object_mut()
        {
            object.insert(
                "in_flight_policy".to_owned(),
                serde_json::Value::String("rollback_chunk".to_owned()),
            );
        }
        if !components.streams.is_empty()
            && let Some(object) = manifest.as_object_mut()
        {
            let streams: Vec<serde_json::Value> = components
                .streams
                .iter()
                .map(|(identity, revision)| {
                    json!({
                        "identity": identity.as_str(),
                        "revision": revision.as_str(),
                    })
                })
                .collect();
            object.insert("streams".to_owned(), serde_json::Value::Array(streams));
        }
        if let Some(policy_revision) = &components.completion_policy
            && let Some(object) = manifest.as_object_mut()
        {
            object.insert(
                "completion_policy".to_owned(),
                serde_json::Value::String(policy_revision.as_str().to_owned()),
            );
        }
        Self::encode(job_name.clone(), revision, &manifest)
    }

    /// Builds the canonical identity for a compiled flow graph.
    ///
    /// The bytes must already be the canonical manifest the plan compiler
    /// normalized and encoded; this constructor validates, bounds, and hashes
    /// them. Taking bytes rather than a parsed document keeps the serializer
    /// out of this contract and makes the encoding the caller is responsible
    /// for explicit rather than implied.
    ///
    /// # Errors
    ///
    /// Returns [`DefinitionError::ManifestEncoding`] when the bytes exceed the
    /// bounded encoding, are not a canonical JSON object, or do not declare a
    /// supported flow manifest format.
    pub fn from_flow_manifest(
        job_name: &JobName,
        revision: DefinitionRevision,
        canonical: &[u8],
    ) -> Result<Self, DefinitionError> {
        if canonical.len() > MAX_MANIFEST_BYTES {
            return Err(DefinitionError::ManifestTooLarge {
                max_bytes: MAX_MANIFEST_BYTES,
            });
        }
        let document: serde_json::Value =
            serde_json::from_slice(canonical).map_err(|_| DefinitionError::ManifestEncoding)?;
        let reencoded =
            serde_json::to_vec(&document).map_err(|_| DefinitionError::ManifestEncoding)?;
        if !document.is_object() || reencoded != canonical {
            return Err(DefinitionError::ManifestEncoding);
        }
        let format = document
            .get("format")
            .and_then(serde_json::Value::as_u64)
            .and_then(|value| u16::try_from(value).ok())
            .filter(|value| {
                matches!(
                    *value,
                    MANIFEST_FORMAT_FLOW
                        | MANIFEST_FORMAT_LOCAL_SCALE
                        | MANIFEST_FORMAT_ADVANCED_FLOW
                )
            })
            .ok_or(DefinitionError::ManifestEncoding)?;

        Ok(Self::from_canonical(
            Some(job_name.clone()),
            revision,
            canonical.to_vec(),
            format,
        ))
    }

    /// Encodes a one-step manifest this crate composed itself.
    fn encode(
        job_name: JobName,
        revision: DefinitionRevision,
        manifest: &serde_json::Value,
    ) -> Result<Self, DefinitionError> {
        let canonical =
            serde_json::to_vec(manifest).map_err(|_| DefinitionError::ManifestEncoding)?;
        if canonical.len() > MAX_MANIFEST_BYTES {
            return Err(DefinitionError::ManifestTooLarge {
                max_bytes: MAX_MANIFEST_BYTES,
            });
        }
        Ok(Self::from_canonical(
            Some(job_name),
            revision,
            canonical,
            MANIFEST_FORMAT_ONE_STEP,
        ))
    }

    fn from_canonical(
        job_name: Option<JobName>,
        revision: DefinitionRevision,
        canonical: Vec<u8>,
        format: u16,
    ) -> Self {
        let digest: [u8; 32] = Sha256::digest(&canonical).into();
        Self {
            job_name,
            revision,
            manifest_format: format,
            manifest_digest: digest,
            canonical_manifest: canonical.into_boxed_slice(),
        }
    }

    /// Reconstructs and validates one exact durable definition identity.
    ///
    /// # Errors
    ///
    /// Fails closed when the manifest is unsupported, non-canonical, too large,
    /// declares a different format, or does not reproduce the stored digest.
    #[doc(hidden)]
    pub fn from_durable(
        job_name: JobName,
        revision: DefinitionRevision,
        manifest_format: u16,
        canonical: &[u8],
        expected_digest: [u8; 32],
    ) -> Result<Self, DefinitionError> {
        if canonical.len() > MAX_MANIFEST_BYTES {
            return Err(DefinitionError::ManifestTooLarge {
                max_bytes: MAX_MANIFEST_BYTES,
            });
        }
        check_manifest_format(manifest_format).map_err(|_| DefinitionError::ManifestEncoding)?;
        let document: serde_json::Value =
            serde_json::from_slice(canonical).map_err(|_| DefinitionError::ManifestEncoding)?;
        let reencoded =
            serde_json::to_vec(&document).map_err(|_| DefinitionError::ManifestEncoding)?;
        if !document.is_object()
            || reencoded != canonical
            || document.get("format").and_then(serde_json::Value::as_u64)
                != Some(u64::from(manifest_format))
        {
            return Err(DefinitionError::ManifestEncoding);
        }
        let identity = Self::from_canonical(
            Some(job_name),
            revision,
            canonical.to_vec(),
            manifest_format,
        );
        if identity.manifest_digest != expected_digest {
            return Err(DefinitionError::ManifestEncoding);
        }
        Ok(identity)
    }

    /// Borrows the application-owned definition revision.
    #[must_use]
    pub const fn revision(&self) -> &DefinitionRevision {
        &self.revision
    }

    /// Borrows the job name bound into a framework-produced manifest.
    ///
    /// Legacy direct repository calls use an internal compatibility manifest
    /// without a bound name.
    #[must_use]
    pub const fn job_name(&self) -> Option<&JobName> {
        self.job_name.as_ref()
    }

    /// Returns the canonical manifest format version.
    #[must_use]
    pub const fn manifest_format(&self) -> u16 {
        self.manifest_format
    }

    /// Returns the framework-produced SHA-256 manifest digest.
    #[must_use]
    pub const fn manifest_digest(&self) -> &[u8; 32] {
        &self.manifest_digest
    }

    /// Borrows the exact canonical manifest bytes that produced the digest.
    ///
    /// The manifest records names, logical identifiers, revisions, schema
    /// versions, and bounded policy values. Parameters, contexts, item values,
    /// credentials, endpoints, and component-private state are never encoded
    /// into it, so operators may inspect and archive these bytes.
    #[must_use]
    pub fn canonical_manifest(&self) -> &[u8] {
        &self.canonical_manifest
    }
}

/// Returns whether this runtime can interpret `format`.
///
/// # Errors
///
/// Returns [`ManifestError::UnsupportedFormat`] for a newer format and
/// [`ManifestError::MissingFormat`] for zero.
pub const fn check_manifest_format(format: u16) -> Result<(), ManifestError> {
    if format == 0 {
        return Err(ManifestError::MissingFormat);
    }
    if format > SUPPORTED_MANIFEST_FORMAT {
        return Err(ManifestError::UnsupportedFormat {
            format,
            supported: SUPPORTED_MANIFEST_FORMAT,
        });
    }
    Ok(())
}

impl fmt::Debug for DefinitionIdentity {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("DefinitionIdentity")
            .field("job_name", &self.job_name)
            .field("revision", &self.revision)
            .field("manifest_format", &self.manifest_format)
            .field(
                "digest_prefix",
                &DigestPrefix([
                    self.manifest_digest[0],
                    self.manifest_digest[1],
                    self.manifest_digest[2],
                    self.manifest_digest[3],
                ]),
            )
            .field("canonical_manifest", &"<redacted>")
            .finish()
    }
}

struct DigestPrefix([u8; 4]);

impl fmt::Debug for DigestPrefix {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in self.0 {
            write!(formatter, "{byte:02x}")?;
        }
        Ok(())
    }
}

/// A validated, read-only view of one canonical definition manifest.
///
/// The reader accepts every manifest format this runtime understands, so a
/// deployment can inspect a definition persisted by an older release. It never
/// guesses: a newer format, a non-canonical encoding, a floating-point value,
/// an out-of-bound graph, or a digest that does not match the supplied bytes
/// fails closed.
///
/// The runnable example lives in the `oxide-batch` facade documentation,
/// because the supported import path is `oxide_batch`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DefinitionManifest {
    format: u16,
    digest: [u8; 32],
    job_name: Option<JobName>,
    node_count: Option<usize>,
    transition_count: Option<usize>,
}

impl DefinitionManifest {
    /// Reads and validates canonical manifest bytes.
    ///
    /// # Errors
    ///
    /// Returns [`ManifestError`] when the bytes exceed the durable bound, are
    /// not a canonical JSON object, omit or overflow the format member, declare
    /// a format this runtime cannot interpret, contain a floating-point value,
    /// or describe a graph outside the accepted bounds.
    pub fn read(bytes: &[u8]) -> Result<Self, ManifestError> {
        if bytes.len() > MAX_MANIFEST_BYTES {
            return Err(ManifestError::TooLarge {
                max_bytes: MAX_MANIFEST_BYTES,
            });
        }
        let document: serde_json::Value =
            serde_json::from_slice(bytes).map_err(|_| ManifestError::MalformedJson)?;
        let members = document.as_object().ok_or(ManifestError::NotAnObject)?;
        if contains_float(&document) {
            return Err(ManifestError::FloatValue);
        }
        let reencoded = serde_json::to_vec(&document).map_err(|_| ManifestError::MalformedJson)?;
        if reencoded != bytes {
            return Err(ManifestError::NonCanonicalEncoding);
        }
        let format = members
            .get("format")
            .and_then(serde_json::Value::as_u64)
            .and_then(|format| u16::try_from(format).ok())
            .ok_or(ManifestError::MissingFormat)?;
        check_manifest_format(format)?;
        if format != MANIFEST_FORMAT_ADVANCED_FLOW
            && (members.contains_key("parameter_incrementer")
                || contains_object_key(&document, "restart_policy"))
        {
            return Err(ManifestError::MalformedGraph);
        }
        let job_name = members
            .get("job")
            .and_then(serde_json::Value::as_str)
            .map(JobName::new)
            .transpose()
            .map_err(|_| ManifestError::InvalidJobName)?;
        let (node_count, transition_count) = match format {
            MANIFEST_FORMAT_FLOW | MANIFEST_FORMAT_LOCAL_SCALE => {
                let nodes_value = members.get("nodes").ok_or(ManifestError::MalformedGraph)?;
                if contains_object_key(nodes_value, "repeat") {
                    return Err(ManifestError::MalformedGraph);
                }
                let nodes = array_len(Some(nodes_value))?;
                let transitions = array_len(members.get("transitions"))?;
                ensure_graph_bounds(nodes, transitions)?;
                (Some(nodes), Some(transitions))
            }
            MANIFEST_FORMAT_ADVANCED_FLOW => {
                validate_parameter_incrementer_manifest(members)?;
                validate_restart_policy_manifest(&document)?;
                let (nodes, transitions) = advanced_graph_counts(members)?;
                ensure_graph_bounds(nodes, transitions)?;
                if let Some(scoped) = members.get("scoped_components") {
                    let scoped = scoped.as_array().ok_or(ManifestError::MalformedGraph)?;
                    if scoped.is_empty() {
                        return Err(ManifestError::MalformedGraph);
                    }
                    let mut job_scoped = 0_usize;
                    let mut step_scoped = 0_usize;
                    for component in scoped {
                        let scope = component
                            .as_object()
                            .and_then(|object| object.get("scope"))
                            .and_then(serde_json::Value::as_str)
                            .ok_or(ManifestError::MalformedGraph)?;
                        let count = match scope {
                            "job" => &mut job_scoped,
                            "step" => &mut step_scoped,
                            _ => return Err(ManifestError::MalformedGraph),
                        };
                        *count += 1;
                        if *count > crate::MAX_SCOPED_COMPONENTS {
                            return Err(ManifestError::MalformedGraph);
                        }
                    }
                }
                validate_repeat_manifests(members)?;
                (Some(nodes), Some(transitions))
            }
            _ => (None, None),
        };
        Ok(Self {
            format,
            digest: Sha256::digest(bytes).into(),
            job_name,
            node_count,
            transition_count,
        })
    }

    /// Reads canonical bytes and requires them to hash to `expected`.
    ///
    /// # Errors
    ///
    /// Returns every [`ManifestError`] [`read`](Self::read) returns, plus
    /// [`ManifestError::DigestMismatch`] when the bytes were altered.
    pub fn read_verified(bytes: &[u8], expected: &[u8; 32]) -> Result<Self, ManifestError> {
        let manifest = Self::read(bytes)?;
        if &manifest.digest != expected {
            return Err(ManifestError::DigestMismatch);
        }
        Ok(manifest)
    }

    /// Returns the declared canonical manifest format.
    #[must_use]
    pub const fn format(&self) -> u16 {
        self.format
    }

    /// Returns the SHA-256 digest of the exact bytes that were read.
    #[must_use]
    pub const fn digest(&self) -> &[u8; 32] {
        &self.digest
    }

    /// Borrows the job name bound into the manifest, when present.
    #[must_use]
    pub const fn job_name(&self) -> Option<&JobName> {
        self.job_name.as_ref()
    }

    /// Returns the compiled node count of a flow manifest.
    #[must_use]
    pub const fn node_count(&self) -> Option<usize> {
        self.node_count
    }

    /// Returns the compiled transition count of a flow manifest.
    #[must_use]
    pub const fn transition_count(&self) -> Option<usize> {
        self.transition_count
    }
}

fn contains_object_key(value: &serde_json::Value, key: &str) -> bool {
    match value {
        serde_json::Value::Object(object) => object
            .iter()
            .any(|(member, value)| member == key || contains_object_key(value, key)),
        serde_json::Value::Array(values) => {
            values.iter().any(|value| contains_object_key(value, key))
        }
        _ => false,
    }
}

fn validate_parameter_incrementer_manifest(
    members: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), ManifestError> {
    let Some(value) = members.get("parameter_incrementer") else {
        return Ok(());
    };
    let object = value.as_object().ok_or(ManifestError::MalformedGraph)?;
    let required = ["kind", "revision"];
    if object.len() != required.len() || object.keys().any(|key| !required.contains(&key.as_str()))
    {
        return Err(ManifestError::MalformedGraph);
    }
    let kind = object
        .get("kind")
        .and_then(serde_json::Value::as_str)
        .ok_or(ManifestError::MalformedGraph)?;
    let revision = object
        .get("revision")
        .and_then(serde_json::Value::as_str)
        .ok_or(ManifestError::MalformedGraph)?;
    DefinitionRevision::new(kind).map_err(|_| ManifestError::MalformedGraph)?;
    DefinitionRevision::new(revision).map_err(|_| ManifestError::MalformedGraph)?;
    Ok(())
}

fn validate_restart_policy_manifest(document: &serde_json::Value) -> Result<(), ManifestError> {
    fn visit(value: &serde_json::Value, root: bool) -> Result<(), ManifestError> {
        match value {
            serde_json::Value::Object(object) => {
                if let Some(policy) = object.get("restart_policy") {
                    let is_start_controls = object.contains_key("start_limit")
                        && object.contains_key("allow_start_if_complete");
                    if (!root && !is_start_controls) || policy.as_str() != Some("not_restartable") {
                        return Err(ManifestError::MalformedGraph);
                    }
                }
                for child in object.values() {
                    visit(child, false)?;
                }
            }
            serde_json::Value::Array(values) => {
                for child in values {
                    visit(child, false)?;
                }
            }
            _ => {}
        }
        Ok(())
    }

    visit(document, true)
}

fn ensure_graph_bounds(nodes: usize, transitions: usize) -> Result<(), ManifestError> {
    if nodes > MAX_NODES || transitions > MAX_TRANSITIONS {
        return Err(ManifestError::GraphOutOfBounds {
            max_nodes: MAX_NODES,
            max_transitions: MAX_TRANSITIONS,
        });
    }
    Ok(())
}

fn advanced_graph_counts(
    members: &serde_json::Map<String, serde_json::Value>,
) -> Result<(usize, usize), ManifestError> {
    let nodes = members
        .get("nodes")
        .and_then(serde_json::Value::as_array)
        .ok_or(ManifestError::MalformedGraph)?;
    let transitions = array_len(members.get("transitions"))?;
    let mut materialized_nodes = nodes.len();
    let mut materialized_transitions = transitions;

    for node in nodes {
        let object = node.as_object().ok_or(ManifestError::MalformedGraph)?;
        match object.get("kind").and_then(serde_json::Value::as_str) {
            Some("step" | "decision" | "join") => {}
            Some("nested_job") => validate_nested_job_manifest(object)?,
            Some("partitioned_step") => {
                if !object
                    .get("worker")
                    .is_some_and(serde_json::Value::is_object)
                {
                    return Err(ManifestError::MalformedGraph);
                }
                materialized_nodes =
                    materialized_nodes
                        .checked_add(1)
                        .ok_or(ManifestError::GraphOutOfBounds {
                            max_nodes: MAX_NODES,
                            max_transitions: MAX_TRANSITIONS,
                        })?;
            }
            Some("split") => {
                let branches = object
                    .get("branches")
                    .and_then(serde_json::Value::as_array)
                    .ok_or(ManifestError::MalformedGraph)?;
                materialized_nodes = materialized_nodes.checked_add(branches.len()).ok_or(
                    ManifestError::GraphOutOfBounds {
                        max_nodes: MAX_NODES,
                        max_transitions: MAX_TRANSITIONS,
                    },
                )?;
                for branch in branches {
                    let branch = branch.as_object().ok_or(ManifestError::MalformedGraph)?;
                    match branch.get("kind").and_then(serde_json::Value::as_str) {
                        Some("linear") => {
                            materialized_nodes = materialized_nodes
                                .checked_add(array_len(branch.get("steps"))?)
                                .ok_or(ManifestError::GraphOutOfBounds {
                                    max_nodes: MAX_NODES,
                                    max_transitions: MAX_TRANSITIONS,
                                })?;
                        }
                        Some("flow") => {
                            if !branch
                                .get("members")
                                .is_some_and(serde_json::Value::is_array)
                                || branch
                                    .get("entry")
                                    .and_then(serde_json::Value::as_str)
                                    .is_none()
                            {
                                return Err(ManifestError::MalformedGraph);
                            }
                        }
                        _ => return Err(ManifestError::MalformedGraph),
                    }
                }
            }
            Some("nested_flow") => {
                let exits = array_len(object.get("exits"))?;
                if !object
                    .get("members")
                    .is_some_and(serde_json::Value::is_array)
                    || object
                        .get("entry")
                        .and_then(serde_json::Value::as_str)
                        .is_none()
                {
                    return Err(ManifestError::MalformedGraph);
                }
                materialized_transitions = materialized_transitions.checked_add(exits).ok_or(
                    ManifestError::GraphOutOfBounds {
                        max_nodes: MAX_NODES,
                        max_transitions: MAX_TRANSITIONS,
                    },
                )?;
            }
            _ => return Err(ManifestError::MalformedGraph),
        }
        ensure_graph_bounds(materialized_nodes, materialized_transitions)?;
    }

    Ok((materialized_nodes, materialized_transitions))
}

fn validate_repeat_manifests(
    members: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), ManifestError> {
    let nodes = members
        .get("nodes")
        .and_then(serde_json::Value::as_array)
        .ok_or(ManifestError::MalformedGraph)?;
    let mut repeat_ids = BTreeSet::new();
    for node in nodes {
        validate_node_repeat(node, &mut repeat_ids)?;
    }
    Ok(())
}

fn validate_node_repeat(
    node: &serde_json::Value,
    repeat_ids: &mut BTreeSet<String>,
) -> Result<(), ManifestError> {
    let object = node.as_object().ok_or(ManifestError::MalformedGraph)?;
    let kind = object.get("kind").and_then(serde_json::Value::as_str);
    if kind != Some("step") && object.contains_key("repeat") {
        return Err(ManifestError::MalformedGraph);
    }
    match kind {
        Some("step") => {
            if let Some(repeat) = object.get("repeat") {
                validate_repeat_definition(repeat, repeat_ids, 1)?;
            }
        }
        Some("partitioned_step") => {
            validate_node_repeat(
                object.get("worker").ok_or(ManifestError::MalformedGraph)?,
                repeat_ids,
            )?;
        }
        Some("split") => {
            let branches = object
                .get("branches")
                .and_then(serde_json::Value::as_array)
                .ok_or(ManifestError::MalformedGraph)?;
            for branch in branches {
                let branch = branch.as_object().ok_or(ManifestError::MalformedGraph)?;
                if branch.get("kind").and_then(serde_json::Value::as_str) == Some("linear") {
                    let steps = branch
                        .get("steps")
                        .and_then(serde_json::Value::as_array)
                        .ok_or(ManifestError::MalformedGraph)?;
                    for step in steps {
                        validate_node_repeat(step, repeat_ids)?;
                    }
                }
            }
        }
        _ => {}
    }
    Ok(())
}

fn validate_repeat_definition(
    value: &serde_json::Value,
    repeat_ids: &mut BTreeSet<String>,
    depth: usize,
) -> Result<(), ManifestError> {
    if depth > MAX_REPEAT_NESTING_DEPTH {
        return Err(ManifestError::MalformedGraph);
    }
    let object = value.as_object().ok_or(ManifestError::MalformedGraph)?;
    let allowed = ["id", "interceptors", "nested", "policy", "state"];
    if object.keys().any(|key| !allowed.contains(&key.as_str())) {
        return Err(ManifestError::MalformedGraph);
    }
    let id = object
        .get("id")
        .and_then(serde_json::Value::as_str)
        .ok_or(ManifestError::MalformedGraph)?;
    validate_token(id, DefinitionTokenKind::Repeat).map_err(|_| ManifestError::MalformedGraph)?;
    if !repeat_ids.insert(id.to_owned()) {
        return Err(ManifestError::MalformedGraph);
    }
    validate_repeat_policy(object.get("policy").ok_or(ManifestError::MalformedGraph)?)?;
    validate_repeat_state(object.get("state").ok_or(ManifestError::MalformedGraph)?)?;
    let interceptors = object
        .get("interceptors")
        .and_then(serde_json::Value::as_array)
        .ok_or(ManifestError::MalformedGraph)?;
    if interceptors.len() > MAX_REPEAT_INTERCEPTORS {
        return Err(ManifestError::MalformedGraph);
    }
    let mut interceptor_ids = BTreeSet::new();
    for interceptor in interceptors {
        validate_repeat_interceptor(interceptor, &mut interceptor_ids)?;
    }
    if let Some(nested) = object.get("nested") {
        validate_repeat_definition(nested, repeat_ids, depth.saturating_add(1))?;
    }
    Ok(())
}

fn validate_repeat_policy(value: &serde_json::Value) -> Result<(), ManifestError> {
    let object = value.as_object().ok_or(ManifestError::MalformedGraph)?;
    let required = ["configuration", "kind", "revision"];
    if object.len() != required.len() || object.keys().any(|key| !required.contains(&key.as_str()))
    {
        return Err(ManifestError::MalformedGraph);
    }
    let configuration = object
        .get("configuration")
        .and_then(serde_json::Value::as_str)
        .ok_or(ManifestError::MalformedGraph)?;
    validate_token(configuration, DefinitionTokenKind::RepeatPolicy)
        .map_err(|_| ManifestError::MalformedGraph)?;
    let kind = object
        .get("kind")
        .and_then(serde_json::Value::as_str)
        .ok_or(ManifestError::MalformedGraph)?;
    validate_token(kind, DefinitionTokenKind::RepeatPolicy)
        .map_err(|_| ManifestError::MalformedGraph)?;
    let revision = object
        .get("revision")
        .and_then(serde_json::Value::as_str)
        .ok_or(ManifestError::MalformedGraph)?;
    ComponentRevision::new(revision.to_owned()).map_err(|_| ManifestError::MalformedGraph)?;
    Ok(())
}

fn validate_repeat_interceptor(
    value: &serde_json::Value,
    ids: &mut BTreeSet<String>,
) -> Result<(), ManifestError> {
    let object = value.as_object().ok_or(ManifestError::MalformedGraph)?;
    let required = ["id", "kind", "revision"];
    if object.len() != required.len() || object.keys().any(|key| !required.contains(&key.as_str()))
    {
        return Err(ManifestError::MalformedGraph);
    }
    let id = object
        .get("id")
        .and_then(serde_json::Value::as_str)
        .ok_or(ManifestError::MalformedGraph)?;
    validate_token(id, DefinitionTokenKind::RepeatInterceptor)
        .map_err(|_| ManifestError::MalformedGraph)?;
    if !ids.insert(id.to_owned()) {
        return Err(ManifestError::MalformedGraph);
    }
    let kind = object
        .get("kind")
        .and_then(serde_json::Value::as_str)
        .ok_or(ManifestError::MalformedGraph)?;
    validate_token(kind, DefinitionTokenKind::RepeatInterceptor)
        .map_err(|_| ManifestError::MalformedGraph)?;
    let revision = object
        .get("revision")
        .and_then(serde_json::Value::as_str)
        .ok_or(ManifestError::MalformedGraph)?;
    ComponentRevision::new(revision.to_owned()).map_err(|_| ManifestError::MalformedGraph)?;
    Ok(())
}

fn validate_repeat_state(value: &serde_json::Value) -> Result<(), ManifestError> {
    let object = value.as_object().ok_or(ManifestError::MalformedGraph)?;
    let required = ["schema", "version"];
    if object.len() != required.len() || object.keys().any(|key| !required.contains(&key.as_str()))
    {
        return Err(ManifestError::MalformedGraph);
    }
    let schema = object
        .get("schema")
        .and_then(serde_json::Value::as_str)
        .ok_or(ManifestError::MalformedGraph)?;
    StateSchemaId::new(schema.to_owned()).map_err(|_| ManifestError::MalformedGraph)?;
    let version = object
        .get("version")
        .and_then(serde_json::Value::as_u64)
        .and_then(|value| u32::try_from(value).ok())
        .ok_or(ManifestError::MalformedGraph)?;
    StateSchemaVersion::new(version).map_err(|_| ManifestError::MalformedGraph)?;
    Ok(())
}
fn validate_nested_job_manifest(
    object: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), ManifestError> {
    if !object
        .get("child")
        .is_some_and(serde_json::Value::is_object)
        || !object
            .get("parameters")
            .is_some_and(serde_json::Value::is_array)
        || object
            .get("mapping_revision")
            .and_then(serde_json::Value::as_str)
            .is_none()
    {
        return Err(ManifestError::MalformedGraph);
    }
    Ok(())
}

fn array_len(value: Option<&serde_json::Value>) -> Result<usize, ManifestError> {
    value
        .and_then(serde_json::Value::as_array)
        .map(Vec::len)
        .ok_or(ManifestError::MalformedGraph)
}

fn contains_float(value: &serde_json::Value) -> bool {
    match value {
        serde_json::Value::Number(number) => number.as_i64().is_none() && number.as_u64().is_none(),
        serde_json::Value::Array(values) => values.iter().any(contains_float),
        serde_json::Value::Object(members) => members.values().any(contains_float),
        _ => false,
    }
}

/// A canonical definition manifest that cannot be interpreted.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ManifestError {
    /// The bytes exceeded the durable manifest bound.
    TooLarge {
        /// Maximum accepted byte length.
        max_bytes: usize,
    },
    /// The bytes are not valid JSON.
    MalformedJson,
    /// The document is not a JSON object.
    NotAnObject,
    /// Re-encoding the document did not reproduce the supplied bytes.
    NonCanonicalEncoding,
    /// The document contains a floating-point number.
    FloatValue,
    /// The format member is absent or not a `u16`.
    MissingFormat,
    /// The manifest is newer than this runtime understands.
    UnsupportedFormat {
        /// Format found in the manifest.
        format: u16,
        /// Newest format this runtime interprets.
        supported: u16,
    },
    /// A flow manifest omitted or malformed its graph members.
    MalformedGraph,
    /// A flow manifest declared a graph larger than this runtime accepts.
    GraphOutOfBounds {
        /// Maximum accepted node count.
        max_nodes: usize,
        /// Maximum accepted transition count.
        max_transitions: usize,
    },
    /// The bound job name is not a valid [`JobName`].
    InvalidJobName,
    /// The bytes do not hash to the expected fingerprint.
    DigestMismatch,
}

impl fmt::Display for ManifestError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TooLarge { max_bytes } => {
                write!(formatter, "definition manifest exceeds {max_bytes} bytes")
            }
            Self::MalformedJson => formatter.write_str("definition manifest is not valid JSON"),
            Self::NotAnObject => formatter.write_str("definition manifest is not a JSON object"),
            Self::NonCanonicalEncoding => {
                formatter.write_str("definition manifest is not canonically encoded")
            }
            Self::FloatValue => {
                formatter.write_str("definition manifest contains a floating-point value")
            }
            Self::MissingFormat => {
                formatter.write_str("definition manifest has no usable format member")
            }
            Self::UnsupportedFormat { format, supported } => write!(
                formatter,
                "definition manifest format {format} is newer than the supported format {supported}"
            ),
            Self::MalformedGraph => {
                formatter.write_str("flow manifest has no readable node and transition members")
            }
            Self::GraphOutOfBounds {
                max_nodes,
                max_transitions,
            } => write!(
                formatter,
                "flow manifest exceeds {max_nodes} nodes or {max_transitions} transitions"
            ),
            Self::InvalidJobName => {
                formatter.write_str("definition manifest binds an invalid job name")
            }
            Self::DigestMismatch => {
                formatter.write_str("definition manifest does not match its fingerprint")
            }
        }
    }
}

impl Error for ManifestError {}

/// Definition token category used by validation diagnostics.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DefinitionTokenKind {
    /// Definition revision.
    Revision,
    /// Opaque component revision.
    Component,
    /// Executable artifact identity.
    Artifact,
    /// Directed compatibility edge key.
    Upgrade,
    /// Bounded fault-classifier revision.
    Classifier,
    /// Stable flow-graph node identifier.
    Node,
    /// Bounded decider revision.
    Decider,
    /// Stable repeat definition identity.
    Repeat,
    /// Repeat policy kind or configuration identity.
    RepeatPolicy,
    /// Repeat interceptor registration or kind identity.
    RepeatInterceptor,
}

/// Failure to construct a bounded restart definition.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DefinitionError {
    /// A start limit of zero can never start its step.
    ZeroStartLimit,
    /// A required token was empty.
    EmptyToken {
        /// Rejected token category.
        kind: DefinitionTokenKind,
    },
    /// A token exceeded its UTF-8 byte bound.
    TokenTooLong {
        /// Rejected token category.
        kind: DefinitionTokenKind,
        /// Maximum accepted byte length.
        max_bytes: usize,
    },
    /// A token had leading or trailing whitespace.
    SurroundingWhitespace {
        /// Rejected token category.
        kind: DefinitionTokenKind,
    },
    /// A token contained a control character.
    ControlCharacter {
        /// Rejected token category.
        kind: DefinitionTokenKind,
    },
    /// The canonical manifest could not be encoded.
    ManifestEncoding,
    /// The canonical manifest exceeded its durable bound.
    ManifestTooLarge {
        /// Maximum accepted byte length.
        max_bytes: usize,
    },
    /// A directed edge pointed from a definition to itself.
    UpgradeSelfEdge,
    /// A directed edge omitted its durable step mapping.
    EmptyStepMapping,
    /// A source step appeared more than once.
    DuplicateSourceStep,
    /// Two source steps mapped to the same target step.
    DuplicateTargetStep,
    /// A transformed edge exceeded its durable source-node bound.
    TooManyUpgradeNodes {
        /// Maximum accepted mapped source nodes.
        max: usize,
    },
    /// A transformed edge exceeded its state-transform declaration bound.
    TooManyUpgradeTransforms {
        /// Maximum accepted state-transform declarations.
        max: usize,
    },
    /// A durable source node appeared more than once.
    DuplicateSourceNode,
    /// Two durable source nodes mapped to the same target node.
    DuplicateTargetNode,
    /// The same state-family member was declared more than once.
    DuplicateStateTransform,
    /// A state transform named a source/target pair outside the node mapping.
    StateTransformOutsideNodeMapping,
    /// A mapping named a source node absent from the source definition.
    UnknownUpgradeSourceNode,
    /// A durable source definition node had no explicit target mapping.
    MissingUpgradeSourceNode,
    /// A mapping named a target node absent from the target definition.
    UnknownUpgradeTargetNode,
    /// A durable source state family has no matching target contract.
    MissingTargetStateContract,
    /// A changed durable schema has no explicit transform declaration.
    MissingRequiredStateTransform,
    /// A declared transform disagrees with source/target manifest schemas.
    StateTransformSchemaMismatch,
    /// A legacy M2 identity-only edge cannot execute an M7 compatible restart.
    LegacyUpgradeExecution,
    /// Two live state transformer implementations reused one revision.
    DuplicateStateTransformer,
    /// Live transformer revisions did not exactly match the durable descriptor.
    StateTransformerSetMismatch,
    /// A step's fault runtime declared a different delivery mode than its
    /// restart contract.
    DeliveryModeMismatch,
    /// A one-step wrapper could not be lowered into its compatibility plan.
    ///
    /// The framework derives the compatibility graph from values it has
    /// already validated, so this variant reports a framework invariant rather
    /// than an application mistake.
    CompatibilityLowering,
    /// A runtime `ItemStream` was registered under a namespace this
    /// definition's [`ChunkComponentRevisions`] does not declare.
    RuntimeStreamNotDeclared {
        /// The undeclared runtime namespace.
        namespace: ComponentStreamIdentity,
    },
    /// A declared stream revision has no matching runtime `ItemStream`
    /// registration.
    DeclaredStreamMissingRuntime {
        /// The declared namespace with no runtime registration.
        namespace: ComponentStreamIdentity,
    },
    /// The same namespace was registered as a runtime `ItemStream` more than
    /// once.
    DuplicateRuntimeStream {
        /// The namespace registered more than once.
        namespace: ComponentStreamIdentity,
    },
    /// A registered `ItemStream` declares
    /// [`RestartabilityDeclaration::NotRestartable`](crate::RestartabilityDeclaration::NotRestartable),
    /// which prevents its owning chunk step from claiming restartability
    /// regardless of reader-checkpoint presence.
    NonRestartableStream {
        /// The namespace whose stream cannot honestly claim restartability.
        namespace: ComponentStreamIdentity,
    },
    /// An installed completion policy's `fingerprint()` panicked while its
    /// configuration was being folded into the chunk definition's
    /// restart-relevant revisions.
    ///
    /// `fingerprint()` is an application-supplied callback (every built-in
    /// policy's own implementation cannot panic), so a definition cannot be
    /// constructed from one that does -- this is reported the same way any
    /// other definition-construction failure is, rather than unwinding out
    /// of a constructor with a `Result` return type.
    CompletionPolicyFingerprintPanic,
    /// A custom completion policy did not provide restart-relevant identity.
    CompletionPolicyFingerprintMissing,
    /// A chunk step's live completion-policy fingerprint does not match the
    /// completion-policy revision already declared in the
    /// [`ChunkComponentRevisions`] a compiled flow node was bound against.
    ///
    /// Unlike a standalone chunk job (which builds its compiled plan and
    /// runtime step from the same call, so it can fold a completion
    /// policy's fingerprint in automatically), a flow node is bound to a
    /// plan that was already compiled from bare `ChunkComponentRevisions`
    /// -- before any concrete step, or its installed policy, existed. The
    /// caller must declare the matching revision up front (the same way a
    /// stream revision is declared up front and validated against its
    /// runtime registration) rather than relying on it being computed
    /// automatically.
    CompletionPolicyRevisionMismatch,
}

impl fmt::Display for DefinitionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ZeroStartLimit => formatter.write_str("start limit must be nonzero"),
            Self::EmptyToken { kind } => write!(formatter, "{kind:?} token must not be empty"),
            Self::TokenTooLong { kind, max_bytes } => {
                write!(formatter, "{kind:?} token exceeds {max_bytes} bytes")
            }
            Self::SurroundingWhitespace { kind } => {
                write!(formatter, "{kind:?} token has surrounding whitespace")
            }
            Self::ControlCharacter { kind } => {
                write!(formatter, "{kind:?} token contains a control character")
            }
            Self::ManifestEncoding => formatter.write_str("definition manifest encoding failed"),
            Self::ManifestTooLarge { max_bytes } => {
                write!(formatter, "definition manifest exceeds {max_bytes} bytes")
            }
            Self::UpgradeSelfEdge => formatter.write_str("definition upgrade is a self-edge"),
            Self::EmptyStepMapping => formatter.write_str("definition upgrade has no step mapping"),
            Self::DuplicateSourceStep => {
                formatter.write_str("definition upgrade repeats a source step")
            }
            Self::DuplicateTargetStep => {
                formatter.write_str("definition upgrade reuses a target step")
            }
            Self::TooManyUpgradeNodes { max } => {
                write!(
                    formatter,
                    "definition upgrade exceeds {max} mapped source nodes"
                )
            }
            Self::TooManyUpgradeTransforms { max } => {
                write!(
                    formatter,
                    "definition upgrade exceeds {max} state transforms"
                )
            }
            Self::DuplicateSourceNode => {
                formatter.write_str("definition upgrade repeats a durable source node")
            }
            Self::DuplicateTargetNode => {
                formatter.write_str("definition upgrade reuses a durable target node")
            }
            Self::DuplicateStateTransform => {
                formatter.write_str("definition upgrade repeats a state transform")
            }
            Self::StateTransformOutsideNodeMapping => {
                formatter.write_str("definition state transform is outside the node mapping")
            }
            Self::UnknownUpgradeSourceNode => {
                formatter.write_str("definition upgrade maps an unknown source node")
            }
            Self::MissingUpgradeSourceNode => {
                formatter.write_str("definition upgrade omits a durable source node")
            }
            Self::UnknownUpgradeTargetNode => {
                formatter.write_str("definition upgrade maps to an unknown target node")
            }
            Self::MissingTargetStateContract => {
                formatter.write_str("definition upgrade drops a durable source state contract")
            }
            Self::MissingRequiredStateTransform => {
                formatter.write_str("definition upgrade omits a required state schema transform")
            }
            Self::StateTransformSchemaMismatch => {
                formatter.write_str("definition state transform disagrees with manifest schemas")
            }
            Self::LegacyUpgradeExecution => formatter
                .write_str("legacy definition upgrade has no transformed execution contract"),
            Self::DuplicateStateTransformer => {
                formatter.write_str("definition upgrade repeats a live state transformer revision")
            }
            Self::StateTransformerSetMismatch => formatter
                .write_str("definition upgrade live transformer set does not match metadata"),
            Self::DeliveryModeMismatch => formatter
                .write_str("fault runtime and restart contract declare different delivery modes"),
            Self::CompatibilityLowering => {
                formatter.write_str("one-step compatibility lowering produced an invalid plan")
            }
            Self::RuntimeStreamNotDeclared { namespace } => write!(
                formatter,
                "runtime ItemStream namespace {:?} is not declared in the chunk definition",
                namespace.as_str()
            ),
            Self::DeclaredStreamMissingRuntime { namespace } => write!(
                formatter,
                "declared stream namespace {:?} has no registered runtime ItemStream",
                namespace.as_str()
            ),
            Self::DuplicateRuntimeStream { namespace } => write!(
                formatter,
                "runtime ItemStream namespace {:?} was registered more than once",
                namespace.as_str()
            ),
            Self::NonRestartableStream { namespace } => write!(
                formatter,
                "ItemStream namespace {:?} declares NotRestartable, so this step cannot claim restartability",
                namespace.as_str()
            ),
            Self::CompletionPolicyFingerprintPanic => {
                formatter.write_str("completion policy fingerprint() panicked")
            }
            Self::CompletionPolicyFingerprintMissing => formatter
                .write_str("custom completion policy must provide a restart-relevant fingerprint"),
            Self::CompletionPolicyRevisionMismatch => formatter.write_str(
                "the step's live completion-policy fingerprint does not match the \
                 completion-policy revision declared in the bound component revisions",
            ),
        }
    }
}

impl Error for DefinitionError {}