oxide-batch-repository 0.5.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
//! Repository, clock, identifier, and unit-of-work contracts.

use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;
use std::future::Future;
use std::num::NonZeroU64;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::SystemTime;

use oxide_batch_core::{
    BatchStatus, DefinitionIdentity, DefinitionRevision, DefinitionUpgrade, DomainError,
    ExecutionMetadata, ExecutionTimestamps, ExecutionVersion, ExitStatus, FailureCategory,
    FailureId, FailureSummary, IdentifierKind, JobExecution, JobExecutionId, JobInstance,
    JobInstanceId, JobInstanceKey, JobName, LifecycleError, LifecycleTransition, NodeId,
    RecoveryDecisionId, StartLimit, StepExecution, StepExecutionId, StepName, StepPartitionId,
};

use crate::{
    ActorRef, FlowDecision, FlowDecisionRequest, FlowStepState, FlowTransitionKind, OperationId,
    OperatorAction, OperatorRecord, OperatorRecordDraft, OwnerToken, PartitionAggregate,
    PartitionAggregationError, PartitionPlanEntry, PurgeCounts, PurgePlan, PurgePlanRequest,
    PurgeSurvey, ReasonCode, RetentionAction, RetentionHold, RetentionRecord, RetentionRecordDraft,
    StepPartition,
};

const MAX_RECOVERY_REASON_BYTES: usize = 64;
const MAX_OPERATOR_REFERENCE_BYTES: usize = 128;

/// An owned, dynamically dispatched future used by public asynchronous ports.
///
/// The alias is runtime-neutral: callers may poll it with Tokio or another
/// compatible executor, and repository implementations need not expose their
/// executor or database-driver types.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

/// Supplies instants to repository and runtime operations.
///
/// Implementations must be thread-safe. Test clocks should return controlled
/// instants rather than consulting wall-clock time.
pub trait Clock: Send + Sync {
    /// Returns the current instant.
    fn now(&self) -> SystemTime;
}

/// An explicitly injected wall-clock implementation.
#[derive(Clone, Copy, Debug, Default)]
pub struct SystemClock;

impl Clock for SystemClock {
    fn now(&self) -> SystemTime {
        SystemTime::now()
    }
}

/// Supplies facade-owned opaque identifiers.
///
/// One generator may use a shared sequence for all identifier kinds or
/// independent sequences. Implementations must never return zero.
pub trait IdGenerator: Send + Sync {
    /// Returns the next job-instance identifier.
    ///
    /// # Errors
    ///
    /// Returns [`IdGenerationError`] when the source is exhausted or produces
    /// an invalid value.
    fn next_job_instance_id(&self) -> Result<JobInstanceId, IdGenerationError>;

    /// Returns the next job-execution identifier.
    ///
    /// # Errors
    ///
    /// Returns [`IdGenerationError`] when the source is exhausted or produces
    /// an invalid value.
    fn next_job_execution_id(&self) -> Result<JobExecutionId, IdGenerationError>;

    /// Returns the next step-execution identifier.
    ///
    /// # Errors
    ///
    /// Returns [`IdGenerationError`] when the source is exhausted or produces
    /// an invalid value.
    fn next_step_execution_id(&self) -> Result<StepExecutionId, IdGenerationError>;

    /// Returns the next opaque failure-correlation identifier.
    ///
    /// # Errors
    ///
    /// Returns [`IdGenerationError`] when the source is exhausted or produces
    /// an invalid value.
    fn next_failure_id(&self) -> Result<FailureId, IdGenerationError>;
}

/// A thread-safe nonzero identifier sequence suitable for local execution.
///
/// The sequence is deterministic for a given call order. A single sequence is
/// shared by all identifier kinds so generated values cannot collide when
/// records are inspected together.
#[derive(Debug)]
pub struct SequentialIdGenerator {
    next: AtomicU64,
}

impl SequentialIdGenerator {
    /// Constructs a sequence whose first returned value is `first`.
    #[must_use]
    pub const fn new(first: NonZeroU64) -> Self {
        Self {
            next: AtomicU64::new(first.get()),
        }
    }

    fn next_raw(&self, kind: IdentifierKind) -> Result<u64, IdGenerationError> {
        self.next
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
                if current == 0 {
                    None
                } else {
                    Some(current.checked_add(1).unwrap_or(0))
                }
            })
            .map_err(|_| IdGenerationError::Exhausted { kind })
    }
}

impl IdGenerator for SequentialIdGenerator {
    fn next_job_instance_id(&self) -> Result<JobInstanceId, IdGenerationError> {
        JobInstanceId::new(self.next_raw(IdentifierKind::JobInstance)?)
            .map_err(IdGenerationError::Invalid)
    }

    fn next_job_execution_id(&self) -> Result<JobExecutionId, IdGenerationError> {
        JobExecutionId::new(self.next_raw(IdentifierKind::JobExecution)?)
            .map_err(IdGenerationError::Invalid)
    }

    fn next_step_execution_id(&self) -> Result<StepExecutionId, IdGenerationError> {
        StepExecutionId::new(self.next_raw(IdentifierKind::StepExecution)?)
            .map_err(IdGenerationError::Invalid)
    }

    fn next_failure_id(&self) -> Result<FailureId, IdGenerationError> {
        FailureId::new(self.next_raw(IdentifierKind::Failure)?).map_err(IdGenerationError::Invalid)
    }
}

/// Failure from an injected identifier source.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum IdGenerationError {
    /// The source cannot issue another identifier of this kind.
    Exhausted {
        /// The identifier category that was requested.
        kind: IdentifierKind,
    },
    /// The source produced a value that violated a domain invariant.
    Invalid(DomainError),
}

impl fmt::Display for IdGenerationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Exhausted { kind } => write!(formatter, "{kind} identifier source is exhausted"),
            Self::Invalid(error) => write!(formatter, "generated identifier was invalid: {error}"),
        }
    }
}

impl Error for IdGenerationError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Invalid(error) => Some(error),
            Self::Exhausted { .. } => None,
        }
    }
}

/// The result of selecting the canonical instance for an identifying key.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum JobInstanceSelection {
    /// This unit of work created the logical instance.
    Created(JobInstance),
    /// The logical instance already existed.
    Existing(JobInstance),
}

impl JobInstanceSelection {
    /// Borrows the selected instance regardless of whether it was created.
    #[must_use]
    pub const fn instance(&self) -> &JobInstance {
        match self {
            Self::Created(instance) | Self::Existing(instance) => instance,
        }
    }

    /// Returns whether the instance was created by this operation.
    #[must_use]
    pub const fn was_created(&self) -> bool {
        matches!(self, Self::Created(_))
    }
}

/// Explicit operator disposition for an orphaned or ambiguous execution.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RecoveryDisposition {
    /// Make the observed attempt restart-eligible.
    MarkFailed,
    /// Make the logical instance permanently non-restartable.
    Abandon,
}

impl RecoveryDisposition {
    /// Returns the durable status produced by this disposition.
    #[must_use]
    pub const fn resulting_status(self) -> BatchStatus {
        match self {
            Self::MarkFailed => BatchStatus::Failed,
            Self::Abandon => BatchStatus::Abandoned,
        }
    }
}

/// Bounded, value-redacted request for one audited recovery decision.
#[derive(Clone, Eq, PartialEq)]
pub struct RecoveryRequest {
    expected_version: ExecutionVersion,
    disposition: RecoveryDisposition,
    reason_code: String,
    operator_reference: String,
    evidence_digest: [u8; 32],
    failure: Option<FailureSummary>,
}

impl RecoveryRequest {
    /// Validates a request that makes an observed execution restart-eligible.
    ///
    /// Authentication and authorization remain deployment responsibilities;
    /// `operator_reference` is an opaque audit correlation, not a credential.
    ///
    /// # Errors
    ///
    /// Rejects empty, oversized, whitespace-padded, or control-containing
    /// reason and operator values.
    pub fn mark_failed(
        expected_version: ExecutionVersion,
        reason_code: impl Into<String>,
        operator_reference: impl Into<String>,
        evidence_digest: [u8; 32],
        failure_category: FailureCategory,
        failure_id: FailureId,
    ) -> Result<Self, RecoveryRequestError> {
        Self::new(
            expected_version,
            RecoveryDisposition::MarkFailed,
            reason_code,
            operator_reference,
            evidence_digest,
            Some(FailureSummary::new(failure_category, failure_id)),
        )
    }

    /// Validates a request that permanently abandons the logical instance.
    ///
    /// # Errors
    ///
    /// Rejects empty, oversized, whitespace-padded, or control-containing
    /// reason and operator values.
    pub fn abandon(
        expected_version: ExecutionVersion,
        reason_code: impl Into<String>,
        operator_reference: impl Into<String>,
        evidence_digest: [u8; 32],
    ) -> Result<Self, RecoveryRequestError> {
        Self::new(
            expected_version,
            RecoveryDisposition::Abandon,
            reason_code,
            operator_reference,
            evidence_digest,
            None,
        )
    }

    fn new(
        expected_version: ExecutionVersion,
        disposition: RecoveryDisposition,
        reason_code: impl Into<String>,
        operator_reference: impl Into<String>,
        evidence_digest: [u8; 32],
        failure: Option<FailureSummary>,
    ) -> Result<Self, RecoveryRequestError> {
        let reason_code = reason_code.into();
        validate_recovery_text(
            &reason_code,
            RecoveryField::ReasonCode,
            MAX_RECOVERY_REASON_BYTES,
        )?;
        let operator_reference = operator_reference.into();
        validate_recovery_text(
            &operator_reference,
            RecoveryField::OperatorReference,
            MAX_OPERATOR_REFERENCE_BYTES,
        )?;
        Ok(Self {
            expected_version,
            disposition,
            reason_code,
            operator_reference,
            evidence_digest,
            failure,
        })
    }

    /// Returns the observed optimistic version.
    #[must_use]
    pub const fn expected_version(&self) -> ExecutionVersion {
        self.expected_version
    }

    /// Returns the requested disposition.
    #[must_use]
    pub const fn disposition(&self) -> RecoveryDisposition {
        self.disposition
    }

    /// Borrows the bounded reason code.
    #[must_use]
    pub fn reason_code(&self) -> &str {
        &self.reason_code
    }

    /// Borrows the opaque operator correlation.
    #[must_use]
    pub fn operator_reference(&self) -> &str {
        &self.operator_reference
    }

    /// Returns the digest of externally retained inspection evidence.
    #[must_use]
    pub const fn evidence_digest(&self) -> &[u8; 32] {
        &self.evidence_digest
    }

    /// Returns the typed failure applied by a `FAILED` disposition.
    #[must_use]
    pub const fn failure(&self) -> Option<FailureSummary> {
        self.failure
    }
}

impl fmt::Debug for RecoveryRequest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RecoveryRequest")
            .field("expected_version", &self.expected_version)
            .field("disposition", &self.disposition)
            .field("reason_code", &self.reason_code)
            .field("operator_reference", &self.operator_reference)
            .field("evidence_digest", &"<redacted>")
            .field("failure", &self.failure)
            .finish()
    }
}

/// One append-only recovery audit record.
#[derive(Clone, Eq, PartialEq)]
pub struct RecoveryDecision {
    id: RecoveryDecisionId,
    job_execution_id: JobExecutionId,
    execution_version: ExecutionVersion,
    prior_status: BatchStatus,
    resulting_status: BatchStatus,
    reason_code: String,
    operator_reference: String,
    evidence_digest: [u8; 32],
    decided_at: SystemTime,
}

impl RecoveryDecision {
    /// Reconstructs one durable recovery decision read by an adapter.
    #[allow(clippy::too_many_arguments)]
    #[doc(hidden)]
    #[must_use]
    pub fn new(
        id: RecoveryDecisionId,
        job_execution_id: JobExecutionId,
        execution_version: ExecutionVersion,
        prior_status: BatchStatus,
        resulting_status: BatchStatus,
        reason_code: String,
        operator_reference: String,
        evidence_digest: [u8; 32],
        decided_at: SystemTime,
    ) -> Self {
        Self {
            id,
            job_execution_id,
            execution_version,
            prior_status,
            resulting_status,
            reason_code,
            operator_reference,
            evidence_digest,
            decided_at,
        }
    }

    /// Returns the opaque append-only decision identifier.
    #[must_use]
    pub const fn id(&self) -> RecoveryDecisionId {
        self.id
    }

    /// Returns the execution whose observed version was resolved.
    #[must_use]
    pub const fn job_execution_id(&self) -> JobExecutionId {
        self.job_execution_id
    }

    /// Returns the observed version before the decision.
    #[must_use]
    pub const fn execution_version(&self) -> ExecutionVersion {
        self.execution_version
    }

    /// Returns the status observed under lock.
    #[must_use]
    pub const fn prior_status(&self) -> BatchStatus {
        self.prior_status
    }

    /// Returns the durable status produced by the decision.
    #[must_use]
    pub const fn resulting_status(&self) -> BatchStatus {
        self.resulting_status
    }

    /// Borrows the bounded reason code.
    #[must_use]
    pub fn reason_code(&self) -> &str {
        &self.reason_code
    }

    /// Borrows the opaque operator correlation.
    #[must_use]
    pub fn operator_reference(&self) -> &str {
        &self.operator_reference
    }

    /// Returns the digest of externally retained evidence.
    #[must_use]
    pub const fn evidence_digest(&self) -> &[u8; 32] {
        &self.evidence_digest
    }

    /// Returns the injected facade-clock decision time.
    #[must_use]
    pub const fn decided_at(&self) -> SystemTime {
        self.decided_at
    }
}

impl fmt::Debug for RecoveryDecision {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RecoveryDecision")
            .field("id", &self.id)
            .field("job_execution_id", &self.job_execution_id)
            .field("execution_version", &self.execution_version)
            .field("prior_status", &self.prior_status)
            .field("resulting_status", &self.resulting_status)
            .field("reason_code", &self.reason_code)
            .field("operator_reference", &self.operator_reference)
            .field("evidence_digest", &"<redacted>")
            .field("decided_at", &self.decided_at)
            .finish()
    }
}

/// Result of atomically appending an audit decision and changing execution state.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RecoveryResult {
    execution: JobExecution,
    decision: RecoveryDecision,
}

impl RecoveryResult {
    /// Pairs one recovered execution with the decision that produced it.
    #[doc(hidden)]
    #[must_use]
    pub const fn new(execution: JobExecution, decision: RecoveryDecision) -> Self {
        Self {
            execution,
            decision,
        }
    }

    /// Borrows the recovered execution snapshot.
    #[must_use]
    pub const fn execution(&self) -> &JobExecution {
        &self.execution
    }

    /// Borrows the append-only audit decision.
    #[must_use]
    pub const fn decision(&self) -> &RecoveryDecision {
        &self.decision
    }
}

/// Recovery request field category.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RecoveryField {
    /// Stable machine-readable reason code.
    ReasonCode,
    /// Opaque authenticated-operator correlation.
    OperatorReference,
}

/// Invalid bounded recovery request.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RecoveryRequestError {
    /// A field was empty.
    Empty {
        /// Invalid field.
        field: RecoveryField,
    },
    /// A field exceeded its UTF-8 byte bound.
    TooLong {
        /// Invalid field.
        field: RecoveryField,
        /// Maximum accepted UTF-8 bytes.
        max_bytes: usize,
    },
    /// A field had surrounding whitespace.
    SurroundingWhitespace {
        /// Invalid field.
        field: RecoveryField,
    },
    /// A field contained a control character.
    ControlCharacter {
        /// Invalid field.
        field: RecoveryField,
    },
}

impl fmt::Display for RecoveryRequestError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty { field } => write!(formatter, "{field:?} must not be empty"),
            Self::TooLong { field, max_bytes } => {
                write!(formatter, "{field:?} exceeds {max_bytes} bytes")
            }
            Self::SurroundingWhitespace { field } => {
                write!(formatter, "{field:?} has surrounding whitespace")
            }
            Self::ControlCharacter { field } => {
                write!(formatter, "{field:?} contains a control character")
            }
        }
    }
}

impl Error for RecoveryRequestError {}

fn validate_recovery_text(
    value: &str,
    field: RecoveryField,
    max_bytes: usize,
) -> Result<(), RecoveryRequestError> {
    if value.is_empty() {
        return Err(RecoveryRequestError::Empty { field });
    }
    if value.len() > max_bytes {
        return Err(RecoveryRequestError::TooLong { field, max_bytes });
    }
    if value.trim() != value {
        return Err(RecoveryRequestError::SurroundingWhitespace { field });
    }
    if value.chars().any(char::is_control) {
        return Err(RecoveryRequestError::ControlCharacter { field });
    }
    Ok(())
}

/// Applies one recovery decision to a prior execution snapshot.
///
/// # Errors
///
/// Returns [`RepositoryError::Lifecycle`] for a stale version and
/// [`RepositoryError::RecoveryNotAllowed`] for a non-recoverable status.
#[doc(hidden)]
pub fn recovered_execution(
    prior: &JobExecution,
    request: &RecoveryRequest,
    decided_at: SystemTime,
) -> Result<JobExecution, RepositoryError> {
    if prior.version() != request.expected_version() {
        return Err(RepositoryError::Lifecycle(LifecycleError::StaleVersion {
            expected: request.expected_version(),
            actual: prior.version(),
        }));
    }
    let prior_status = prior.metadata().status();
    if !matches!(
        prior_status,
        BatchStatus::Starting | BatchStatus::Started | BatchStatus::Stopping | BatchStatus::Unknown
    ) {
        return Err(RepositoryError::RecoveryNotAllowed {
            id: prior.id(),
            status: prior_status,
        });
    }
    let current_time = prior.metadata().timestamps();
    let timestamps = ExecutionTimestamps::new(
        current_time.created_at(),
        current_time.started_at(),
        Some(decided_at),
    )?;
    let resulting_status = request.disposition().resulting_status();
    let metadata = ExecutionMetadata::new(
        resulting_status,
        prior.metadata().exit_status().clone(),
        timestamps,
        prior.metadata().counts(),
        request.failure(),
    )?;
    Ok(JobExecution::from_snapshot(
        prior.id(),
        prior.job_instance_id(),
        metadata,
        prior.version().next()?,
    ))
}

/// Starts isolated repository units of work.
///
/// A unit of work does not become visible until it is committed. Dropping one
/// without committing has rollback semantics.
pub trait JobRepository: Send + Sync {
    /// Returns the finite connection budget available to one execution tree.
    ///
    /// In-memory adapters report a finite logical budget; durable adapters
    /// report the configured pool ceiling. Local-scale launch rejects a plan
    /// whose declared repository budget exceeds this value.
    fn connection_capacity(&self) -> u32 {
        1
    }

    /// Publishes the versioned capability descriptor for this deployment.
    ///
    /// The default declares nothing beyond the always-available lifecycle and
    /// checkpoint surface, so an adapter that has not been reviewed against a
    /// capability is negotiated as not providing it. Failing closed here costs
    /// a rejected launch; failing open would cost a silently weaker guarantee.
    fn descriptor(&self) -> RepositoryDescriptor {
        RepositoryDescriptor::new(0, [])
    }

    /// Begins a repository-owned unit of work.
    ///
    /// The returned object may borrow this repository and cannot outlive it.
    fn begin<'a>(
        &'a self,
    ) -> BoxFuture<'a, Result<Box<dyn RepositoryUnitOfWork + 'a>, RepositoryError>>;
}

/// The owning runtime's bounded observation of one durable execution control.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExecutionControl {
    execution: JobExecution,
    owner_matches: bool,
    stop_requested: bool,
}

impl ExecutionControl {
    /// Records one bounded durable observation of an execution control.
    ///
    /// A metadata adapter constructs this value after comparing the complete
    /// owner token and reading the durable stop request.
    #[doc(hidden)]
    #[must_use]
    pub const fn new(execution: JobExecution, owner_matches: bool, stop_requested: bool) -> Self {
        Self {
            execution,
            owner_matches,
            stop_requested,
        }
    }

    /// Borrows the durable execution snapshot after the observation.
    #[must_use]
    pub const fn execution(&self) -> &JobExecution {
        &self.execution
    }

    /// Returns whether the complete durable token matched this process.
    #[must_use]
    pub const fn owner_matches(&self) -> bool {
        self.owner_matches
    }

    /// Returns whether a durable stop request was observed.
    #[must_use]
    pub const fn stop_requested(&self) -> bool {
        self.stop_requested
    }
}

/// Transaction-scoped metadata operations required by the executable kernel.
///
/// Methods borrow the unit of work for the returned future, allowing a future
/// `PostgreSQL` adapter to keep its concrete transaction private. A successful
/// operation is still provisional until [`commit`](Self::commit) succeeds.
pub trait RepositoryUnitOfWork: Send {
    /// Registers one explicit directed definition compatibility edge.
    fn register_definition_upgrade<'a>(
        &'a mut self,
        job_name: &'a JobName,
        upgrade: &'a DefinitionUpgrade,
    ) -> BoxFuture<'a, Result<(), RepositoryError>>;

    /// Selects or creates the unique logical instance for `key`.
    fn select_or_create_job_instance<'a>(
        &'a mut self,
        key: &'a JobInstanceKey,
    ) -> BoxFuture<'a, Result<JobInstanceSelection, RepositoryError>>;

    /// Creates a new launch or restart attempt for an existing instance.
    ///
    /// A first attempt is allowed when no prior execution exists. A later
    /// attempt is allowed only after `STOPPED` or `FAILED`. Completed,
    /// abandoned, active, and unknown instances are rejected.
    fn create_job_execution(
        &mut self,
        job_instance_id: JobInstanceId,
    ) -> BoxFuture<'_, Result<JobExecution, RepositoryError>>;

    /// Creates an attempt bound to an exact restart-relevant definition.
    ///
    /// Durable adapters compare the supplied identity with the definition that
    /// produced the latest checkpoint before creating a restart attempt.
    fn create_job_execution_with_definition<'a>(
        &'a mut self,
        job_instance_id: JobInstanceId,
        definition: &'a DefinitionIdentity,
    ) -> BoxFuture<'a, Result<JobExecution, RepositoryError>>;

    /// Creates a step attempt linked to an existing job execution.
    fn create_step_execution<'a>(
        &'a mut self,
        job_execution_id: JobExecutionId,
        step_name: &'a StepName,
    ) -> BoxFuture<'a, Result<StepExecution, RepositoryError>>;

    /// Atomically checks an instance-wide start limit and creates one logical
    /// step attempt.
    ///
    /// Entering `STARTING` consumes one start. The logical ID is independent
    /// of the display/durable step name and is the restart authority for a
    /// format-2 plan.
    fn create_flow_step_execution<'a>(
        &'a mut self,
        _job_execution_id: JobExecutionId,
        _step_name: &'a StepName,
        _node_id: &'a NodeId,
        _start_limit: StartLimit,
    ) -> BoxFuture<'a, Result<StepExecution, RepositoryError>> {
        Box::pin(async { Err(RepositoryError::FlowStateCorrupt) })
    }

    /// Applies a compare-and-swap lifecycle transition to a job execution.
    fn transition_job_execution(
        &mut self,
        id: JobExecutionId,
        expected_version: ExecutionVersion,
        transition: LifecycleTransition,
    ) -> BoxFuture<'_, Result<JobExecution, RepositoryError>>;

    /// Enriches a job execution's exit status with compare-and-swap semantics.
    fn enrich_job_exit_status<'a>(
        &'a mut self,
        id: JobExecutionId,
        expected_version: ExecutionVersion,
        exit_status: &'a ExitStatus,
    ) -> BoxFuture<'a, Result<JobExecution, RepositoryError>>;

    /// Applies a compare-and-swap lifecycle transition to a step execution.
    fn transition_step_execution(
        &mut self,
        id: StepExecutionId,
        expected_version: ExecutionVersion,
        transition: LifecycleTransition,
    ) -> BoxFuture<'_, Result<StepExecution, RepositoryError>>;

    /// Enriches a step execution's exit status with compare-and-swap semantics.
    fn enrich_step_exit_status<'a>(
        &'a mut self,
        id: StepExecutionId,
        expected_version: ExecutionVersion,
        exit_status: &'a ExitStatus,
    ) -> BoxFuture<'a, Result<StepExecution, RepositoryError>>;

    /// Finds a job instance by its canonical identifying key.
    fn find_job_instance<'a>(
        &'a mut self,
        key: &'a JobInstanceKey,
    ) -> BoxFuture<'a, Result<Option<JobInstance>, RepositoryError>>;

    /// Loads one job instance snapshot by its opaque identifier.
    fn get_job_instance(
        &mut self,
        id: JobInstanceId,
    ) -> BoxFuture<'_, Result<Option<JobInstance>, RepositoryError>>;

    /// Loads one job execution snapshot for inspection.
    fn get_job_execution(
        &mut self,
        id: JobExecutionId,
    ) -> BoxFuture<'_, Result<Option<JobExecution>, RepositoryError>>;

    /// Loads job execution snapshots in creation order.
    fn job_executions(
        &mut self,
        job_instance_id: JobInstanceId,
    ) -> BoxFuture<'_, Result<Vec<JobExecution>, RepositoryError>>;

    /// Loads one step execution snapshot for inspection.
    fn get_step_execution(
        &mut self,
        id: StepExecutionId,
    ) -> BoxFuture<'_, Result<Option<StepExecution>, RepositoryError>>;

    /// Loads step execution snapshots in creation order.
    fn step_executions(
        &mut self,
        job_execution_id: JobExecutionId,
    ) -> BoxFuture<'_, Result<Vec<StepExecution>, RepositoryError>>;

    /// Loads the latest durable attempt for one instance/logical-step pair.
    fn latest_flow_step<'a>(
        &'a mut self,
        _job_instance_id: JobInstanceId,
        _node_id: &'a NodeId,
    ) -> BoxFuture<'a, Result<Option<FlowStepState>, RepositoryError>> {
        Box::pin(async { Err(RepositoryError::FlowStateCorrupt) })
    }

    /// Appends one already plan-validated transition before its target starts.
    fn append_flow_decision<'a>(
        &'a mut self,
        _request: &'a FlowDecisionRequest,
    ) -> BoxFuture<'a, Result<FlowDecision, RepositoryError>> {
        Box::pin(async { Err(RepositoryError::FlowStateCorrupt) })
    }

    /// Finds a prior decision whose exact durable input may be reused.
    fn find_reusable_flow_decision<'a>(
        &'a mut self,
        _job_instance_id: JobInstanceId,
        _node_id: &'a NodeId,
        _plan_fingerprint: &'a [u8; 32],
        _input_digest: &'a [u8; 32],
        _kind: FlowTransitionKind,
    ) -> BoxFuture<'a, Result<Option<FlowDecision>, RepositoryError>> {
        Box::pin(async { Err(RepositoryError::FlowStateCorrupt) })
    }

    /// Loads one execution's flow decisions in sequence order.
    fn flow_decisions(
        &mut self,
        _job_execution_id: JobExecutionId,
    ) -> BoxFuture<'_, Result<Vec<FlowDecision>, RepositoryError>> {
        Box::pin(async { Err(RepositoryError::FlowStateCorrupt) })
    }

    /// Inserts one complete bounded partition plan before any worker starts.
    ///
    /// Entry order becomes the stable one-based partition ordinal. The method
    /// rejects an empty, oversized, duplicate-key, or already-created plan
    /// without publishing a partial plan.
    fn create_step_partition_plan<'a>(
        &'a mut self,
        _step_execution_id: StepExecutionId,
        _entries: &'a [PartitionPlanEntry],
    ) -> BoxFuture<'a, Result<Vec<StepPartition>, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::StepPartitions,
            })
        })
    }

    /// Loads the complete partition plan in partition-key byte order.
    fn step_partition_plan(
        &mut self,
        _step_execution_id: StepExecutionId,
    ) -> BoxFuture<'_, Result<Vec<StepPartition>, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::StepPartitions,
            })
        })
    }

    /// Carries one prior attempt's committed partition plan into a new parent.
    ///
    /// Completed results are retained without rerunning their worker. Other
    /// results become unassigned `STARTING` work only after the source job has
    /// reached a restartable terminal state through ordinary failure/stop or
    /// explicit recovery. The operation publishes the complete target plan or
    /// nothing.
    fn restart_step_partition_plan(
        &mut self,
        _source_step_execution_id: StepExecutionId,
        _target_step_execution_id: StepExecutionId,
    ) -> BoxFuture<'_, Result<Vec<StepPartition>, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::StepPartitions,
            })
        })
    }

    /// Assigns a new or restart-eligible partition to a worker attempt by CAS.
    fn assign_step_partition(
        &mut self,
        _id: StepPartitionId,
        _expected_version: ExecutionVersion,
        _worker_step_execution_id: StepExecutionId,
    ) -> BoxFuture<'_, Result<StepPartition, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::StepPartitions,
            })
        })
    }

    /// Publishes one assigned worker's durable terminal snapshot by CAS.
    ///
    /// The adapter locks and verifies the exact assigned worker. Status, exit
    /// status, and counters are derived from that worker rather than accepted
    /// from a caller-supplied result, so an active or crossed worker cannot
    /// fabricate a partition result.
    fn complete_step_partition(
        &mut self,
        _id: StepPartitionId,
        _expected_version: ExecutionVersion,
        _worker_step_execution_id: StepExecutionId,
    ) -> BoxFuture<'_, Result<StepPartition, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::StepPartitions,
            })
        })
    }

    /// Aggregates every durable child and atomically terminates its parent step.
    ///
    /// The adapter reads the complete plan, derives the fixed key-ordered
    /// aggregate, and updates status, exit status, counters, failure, timestamp,
    /// and optimistic version in this unit of work. An active child prevents
    /// any parent mutation.
    fn aggregate_step_partitions(
        &mut self,
        _step_execution_id: StepExecutionId,
        _expected_version: ExecutionVersion,
        _transitioned_at: SystemTime,
    ) -> BoxFuture<'_, Result<StepExecution, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::StepPartitions,
            })
        })
    }

    /// Atomically resolves one orphaned or ambiguous execution and appends its audit record.
    fn recover_job_execution<'a>(
        &'a mut self,
        id: JobExecutionId,
        request: &'a RecoveryRequest,
    ) -> BoxFuture<'a, Result<RecoveryResult, RepositoryError>>;

    /// Loads the append-only recovery decision for one execution, when present.
    fn recovery_decision(
        &mut self,
        id: JobExecutionId,
    ) -> BoxFuture<'_, Result<Option<RecoveryDecision>, RepositoryError>>;

    /// Reads the recorded outcome of one `(action, operation id)` pair.
    ///
    /// An adapter without durable operator audit rejects the capability rather
    /// than inferring idempotency from timing or request similarity.
    fn find_operator_request<'a>(
        &'a mut self,
        _action: OperatorAction,
        _operation_id: &'a OperationId,
    ) -> BoxFuture<'a, Result<Option<OperatorRecord>, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::OperatorRequests,
            })
        })
    }

    /// Appends one operator audit row in the transaction of its effect.
    fn append_operator_request<'a>(
        &'a mut self,
        _draft: &'a OperatorRecordDraft,
    ) -> BoxFuture<'a, Result<OperatorRecord, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::OperatorRequests,
            })
        })
    }

    /// Records a durable stop request under compare-and-swap.
    ///
    /// The request does not transition the execution. The owning runtime
    /// observes it at the next chunk-commit boundary and at least once per its
    /// configured poll interval.
    fn request_execution_stop<'a>(
        &'a mut self,
        _id: JobExecutionId,
        _expected_version: ExecutionVersion,
        _actor: &'a ActorRef,
        _requested_at: SystemTime,
    ) -> BoxFuture<'a, Result<JobExecution, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::StopRequests,
            })
        })
    }

    /// Claims one newly created `STARTING` execution for the current process.
    ///
    /// The token is evidence rather than a lease. A different recorded token
    /// rejects the claim and never authorizes takeover of an existing attempt.
    fn claim_execution_owner<'a>(
        &'a mut self,
        _id: JobExecutionId,
        _expected_version: ExecutionVersion,
        _owner: &'a OwnerToken,
        _claimed_at: SystemTime,
    ) -> BoxFuture<'a, Result<JobExecution, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::ExecutionOwnership,
            })
        })
    }

    /// Observes a durable stop request as the owning process.
    ///
    /// When the owner matches and an active execution has a request, this call
    /// moves it to `STOPPING` in the same transaction. It never treats a token
    /// as a lease or takeover authority.
    fn observe_execution_control<'a>(
        &'a mut self,
        _id: JobExecutionId,
        _owner: &'a OwnerToken,
        _observed_at: SystemTime,
    ) -> BoxFuture<'a, Result<ExecutionControl, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::ExecutionOwnership,
            })
        })
    }

    /// Reads the active retention hold of one logical instance.
    fn job_instance_hold(
        &mut self,
        _id: JobInstanceId,
    ) -> BoxFuture<'_, Result<Option<RetentionHold>, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::InstanceHolds,
            })
        })
    }

    /// Places the single retention hold of one logical instance.
    fn place_instance_hold<'a>(
        &'a mut self,
        _id: JobInstanceId,
        _actor: &'a ActorRef,
        _reason: &'a ReasonCode,
        _placed_at: SystemTime,
    ) -> BoxFuture<'a, Result<RetentionHold, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::InstanceHolds,
            })
        })
    }

    /// Releases the retention hold of one logical instance.
    fn release_instance_hold(
        &mut self,
        _id: JobInstanceId,
    ) -> BoxFuture<'_, Result<Option<RetentionHold>, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::InstanceHolds,
            })
        })
    }

    /// Reads the recorded outcome of one retention `(action, operation id)`.
    fn find_retention_action<'a>(
        &'a mut self,
        _action: RetentionAction,
        _operation_id: &'a OperationId,
    ) -> BoxFuture<'a, Result<Option<RetentionRecord>, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::RetentionPurge,
            })
        })
    }

    /// Appends one retention audit row in the transaction it audits.
    fn append_retention_action<'a>(
        &'a mut self,
        _draft: &'a RetentionRecordDraft,
    ) -> BoxFuture<'a, Result<RetentionRecord, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::RetentionPurge,
            })
        })
    }

    /// Surveys bounded purge candidates with the versions observed for them.
    fn purge_survey<'a>(
        &'a mut self,
        _request: &'a PurgePlanRequest,
    ) -> BoxFuture<'a, Result<PurgeSurvey, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::RetentionPurge,
            })
        })
    }

    /// Re-validates a plan and deletes one bounded batch in instance-owned order.
    ///
    /// Any candidate whose eligibility or version changed produces
    /// [`RepositoryError::RetentionPlanStale`] and deletes nothing.
    fn apply_purge<'a>(
        &'a mut self,
        _plan: &'a PurgePlan,
    ) -> BoxFuture<'a, Result<PurgeCounts, RepositoryError>> {
        Box::pin(async {
            Err(RepositoryError::UnsupportedCapability {
                capability: RepositoryCapability::RetentionPurge,
            })
        })
    }

    /// Atomically publishes all changes made by this unit of work.
    fn commit<'a>(self: Box<Self>) -> BoxFuture<'a, Result<(), RepositoryError>>
    where
        Self: 'a;

    /// Explicitly rolls back this unit of work.
    ///
    /// Dropping a unit of work has the same metadata effect.
    fn rollback<'a>(self: Box<Self>) -> BoxFuture<'a, Result<(), RepositoryError>>
    where
        Self: 'a;
}

/// A separately negotiated durable repository capability.
///
/// An adapter that cannot provide a capability rejects it with a typed error
/// rather than emulating it with an unbounded scan or an inferred guarantee.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[non_exhaustive]
pub enum RepositoryCapability {
    /// Append-only operator audit and idempotency rows.
    OperatorRequests,
    /// Durable compare-and-swap stop requests.
    StopRequests,
    /// Per-process execution ownership evidence and stop observation.
    ExecutionOwnership,
    /// The single retention hold of a logical instance.
    InstanceHolds,
    /// Bounded two-phase retention purge.
    RetentionPurge,
    /// Durable local partition plans and compare-and-swap results.
    StepPartitions,
}

impl RepositoryCapability {
    /// Returns the stable name of the capability.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::OperatorRequests => "operator requests",
            Self::StopRequests => "durable stop requests",
            Self::ExecutionOwnership => "execution ownership evidence",
            Self::InstanceHolds => "instance holds",
            Self::RetentionPurge => "retention purge",
            Self::StepPartitions => "durable step partitions",
        }
    }
}

/// The versioned capability descriptor a durable adapter publishes.
///
/// Negotiation reads this descriptor before a launch does any durable work, so
/// a requirement the deployed adapter does not declare is rejected up front
/// rather than discovered part-way through an execution. The descriptor is the
/// adapter's own claim about the deployment it is connected to; it is not
/// derived from the compiled plan and never weakens a declared guarantee.
///
/// `descriptor_version` versions the shape of this declaration. It is distinct
/// from `schema_version`, which is the durable metadata schema the adapter is
/// connected to: a runtime can understand a descriptor whose schema it refuses.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RepositoryDescriptor {
    descriptor_version: u32,
    schema_version: u32,
    capabilities: BTreeSet<RepositoryCapability>,
}

impl RepositoryDescriptor {
    /// The descriptor shape this runtime publishes and understands.
    pub const CURRENT_VERSION: u32 = 1;

    /// Declares the capabilities an adapter connected to `schema_version`
    /// provides.
    ///
    /// A capability that is absent is undeclared, which negotiation treats as
    /// unavailable. Declaring nothing is the conservative claim, not a
    /// permissive one.
    #[must_use]
    pub fn new(
        schema_version: u32,
        capabilities: impl IntoIterator<Item = RepositoryCapability>,
    ) -> Self {
        Self {
            descriptor_version: Self::CURRENT_VERSION,
            schema_version,
            capabilities: capabilities.into_iter().collect(),
        }
    }

    /// Returns the version of this descriptor's shape.
    #[must_use]
    pub const fn descriptor_version(&self) -> u32 {
        self.descriptor_version
    }

    /// Returns the durable metadata schema version the adapter is connected to.
    #[must_use]
    pub const fn schema_version(&self) -> u32 {
        self.schema_version
    }

    /// Reports whether the adapter declared `capability`.
    #[must_use]
    pub fn declares(&self, capability: RepositoryCapability) -> bool {
        self.capabilities.contains(&capability)
    }

    /// Lists the declared capabilities in a stable order.
    #[must_use]
    pub fn capabilities(&self) -> impl ExactSizeIterator<Item = RepositoryCapability> + '_ {
        self.capabilities.iter().copied()
    }

    /// Requires `capability`, failing with a typed rejection when undeclared.
    ///
    /// # Errors
    ///
    /// Returns [`RepositoryError::UnsupportedCapability`] naming the
    /// requirement. The requirement is never silently downgraded to a weaker
    /// guarantee.
    pub fn require(&self, capability: RepositoryCapability) -> Result<(), RepositoryError> {
        if self.declares(capability) {
            Ok(())
        } else {
            Err(RepositoryError::UnsupportedCapability { capability })
        }
    }
}

impl fmt::Display for RepositoryCapability {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// A stable repository failure independent of a database or async runtime.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RepositoryError {
    /// The durable metadata schema has not been initialized.
    SchemaUninitialized,
    /// The durable metadata schema must be migrated before use.
    MigrationRequired {
        /// The version found in the database.
        current: u32,
        /// The version understood by this runtime.
        supported: u32,
    },
    /// The durable metadata schema is newer than this runtime.
    NewerSchema {
        /// The version found in the database.
        current: u32,
        /// The version understood by this runtime.
        supported: u32,
    },
    /// A facade identifier cannot be represented by the durable adapter.
    IdentifierOutOfRange {
        /// The identifier category.
        kind: IdentifierKind,
        /// The rejected facade value.
        value: u64,
    },
    /// A referenced job instance does not exist.
    JobInstanceNotFound {
        /// The missing identifier.
        id: JobInstanceId,
    },
    /// A referenced job execution does not exist.
    JobExecutionNotFound {
        /// The missing identifier.
        id: JobExecutionId,
    },
    /// A referenced step execution does not exist.
    StepExecutionNotFound {
        /// The missing identifier.
        id: StepExecutionId,
    },
    /// A referenced durable step partition does not exist.
    StepPartitionNotFound {
        /// The missing partition identifier.
        id: StepPartitionId,
    },
    /// A partition plan contained no work.
    EmptyPartitionPlan,
    /// A partition plan exceeded the accepted M4 bound.
    PartitionPlanTooLarge {
        /// Maximum accepted partition count.
        max: usize,
    },
    /// A partition plan repeated a byte-exact key.
    DuplicatePartitionKey,
    /// A durable plan already exists for the parent step execution.
    PartitionPlanExists {
        /// Parent partitioned step execution.
        step_execution_id: StepExecutionId,
    },
    /// Worker assignment was attempted before the new plan transaction committed.
    PartitionPlanNotCommitted {
        /// Parent partitioned step execution.
        step_execution_id: StepExecutionId,
    },
    /// A partition update was not valid for its durable state.
    PartitionUpdateNotAllowed {
        /// Rejected partition.
        id: StepPartitionId,
        /// Status observed under compare-and-swap.
        status: BatchStatus,
    },
    /// The worker attempt does not belong to the partition parent's job execution.
    PartitionWorkerMismatch {
        /// Rejected partition.
        partition_id: StepPartitionId,
        /// Worker attempt from a different job execution.
        worker_step_execution_id: StepExecutionId,
    },
    /// A worker attempt is already bound to another durable partition.
    PartitionWorkerAlreadyAssigned {
        /// Reused worker attempt.
        worker_step_execution_id: StepExecutionId,
    },
    /// A completion did not name the currently assigned worker attempt.
    PartitionWorkerStale {
        /// Rejected partition.
        partition_id: StepPartitionId,
        /// Worker expected by the caller.
        worker_step_execution_id: StepExecutionId,
    },
    /// The partition manager is no longer active and cannot mutate children.
    PartitionParentNotActive {
        /// Parent partitioned step execution.
        step_execution_id: StepExecutionId,
        /// Current parent lifecycle status.
        status: BatchStatus,
    },
    /// At least one durable child has not published a runtime-terminal result.
    PartitionAggregationIncomplete {
        /// Parent partitioned step execution.
        step_execution_id: StepExecutionId,
        /// Child status that prevented aggregation.
        status: BatchStatus,
    },
    /// Durable partition state is contradictory, corrupt, or cannot be decoded.
    PartitionStateCorrupt,
    /// An injected source reused an existing identifier.
    DuplicateIdentifier {
        /// The duplicated identifier category.
        kind: IdentifierKind,
        /// The duplicated numeric value.
        value: u64,
    },
    /// A completed logical instance cannot be launched again.
    CompletedInstance {
        /// The terminal logical instance.
        id: JobInstanceId,
    },
    /// An abandoned logical instance cannot be launched again.
    AbandonedInstance {
        /// The terminal logical instance.
        id: JobInstanceId,
    },
    /// A prior attempt is active or requires explicit recovery.
    ExecutionAlreadyActive {
        /// The logical instance selected for launch.
        instance_id: JobInstanceId,
        /// The attempt preventing another launch.
        execution_id: JobExecutionId,
        /// Its current framework status.
        status: BatchStatus,
    },
    /// One job name and revision were bound to a different manifest.
    DefinitionDrift {
        /// Definition whose application revision drifted.
        job_name: JobName,
        /// Reused application-owned revision.
        revision: DefinitionRevision,
    },
    /// A manifest was registered or launched under a different job name.
    DefinitionJobMismatch {
        /// Job name selected by the instance or registration call.
        expected: JobName,
        /// Job name encoded in the definition manifest.
        actual: JobName,
    },
    /// The proposed definition cannot interpret the latest checkpoint.
    IncompatibleDefinition {
        /// Logical instance whose last definition is incompatible.
        instance_id: JobInstanceId,
    },
    /// The runtime cannot interpret the supplied or persisted manifest format.
    UnsupportedManifestVersion {
        /// Unsupported format version.
        format: u16,
    },
    /// A registered directed edge did not map a required durable step.
    InvalidDefinitionUpgrade {
        /// New execution whose mapped state could not be resolved.
        execution_id: JobExecutionId,
    },
    /// A directed edge was already registered with different immutable content.
    DefinitionUpgradeConflict {
        /// Job whose edge conflicted.
        job_name: JobName,
    },
    /// A restartable definition required durable step state that was absent.
    RestartStateNotFound {
        /// New restart execution.
        execution_id: JobExecutionId,
        /// Target step whose source state was absent.
        step_name: StepName,
    },
    /// Durable fault state could not be interpreted, so no work may begin.
    ///
    /// Corruption, an unsupported fault-state version, a checksum mismatch, or
    /// state that belongs to a superseded checkpoint fails closed.
    FaultStateCorrupt,
    /// The instance-wide start limit for a logical step is exhausted.
    StartLimitExceeded {
        /// Logical instance whose historical starts were counted.
        instance_id: JobInstanceId,
        /// Stable logical step identifier.
        node_id: NodeId,
        /// Configured finite limit.
        limit: StartLimit,
    },
    /// Durable flow history is missing, contradictory, or corrupt.
    FlowStateCorrupt,
    /// Recovery was requested for a state that needs no recovery decision.
    RecoveryNotAllowed {
        /// Rejected execution.
        id: JobExecutionId,
        /// Durable status observed under lock.
        status: BatchStatus,
    },
    /// A different process token is already recorded for the execution.
    ExecutionOwned {
        /// Execution that remains owned by another process token.
        id: JobExecutionId,
    },
    /// Ownership was requested outside the newly-created `STARTING` boundary.
    ExecutionOwnershipNotAllowed {
        /// Execution that was not claimable.
        id: JobExecutionId,
        /// Durable status observed under lock.
        status: BatchStatus,
    },
    /// A domain value could not be constructed.
    Domain(DomainError),
    /// An injected identifier source failed.
    Identifier(IdGenerationError),
    /// A lifecycle or optimistic-version rule rejected an update.
    Lifecycle(LifecycleError),
    /// A purge candidate changed after its plan was produced.
    ///
    /// Nothing was deleted. A new plan observes the remaining candidates.
    RetentionPlanStale,
    /// The adapter does not provide a required repository capability.
    UnsupportedCapability {
        /// The capability the caller required.
        capability: RepositoryCapability,
    },
    /// Another committed unit of work invalidated this snapshot.
    ConcurrentModification,
    /// A commit failed after `PostgreSQL` may have made it durable.
    ///
    /// Callers must inspect durable metadata through a new healthy unit of
    /// work before deciding whether to retry.
    CommitOutcomeUnknown,
    /// The repository is unavailable because of an infrastructure failure.
    Unavailable,
}

impl fmt::Display for RepositoryError {
    #[allow(clippy::too_many_lines)]
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SchemaUninitialized => {
                formatter.write_str("PostgreSQL metadata schema is not initialized")
            }
            Self::MigrationRequired { current, supported } => write!(
                formatter,
                "PostgreSQL metadata schema version {current} requires migration to {supported}"
            ),
            Self::NewerSchema { current, supported } => write!(
                formatter,
                "PostgreSQL metadata schema version {current} is newer than supported version {supported}"
            ),
            Self::IdentifierOutOfRange { kind, value } => {
                write!(
                    formatter,
                    "{kind} identifier {value} exceeds PostgreSQL bigint"
                )
            }
            Self::JobInstanceNotFound { id } => {
                write!(formatter, "job instance {id} was not found")
            }
            Self::JobExecutionNotFound { id } => {
                write!(formatter, "job execution {id} was not found")
            }
            Self::StepExecutionNotFound { id } => {
                write!(formatter, "step execution {id} was not found")
            }
            Self::StepPartitionNotFound { id } => {
                write!(formatter, "step partition {id} was not found")
            }
            Self::EmptyPartitionPlan => {
                formatter.write_str("partition plan must contain at least one entry")
            }
            Self::PartitionPlanTooLarge { max } => {
                write!(formatter, "partition plan exceeds {max} entries")
            }
            Self::DuplicatePartitionKey => {
                formatter.write_str("partition plan contains a duplicate key")
            }
            Self::PartitionPlanExists { step_execution_id } => write!(
                formatter,
                "step execution {step_execution_id} already has a partition plan"
            ),
            Self::PartitionPlanNotCommitted { step_execution_id } => write!(
                formatter,
                "step execution {step_execution_id} partition plan must commit before assignment"
            ),
            Self::PartitionUpdateNotAllowed { id, status } => write!(
                formatter,
                "step partition {id} cannot be updated from {status}"
            ),
            Self::PartitionWorkerMismatch {
                partition_id,
                worker_step_execution_id,
            } => write!(
                formatter,
                "worker step execution {worker_step_execution_id} does not belong to partition {partition_id}"
            ),
            Self::PartitionWorkerAlreadyAssigned {
                worker_step_execution_id,
            } => write!(
                formatter,
                "worker step execution {worker_step_execution_id} is already assigned to a partition"
            ),
            Self::PartitionWorkerStale {
                partition_id,
                worker_step_execution_id,
            } => write!(
                formatter,
                "worker step execution {worker_step_execution_id} is not the current worker for partition {partition_id}"
            ),
            Self::PartitionParentNotActive {
                step_execution_id,
                status,
            } => write!(
                formatter,
                "partition parent step execution {step_execution_id} cannot mutate children from {status}"
            ),
            Self::PartitionAggregationIncomplete {
                step_execution_id,
                status,
            } => write!(
                formatter,
                "step execution {step_execution_id} cannot aggregate a child in {status}"
            ),
            Self::PartitionStateCorrupt => {
                formatter.write_str("durable partition state is unusable and no work may begin")
            }
            Self::DuplicateIdentifier { kind, value } => {
                write!(formatter, "{kind} identifier {value} already exists")
            }
            Self::CompletedInstance { id } => {
                write!(formatter, "job instance {id} is already completed")
            }
            Self::AbandonedInstance { id } => {
                write!(formatter, "job instance {id} is abandoned")
            }
            Self::ExecutionAlreadyActive {
                instance_id,
                execution_id,
                status,
            } => write!(
                formatter,
                "job instance {instance_id} already has execution {execution_id} in {status}"
            ),
            Self::DefinitionDrift { job_name, revision } => write!(
                formatter,
                "job {job_name} definition revision {} has drifted",
                revision.as_str()
            ),
            Self::DefinitionJobMismatch { expected, actual } => write!(
                formatter,
                "definition for job {actual} cannot be used for job {expected}"
            ),
            Self::IncompatibleDefinition { instance_id } => write!(
                formatter,
                "job instance {instance_id} has no direct compatible definition"
            ),
            Self::UnsupportedManifestVersion { format } => {
                write!(
                    formatter,
                    "definition manifest format {format} is unsupported"
                )
            }
            Self::InvalidDefinitionUpgrade { execution_id } => write!(
                formatter,
                "definition upgrade for execution {execution_id} is incomplete"
            ),
            Self::DefinitionUpgradeConflict { job_name } => {
                write!(formatter, "job {job_name} definition upgrade conflicts")
            }
            Self::RestartStateNotFound {
                execution_id,
                step_name,
            } => write!(
                formatter,
                "restart execution {execution_id} has no durable source for step {step_name}"
            ),
            Self::FaultStateCorrupt => {
                formatter.write_str("durable fault state is unusable and no work may begin")
            }
            Self::StartLimitExceeded {
                instance_id,
                node_id,
                limit,
            } => write!(
                formatter,
                "job instance {instance_id} exhausted start limit {} for node {}",
                limit.get(),
                node_id.as_str()
            ),
            Self::FlowStateCorrupt => {
                formatter.write_str("durable flow history is unusable and no work may begin")
            }
            Self::RecoveryNotAllowed { id, status } => {
                write!(
                    formatter,
                    "job execution {id} in {status} cannot be recovered"
                )
            }
            Self::ExecutionOwned { id } => {
                write!(formatter, "job execution {id} is owned by another process")
            }
            Self::ExecutionOwnershipNotAllowed { id, status } => write!(
                formatter,
                "job execution {id} in {status} cannot acquire process ownership"
            ),
            Self::Domain(error) => write!(formatter, "invalid repository domain value: {error}"),
            Self::Identifier(error) => write!(formatter, "identifier generation failed: {error}"),
            Self::Lifecycle(error) => error.fmt(formatter),
            Self::RetentionPlanStale => {
                formatter.write_str("the purge plan is stale and nothing was deleted")
            }
            Self::UnsupportedCapability { capability } => {
                write!(formatter, "the adapter does not support {capability}")
            }
            Self::ConcurrentModification => {
                formatter.write_str("repository unit of work is based on a stale snapshot")
            }
            Self::CommitOutcomeUnknown => formatter.write_str(
                "PostgreSQL commit outcome is unknown; inspect durable metadata before recovery",
            ),
            Self::Unavailable => formatter.write_str("repository is unavailable"),
        }
    }
}

/// Applies one partition aggregate to its parent step execution.
///
/// # Errors
///
/// Returns [`RepositoryError::Lifecycle`] when the parent cannot take the
/// aggregated transition.
#[doc(hidden)]
pub fn aggregate_partition_parent(
    parent: &StepExecution,
    expected_version: ExecutionVersion,
    aggregate: &PartitionAggregate,
    transitioned_at: SystemTime,
    failure: Option<FailureSummary>,
) -> Result<StepExecution, RepositoryError> {
    let transition = if aggregate.status() == BatchStatus::Failed {
        LifecycleTransition::failed(
            transitioned_at,
            failure.ok_or(LifecycleError::FailedTransitionMissingFailure)?,
        )
    } else {
        LifecycleTransition::new(aggregate.status(), transitioned_at)
    };
    let mut transitioned = parent.clone();
    transitioned.transition(expected_version, transition)?;
    let metadata = ExecutionMetadata::new(
        aggregate.status(),
        aggregate.exit_status().clone(),
        transitioned.metadata().timestamps(),
        aggregate.counts(),
        transitioned.metadata().failure(),
    )?;
    Ok(StepExecution::from_snapshot(
        transitioned.id(),
        transitioned.job_execution_id(),
        transitioned.step_name().clone(),
        metadata,
        transitioned.version(),
    ))
}

/// Maps one partition aggregation failure onto its repository error.
#[doc(hidden)]
#[must_use]
pub fn map_partition_aggregation(
    step_execution_id: StepExecutionId,
    error: PartitionAggregationError,
) -> RepositoryError {
    match error {
        PartitionAggregationError::Incomplete { status } => {
            RepositoryError::PartitionAggregationIncomplete {
                step_execution_id,
                status,
            }
        }
        PartitionAggregationError::CountExhausted => {
            RepositoryError::Lifecycle(LifecycleError::CountExhausted)
        }
        PartitionAggregationError::EmptyPlan
        | PartitionAggregationError::PlanTooLarge { .. }
        | PartitionAggregationError::DuplicateKey => RepositoryError::PartitionStateCorrupt,
    }
}

impl Error for RepositoryError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Domain(error) => Some(error),
            Self::Identifier(error) => Some(error),
            Self::Lifecycle(error) => Some(error),
            _ => None,
        }
    }
}

impl From<DomainError> for RepositoryError {
    fn from(error: DomainError) -> Self {
        Self::Domain(error)
    }
}

impl From<IdGenerationError> for RepositoryError {
    fn from(error: IdGenerationError) -> Self {
        Self::Identifier(error)
    }
}

impl From<LifecycleError> for RepositoryError {
    fn from(error: LifecycleError) -> Self {
        Self::Lifecycle(error)
    }
}