sabiquant 0.1.0-alpha.1

An independent quantitative finance library written natively in Rust, using only the standard library.
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
//! Explicit contractual schedules with separate business-day adjustment.
//!
//! Ordinary schedules support Forward, Backward, Zero, four civil rolls and
//! the automatic local OldCDS rule on quarterly-twentieth anchors. Separate modern CDS
//! plans retain explicit trade, raw maturity, payment and adjusted accrual
//! roles. Ordinary recurrence is
//! anchored to the original directional endpoint or explicitly named coupon;
//! repeated month clamping and
//! business-day advancement are not recurrence rules. Dates and regularity
//! remain contractual even when adjustment changes interval lengths.
//!
//! The [local M7 contract](https://github.com/iceman951/sabiquant/blob/main/docs/M7_LOCAL_READINESS.md)
//! and [explicit coupon contract](https://github.com/iceman951/sabiquant/blob/main/docs/M7_EXPLICIT_STUB_CONTRACT.md)
//! record scope and unresolved acceptance gates. Generated ICMA contexts use
//! the [retained contractual lattice](https://github.com/iceman951/sabiquant/blob/main/docs/M7_ICMA_REFERENCE_CONTRACT.md)
//! and an explicit matching frequency. The four civil rolls retain separate
//! requested/resolved provenance and generate references on their exact roll
//! points. Modern CDS plans separate raw, payment and adjusted accrual dates,
//! including final raw maturity. Under the [OldCDS contract](https://github.com/iceman951/sabiquant/blob/main/docs/M7_OLD_CDS_CONTRACT.md),
//! OldCDS provenance retains the requested end and stored tenor with the
//! resolved quarters; it is a local date rule, not a historical premium leg.

use crate::calendar::{
    BusinessDayConvention, Calendar, CalendarError, EndOfMonth, EndpointInclusion, TargetCalendar,
};
use crate::daycount::{ActualActualIcma, DeterminationPeriod, IcmaError};
use crate::error::IdentifierError;
use crate::identifier::{Entry, Identifiers};
use crate::time::{Date, DateError, Frequency, Period, TimeUnit};
use std::error::Error as StdError;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::str::FromStr;

mod cds;
mod cds_maturity;
mod old_cds;
mod roll;
pub use cds::{CdsCouponDates, CdsDatePlan};
pub use cds_maturity::{
    CdsMaturityConvention, CdsMaturityOutcome, CdsMaturityResolution, resolve_cds_maturity,
};
pub use old_cds::OldCdsProvenance;
pub use roll::{RollProvenance, SpecialRollRule};

/// An explicit ordinary recurrence, civil roll, OldCDS or modern CDS plan rule.
///
/// Canonical text is `Forward`, `Backward`, `Zero`, a [`SpecialRollRule`]
/// identifier, `OldCDS`, `CDS` or `CDS2015`. There are no aliases, case
/// folding or whitespace trimming.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DateGenerationRule {
    /// Generate from the original start; an automatic residual is at the end.
    Forward,
    /// Generate from the original end; return chronological dates and a first residual.
    Backward,
    /// Exactly start/end, with no periodic tenor, stub or EOM configuration.
    Zero,
    /// A civil month roll, built only by [`ScheduleBuilder::build_roll`].
    Roll(SpecialRollRule),
    /// Automatic local twentieth rule on quarterly anchors, built only by [`ScheduleBuilder::build_old_cds`].
    OldCds,
    /// Standard Following CDS plan under the quarterly 2009 maturity regime.
    Cds,
    /// Standard Following CDS plan under the semiannual 2015 maturity regime.
    Cds2015,
}

impl DateGenerationRule {
    /// All currently supported rule labels in canonical order.
    pub const ALL: [Self; 10] = [
        Self::Forward,
        Self::Backward,
        Self::Zero,
        Self::Roll(SpecialRollRule::ThirdWednesday),
        Self::Roll(SpecialRollRule::ThirdWednesdayInclusive),
        Self::Roll(SpecialRollRule::Twentieth),
        Self::Roll(SpecialRollRule::TwentiethIMM),
        Self::OldCds,
        Self::Cds,
        Self::Cds2015,
    ];

    /// Returns the exact canonical identifier.
    #[must_use]
    pub const fn canonical_identifier(self) -> &'static str {
        match self {
            Self::Forward => "Forward",
            Self::Backward => "Backward",
            Self::Zero => "Zero",
            Self::Roll(rule) => rule.canonical_identifier(),
            Self::OldCds => "OldCDS",
            Self::Cds => "CDS",
            Self::Cds2015 => "CDS2015",
        }
    }
}

const RULE_IDS: Identifiers<DateGenerationRule> = Identifiers::new(
    "date generation rule",
    &[
        Entry {
            value: DateGenerationRule::Forward,
            canonical: "Forward",
            aliases: &[],
        },
        Entry {
            value: DateGenerationRule::Backward,
            canonical: "Backward",
            aliases: &[],
        },
        Entry {
            value: DateGenerationRule::Zero,
            canonical: "Zero",
            aliases: &[],
        },
        Entry {
            value: DateGenerationRule::Roll(SpecialRollRule::ThirdWednesday),
            canonical: "ThirdWednesday",
            aliases: &[],
        },
        Entry {
            value: DateGenerationRule::Roll(SpecialRollRule::ThirdWednesdayInclusive),
            canonical: "ThirdWednesdayInclusive",
            aliases: &[],
        },
        Entry {
            value: DateGenerationRule::Roll(SpecialRollRule::Twentieth),
            canonical: "Twentieth",
            aliases: &[],
        },
        Entry {
            value: DateGenerationRule::Roll(SpecialRollRule::TwentiethIMM),
            canonical: "TwentiethIMM",
            aliases: &[],
        },
        Entry {
            value: DateGenerationRule::OldCds,
            canonical: "OldCDS",
            aliases: &[],
        },
        Entry {
            value: DateGenerationRule::Cds,
            canonical: "CDS",
            aliases: &[],
        },
        Entry {
            value: DateGenerationRule::Cds2015,
            canonical: "CDS2015",
            aliases: &[],
        },
    ],
    &[],
);

impl fmt::Display for DateGenerationRule {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.canonical_identifier())
    }
}

impl FromStr for DateGenerationRule {
    type Err = IdentifierError;
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        RULE_IDS.parse(text)
    }
}

/// The policy for an automatic off-lattice first or final residual interval.
///
/// Exact canonical text is `None`, `Short` or `Long`, with no aliases or
/// trimming. An exact lattice never creates an artificial stub, even when
/// `Long` is requested.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StubPolicy {
    /// Reject a residual rather than infer a coupon interval.
    None,
    /// Retain the neighboring regular boundary and the original endpoint.
    Short,
    /// Remove the neighboring regular boundary, merging its interval with the residual.
    Long,
}

impl StubPolicy {
    /// All currently supported stub labels in canonical order.
    pub const ALL: [Self; 3] = [Self::None, Self::Short, Self::Long];

    /// Returns the exact canonical identifier.
    #[must_use]
    pub const fn canonical_identifier(self) -> &'static str {
        match self {
            Self::None => "None",
            Self::Short => "Short",
            Self::Long => "Long",
        }
    }
}

const STUB_IDS: Identifiers<StubPolicy> = Identifiers::new(
    "stub policy",
    &[
        Entry {
            value: StubPolicy::None,
            canonical: "None",
            aliases: &[],
        },
        Entry {
            value: StubPolicy::Short,
            canonical: "Short",
            aliases: &[],
        },
        Entry {
            value: StubPolicy::Long,
            canonical: "Long",
            aliases: &[],
        },
    ],
    &[],
);

impl fmt::Display for StubPolicy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.canonical_identifier())
    }
}

impl FromStr for StubPolicy {
    type Err = IdentifierError;
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        STUB_IDS.parse(text)
    }
}

/// Contractual provenance of one adjacent boundary pair.
///
/// Canonical text is exactly `Regular`, `Stub` or `NonPeriodic`, with no
/// aliases or trimming. Business-day adjustment never changes this flag.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PeriodRegularity {
    /// One complete interval on the retained recurrence, civil roll or OldCDS lattice.
    Regular,
    /// An automatic residual, explicit outer, civil roll or OldCDS interval off the named lattice.
    Stub,
    /// Zero's single interval, for which no periodic lattice is claimed.
    NonPeriodic,
}

impl PeriodRegularity {
    /// All currently supported regularity labels in canonical order.
    pub const ALL: [Self; 3] = [Self::Regular, Self::Stub, Self::NonPeriodic];

    /// Returns the exact canonical identifier.
    #[must_use]
    pub const fn canonical_identifier(self) -> &'static str {
        match self {
            Self::Regular => "Regular",
            Self::Stub => "Stub",
            Self::NonPeriodic => "NonPeriodic",
        }
    }
}

const REGULARITY_IDS: Identifiers<PeriodRegularity> = Identifiers::new(
    "period regularity",
    &[
        Entry {
            value: PeriodRegularity::Regular,
            canonical: "Regular",
            aliases: &[],
        },
        Entry {
            value: PeriodRegularity::Stub,
            canonical: "Stub",
            aliases: &[],
        },
        Entry {
            value: PeriodRegularity::NonPeriodic,
            canonical: "NonPeriodic",
            aliases: &[],
        },
    ],
    &[],
);

impl fmt::Display for PeriodRegularity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.canonical_identifier())
    }
}

impl FromStr for PeriodRegularity {
    type Err = IdentifierError;
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        REGULARITY_IDS.parse(text)
    }
}

/// An owned calendar, retaining any TARGET validity, coverage and joint guard.
///
/// Calendar names cannot supply the required definition or projection policy.
/// This contextual value therefore has neither text parsing nor a default.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ScheduleCalendar {
    /// An immutable custom, weekend, null or plain joint definition.
    Plain(Calendar),
    /// A guarded TARGET definition, including explicit overrides/joint members.
    Target(TargetCalendar),
}

impl ScheduleCalendar {
    fn validate_span(&self, start: Date, end: Date) -> Result<(), ScheduleError> {
        self.validate_span_for(start, end, "coverage")
    }

    fn validate_span_for(
        &self,
        start: Date,
        end: Date,
        phase: &'static str,
    ) -> Result<(), ScheduleError> {
        if let Self::Target(calendar) = self {
            calendar
                .business_days_between(
                    start,
                    end,
                    EndpointInclusion::Include,
                    EndpointInclusion::Include,
                )
                .map_err(|cause| ScheduleError::Calendar {
                    index: None,
                    phase,
                    cause,
                })?;
        }
        Ok(())
    }

    fn adjust(
        &self,
        date: Date,
        convention: BusinessDayConvention,
        index: usize,
    ) -> Result<Date, ScheduleError> {
        let result = match self {
            Self::Plain(calendar) => calendar.adjust(date, convention),
            Self::Target(calendar) => calendar.adjust(date, convention),
        };
        result.map_err(|cause| ScheduleError::Calendar {
            index: Some(index),
            phase: "adjustment",
            cause,
        })
    }
}

/// Explicit first/penultimate coupon roles, independent of a builder's range.
///
/// At least one role is present. When both are present, first cannot follow
/// penultimate. Equal roles name one interior coupon, allowing two outer
/// intervals without a regular middle interval. Each supplied date must be
/// strictly interior to the range passed to [`ScheduleBuilder::build_explicit`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ExplicitStubDates {
    first: Option<Date>,
    penultimate: Option<Date>,
}

impl ExplicitStubDates {
    /// Validates presence and role ordering, without inferring a schedule range.
    ///
    /// # Errors
    /// Returns [`ScheduleError::EmptyExplicitStubDates`] for two absent roles,
    /// then [`ScheduleError::ReversedExplicitStubDates`] if first is later.
    pub fn new(first: Option<Date>, penultimate: Option<Date>) -> Result<Self, ScheduleError> {
        if first.is_none() && penultimate.is_none() {
            return Err(ScheduleError::EmptyExplicitStubDates);
        }
        if let (Some(first), Some(penultimate)) = (first, penultimate)
            && first > penultimate
        {
            return Err(ScheduleError::ReversedExplicitStubDates { first, penultimate });
        }
        Ok(Self { first, penultimate })
    }

    /// Returns the supplied first coupon date, if present.
    #[must_use]
    pub const fn first(self) -> Option<Date> {
        self.first
    }

    /// Returns the supplied penultimate coupon date, if present.
    #[must_use]
    pub const fn penultimate(self) -> Option<Date> {
        self.penultimate
    }
}

/// An immutable explicit range, calendar and pair of adjustment conventions.
///
/// Construction validates only `start < end`. Building checks options before
/// TARGET coverage, generates contractual dates, adjusts them, then rejects
/// collisions/reversals. No convention, frequency or current date is inferred.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ScheduleBuilder {
    start: Date,
    end: Date,
    calendar: ScheduleCalendar,
    convention: BusinessDayConvention,
    termination_convention: BusinessDayConvention,
}

impl ScheduleBuilder {
    /// Minimum final boundary count for every supported schedule.
    pub const MIN_BOUNDARIES: u32 = 2;

    /// Maximum final boundary count: every date in the supported civil range.
    pub const MAX_BOUNDARIES: u32 = 3_652_059;

    /// Owns the explicit inputs after validating an increasing date range.
    ///
    /// Coverage and recurrence-specific options are checked by the build
    /// operation, so a builder is not a claim that any schedule is valid.
    ///
    /// # Errors
    /// Returns [`ScheduleError::InvalidRange`] for equal or reversed endpoints.
    pub fn new(
        start: Date,
        end: Date,
        calendar: ScheduleCalendar,
        convention: BusinessDayConvention,
        termination_convention: BusinessDayConvention,
    ) -> Result<Self, ScheduleError> {
        if start >= end {
            return Err(ScheduleError::InvalidRange { start, end });
        }
        Ok(Self {
            start,
            end,
            calendar,
            convention,
            termination_convention,
        })
    }

    /// Returns the original contractual start.
    #[must_use]
    pub const fn start(&self) -> Date {
        self.start
    }

    /// Returns the original contractual end.
    #[must_use]
    pub const fn end(&self) -> Date {
        self.end
    }

    /// Borrows the retained calendar definition and any market guard.
    #[must_use]
    pub const fn calendar(&self) -> &ScheduleCalendar {
        &self.calendar
    }

    /// Returns the adjustment for start and interior boundaries.
    #[must_use]
    pub const fn convention(&self) -> BusinessDayConvention {
        self.convention
    }

    /// Returns the separate final-boundary adjustment.
    #[must_use]
    pub const fn termination_convention(&self) -> BusinessDayConvention {
        self.termination_convention
    }

    /// Builds an anchored Forward or Backward contractual lattice.
    ///
    /// The stored tenor length must be positive. Days and Weeks count calendar
    /// days; Months and Years use checked date arithmetic from the same
    /// original start/end on every step. `Preserve` is accepted only for month
    /// families, and activates only when the directional anchor is a calendar
    /// month end. It rolls generated regular candidates to calendar month end;
    /// original start/end remain unchanged. Business month end is not inferred.
    ///
    /// `None` rejects a residual; `Short` retains it; `Long` merges it with a
    /// preceding generated regular interval in that direction. Long fails
    /// when the span is shorter than one tenor. An exact lattice has only
    /// Regular intervals regardless of the retained stub policy.
    ///
    /// `max_boundaries` bounds the FINAL count, including endpoints. Long
    /// removes its neighboring regular boundary before adding the endpoint,
    /// so it may fit where Short would not. Generation terminates after at
    /// most O(final boundaries) steps plus the declared calendar costs.
    /// Schedule-vector growth uses fallible reservation and O(boundaries)
    /// storage; cloning an existing calendar follows its standard Clone
    /// allocation semantics. No partially generated schedule is returned.
    ///
    /// ```
    /// use sabiquant::calendar::{BusinessDayConvention, Calendar, EndOfMonth};
    /// use sabiquant::schedule::{DateGenerationRule, ScheduleBuilder, ScheduleCalendar, StubPolicy};
    /// use sabiquant::time::{Date, Period, TimeUnit};
    /// let builder = ScheduleBuilder::new(Date::from_ymd(2024, 1, 31)?,
    ///     Date::from_ymd(2024, 4, 30)?, ScheduleCalendar::Plain(Calendar::null()),
    ///     BusinessDayConvention::Unadjusted, BusinessDayConvention::Unadjusted)?;
    /// let schedule = builder.build_recurrent(Period::new(1, TimeUnit::Months),
    ///     DateGenerationRule::Forward, StubPolicy::None, EndOfMonth::Preserve, 4)?;
    /// assert_eq!(schedule.contractual_dates()[2], Date::from_ymd(2024, 3, 31)?);
    /// assert_eq!(schedule.contractual_dates(), schedule.adjusted_dates());
    /// # Ok::<(), sabiquant::error::Error>(())
    /// ```
    ///
    /// # Errors
    /// Checks the limit, rule, tenor and EOM compatibility in that order, then
    /// validates the whole TARGET span (including omitted holidays) before
    /// generation. Reports residual policy, final-count or allocation errors,
    /// checked date/calendar causes and adjusted-order conflicts. Unused
    /// candidates provably beyond the supported civil range terminate the
    /// lattice normally; unrelated date errors are preserved.
    pub fn build_recurrent(
        &self,
        tenor: Period,
        rule: DateGenerationRule,
        stub: StubPolicy,
        eom: EndOfMonth,
        max_boundaries: u32,
    ) -> Result<Schedule, ScheduleError> {
        validate_limit(max_boundaries)?;
        let forward = match rule {
            DateGenerationRule::Forward => true,
            DateGenerationRule::Backward => false,
            DateGenerationRule::Zero
            | DateGenerationRule::Roll(_)
            | DateGenerationRule::OldCds
            | DateGenerationRule::Cds
            | DateGenerationRule::Cds2015 => {
                return Err(ScheduleError::InvalidRule { rule });
            }
        };
        if tenor.length() <= 0 {
            return Err(ScheduleError::InvalidTenor { tenor });
        }
        if eom == EndOfMonth::Preserve && matches!(tenor.unit(), TimeUnit::Days | TimeUnit::Weeks) {
            return Err(ScheduleError::IncompatibleEndOfMonth {
                tenor,
                end_of_month: eom,
            });
        }
        self.calendar.validate_span(self.start, self.end)?;
        let (anchor, endpoint) = if forward {
            (self.start, self.end)
        } else {
            (self.end, self.start)
        };
        let preserve = eom == EndOfMonth::Preserve && anchor.is_end_of_month();
        let mut rolling = Rolling::new(anchor)?;
        loop {
            // Before residual handling, count is both the next recurrence step
            // and the current number of stored boundaries. It cannot exceed
            // MAX_BOUNDARIES, making all i64 scaled-tenor products safe.
            let candidate = anchored_candidate(
                anchor,
                tenor,
                rolling.count,
                forward,
                preserve,
                rolling.dates.len(),
            )?;
            if let Some(date) = candidate
                && if forward {
                    date < endpoint
                } else {
                    date > endpoint
                }
            {
                let required = rolling.count + if stub == StubPolicy::Long { 1 } else { 2 };
                if required > max_boundaries {
                    return Err(ScheduleError::BoundaryLimitExceeded {
                        maximum: max_boundaries,
                        required_at_least: required,
                    });
                }
                rolling.push(date, PeriodRegularity::Regular)?;
                continue;
            }
            if candidate == Some(endpoint) {
                rolling.push_limited(endpoint, PeriodRegularity::Regular, max_boundaries)?;
            } else {
                match stub {
                    StubPolicy::None => {
                        return Err(ScheduleError::StubRequired {
                            rule,
                            tenor,
                            start: self.start,
                            end: self.end,
                            regular_boundary: rolling.dates.last().copied().unwrap_or(anchor),
                        });
                    }
                    StubPolicy::Short => {
                        rolling.push_limited(endpoint, PeriodRegularity::Stub, max_boundaries)?
                    }
                    StubPolicy::Long => {
                        if rolling.regularity.is_empty() {
                            return Err(ScheduleError::LongStubWithoutRegularPeriod {
                                rule,
                                tenor,
                                start: self.start,
                                end: self.end,
                            });
                        }
                        // The final-count cap is applied after removing the
                        // neighboring regular boundary, never to a Short draft.
                        rolling.dates.pop();
                        rolling.regularity.pop();
                        rolling.count -= 1;
                        rolling.push_limited(endpoint, PeriodRegularity::Stub, max_boundaries)?;
                    }
                }
            }
            break;
        }
        if !forward {
            rolling.dates.reverse();
            rolling.regularity.reverse();
        }
        self.finish(rolling, rule, Some(tenor), Some(stub), Some(eom), None)
    }

    /// Builds a regular middle with explicitly named first/penultimate coupons.
    ///
    /// Forward anchors at the supplied first date, otherwise start. Backward
    /// anchors at the supplied penultimate date, otherwise end. The opposite
    /// middle endpoint MUST lie on that same original-anchor lattice; no
    /// additional implicit stub is generated. Equal first/penultimate roles
    /// produce one interior boundary and no middle interval.
    ///
    /// Calendar EOM preservation activates from this middle anchor, and never
    /// rewrites the supplied coupon dates or range endpoints. Each outer
    /// interval is Regular only if its endpoint equals the adjacent boundary
    /// of this SAME lattice; otherwise it is Stub. A clamped date is never
    /// reused as a new seed. Thus Forward with first February 28 and start
    /// January 31 is Stub under Ignore: February 28 minus one month is January
    /// 28. This records named lattice provenance, not general equivalence of
    /// date conventions. An out-of-range classification-only adjacent date
    /// cannot match the in-range endpoint, so that interval is Stub.
    ///
    /// `max_boundaries` counts ALL final boundaries including explicit dates
    /// and range endpoints. Generation uses O(boundaries) steps/storage and
    /// the same fallible reservations as recurrent construction. Adjustment
    /// retains one boundary per contractual date and rejects collisions.
    /// The result retains the supplied explicit roles, tenor, rule and EOM;
    /// [`Schedule::stub_policy`] is None because no automatic policy applies.
    ///
    /// ```
    /// use sabiquant::calendar::{BusinessDayConvention, Calendar, EndOfMonth};
    /// use sabiquant::schedule::{DateGenerationRule, ExplicitStubDates,
    ///     PeriodRegularity, ScheduleBuilder, ScheduleCalendar};
    /// use sabiquant::time::{Date, Period, TimeUnit};
    /// let builder = ScheduleBuilder::new(Date::from_ymd(2026, 1, 15)?,
    ///     Date::from_ymd(2026, 11, 15)?, ScheduleCalendar::Plain(Calendar::null()),
    ///     BusinessDayConvention::Unadjusted, BusinessDayConvention::Unadjusted)?;
    /// let explicit = ExplicitStubDates::new(Some(Date::from_ymd(2026, 1, 31)?),
    ///     Some(Date::from_ymd(2026, 10, 31)?))?;
    /// let schedule = builder.build_explicit(Period::new(3, TimeUnit::Months),
    ///     DateGenerationRule::Forward, explicit, EndOfMonth::Ignore, 6)?;
    /// assert_eq!(schedule.regularity(), &[PeriodRegularity::Stub,
    ///     PeriodRegularity::Regular, PeriodRegularity::Regular,
    ///     PeriodRegularity::Regular, PeriodRegularity::Stub]);
    /// assert_eq!(schedule.explicit_stub_dates(), Some(explicit));
    /// # Ok::<(), sabiquant::error::Error>(())
    /// ```
    ///
    /// # Errors
    /// Checks the limit, rule, tenor, EOM compatibility, first then penultimate
    /// strictly-interior roles, then whole original TARGET-span coverage.
    /// Reports off-lattice middle endpoints with contextual metadata, final
    /// cap/allocation errors, checked causes and adjusted-order conflicts.
    pub fn build_explicit(
        &self,
        tenor: Period,
        rule: DateGenerationRule,
        dates: ExplicitStubDates,
        eom: EndOfMonth,
        max_boundaries: u32,
    ) -> Result<Schedule, ScheduleError> {
        validate_limit(max_boundaries)?;
        let forward = match rule {
            DateGenerationRule::Forward => true,
            DateGenerationRule::Backward => false,
            DateGenerationRule::Zero
            | DateGenerationRule::Roll(_)
            | DateGenerationRule::OldCds
            | DateGenerationRule::Cds
            | DateGenerationRule::Cds2015 => {
                return Err(ScheduleError::InvalidRule { rule });
            }
        };
        if tenor.length() <= 0 {
            return Err(ScheduleError::InvalidTenor { tenor });
        }
        if eom == EndOfMonth::Preserve && matches!(tenor.unit(), TimeUnit::Days | TimeUnit::Weeks) {
            return Err(ScheduleError::IncompatibleEndOfMonth {
                tenor,
                end_of_month: eom,
            });
        }
        for (role, date) in [("first", dates.first), ("penultimate", dates.penultimate)] {
            if let Some(date) = date
                && (date <= self.start || date >= self.end)
            {
                return Err(ScheduleError::ExplicitStubOutsideRange {
                    role,
                    date,
                    start: self.start,
                    end: self.end,
                });
            }
        }
        self.calendar.validate_span(self.start, self.end)?;
        let regular_start = dates.first.unwrap_or(self.start);
        let regular_end = dates.penultimate.unwrap_or(self.end);
        let (anchor, endpoint, leading, trailing) = if forward {
            (
                regular_start,
                regular_end,
                dates.first.map(|_| self.start),
                dates.penultimate.map(|_| self.end),
            )
        } else {
            (
                regular_end,
                regular_start,
                dates.penultimate.map(|_| self.end),
                dates.first.map(|_| self.start),
            )
        };
        let preserve = eom == EndOfMonth::Preserve && anchor.is_end_of_month();
        let extra = u32::from(leading.is_some()) + u32::from(trailing.is_some());
        let required = extra + if anchor == endpoint { 1 } else { 2 };
        if required > max_boundaries {
            return Err(ScheduleError::BoundaryLimitExceeded {
                maximum: max_boundaries,
                required_at_least: required,
            });
        }
        let mut rolling = Rolling::new(leading.unwrap_or(anchor))?;
        if let Some(outer) = leading {
            let adjacent = anchored_candidate(anchor, tenor, 1, !forward, preserve, 0)?;
            rolling.push(anchor, outer_regularity(adjacent, outer))?;
        }
        // Unlike automatic construction, the count also contains any leading
        // endpoint. Keep the recurrence step independent of vector length.
        let mut step = 0;
        if anchor != endpoint {
            loop {
                step += 1;
                let candidate = anchored_candidate(
                    anchor,
                    tenor,
                    step,
                    forward,
                    preserve,
                    rolling.dates.len(),
                )?;
                if candidate == Some(endpoint) {
                    // The initial minimum or the preceding strict-interior check
                    // already reserves this endpoint and any trailing boundary.
                    rolling.push(endpoint, PeriodRegularity::Regular)?;
                    break;
                }
                if let Some(date) = candidate
                    && if forward {
                        date < endpoint
                    } else {
                        date > endpoint
                    }
                {
                    // This interior and the middle endpoint must still be stored,
                    // as must the outer trailing boundary if supplied.
                    let required = rolling.count + 2 + u32::from(trailing.is_some());
                    if required > max_boundaries {
                        return Err(ScheduleError::BoundaryLimitExceeded {
                            maximum: max_boundaries,
                            required_at_least: required,
                        });
                    }
                    rolling.push(date, PeriodRegularity::Regular)?;
                } else {
                    return Err(ScheduleError::IrregularExplicitMiddle {
                        rule,
                        tenor,
                        anchor,
                        endpoint,
                        regular_boundary: rolling.dates.last().copied().unwrap_or(anchor),
                    });
                }
            }
        }
        if let Some(outer) = trailing {
            let adjacent = anchored_candidate(
                anchor,
                tenor,
                step + 1,
                forward,
                preserve,
                rolling.dates.len(),
            )?;
            rolling.push_limited(outer, outer_regularity(adjacent, outer), max_boundaries)?;
        }
        if !forward {
            rolling.dates.reverse();
            rolling.regularity.reverse();
        }
        self.finish(rolling, rule, Some(tenor), None, Some(eom), Some(dates))
    }

    /// Builds exactly the original start/end pair and one NonPeriodic interval.
    ///
    /// There is no artificial tenor, stub or EOM metadata. Both endpoints and
    /// the entire raw TARGET span are still guarded, including Unadjusted and
    /// joint calendars. Adjustment conventions remain explicit and separate.
    ///
    /// ```
    /// use sabiquant::calendar::{BusinessDayConvention, Calendar};
    /// use sabiquant::schedule::{PeriodRegularity, ScheduleBuilder, ScheduleCalendar};
    /// use sabiquant::time::Date;
    /// let builder = ScheduleBuilder::new(Date::from_ymd(2026, 1, 2)?,
    ///     Date::from_ymd(2026, 2, 2)?, ScheduleCalendar::Plain(Calendar::weekends_only()),
    ///     BusinessDayConvention::Following, BusinessDayConvention::Following)?;
    /// let schedule = builder.build_zero(2)?;
    /// assert_eq!(schedule.regularity(), &[PeriodRegularity::NonPeriodic]);
    /// assert_eq!(schedule.tenor(), None);
    /// # Ok::<(), sabiquant::error::Error>(())
    /// ```
    ///
    /// # Errors
    /// Returns a limit error before coverage, then typed coverage/adjustment,
    /// allocation or adjusted-order errors. No partial value is returned.
    pub fn build_zero(&self, max_boundaries: u32) -> Result<Schedule, ScheduleError> {
        validate_limit(max_boundaries)?;
        self.calendar.validate_span(self.start, self.end)?;
        let mut rolling = Rolling::new(self.start)?;
        rolling.push_limited(self.end, PeriodRegularity::NonPeriodic, max_boundaries)?;
        self.finish(rolling, DateGenerationRule::Zero, None, None, None, None)
    }

    fn finish(
        &self,
        rolling: Rolling,
        rule: DateGenerationRule,
        tenor: Option<Period>,
        stub: Option<StubPolicy>,
        eom: Option<EndOfMonth>,
        explicit: Option<ExplicitStubDates>,
    ) -> Result<Schedule, ScheduleError> {
        let mut adjusted = Vec::new();
        adjusted
            .try_reserve_exact(rolling.dates.len())
            .map_err(|_| ScheduleError::AllocationFailed {
                phase: "adjusted boundaries",
                requested: rolling.dates.len(),
            })?;
        for (index, &date) in rolling.dates.iter().enumerate() {
            let convention = if index + 1 == rolling.dates.len() {
                self.termination_convention
            } else {
                self.convention
            };
            let value = self.calendar.adjust(date, convention, index)?;
            if let Some(&previous_adjusted) = adjusted.last()
                && value <= previous_adjusted
            {
                return Err(ScheduleError::AdjustedOrder {
                    index,
                    previous_contractual: rolling.dates[index - 1],
                    contractual: date,
                    previous_adjusted,
                    adjusted: value,
                });
            }
            adjusted.push(value);
        }
        Ok(Schedule {
            contractual: rolling.dates,
            adjusted,
            regularity: rolling.regularity,
            generation_rule: rule,
            tenor,
            stub_policy: stub,
            end_of_month: eom,
            explicit_stub_dates: explicit,
            roll_provenance: None,
            old_cds_provenance: None,
            calendar: self.calendar.clone(),
            convention: self.convention,
            termination_convention: self.termination_convention,
        })
    }
}

/// A fully built chronological contractual/adjusted schedule with provenance.
///
/// Both date slices have equal length, at least two, with strictly increasing
/// dates; regularity has exactly one fewer element. No adjustment collision
/// is repaired by sorting or deduplication. Metadata remains the supplied
/// configuration, including an inactive Preserve or an unused Long policy.
///
/// Equality and hashing compare the defined vectors and retained metadata,
/// including the tenor's STORED length and unit. Therefore 12M and 1Y can
/// generate identical dates and still define unequal schedules, even though
/// their Period values compare equal. This is definition identity, not general
/// financial equivalence; clone and inspection introduce no mutable cache.
#[derive(Clone, Debug)]
pub struct Schedule {
    contractual: Vec<Date>,
    adjusted: Vec<Date>,
    regularity: Vec<PeriodRegularity>,
    generation_rule: DateGenerationRule,
    tenor: Option<Period>,
    stub_policy: Option<StubPolicy>,
    end_of_month: Option<EndOfMonth>,
    explicit_stub_dates: Option<ExplicitStubDates>,
    roll_provenance: Option<RollProvenance>,
    old_cds_provenance: Option<OldCdsProvenance>,
    calendar: ScheduleCalendar,
    convention: BusinessDayConvention,
    termination_convention: BusinessDayConvention,
}

impl Schedule {
    /// Minimum supported final determination-period count.
    pub const MIN_ICMA_PERIODS: u32 = 1;

    /// Maximum positive one-day determination periods in the civil date range.
    pub const MAX_ICMA_PERIODS: u32 = 3_652_058;

    /// Builds the minimal same-anchor ICMA reference hull over raw accrual dates.
    ///
    /// The frequency is explicit and periodic, and its period must compare
    /// normalized-equal to the retained tenor. Thus 12M/1Y or 7D/1W may match;
    /// no frequency is inferred from a stub. The declared event counts for
    /// day/week frequencies remain 365/52/26/13, even in leap years. This is
    /// an analytical contractual definition, not approval of every market roll.
    ///
    /// References use the original named lattice anchor and calendar-EOM
    /// policy, the retained civil roll's exact Wednesday/twentieth points, or
    /// OldCDS steps of its stored tenor from the retained recurrence anchor.
    /// A roll's requested endpoints do not replace its resolved raw endpoints.
    /// The greatest lattice date no later than raw start and the least
    /// lattice date no earlier than raw end bound the MINIMAL contiguous hull.
    /// Exact endpoints need no extra period. Long/equal-role outer spans may
    /// require multiple quasi-periods, including dates absent from coupons.
    /// Adjusted payment dates and business-day conventions do not alter them.
    ///
    /// Every required extension uses checked civil arithmetic; an out-of-range
    /// quasi-date is an error. The entire extended TARGET span is validated
    /// under the owned strict/projected policy before returning the immutable
    /// context. Its subsequent queries use only supplied references and their
    /// coverage; they do not query a calendar or grant new market coverage.
    ///
    /// `max_periods` bounds ALL final positive reference intervals, shared by
    /// both extension directions. Work/storage is O(reference periods), plus
    /// the existing market-span validation cost. Boundary/period vectors use
    /// fallible reservation. No partial context or mutable cache is returned.
    ///
    /// ```
    /// use sabiquant::calendar::{BusinessDayConvention, Calendar, EndOfMonth};
    /// use sabiquant::schedule::{DateGenerationRule, ScheduleBuilder,
    ///     ScheduleCalendar, StubPolicy};
    /// use sabiquant::time::{Date, Frequency, Period, TimeUnit};
    /// let start = Date::from_ymd(1999, 2, 1)?;
    /// let end = Date::from_ymd(1999, 7, 1)?;
    /// let schedule = ScheduleBuilder::new(start, end,
    ///     ScheduleCalendar::Plain(Calendar::null()),
    ///     BusinessDayConvention::Unadjusted, BusinessDayConvention::Unadjusted)?
    ///     .build_recurrent(Period::new(1, TimeUnit::Years),
    ///         DateGenerationRule::Backward, StubPolicy::Short, EndOfMonth::Ignore, 2)?;
    /// let icma = schedule.build_icma_context(Frequency::Annual, 1)?;
    /// assert_eq!(icma.coverage_start(), Date::from_ymd(1998, 7, 1)?);
    /// assert_eq!(icma.year_fraction(start, end)?.to_bits(), (150.0_f64 / 365.0).to_bits());
    /// # Ok::<(), sabiquant::error::Error>(())
    /// ```
    ///
    /// Civil rolls recompute each month's roll date instead of carrying the
    /// anchor's day of month into subsequent references:
    ///
    /// ```
    /// use sabiquant::calendar::{BusinessDayConvention as Bdc, Calendar};
    /// use sabiquant::schedule::{ScheduleBuilder, ScheduleCalendar, SpecialRollRule};
    /// use sabiquant::time::{Date, Frequency, Period, TimeUnit};
    /// let schedule = ScheduleBuilder::new(Date::from_ymd(2024, 1, 16)?,
    ///     Date::from_ymd(2024, 1, 18)?, ScheduleCalendar::Plain(Calendar::null()),
    ///     Bdc::Unadjusted, Bdc::Unadjusted)?
    ///     .build_roll(Period::new(1, TimeUnit::Months), SpecialRollRule::ThirdWednesday, 2)?;
    /// let icma = schedule.build_icma_context(Frequency::Monthly, 2)?;
    /// assert_eq!(icma.coverage_start(), Date::from_ymd(2023, 12, 20)?);
    /// assert_eq!(icma.periods()[0].end(), Date::from_ymd(2024, 1, 17)?);
    /// assert_eq!(icma.coverage_end(), Date::from_ymd(2024, 2, 21)?);
    /// # Ok::<(), sabiquant::error::Error>(())
    /// ```
    ///
    /// An OldCDS hull can need several earlier references. Here March 20 is
    /// omitted from the raw coupons yet still bounds a Quarterly reference:
    ///
    /// ```
    /// use sabiquant::calendar::{BusinessDayConvention as Bdc, Calendar};
    /// use sabiquant::schedule::{ScheduleBuilder, ScheduleCalendar};
    /// use sabiquant::time::{Date, Frequency, Period, TimeUnit};
    /// let start = Date::from_ymd(2026, 2, 19)?;
    /// let schedule = ScheduleBuilder::new(start, Date::from_ymd(2026, 6, 1)?,
    ///     ScheduleCalendar::Plain(Calendar::null()), Bdc::Unadjusted, Bdc::Unadjusted)?
    ///     .build_old_cds(Period::new(3, TimeUnit::Months), 2)?;
    /// let icma = schedule.build_icma_context(Frequency::Quarterly, 2)?;
    /// assert_eq!(icma.coverage_start(), Date::from_ymd(2025, 12, 20)?);
    /// assert_eq!(icma.periods()[0].end(), Date::from_ymd(2026, 3, 20)?);
    /// let fraction = icma.year_fraction(start, Date::from_ymd(2026, 6, 20)?)?;
    /// assert_eq!(fraction.to_bits(), (119.0_f64 / 360.0).to_bits());
    /// # Ok::<(), sabiquant::error::Error>(())
    /// ```
    ///
    /// # Errors
    /// Checks the cap, periodic schedule, frequency and tenor match in order.
    /// A proved cap insufficiency precedes computing the disallowed required
    /// date. Then reports checked Date causes, extended Calendar coverage,
    /// allocation failures or preserved ICMA constructor causes. Zero and Once
    /// are rejected. Required roll extensions retain the exact roll anchor
    /// and signed month offset in their Date cause, including stored Years.
    /// No unused-candidate absence hides a required quasi-date.
    pub fn build_icma_context(
        &self,
        frequency: Frequency,
        max_periods: u32,
    ) -> Result<ActualActualIcma, ScheduleError> {
        if !(Self::MIN_ICMA_PERIODS..=Self::MAX_ICMA_PERIODS).contains(&max_periods) {
            return Err(ScheduleError::InvalidIcmaPeriodLimit {
                requested: max_periods,
                minimum: Self::MIN_ICMA_PERIODS,
                maximum: Self::MAX_ICMA_PERIODS,
            });
        }
        let lattice = match self.generation_rule {
            DateGenerationRule::Forward | DateGenerationRule::Backward => self
                .end_of_month
                .zip(self.lattice_anchor())
                .map(|(eom, anchor)| IcmaLattice::Anchored {
                    anchor,
                    preserve: eom == EndOfMonth::Preserve && anchor.is_end_of_month(),
                }),
            DateGenerationRule::Roll(_) => self.roll_provenance.map(IcmaLattice::Roll),
            // Every twentieth exists, so unclamped stored-unit steps from B
            // reproduce the OldCDS stride lattice exactly.
            DateGenerationRule::OldCds => {
                self.old_cds_provenance
                    .map(|provenance| IcmaLattice::Anchored {
                        anchor: provenance.recurrence_anchor(),
                        preserve: false,
                    })
            }
            DateGenerationRule::Zero | DateGenerationRule::Cds | DateGenerationRule::Cds2015 => {
                None
            }
        };
        let (Some(tenor), Some(lattice)) = (self.tenor, lattice) else {
            return Err(ScheduleError::NonPeriodicIcma {
                rule: self.generation_rule,
            });
        };
        let Some(expected_tenor) = frequency.period() else {
            return Err(ScheduleError::InvalidIcmaFrequency { frequency });
        };
        if tenor != expected_tenor {
            return Err(ScheduleError::IcmaFrequencyMismatch {
                tenor,
                frequency,
                expected_tenor,
            });
        }
        // Private construction guarantees chronological nonempty raw slices.
        let (Some(&start), Some(&end)) = (self.contractual.first(), self.contractual.last()) else {
            return Err(ScheduleError::NonPeriodicIcma {
                rule: self.generation_rule,
            });
        };
        let anchor = lattice.anchor()?;
        // Each supported definition places q(0) inside its minimal hull.
        // Roll starts share the Wednesday anchor month or precede the first
        // eligible twentieth by less than one stride. Their raw end can lie
        // before q(0), so only anchor < end proves an upper period is needed.
        // OldCDS has start < B <= end, but its start may precede B by several
        // strides; the general lower loop below takes as many steps as needed.
        let remaining_upper = u32::from(anchor < end);
        let mut count = 0;
        let mut boundaries = Vec::new();
        reserve_one(&mut boundaries, "ICMA reference boundaries")?;
        boundaries.push(anchor);
        let mut lower = anchor;
        let mut step = 0;
        while lower > start {
            check_icma_count(count + 1 + remaining_upper, max_periods)?;
            step += 1;
            lower = lattice.date(anchor, tenor, step, false, boundaries.len())?;
            reserve_one(&mut boundaries, "ICMA reference boundaries")?;
            boundaries.push(lower);
            count += 1;
        }
        boundaries.reverse();
        let mut upper = anchor;
        step = 0;
        while upper < end {
            check_icma_count(count + 1, max_periods)?;
            step += 1;
            upper = lattice.date(anchor, tenor, step, true, boundaries.len())?;
            reserve_one(&mut boundaries, "ICMA reference boundaries")?;
            boundaries.push(upper);
            count += 1;
        }
        self.calendar
            .validate_span_for(lower, upper, "ICMA reference coverage")?;
        let mut periods = Vec::new();
        periods
            .try_reserve_exact(boundaries.len() - 1)
            .map_err(|_| ScheduleError::AllocationFailed {
                phase: "ICMA determination periods",
                requested: boundaries.len() - 1,
            })?;
        for pair in boundaries.windows(2) {
            let period = DeterminationPeriod::new(pair[0], pair[1])
                .map_err(|cause| ScheduleError::Icma { cause })?;
            periods.push(period);
        }
        ActualActualIcma::new(periods, frequency).map_err(|cause| ScheduleError::Icma { cause })
    }

    /// Borrows chronological raw contractual boundaries, including endpoints.
    #[must_use]
    pub fn contractual_dates(&self) -> &[Date] {
        &self.contractual
    }

    /// Borrows one adjusted date per contractual boundary, in the same order.
    #[must_use]
    pub fn adjusted_dates(&self) -> &[Date] {
        &self.adjusted
    }

    /// Borrows contractual interval provenance; adjustment never changes it.
    #[must_use]
    pub fn regularity(&self) -> &[PeriodRegularity] {
        &self.regularity
    }

    /// Returns the selected rule; Zero is explicit, not missing metadata.
    #[must_use]
    pub const fn generation_rule(&self) -> DateGenerationRule {
        self.generation_rule
    }

    /// Returns the supplied stored tenor, or None for Zero.
    #[must_use]
    pub const fn tenor(&self) -> Option<Period> {
        self.tenor
    }

    /// Returns the supplied automatic residual policy, or None for explicit/Zero/roll/OldCDS.
    #[must_use]
    pub const fn stub_policy(&self) -> Option<StubPolicy> {
        self.stub_policy
    }

    /// Returns the supplied calendar EOM policy, or None for Zero/roll/OldCDS.
    #[must_use]
    pub const fn end_of_month(&self) -> Option<EndOfMonth> {
        self.end_of_month
    }

    /// Returns the supplied explicit coupon roles, or None for automatic/Zero/roll.
    #[must_use]
    pub const fn explicit_stub_dates(&self) -> Option<ExplicitStubDates> {
        self.explicit_stub_dates
    }

    /// Borrows civil roll provenance, or None for recurrent/explicit/Zero/OldCDS.
    #[must_use]
    pub const fn roll_provenance(&self) -> Option<&RollProvenance> {
        self.roll_provenance.as_ref()
    }

    /// Borrows the OldCDS definition, or None for every other constructor.
    ///
    /// The requested end and stored tenor cannot be recovered from the raw
    /// dates; the generation start, quarters and recurrence anchor are kept
    /// alongside them for direct inspection. Two requested ends projecting to
    /// one vector differ here.
    #[must_use]
    pub const fn old_cds_provenance(&self) -> Option<&OldCdsProvenance> {
        self.old_cds_provenance.as_ref()
    }

    /// Returns the original clamped-date lattice seed, or None for Zero/roll/OldCDS.
    ///
    /// Forward uses explicit first, otherwise original start. Backward uses
    /// explicit penultimate, otherwise original end. Adjustment does not alter
    /// this seed. The slices are privately guaranteed nonempty.
    #[must_use]
    pub fn lattice_anchor(&self) -> Option<Date> {
        match self.generation_rule {
            DateGenerationRule::Forward => self
                .explicit_stub_dates
                .and_then(ExplicitStubDates::first)
                .or_else(|| self.contractual.first().copied()),
            DateGenerationRule::Backward => self
                .explicit_stub_dates
                .and_then(ExplicitStubDates::penultimate)
                .or_else(|| self.contractual.last().copied()),
            DateGenerationRule::Zero
            | DateGenerationRule::Roll(_)
            | DateGenerationRule::OldCds
            | DateGenerationRule::Cds
            | DateGenerationRule::Cds2015 => None,
        }
    }

    /// Borrows the owned calendar definition and retained market guard.
    #[must_use]
    pub const fn calendar(&self) -> &ScheduleCalendar {
        &self.calendar
    }

    /// Returns the adjustment for start/interior boundaries.
    #[must_use]
    pub const fn convention(&self) -> BusinessDayConvention {
        self.convention
    }

    /// Returns the distinct adjustment applied only to the last boundary.
    #[must_use]
    pub const fn termination_convention(&self) -> BusinessDayConvention {
        self.termination_convention
    }
}

impl PartialEq for Schedule {
    fn eq(&self, other: &Self) -> bool {
        self.contractual == other.contractual
            && self.adjusted == other.adjusted
            && self.regularity == other.regularity
            && self.generation_rule == other.generation_rule
            && stored_tenor(self.tenor) == stored_tenor(other.tenor)
            && self.stub_policy == other.stub_policy
            && self.end_of_month == other.end_of_month
            && self.explicit_stub_dates == other.explicit_stub_dates
            && self.roll_provenance == other.roll_provenance
            && self.old_cds_provenance == other.old_cds_provenance
            && self.calendar == other.calendar
            && self.convention == other.convention
            && self.termination_convention == other.termination_convention
    }
}

impl Eq for Schedule {}

impl Hash for Schedule {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.contractual.hash(state);
        self.adjusted.hash(state);
        self.regularity.hash(state);
        self.generation_rule.hash(state);
        stored_tenor(self.tenor).hash(state);
        self.stub_policy.hash(state);
        self.end_of_month.hash(state);
        self.explicit_stub_dates.hash(state);
        self.roll_provenance.hash(state);
        self.old_cds_provenance.hash(state);
        self.calendar.hash(state);
        self.convention.hash(state);
        self.termination_convention.hash(state);
    }
}

fn stored_tenor(tenor: Option<Period>) -> Option<(i32, TimeUnit)> {
    tenor.map(|value| (value.length(), value.unit()))
}

/// A rejected schedule configuration, resource request or generated boundary.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScheduleError {
    /// Unsupported stored quoted tenor; `schedule.invalid_cds_tenor`.
    #[non_exhaustive]
    InvalidCdsTenor {
        /// Supplied trade date.
        trade_date: Date,
        /// Original stored quote, before normalization.
        tenor: Period,
        /// Explicit modern maturity regime.
        convention: CdsMaturityConvention,
    },
    /// Required quoted maturity is out of range; `schedule.cds_maturity_date`.
    #[non_exhaustive]
    CdsMaturityDate {
        /// Supplied trade date.
        trade_date: Date,
        /// Original stored quote.
        tenor: Period,
        /// Explicit modern maturity regime.
        convention: CdsMaturityConvention,
        /// Preserved required final-target Date cause.
        cause: DateError,
    },
    /// Supplied maturity is not a quarterly twentieth; `schedule.invalid_cds_maturity`.
    #[non_exhaustive]
    InvalidCdsMaturity {
        /// Rejected raw maturity.
        maturity: Date,
        /// Explicit modern maturity regime.
        convention: CdsMaturityConvention,
    },
    /// Unsupported coupon cap; `schedule.invalid_cds_coupon_limit`.
    #[non_exhaustive]
    InvalidCdsCouponLimit {
        /// Requested final coupon cap.
        requested: u32,
        /// Minimum supported cap.
        minimum: u32,
        /// Maximum supported cap.
        maximum: u32,
    },
    /// Selected coupons exceed the cap; `schedule.cds_coupon_limit_exceeded`.
    #[non_exhaustive]
    CdsCouponLimitExceeded {
        /// Caller-supplied cap.
        maximum: u32,
        /// Exact required final coupon count.
        required: u32,
    },
    /// No payment is strictly after the cutoff; `schedule.no_eligible_cds_payment`.
    ///
    /// This is an operation outcome, not a declaration of legal invalidity.
    #[non_exhaustive]
    NoEligibleCdsPayment {
        /// Supplied trade date.
        trade_date: Date,
        /// Unadjusted trade plus one calendar day.
        payment_selection_cutoff: Date,
        /// Supplied raw maturity.
        unadjusted_maturity: Date,
        /// Adjusted payment at that maturity.
        final_payment: Date,
    },
    /// A required plan date is unavailable; `schedule.cds_date`.
    #[non_exhaustive]
    CdsDate {
        /// Supplied trade date.
        trade_date: Date,
        /// Supplied raw maturity.
        unadjusted_maturity: Date,
        /// Required date role.
        role: &'static str,
        /// Date from which checked arithmetic was performed.
        input: Date,
        /// Preserved checked date cause.
        cause: DateError,
    },
    /// CDS coverage or adjustment failed; `schedule.cds_calendar`.
    #[non_exhaustive]
    CdsCalendar {
        /// Supplied trade date.
        trade_date: Date,
        /// Supplied raw maturity.
        unadjusted_maturity: Date,
        /// Coverage or adjustment phase.
        phase: &'static str,
        /// Zero-based coupon index, absent for coverage or initial selection.
        index: Option<usize>,
        /// Queried span start; raw date for adjustment.
        start: Date,
        /// Queried span end; raw date for adjustment.
        end: Date,
        /// Preserved calendar cause.
        cause: CalendarError,
    },
    /// CDS adjusted boundaries collide; `schedule.cds_adjusted_order`.
    #[non_exhaustive]
    CdsAdjustedOrder {
        /// Zero-based failing coupon, including zero for its precursor pair.
        index: usize,
        /// Preceding raw quarterly twentieth.
        previous_contractual: Date,
        /// Current raw quarterly twentieth.
        contractual: Date,
        /// Preceding adjusted boundary.
        previous_adjusted: Date,
        /// Current adjusted boundary.
        adjusted: Date,
    },
    /// A stored tenor is incompatible with a roll; `schedule.invalid_roll_tenor`.
    #[non_exhaustive]
    InvalidRollTenor {
        /// Requested civil rule.
        rule: SpecialRollRule,
        /// Original stored tenor.
        tenor: Period,
    },
    /// Projected endpoints fail to increase; `schedule.resolved_roll_range`.
    #[non_exhaustive]
    ResolvedRollRange {
        /// Requested civil rule.
        rule: SpecialRollRule,
        /// Original stored tenor.
        tenor: Period,
        /// Original start.
        requested_start: Date,
        /// Original end.
        requested_end: Date,
        /// Projected contractual start.
        resolved_start: Date,
        /// Projected contractual end.
        resolved_end: Date,
    },
    /// A required roll date is unavailable; `schedule.roll_date`.
    #[non_exhaustive]
    RollDate {
        /// Requested civil rule.
        rule: SpecialRollRule,
        /// Original stored tenor.
        tenor: Period,
        /// Required date role, such as `anchor`, `start` or `end`.
        role: &'static str,
        /// Date from which the required roll was resolved.
        input: Date,
        /// Preserved checked civil-date cause.
        cause: DateError,
    },
    /// A stored tenor is outside the OldCDS domain; `schedule.invalid_old_cds_tenor`.
    #[non_exhaustive]
    InvalidOldCdsTenor {
        /// Builder start used as the OldCDS generation start.
        generation_start: Date,
        /// Builder end used as the requested end.
        requested_end: Date,
        /// Original stored tenor; positive Months or Years are required.
        tenor: Period,
    },
    /// A required OldCDS quarter is unavailable; `schedule.old_cds_date`.
    #[non_exhaustive]
    OldCdsDate {
        /// Builder start used as the OldCDS generation start.
        generation_start: Date,
        /// Builder end used as the requested end.
        requested_end: Date,
        /// Original stored tenor.
        tenor: Period,
        /// Required role: `terminal quarter`, `initial quarter`,
        /// `recurrence anchor` or `stride point`.
        role: &'static str,
        /// Date from which the required quarter was resolved.
        input: Date,
        /// Preserved checked civil-date cause.
        cause: DateError,
    },
    /// Equal or reversed endpoints; `schedule.invalid_range`.
    #[non_exhaustive]
    InvalidRange {
        /// Requested original start.
        start: Date,
        /// Requested original end.
        end: Date,
    },
    /// An unsupported final-boundary cap; `schedule.invalid_boundary_limit`.
    #[non_exhaustive]
    InvalidBoundaryLimit {
        /// Requested cap.
        requested: u32,
        /// Minimum supported cap.
        minimum: u32,
        /// Maximum supported cap.
        maximum: u32,
    },
    /// A non-recurrence rule passed to recurrent or explicit generation; `schedule.invalid_rule`.
    #[non_exhaustive]
    InvalidRule {
        /// Rejected rule; use build_zero for Zero.
        rule: DateGenerationRule,
    },
    /// A stored tenor length is nonpositive; `schedule.invalid_tenor`.
    #[non_exhaustive]
    InvalidTenor {
        /// Rejected period, preserving its stored representation.
        tenor: Period,
    },
    /// Preserve used for Days/Weeks; `schedule.incompatible_end_of_month`.
    #[non_exhaustive]
    IncompatibleEndOfMonth {
        /// Rejected recurrence period.
        tenor: Period,
        /// Rejected EOM option.
        end_of_month: EndOfMonth,
    },
    /// Neither coupon role is supplied; `schedule.empty_explicit_stub_dates`.
    EmptyExplicitStubDates,
    /// First follows penultimate; `schedule.reversed_explicit_stub_dates`.
    #[non_exhaustive]
    ReversedExplicitStubDates {
        /// Rejected first coupon date.
        first: Date,
        /// Rejected penultimate coupon date.
        penultimate: Date,
    },
    /// A coupon is not strictly interior; `schedule.explicit_stub_outside_range`.
    #[non_exhaustive]
    ExplicitStubOutsideRange {
        /// First or penultimate role.
        role: &'static str,
        /// Rejected coupon date.
        date: Date,
        /// Original range start.
        start: Date,
        /// Original range end.
        end: Date,
    },
    /// Middle endpoint is off the named lattice; `schedule.irregular_explicit_middle`.
    #[non_exhaustive]
    IrregularExplicitMiddle {
        /// Generation direction.
        rule: DateGenerationRule,
        /// Supplied stored tenor.
        tenor: Period,
        /// Original directional regular seed.
        anchor: Date,
        /// Opposite middle endpoint.
        endpoint: Date,
        /// Last generated regular boundary in the directional sequence.
        regular_boundary: Date,
    },
    /// Unsupported reference-period cap; `schedule.invalid_icma_period_limit`.
    #[non_exhaustive]
    InvalidIcmaPeriodLimit {
        /// Requested final positive-period cap.
        requested: u32,
        /// Minimum supported count.
        minimum: u32,
        /// Maximum supported count.
        maximum: u32,
    },
    /// A schedule has no recurring lattice; `schedule.non_periodic_icma`.
    #[non_exhaustive]
    NonPeriodicIcma {
        /// Rejected schedule rule, currently Zero.
        rule: DateGenerationRule,
    },
    /// Frequency is not periodic; `schedule.invalid_icma_frequency`.
    #[non_exhaustive]
    InvalidIcmaFrequency {
        /// Rejected named frequency, currently Once.
        frequency: Frequency,
    },
    /// Tenor does not match the explicit frequency; `schedule.icma_frequency_mismatch`.
    #[non_exhaustive]
    IcmaFrequencyMismatch {
        /// Stored schedule tenor.
        tenor: Period,
        /// Supplied annual frequency.
        frequency: Frequency,
        /// Period defined by that frequency.
        expected_tenor: Period,
    },
    /// Required references cannot fit the cap; `schedule.icma_period_limit_exceeded`.
    #[non_exhaustive]
    IcmaPeriodLimitExceeded {
        /// Original caller-supplied final-period cap.
        maximum: u32,
        /// Proved minimum required final-period count.
        required_at_least: u32,
    },
    /// A generated period/context failed validation; `schedule.icma`.
    #[non_exhaustive]
    Icma {
        /// Preserved typed ICMA constructor cause.
        cause: IcmaError,
    },
    /// An off-lattice endpoint requires a permitted residual; `schedule.stub_required`.
    #[non_exhaustive]
    StubRequired {
        /// Generation direction.
        rule: DateGenerationRule,
        /// Requested tenor.
        tenor: Period,
        /// Original start.
        start: Date,
        /// Original end.
        end: Date,
        /// Last generated boundary in the directional sequence.
        regular_boundary: Date,
    },
    /// Long has no complete neighboring regular interval; `schedule.long_stub_without_regular_period`.
    #[non_exhaustive]
    LongStubWithoutRegularPeriod {
        /// Generation direction.
        rule: DateGenerationRule,
        /// Requested tenor.
        tenor: Period,
        /// Original start.
        start: Date,
        /// Original end.
        end: Date,
    },
    /// Final boundaries cannot fit the supplied cap; `schedule.boundary_limit_exceeded`.
    #[non_exhaustive]
    BoundaryLimitExceeded {
        /// Supplied final cap.
        maximum: u32,
        /// A proved lower bound on required final boundaries.
        required_at_least: u32,
    },
    /// A schedule vector could not reserve memory; `schedule.allocation_failed`.
    #[non_exhaustive]
    AllocationFailed {
        /// Vector being grown.
        phase: &'static str,
        /// Requested element count; no partially usable schedule is returned.
        requested: usize,
    },
    /// Unexpected required date arithmetic failure; `schedule.date`.
    #[non_exhaustive]
    Date {
        /// Boundary-generation position before final chronological ordering.
        index: usize,
        /// Generation, ICMA anchor reconstruction or required reference extension.
        phase: &'static str,
        /// Preserved date cause.
        cause: DateError,
    },
    /// Market coverage or adjustment failure; `schedule.calendar`.
    #[non_exhaustive]
    Calendar {
        /// None for full-span coverage, otherwise the chronological boundary index.
        index: Option<usize>,
        /// Coverage or adjustment phase.
        phase: &'static str,
        /// Preserved calendar cause, including any nested date or TARGET failure.
        cause: CalendarError,
    },
    /// Adjustment collapsed or reversed adjacent dates; `schedule.adjusted_order`.
    #[non_exhaustive]
    AdjustedOrder {
        /// Index of the second offending boundary.
        index: usize,
        /// First raw boundary.
        previous_contractual: Date,
        /// Second raw boundary.
        contractual: Date,
        /// First adjusted boundary.
        previous_adjusted: Date,
        /// Second adjusted boundary.
        adjusted: Date,
    },
}

impl ScheduleError {
    /// Returns the stable schedule-domain kind.
    #[must_use]
    pub const fn kind(&self) -> &'static str {
        match self {
            Self::InvalidCdsTenor { .. } => "schedule.invalid_cds_tenor",
            Self::CdsMaturityDate { .. } => "schedule.cds_maturity_date",
            Self::InvalidCdsMaturity { .. } => "schedule.invalid_cds_maturity",
            Self::InvalidCdsCouponLimit { .. } => "schedule.invalid_cds_coupon_limit",
            Self::CdsCouponLimitExceeded { .. } => "schedule.cds_coupon_limit_exceeded",
            Self::NoEligibleCdsPayment { .. } => "schedule.no_eligible_cds_payment",
            Self::CdsDate { .. } => "schedule.cds_date",
            Self::CdsCalendar { .. } => "schedule.cds_calendar",
            Self::CdsAdjustedOrder { .. } => "schedule.cds_adjusted_order",
            Self::InvalidRollTenor { .. } => "schedule.invalid_roll_tenor",
            Self::ResolvedRollRange { .. } => "schedule.resolved_roll_range",
            Self::RollDate { .. } => "schedule.roll_date",
            Self::InvalidOldCdsTenor { .. } => "schedule.invalid_old_cds_tenor",
            Self::OldCdsDate { .. } => "schedule.old_cds_date",
            Self::InvalidRange { .. } => "schedule.invalid_range",
            Self::InvalidBoundaryLimit { .. } => "schedule.invalid_boundary_limit",
            Self::InvalidRule { .. } => "schedule.invalid_rule",
            Self::InvalidTenor { .. } => "schedule.invalid_tenor",
            Self::IncompatibleEndOfMonth { .. } => "schedule.incompatible_end_of_month",
            Self::EmptyExplicitStubDates => "schedule.empty_explicit_stub_dates",
            Self::ReversedExplicitStubDates { .. } => "schedule.reversed_explicit_stub_dates",
            Self::ExplicitStubOutsideRange { .. } => "schedule.explicit_stub_outside_range",
            Self::IrregularExplicitMiddle { .. } => "schedule.irregular_explicit_middle",
            Self::InvalidIcmaPeriodLimit { .. } => "schedule.invalid_icma_period_limit",
            Self::NonPeriodicIcma { .. } => "schedule.non_periodic_icma",
            Self::InvalidIcmaFrequency { .. } => "schedule.invalid_icma_frequency",
            Self::IcmaFrequencyMismatch { .. } => "schedule.icma_frequency_mismatch",
            Self::IcmaPeriodLimitExceeded { .. } => "schedule.icma_period_limit_exceeded",
            Self::Icma { .. } => "schedule.icma",
            Self::StubRequired { .. } => "schedule.stub_required",
            Self::LongStubWithoutRegularPeriod { .. } => {
                "schedule.long_stub_without_regular_period"
            }
            Self::BoundaryLimitExceeded { .. } => "schedule.boundary_limit_exceeded",
            Self::AllocationFailed { .. } => "schedule.allocation_failed",
            Self::Date { .. } => "schedule.date",
            Self::Calendar { .. } => "schedule.calendar",
            Self::AdjustedOrder { .. } => "schedule.adjusted_order",
        }
    }
}

impl fmt::Display for ScheduleError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidCdsTenor {
                trade_date,
                tenor,
                convention,
            } => write!(
                f,
                "CDS {convention} trade {trade_date} rejects stored quote {tenor}; use nonnegative Years or quarter-multiple Months"
            ),
            Self::CdsMaturityDate {
                trade_date,
                tenor,
                convention,
                cause,
            } => write!(
                f,
                "CDS {convention} trade {trade_date} quote {tenor} required maturity: {cause}"
            ),
            Self::InvalidCdsMaturity {
                maturity,
                convention,
            } => write!(
                f,
                "CDS {convention} maturity {maturity} must be a quarterly twentieth"
            ),
            Self::InvalidCdsCouponLimit {
                requested,
                minimum,
                maximum,
            } => write!(
                f,
                "CDS coupon cap {requested} must be in {minimum}..={maximum}"
            ),
            Self::CdsCouponLimitExceeded { maximum, required } => {
                write!(f, "CDS needs {required} coupons, exceeding cap {maximum}")
            }
            Self::NoEligibleCdsPayment {
                trade_date,
                payment_selection_cutoff,
                unadjusted_maturity,
                final_payment,
            } => write!(
                f,
                "CDS trade {trade_date} maturity {unadjusted_maturity} final payment {final_payment} is not after cutoff {payment_selection_cutoff}"
            ),
            Self::CdsDate {
                trade_date,
                unadjusted_maturity,
                role,
                input,
                cause,
            } => write!(
                f,
                "CDS trade {trade_date} maturity {unadjusted_maturity} required {role} from {input}: {cause}"
            ),
            Self::CdsCalendar {
                trade_date,
                unadjusted_maturity,
                phase,
                index,
                start,
                end,
                cause,
            } => write!(
                f,
                "CDS trade {trade_date} maturity {unadjusted_maturity} {phase} coupon {index:?} over {start} to {end}: {cause}"
            ),
            Self::CdsAdjustedOrder {
                index,
                previous_contractual,
                contractual,
                previous_adjusted,
                adjusted,
            } => write!(
                f,
                "CDS adjustment conflicts at coupon {index}: raw {previous_contractual}, {contractual}; adjusted {previous_adjusted}, {adjusted}"
            ),
            Self::InvalidRollTenor { rule, tenor } => write!(
                f,
                "schedule roll {rule} does not accept stored tenor {tenor}; use positive Months/Years and a quarter-multiple stride for TwentiethIMM"
            ),
            Self::ResolvedRollRange {
                rule,
                tenor,
                requested_start,
                requested_end,
                resolved_start,
                resolved_end,
            } => write!(
                f,
                "schedule roll {rule} {tenor} resolves {requested_start} to {requested_end} into non-increasing {resolved_start} to {resolved_end}"
            ),
            Self::RollDate {
                rule,
                tenor,
                role,
                input,
                cause,
            } => write!(
                f,
                "schedule roll {rule} {tenor} required {role} from {input}: {cause}"
            ),
            Self::InvalidOldCdsTenor {
                generation_start,
                requested_end,
                tenor,
            } => write!(
                f,
                "schedule OldCDS from {generation_start} to {requested_end} does not accept stored tenor {tenor}; use positive Months/Years"
            ),
            Self::OldCdsDate {
                generation_start,
                requested_end,
                tenor,
                role,
                input,
                cause,
            } => write!(
                f,
                "schedule OldCDS {tenor} from {generation_start} to {requested_end} required {role} from {input}: {cause}"
            ),
            Self::InvalidRange { start, end } => {
                write!(f, "schedule range must increase: {start} to {end}")
            }
            Self::InvalidBoundaryLimit {
                requested,
                minimum,
                maximum,
            } => write!(
                f,
                "schedule cap {requested} must be in {minimum}..={maximum}"
            ),
            Self::InvalidRule { rule } => write!(
                f,
                "schedule recurrence does not accept {rule}; use the constructor for its rule family"
            ),
            Self::InvalidTenor { tenor } => write!(
                f,
                "schedule tenor {tenor} must have a positive stored length"
            ),
            Self::IncompatibleEndOfMonth {
                tenor,
                end_of_month,
            } => write!(
                f,
                "schedule EOM {end_of_month} is incompatible with {tenor}"
            ),
            Self::EmptyExplicitStubDates => {
                f.write_str("schedule needs a first or penultimate coupon date")
            }
            Self::ReversedExplicitStubDates { first, penultimate } => write!(
                f,
                "schedule first coupon {first} follows penultimate coupon {penultimate}"
            ),
            Self::ExplicitStubOutsideRange {
                role,
                date,
                start,
                end,
            } => write!(
                f,
                "schedule {role} coupon {date} must be strictly inside {start} to {end}"
            ),
            Self::IrregularExplicitMiddle {
                rule,
                tenor,
                anchor,
                endpoint,
                regular_boundary,
            } => write!(
                f,
                "schedule explicit {rule} {tenor} middle from {anchor} to {endpoint} is off lattice after {regular_boundary}"
            ),
            Self::InvalidIcmaPeriodLimit {
                requested,
                minimum,
                maximum,
            } => write!(
                f,
                "schedule ICMA period cap {requested} must be in {minimum}..={maximum}"
            ),
            Self::NonPeriodicIcma { rule } => {
                write!(f, "schedule {rule} has no recurring ICMA reference lattice")
            }
            Self::InvalidIcmaFrequency { frequency } => {
                write!(f, "schedule ICMA frequency {frequency} must be periodic")
            }
            Self::IcmaFrequencyMismatch {
                tenor,
                frequency,
                expected_tenor,
            } => write!(
                f,
                "schedule tenor {tenor} does not match ICMA frequency {frequency} ({expected_tenor})"
            ),
            Self::IcmaPeriodLimitExceeded {
                maximum,
                required_at_least,
            } => write!(
                f,
                "schedule ICMA needs at least {required_at_least} periods, exceeding cap {maximum}"
            ),
            Self::Icma { cause } => write!(f, "schedule ICMA reference context: {cause}"),
            Self::StubRequired {
                rule,
                tenor,
                start,
                end,
                regular_boundary,
            } => write!(
                f,
                "schedule {rule} {tenor} from {start} to {end} needs a stub after directional boundary {regular_boundary}"
            ),
            Self::LongStubWithoutRegularPeriod {
                rule,
                tenor,
                start,
                end,
            } => write!(
                f,
                "schedule {rule} {tenor} from {start} to {end} has no complete regular interval to merge into Long"
            ),
            Self::BoundaryLimitExceeded {
                maximum,
                required_at_least,
            } => write!(
                f,
                "schedule needs at least {required_at_least} final boundaries, exceeding cap {maximum}"
            ),
            Self::AllocationFailed { phase, requested } => {
                write!(f, "schedule {phase} cannot reserve {requested} elements")
            }
            Self::Date {
                index,
                phase,
                cause,
            } => write!(f, "schedule {phase} step {index}: {cause}"),
            Self::Calendar {
                index,
                phase,
                cause,
            } => write!(f, "schedule {phase} boundary {index:?}: {cause}"),
            Self::AdjustedOrder {
                index,
                previous_contractual,
                contractual,
                previous_adjusted,
                adjusted,
            } => write!(
                f,
                "schedule adjustment conflicts at boundary {index}: raw {previous_contractual}, {contractual}; adjusted {previous_adjusted}, {adjusted}"
            ),
        }
    }
}

impl StdError for ScheduleError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Self::Date { cause, .. }
            | Self::RollDate { cause, .. }
            | Self::OldCdsDate { cause, .. }
            | Self::CdsDate { cause, .. }
            | Self::CdsMaturityDate { cause, .. } => Some(cause),
            Self::Calendar { cause, .. } | Self::CdsCalendar { cause, .. } => Some(cause),
            Self::Icma { cause } => Some(cause),
            _ => None,
        }
    }
}

fn validate_limit(requested: u32) -> Result<(), ScheduleError> {
    if !(ScheduleBuilder::MIN_BOUNDARIES..=ScheduleBuilder::MAX_BOUNDARIES).contains(&requested) {
        return Err(ScheduleError::InvalidBoundaryLimit {
            requested,
            minimum: ScheduleBuilder::MIN_BOUNDARIES,
            maximum: ScheduleBuilder::MAX_BOUNDARIES,
        });
    }
    Ok(())
}

fn outer_regularity(adjacent: Option<Date>, endpoint: Date) -> PeriodRegularity {
    if adjacent == Some(endpoint) {
        PeriodRegularity::Regular
    } else {
        PeriodRegularity::Stub
    }
}

#[derive(Clone, Copy)]
enum IcmaLattice {
    Anchored { anchor: Date, preserve: bool },
    Roll(RollProvenance),
}

impl IcmaLattice {
    fn anchor(self) -> Result<Date, ScheduleError> {
        match self {
            Self::Anchored { anchor, .. } => Ok(anchor),
            // The private provenance contains a valid civil anchor month.
            // Retain a typed cause if its reconstruction is ever extended.
            Self::Roll(provenance) => {
                provenance
                    .reference_anchor()
                    .map_err(|cause| ScheduleError::Date {
                        index: 0,
                        phase: "ICMA reference anchor",
                        cause,
                    })
            }
        }
    }

    fn date(
        self,
        anchor: Date,
        tenor: Period,
        step: u32,
        forward: bool,
        index: usize,
    ) -> Result<Date, ScheduleError> {
        match self {
            Self::Anchored { preserve, .. } => checked_anchored_date(
                anchor,
                tenor,
                step,
                forward,
                preserve,
                index,
                "ICMA reference extension",
            ),
            Self::Roll(provenance) => {
                provenance
                    .reference_date(anchor, step, forward)
                    .map_err(|cause| ScheduleError::Date {
                        index,
                        phase: "ICMA reference extension",
                        cause,
                    })
            }
        }
    }
}

fn check_icma_count(required: u32, maximum: u32) -> Result<(), ScheduleError> {
    if required > maximum {
        Err(ScheduleError::IcmaPeriodLimitExceeded {
            maximum,
            required_at_least: required,
        })
    } else {
        Ok(())
    }
}

struct Rolling {
    dates: Vec<Date>,
    regularity: Vec<PeriodRegularity>,
    count: u32,
}

impl Rolling {
    fn new(anchor: Date) -> Result<Self, ScheduleError> {
        let mut dates = Vec::new();
        reserve_one(&mut dates, "contractual boundaries")?;
        dates.push(anchor);
        Ok(Self {
            dates,
            regularity: Vec::new(),
            count: 1,
        })
    }

    fn push(&mut self, date: Date, flag: PeriodRegularity) -> Result<(), ScheduleError> {
        reserve_one(&mut self.dates, "contractual boundaries")?;
        reserve_one(&mut self.regularity, "contractual regularity")?;
        self.dates.push(date);
        self.regularity.push(flag);
        self.count += 1;
        Ok(())
    }

    fn push_limited(
        &mut self,
        date: Date,
        flag: PeriodRegularity,
        maximum: u32,
    ) -> Result<(), ScheduleError> {
        if self.count + 1 > maximum {
            return Err(ScheduleError::BoundaryLimitExceeded {
                maximum,
                required_at_least: self.count + 1,
            });
        }
        self.push(date, flag)
    }
}

fn reserve_one<T>(values: &mut Vec<T>, phase: &'static str) -> Result<(), ScheduleError> {
    if values.len() == values.capacity() {
        values
            .try_reserve(1)
            .map_err(|_| ScheduleError::AllocationFailed {
                phase,
                requested: values.len() + 1,
            })?;
    }
    Ok(())
}

fn anchored_candidate(
    anchor: Date,
    tenor: Period,
    step: u32,
    forward: bool,
    preserve: bool,
    index: usize,
) -> Result<Option<Date>, ScheduleError> {
    let magnitude = i64::from(tenor.length()) * i64::from(step);
    // These supported-range comparisons prove an unused candidate is beyond
    // every valid endpoint. They do not catch and discard arbitrary DateErrors.
    // The count cap bounds magnitude by i32::MAX * 3_652_059, inside i64;
    // the subsequent factors seven/twelve also fit comfortably inside i64.
    let days_available = if forward {
        Date::MAX.days_since(anchor)
    } else {
        anchor.days_since(Date::MIN)
    };
    let months_available = if forward {
        i64::from(9999 - anchor.year()) * 12 + (12 - i64::from(anchor.month()))
    } else {
        i64::from(anchor.year() - 1) * 12 + (i64::from(anchor.month()) - 1)
    };
    let years_available = if forward {
        9999 - anchor.year()
    } else {
        anchor.year() - 1
    };
    let outside = match tenor.unit() {
        TimeUnit::Days => magnitude > i64::from(days_available),
        TimeUnit::Weeks => magnitude > i64::from(days_available) / 7,
        TimeUnit::Months => magnitude > months_available,
        TimeUnit::Years => magnitude > i64::from(years_available),
    };
    if outside {
        return Ok(None);
    }
    checked_anchored_date(anchor, tenor, step, forward, preserve, index, "generation").map(Some)
}

fn checked_anchored_date(
    anchor: Date,
    tenor: Period,
    step: u32,
    forward: bool,
    preserve: bool,
    index: usize,
    phase: &'static str,
) -> Result<Date, ScheduleError> {
    // Both construction operations cap their step before evaluating it.
    // Even the widest positive stored tenor and all factors fit i64.
    let magnitude = i64::from(tenor.length()) * i64::from(step);
    let offset = if forward { magnitude } else { -magnitude };
    let date = match tenor.unit() {
        TimeUnit::Days => anchor.checked_add_days(offset),
        TimeUnit::Weeks => anchor.checked_add_weeks(offset),
        TimeUnit::Months => anchor.checked_add_months(offset),
        TimeUnit::Years => anchor.checked_add_years(offset),
    }
    .map_err(|cause| ScheduleError::Date {
        index,
        phase,
        cause,
    })?;
    Ok(if preserve {
        date.last_day_of_month()
    } else {
        date
    })
}