sonda-core 1.0.1

Core engine for Sonda — synthetic telemetry generation 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
//! `after` clause compilation and clock-group assignment (Phases 4 & 5).
//!
//! This module takes an [`ExpandedFile`] (the output of
//! [`super::expand::expand`]) and produces a [`CompiledFile`] where every
//! `after:` clause has been resolved into a concrete `phase_offset` and
//! every signal participating in a dependency chain has been assigned a
//! deterministic `clock_group`. The runtime never sees [`AfterClause`]
//! objects — by the time the runtime receives entries, causal ordering is
//! expressed purely through `phase_offset` + `clock_group`.
//!
//! # Pipeline position
//!
//! ```text
//! parse (§4.1) → normalize (§4.2) → expand (§4.3) → compile_after (§4.4 + §4.5) → runtime
//! ```
//!
//! The type itself witnesses the transition: [`CompiledEntry`] drops
//! [`AfterClause`] from its shape, exposing only `phase_offset: Option<String>`
//! and `clock_group: Option<String>`. If you have a `CompiledEntry`, all
//! `after` clauses in the file were resolvable.
//!
//! # Reference resolution (§3.2)
//!
//! The pass builds a flat `BTreeMap<String, &ExpandedEntry>` keyed on
//! [`ExpandedEntry::id`]. Inline entries with `id: None` are still valid
//! signals — they just cannot be referenced by any `after.ref`. Pack
//! sub-signals are addressable as `{entry}.{metric}` (for unique-by-name
//! packs) or `{entry}.{metric}#{spec_index}` for packs that ship multiple
//! [`MetricSpec`][crate::packs::MetricSpec]s under the same metric name.
//! When a user writes the bare `{entry}.{metric}` form against a
//! duplicate-name pack the compiler emits
//! [`CompileAfterError::AmbiguousSubSignalRef`] with the concrete
//! candidates so they know which `#N` to pick.
//!
//! # Timing computation (§3.3)
//!
//! For each signal with `after: Some(_)`:
//!
//! 1. Lower any operational alias on the **target's** generator into its
//!    core [`GeneratorConfig`] variant. The timing math in
//!    [`super::timing`] operates exclusively on the desugared form, which
//!    matches the runtime's view of the signal.
//! 2. Dispatch on the core variant to the matching `*_crossing_secs`
//!    function. Each generator has its own crossing formula; generators
//!    with ambiguous or non-deterministic output (`sine`, `uniform`,
//!    `csv_replay`) are rejected with [`CompileAfterError::UnsupportedGenerator`].
//! 3. Propagate the computed crossing time to the dependent signal,
//!    accumulating transitive offsets across the dependency chain.
//!
//! # Offset formula (§3.3, matrix 11.14)
//!
//! ```text
//! total_secs = user_phase_offset_secs + Σ crossing_time_secs + Σ delay_secs
//! ```
//!
//! The result is formatted back into a parseable duration string (e.g.
//! `"162.308s"`) for storage on [`CompiledEntry::phase_offset`]. The string
//! round-trips through
//! [`crate::config::validate::parse_duration`] so downstream passes can
//! treat it the same way they treat a user-supplied `phase_offset`.
//!
//! # Clock-group derivation (§4.5)
//!
//! The `after` dependency graph partitions signals into connected
//! components (treating edges as undirected for grouping purposes).
//! For every component with two or more members the pass assigns one
//! clock group:
//!
//! - if no entry in the component has an explicit `clock_group`, it is
//!   auto-assigned as `chain_{lowest_lex_entry_id}`;
//! - if exactly one distinct non-empty value is present, that value
//!   becomes the group for the whole component;
//! - if two distinct values are present, the pass emits
//!   [`CompileAfterError::ConflictingClockGroup`] naming both values and
//!   the offending entries (matrix row 11.16).
//!
//! Single-entry components (signals with no `after` and no dependents)
//! keep their explicit `clock_group` if set, otherwise stay `None`.
//!
//! # Cycle detection (§3.4, matrix row 10.6)
//!
//! A Kahn topological sort on the directed dependency graph yields the
//! resolution order. When the sort's output covers fewer entries than the
//! graph, a recursive DFS with white/gray/black coloring reconstructs the
//! cycle path (e.g. `["A", "B", "C", "A"]`) and surfaces it via
//! [`CompileAfterError::CircularDependency`]. Back-edge detection is
//! driven by `color[dep] == Gray`; the path-reconstruction vector records
//! the current ancestor chain so the cycle can be sliced out directly.
//!
//! # Cross-signal-type support (§3.5, matrix row 11.11)
//!
//! A dependent signal can be any `signal_type` — metrics, logs, histogram,
//! or summary — but the **target** must be a metrics signal with a
//! deterministic generator. Crossing math requires inverting a generator's
//! analytical form, which the non-metric signal types do not have; the
//! pass rejects such targets with
//! [`CompileAfterError::NonMetricsTarget`].
//!
//! # Pack references
//!
//! Pack entries are not themselves referenceable — the expand pass does
//! not emit an [`ExpandedEntry`] whose `id` matches the bare pack entry
//! id (e.g. `B`). Only the individual sub-signals materialize as
//! addressable entries, using the dotted form `{entry}.{metric}` (and
//! `{entry}.{metric}#{spec_index}` for duplicate-name packs). Writing
//! `after.ref: B` against a pack entry therefore fails with
//! [`CompileAfterError::UnknownRef`]; the `available` list in the
//! diagnostic shows the valid dotted ids. To attach `after:` to the whole
//! pack, set it on the pack entry itself — the expand pass propagates it
//! to every sub-signal — or use a specific dotted metric path.
//!
//! # Clock-group string equality
//!
//! Clock-group comparisons use exact string equality after filtering out
//! empty strings: `Some("")` is treated as "no explicit value" and
//! participates in auto-naming, while `Some("x")` and `Some("x ")` are
//! considered distinct (trailing whitespace is significant). Mixing a
//! blank and a concrete value inside one component resolves to the
//! concrete value without error; mixing two different non-empty values
//! (including whitespace variants) triggers
//! [`CompileAfterError::ConflictingClockGroup`].

use std::collections::{BTreeMap, VecDeque};

use super::expand::{ExpandedEntry, ExpandedFile};
use super::timing::{
    self, constant_crossing_secs, csv_replay_crossing_secs, sawtooth_crossing_secs,
    sequence_crossing_secs, sine_crossing_secs, spike_crossing_secs, step_crossing_secs,
    uniform_crossing_secs, Operator, TimingError,
};
use super::AfterOp;
use crate::config::validate::parse_duration;
use crate::config::{
    BurstConfig, CardinalitySpikeConfig, DistributionConfig, DynamicLabelConfig, GapConfig,
};
use crate::encoder::EncoderConfig;
use crate::generator::{GeneratorConfig, LogGeneratorConfig};
use crate::sink::SinkConfig;

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Errors produced by the `after` clause compilation pass.
///
/// Every variant captures enough context to identify the offending entry
/// without re-reading the source YAML. Variants map one-to-one onto the
/// spec §3.4 validation table so diagnostics stay aligned with the
/// published error messages.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum CompileAfterError {
    /// An `after.ref` pointed to a signal id that does not exist in the
    /// expanded file.
    ///
    /// The `available` list contains every known signal id (sorted) so the
    /// user can spot the typo or missing entry quickly.
    #[error(
        "entry '{source_id}': after.ref '{ref_id}' does not match any signal id in this file. \
         Available ids: [{available}]"
    )]
    UnknownRef {
        /// The `id` (or descriptive label) of the entry whose `after` failed.
        source_id: String,
        /// The unresolved reference as written in the scenario file.
        ref_id: String,
        /// Comma-separated list of known ids in the file.
        available: String,
    },

    /// An `after.ref` used the bare `{entry}.{metric}` form against a
    /// duplicate-name pack metric. The user must pick one of the
    /// `#{spec_index}` variants.
    #[error(
        "after.ref '{ref_id}' is ambiguous: pack '{pack_entry_id}' ships multiple specs with \
         this metric name. Use one of: [{candidates}]"
    )]
    AmbiguousSubSignalRef {
        /// The ambiguous reference as written.
        ref_id: String,
        /// The pack entry id that produced the colliding sub-signals.
        pack_entry_id: String,
        /// Comma-separated list of disambiguated sub-signal ids.
        candidates: String,
    },

    /// An entry's `after.ref` pointed to its own id.
    #[error("entry '{source_id}': after.ref references itself")]
    SelfReference {
        /// The offending entry's id.
        source_id: String,
    },

    /// The dependency graph contains a cycle.
    ///
    /// `cycle` is a path of entry ids starting and ending at the same
    /// vertex (e.g. `["A", "B", "C", "A"]`).
    #[error("circular dependency detected: {}", .cycle.join(" -> "))]
    CircularDependency {
        /// Ordered list of entry ids forming the cycle, with the start
        /// vertex repeated at the end.
        cycle: Vec<String>,
    },

    /// The target of an `after.ref` uses a generator that does not support
    /// the requested operator.
    #[error(
        "entry '{source_id}': after.ref '{ref_id}' uses generator '{generator}' which does \
         not support {op} threshold crossings: {reason}"
    )]
    UnsupportedGenerator {
        /// The dependent entry.
        source_id: String,
        /// The referenced target.
        ref_id: String,
        /// The target's generator type (as the serde tag, e.g. `"sine"`).
        generator: String,
        /// The operator from the after clause.
        op: String,
        /// Diagnostic detail from the timing-math layer.
        reason: String,
    },

    /// The after clause threshold is outside the target signal's output
    /// range — the crossing will never happen.
    #[error("entry '{source_id}': after.ref '{ref_id}' op '{op}' value {value} -- {reason}")]
    OutOfRangeThreshold {
        /// The dependent entry.
        source_id: String,
        /// The referenced target.
        ref_id: String,
        /// The operator from the after clause.
        op: String,
        /// The threshold value from the after clause.
        value: f64,
        /// Diagnostic detail from the timing-math layer.
        reason: String,
    },

    /// The crossing condition is already satisfied at `t=0`; the crossing
    /// time is ambiguous.
    #[error(
        "entry '{source_id}': after.ref '{ref_id}' op '{op}' value {value} -- condition is \
         true at t=0, timing is ambiguous: {reason}"
    )]
    AmbiguousAtT0 {
        /// The dependent entry.
        source_id: String,
        /// The referenced target.
        ref_id: String,
        /// The operator from the after clause.
        op: String,
        /// The threshold value from the after clause.
        value: f64,
        /// Diagnostic detail from the timing-math layer.
        reason: String,
    },

    /// Two entries in the same dependency chain have different explicit
    /// `clock_group` values.
    #[error(
        "conflicting clock_group in dependency chain: entry '{first_entry}' has \
         clock_group '{first_group}', entry '{second_entry}' has clock_group '{second_group}'"
    )]
    ConflictingClockGroup {
        /// First entry whose clock_group participates in the conflict.
        first_entry: String,
        /// The first clock_group value.
        first_group: String,
        /// Second entry whose clock_group differs from the first.
        second_entry: String,
        /// The conflicting clock_group value.
        second_group: String,
    },

    /// The target of an `after.ref` is not a metrics signal.
    ///
    /// Cross-signal-type `after` (spec §3.5) allows the **dependent** to be
    /// any type, but the **target** must be metrics so the compiler can
    /// invert its analytical model for crossing math.
    #[error(
        "entry '{source_id}': after.ref '{ref_id}' resolves to a {signal_type} signal; \
         only metrics signals can be `after` targets"
    )]
    NonMetricsTarget {
        /// The dependent entry.
        source_id: String,
        /// The referenced target.
        ref_id: String,
        /// The target's actual signal type.
        signal_type: String,
    },

    /// A duration string on `after.delay`, the entry's `phase_offset`, or
    /// an alias parameter (e.g. `flap.up_duration`) was not parseable.
    #[error("entry '{source_id}': invalid duration '{input}' in {field}: {reason}")]
    InvalidDuration {
        /// The entry whose duration field failed to parse.
        source_id: String,
        /// Which field carried the bad value (`"after.delay"`, `"phase_offset"`, etc.).
        field: &'static str,
        /// The offending string as written.
        input: String,
        /// The underlying parse error message.
        reason: String,
    },
}

// ---------------------------------------------------------------------------
// Compiled representation
// ---------------------------------------------------------------------------

/// A v2 scenario file with every `after:` clause resolved.
///
/// Mirrors [`ExpandedFile`] shape-for-shape, replacing [`ExpandedEntry`]
/// with [`CompiledEntry`]. The type witnesses that all reference
/// resolution, timing math, and clock-group assignment have completed
/// successfully.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Serialize))]
pub struct CompiledFile {
    /// Schema version. Always `2` after compilation.
    pub version: u32,
    /// Concrete scenario entries, in source order. Pack-expanded sub-signals
    /// appear consecutively as their parent entry was processed.
    pub entries: Vec<CompiledEntry>,
}

/// A single scenario entry with `after:` resolved and `clock_group`
/// finalized.
///
/// The `after: Option<AfterClause>` field from [`ExpandedEntry`] is gone
/// — the causal information it carried has been folded into
/// [`Self::phase_offset`] (computed crossing time plus any user-provided
/// offset plus the optional `delay`) and [`Self::clock_group`] (either the
/// user's explicit value or an auto-assigned `chain_{lowest_lex_id}`).
///
/// All other fields are copied verbatim from [`ExpandedEntry`]; this is a
/// pure enrichment pass, not a structural rewrite.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "config", derive(serde::Serialize))]
pub struct CompiledEntry {
    /// Signal identifier, identical to [`ExpandedEntry::id`].
    pub id: Option<String>,
    /// Signal type: `"metrics"`, `"logs"`, `"histogram"`, or `"summary"`.
    pub signal_type: String,
    /// Metric or scenario name.
    pub name: String,
    /// Event rate in events per second.
    pub rate: f64,
    /// Total run duration (e.g. `"30s"`, `"5m"`).
    pub duration: Option<String>,
    /// Value generator configuration (metrics signals only).
    pub generator: Option<GeneratorConfig>,
    /// Log generator configuration (logs signals only).
    pub log_generator: Option<LogGeneratorConfig>,
    /// Static labels, already composed through the full precedence chain.
    pub labels: Option<BTreeMap<String, String>>,
    /// Dynamic (rotating) label configurations.
    pub dynamic_labels: Option<Vec<DynamicLabelConfig>>,
    /// Encoder configuration.
    pub encoder: EncoderConfig,
    /// Sink configuration.
    pub sink: SinkConfig,
    /// Jitter amplitude applied to generated values.
    pub jitter: Option<f64>,
    /// Deterministic seed for jitter RNG.
    pub jitter_seed: Option<u64>,
    /// Recurring silent-period configuration.
    pub gaps: Option<GapConfig>,
    /// Recurring high-rate burst configuration.
    pub bursts: Option<BurstConfig>,
    /// Cardinality spike configurations.
    pub cardinality_spikes: Option<Vec<CardinalitySpikeConfig>>,
    /// Phase offset. Equals `user_phase_offset + Σ crossing_time + Σ delay`
    /// when the entry participated in an `after:` chain; otherwise the
    /// user's original value (or `None`).
    pub phase_offset: Option<String>,
    /// Clock group — either the user's explicit value, or an
    /// auto-assigned `chain_{lowest_lex_id}` for every member of a
    /// dependency chain with no explicit group.
    pub clock_group: Option<String>,
    /// Provenance of [`Self::clock_group`].
    ///
    /// `true` exactly when the compiler synthesized the
    /// `chain_{lowest_lex_id}` name for a multi-node `after:` component
    /// that had no user-supplied value. `false` when the value was
    /// adopted from an explicit user assignment (including explicit
    /// values that happen to start with `chain_`). Always `false` when
    /// [`Self::clock_group`] is `None`.
    ///
    /// Downstream display code uses this to decide whether to suffix the
    /// rendered value with `(auto)`. The `chain_` prefix alone is not a
    /// reliable proxy because users are free to write
    /// `clock_group: chain_alpha` themselves.
    pub clock_group_is_auto: bool,

    // -- Histogram / summary fields (inline entries only) --
    /// Distribution model for histogram or summary observations.
    pub distribution: Option<DistributionConfig>,
    /// Histogram bucket boundaries (histogram only).
    pub buckets: Option<Vec<f64>>,
    /// Summary quantile boundaries (summary only).
    pub quantiles: Option<Vec<f64>>,
    /// Number of observations sampled per tick.
    pub observations_per_tick: Option<u32>,
    /// Linear drift applied to the distribution mean each second.
    pub mean_shift_per_sec: Option<f64>,
    /// Deterministic seed for histogram/summary sampling.
    pub seed: Option<u64>,
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Compile every `after:` clause in an expanded v2 scenario file.
///
/// The returned [`CompiledFile`] contains one [`CompiledEntry`] per input
/// entry with `after:` resolved into `phase_offset`, and a deterministic
/// `clock_group` assigned to every signal participating in a dependency
/// chain. Entries without `after:` pass through unchanged.
///
/// # Behavior
///
/// - **Reference index.** A flat map keyed on [`ExpandedEntry::id`] covers
///   inline entries and pack sub-signals alike. Bare `{entry}.{metric}`
///   references against duplicate-name packs raise
///   [`CompileAfterError::AmbiguousSubSignalRef`].
/// - **Crossing math.** Aliases (`flap`, `saturation`, `leak`,
///   `degradation`, `spike_event`, `steady`) are desugared on the target
///   before dispatching to the matching `timing::*_crossing_secs` routine.
/// - **Transitive accumulation.** Kahn's topological sort orders entries
///   so that `phase_offset` for a dependent signal includes its target's
///   already-resolved offset.
/// - **Clock-group assignment.** Signals linked by `after:` are grouped
///   into connected components. If any component member carries an
///   explicit `clock_group`, that value is used; otherwise the group is
///   named `chain_{lowest_lex_id}`.
///
/// # Errors
///
/// Every variant of [`CompileAfterError`] is reachable; see the type-level
/// documentation for the one-to-one mapping onto spec §3.4 validation
/// conditions.
pub fn compile_after(file: ExpandedFile) -> Result<CompiledFile, CompileAfterError> {
    let ExpandedFile { version, entries } = file;

    // -----------------------------------------------------------------
    // Reference index
    // -----------------------------------------------------------------
    let id_to_idx = build_id_index(&entries);

    // -----------------------------------------------------------------
    // Validate each `after` clause against the index (before any math).
    // This catches unknown refs / ambiguous bare refs / self-references
    // early, producing clean diagnostics even when the graph is malformed
    // enough to thwart topological ordering.
    // -----------------------------------------------------------------
    for entry in &entries {
        let Some(clause) = &entry.after else { continue };
        let source_id = source_label(entry);

        resolve_reference(&clause.ref_id, &id_to_idx, &source_id)?;

        if let Some(own_id) = entry.id.as_deref() {
            if own_id == clause.ref_id {
                return Err(CompileAfterError::SelfReference {
                    source_id: source_id.into_owned(),
                });
            }
        }
    }

    // -----------------------------------------------------------------
    // Topological sort (Kahn's algorithm with in-degree tracking)
    // -----------------------------------------------------------------
    let n = entries.len();
    let mut in_degree = vec![0u32; n];
    let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); n];
    for (i, entry) in entries.iter().enumerate() {
        if let Some(clause) = &entry.after {
            let dep_idx = id_to_idx[clause.ref_id.as_str()];
            in_degree[i] += 1;
            dependents[dep_idx].push(i);
        }
    }

    let mut queue: VecDeque<usize> = (0..n).filter(|&i| in_degree[i] == 0).collect();
    let mut sorted: Vec<usize> = Vec::with_capacity(n);
    while let Some(idx) = queue.pop_front() {
        sorted.push(idx);
        for &dependent in &dependents[idx] {
            in_degree[dependent] -= 1;
            if in_degree[dependent] == 0 {
                queue.push_back(dependent);
            }
        }
    }
    if sorted.len() < n {
        let cycle = find_cycle(&entries, &id_to_idx);
        return Err(CompileAfterError::CircularDependency { cycle });
    }

    // -----------------------------------------------------------------
    // Offset accumulation
    // -----------------------------------------------------------------
    let mut total_offsets = vec![0.0_f64; n];
    let mut base_offsets = vec![0.0_f64; n]; // user-set phase_offset per entry

    for (i, entry) in entries.iter().enumerate() {
        if let Some(s) = entry.phase_offset.as_deref() {
            base_offsets[i] = parse_duration_secs(s, &source_label(entry), "phase_offset")?;
        }
    }

    for &idx in &sorted {
        let entry = &entries[idx];
        let Some(clause) = &entry.after else {
            total_offsets[idx] = base_offsets[idx];
            continue;
        };

        let source_id = source_label(entry).into_owned();
        let dep_idx = id_to_idx[clause.ref_id.as_str()];
        let target = &entries[dep_idx];

        // §3.5: only metrics signals can be `after` targets.
        if target.signal_type != "metrics" {
            return Err(CompileAfterError::NonMetricsTarget {
                source_id,
                ref_id: clause.ref_id.clone(),
                signal_type: target.signal_type.clone(),
            });
        }

        // Metrics non-pack inline entries are required to carry a `generator`
        // by the parser (`ParseError::MissingGeneratorOrPack`), and pack
        // expansion always materializes a generator on every sub-signal
        // (falling back to `constant(0)` when the pack spec has none).
        // Combined with the §3.5 metrics-target check above, a metrics
        // target with `generator: None` cannot occur at this point.
        let generator = target.generator.as_ref().unwrap_or_else(|| {
            unreachable!(
                "metrics target '{ref_id}' has no generator — parser and expand \
                 pass both guarantee metrics entries always carry one",
                ref_id = clause.ref_id
            )
        });

        let op = operator_from(&clause.op);
        let crossing = crossing_secs(generator, op, clause.value, target.rate).map_err(|err| {
            timing_to_error(err, &source_id, &clause.ref_id, generator, op, clause.value)
        })?;

        let delay = match clause.delay.as_deref() {
            Some(s) => parse_duration_secs(s, &source_id, "after.delay")?,
            None => 0.0,
        };

        total_offsets[idx] = base_offsets[idx] + total_offsets[dep_idx] + crossing + delay;
    }

    // -----------------------------------------------------------------
    // Clock-group assignment (spec §4.5)
    // -----------------------------------------------------------------
    let clock_groups = assign_clock_groups(&entries, &id_to_idx)?;

    // -----------------------------------------------------------------
    // Build CompiledEntry list
    // -----------------------------------------------------------------
    let mut out: Vec<CompiledEntry> = Vec::with_capacity(n);
    for (i, entry) in entries.into_iter().enumerate() {
        let phase_offset = if entry.after.is_some() || total_offsets[i] != 0.0 {
            Some(format_duration_secs(total_offsets[i]))
        } else {
            // No `after:` and no user-set offset → leave None.
            entry.phase_offset.clone()
        };

        // Resolve the clock_group + provenance:
        // - Multi-node component: `clock_groups[i]` holds the assignment.
        // - Single-node component (Unassigned): fall back to the entry's
        //   own explicit value, which is by definition not auto-named.
        let (clock_group, clock_group_is_auto) = match &clock_groups[i] {
            ClockGroupAssignment::Resolved { name, is_auto } => (Some(name.clone()), *is_auto),
            ClockGroupAssignment::Unassigned => (entry.clock_group.clone(), false),
        };

        out.push(CompiledEntry {
            id: entry.id,
            signal_type: entry.signal_type,
            name: entry.name,
            rate: entry.rate,
            duration: entry.duration,
            generator: entry.generator,
            log_generator: entry.log_generator,
            labels: entry.labels,
            dynamic_labels: entry.dynamic_labels,
            encoder: entry.encoder,
            sink: entry.sink,
            jitter: entry.jitter,
            jitter_seed: entry.jitter_seed,
            gaps: entry.gaps,
            bursts: entry.bursts,
            cardinality_spikes: entry.cardinality_spikes,
            phase_offset,
            clock_group,
            clock_group_is_auto,
            distribution: entry.distribution,
            buckets: entry.buckets,
            quantiles: entry.quantiles,
            observations_per_tick: entry.observations_per_tick,
            mean_shift_per_sec: entry.mean_shift_per_sec,
            seed: entry.seed,
        });
    }

    Ok(CompiledFile {
        version,
        entries: out,
    })
}

// ---------------------------------------------------------------------------
// Reference index + resolution
// ---------------------------------------------------------------------------

/// Build a map from signal id to its index in the entries list.
///
/// Only entries with `Some(id)` are included. [`ExpandedEntry::id`]
/// uniqueness is enforced upstream by [`super::expand::expand`], so
/// duplicate inserts cannot occur here.
fn build_id_index(entries: &[ExpandedEntry]) -> BTreeMap<&str, usize> {
    let mut idx = BTreeMap::new();
    for (i, entry) in entries.iter().enumerate() {
        if let Some(id) = entry.id.as_deref() {
            idx.insert(id, i);
        }
    }
    idx
}

/// Resolve an `after.ref` against the reference index, producing a
/// precise diagnostic for unknown or ambiguous references.
///
/// Returns the resolved target index on success.
fn resolve_reference(
    ref_id: &str,
    id_to_idx: &BTreeMap<&str, usize>,
    source_id: &str,
) -> Result<usize, CompileAfterError> {
    if let Some(&idx) = id_to_idx.get(ref_id) {
        return Ok(idx);
    }

    // Ambiguous bare `{entry}.{metric}` against a duplicate-name pack?
    // Look for ids of the form `{ref_id}#{n}`.
    let prefix = format!("{ref_id}#");
    let candidates: Vec<&str> = id_to_idx
        .keys()
        .filter(|k| k.starts_with(&prefix))
        .copied()
        .collect();
    if !candidates.is_empty() {
        // Strip everything after the final `.` to reconstruct the pack
        // entry id for the diagnostic.
        let pack_entry_id = ref_id
            .rsplit_once('.')
            .map(|(left, _)| left.to_string())
            .unwrap_or_default();
        return Err(CompileAfterError::AmbiguousSubSignalRef {
            ref_id: ref_id.to_string(),
            pack_entry_id,
            candidates: candidates.join(", "),
        });
    }

    let available: Vec<&str> = id_to_idx.keys().copied().collect();
    Err(CompileAfterError::UnknownRef {
        source_id: source_id.to_string(),
        ref_id: ref_id.to_string(),
        available: available.join(", "),
    })
}

/// Format an entry into a human-readable label for error messages.
///
/// Priority: `id` → `name` → `<anonymous entry>`. Returns `Cow<str>` so
/// the caller can avoid an allocation when the id is already available.
fn source_label(entry: &ExpandedEntry) -> std::borrow::Cow<'_, str> {
    if let Some(id) = entry.id.as_deref() {
        std::borrow::Cow::Borrowed(id)
    } else {
        std::borrow::Cow::Owned(format!("<anonymous:{}>", entry.name))
    }
}

// ---------------------------------------------------------------------------
// Crossing time dispatch
// ---------------------------------------------------------------------------

/// Dispatch a [`GeneratorConfig`] to the matching `timing::*_crossing_secs`
/// routine, desugaring operational aliases as needed.
///
/// The `rate` parameter is required by generators whose crossing time is
/// expressed in ticks (`step`, `sequence`, and anything derived from a
/// `Sequence` via the `flap` alias). Sawtooth / spike / sine variants
/// already encode their periods in seconds and ignore the rate.
fn crossing_secs(
    generator: &GeneratorConfig,
    op: Operator,
    threshold: f64,
    rate: f64,
) -> Result<f64, TimingError> {
    match generator {
        GeneratorConfig::Constant { value } => constant_crossing_secs(op, threshold, *value),
        GeneratorConfig::Uniform { .. } => uniform_crossing_secs(),
        GeneratorConfig::Sine { .. } => sine_crossing_secs(),
        GeneratorConfig::CsvReplay { .. } => csv_replay_crossing_secs(),
        GeneratorConfig::Sawtooth {
            min,
            max,
            period_secs,
        } => sawtooth_crossing_secs(op, threshold, *min, *max, *period_secs),
        GeneratorConfig::Sequence { values, repeat } => {
            sequence_crossing_secs(op, threshold, values, *repeat, rate)
        }
        GeneratorConfig::Step {
            start,
            step_size,
            max,
        } => step_crossing_secs(op, threshold, start.unwrap_or(0.0), *step_size, *max, rate),
        GeneratorConfig::Spike {
            baseline,
            magnitude,
            duration_secs,
            ..
        } => spike_crossing_secs(op, threshold, *baseline, *magnitude, *duration_secs),

        // --- Operational aliases (desugar before dispatch) ---
        GeneratorConfig::Flap {
            up_duration,
            down_duration,
            up_value,
            down_value,
        } => {
            let up_secs = duration_or_default(up_duration.as_deref(), 10.0, "flap.up_duration")?;
            let down_secs =
                duration_or_default(down_duration.as_deref(), 5.0, "flap.down_duration")?;
            let up_val = up_value.unwrap_or(1.0);
            let down_val = down_value.unwrap_or(0.0);
            timing::flap_crossing_secs(op, threshold, up_secs, down_secs, up_val, down_val)
        }
        GeneratorConfig::Saturation {
            baseline,
            ceiling,
            time_to_saturate,
        } => {
            let bl = baseline.unwrap_or(0.0);
            let cl = ceiling.unwrap_or(100.0);
            let period = duration_or_default(
                time_to_saturate.as_deref(),
                5.0 * 60.0,
                "saturation.time_to_saturate",
            )?;
            sawtooth_crossing_secs(op, threshold, bl, cl, period)
        }
        GeneratorConfig::Leak {
            baseline,
            ceiling,
            time_to_ceiling,
        } => {
            let bl = baseline.unwrap_or(0.0);
            let cl = ceiling.unwrap_or(100.0);
            let period = duration_or_default(
                time_to_ceiling.as_deref(),
                10.0 * 60.0,
                "leak.time_to_ceiling",
            )?;
            sawtooth_crossing_secs(op, threshold, bl, cl, period)
        }
        GeneratorConfig::Degradation {
            baseline,
            ceiling,
            time_to_degrade,
            ..
        } => {
            let bl = baseline.unwrap_or(0.0);
            let cl = ceiling.unwrap_or(100.0);
            let period = duration_or_default(
                time_to_degrade.as_deref(),
                5.0 * 60.0,
                "degradation.time_to_degrade",
            )?;
            sawtooth_crossing_secs(op, threshold, bl, cl, period)
        }
        GeneratorConfig::Steady { .. } => timing::steady_crossing_secs(),
        GeneratorConfig::SpikeEvent {
            baseline,
            spike_height,
            spike_duration,
            ..
        } => {
            let bl = baseline.unwrap_or(0.0);
            let height = spike_height.unwrap_or(100.0);
            let dur = duration_or_default(
                spike_duration.as_deref(),
                10.0,
                "spike_event.spike_duration",
            )?;
            spike_crossing_secs(op, threshold, bl, height, dur)
        }
    }
}

/// Return the generator's serde tag as a `&'static str` for error messages.
fn generator_kind(generator: &GeneratorConfig) -> &'static str {
    match generator {
        GeneratorConfig::Constant { .. } => "constant",
        GeneratorConfig::Uniform { .. } => "uniform",
        GeneratorConfig::Sine { .. } => "sine",
        GeneratorConfig::Sawtooth { .. } => "sawtooth",
        GeneratorConfig::Sequence { .. } => "sequence",
        GeneratorConfig::Spike { .. } => "spike",
        GeneratorConfig::CsvReplay { .. } => "csv_replay",
        GeneratorConfig::Step { .. } => "step",
        GeneratorConfig::Flap { .. } => "flap",
        GeneratorConfig::Saturation { .. } => "saturation",
        GeneratorConfig::Leak { .. } => "leak",
        GeneratorConfig::Degradation { .. } => "degradation",
        GeneratorConfig::Steady { .. } => "steady",
        GeneratorConfig::SpikeEvent { .. } => "spike_event",
    }
}

/// Convert a [`TimingError`] into the appropriate [`CompileAfterError`]
/// variant, preserving the underlying reason string.
fn timing_to_error(
    err: TimingError,
    source_id: &str,
    ref_id: &str,
    generator: &GeneratorConfig,
    op: Operator,
    value: f64,
) -> CompileAfterError {
    let op = op.to_string();
    match err {
        TimingError::Unsupported { message } => CompileAfterError::UnsupportedGenerator {
            source_id: source_id.to_string(),
            ref_id: ref_id.to_string(),
            generator: generator_kind(generator).to_string(),
            op,
            reason: message,
        },
        TimingError::OutOfRange { message } => CompileAfterError::OutOfRangeThreshold {
            source_id: source_id.to_string(),
            ref_id: ref_id.to_string(),
            op,
            value,
            reason: message,
        },
        TimingError::Ambiguous { message } => CompileAfterError::AmbiguousAtT0 {
            source_id: source_id.to_string(),
            ref_id: ref_id.to_string(),
            op,
            value,
            reason: message,
        },
        TimingError::InvalidDuration {
            field,
            input,
            reason,
        } => CompileAfterError::InvalidDuration {
            source_id: source_id.to_string(),
            field,
            input,
            reason,
        },
    }
}

// ---------------------------------------------------------------------------
// Clock-group assignment
// ---------------------------------------------------------------------------

/// Resolved clock-group assignment for one entry.
///
/// Carries the resolved group name alongside its provenance:
///
/// - `Resolved { name, is_auto: true }` — auto-named
///   `chain_{lowest_lex_id}` for a multi-node component with no
///   user-supplied value.
/// - `Resolved { name, is_auto: false }` — user-supplied value adopted
///   for the component (or, in the single-node fall-through path, the
///   entry's own explicit value).
/// - `Unassigned` — single-node component with no explicit value.
///
/// Kept private to the compiler module; downstream consumers see only
/// the resulting `(clock_group, clock_group_is_auto)` pair on
/// [`CompiledEntry`].
#[derive(Debug, Clone, PartialEq, Eq)]
enum ClockGroupAssignment {
    Resolved { name: String, is_auto: bool },
    Unassigned,
}

/// Assign a clock group to every entry based on the `after:` dependency
/// graph (treated as undirected for component detection).
///
/// The returned vector is indexed in parallel with `entries`. Each slot
/// witnesses both the chosen value and whether the compiler auto-named
/// it. See [`ClockGroupAssignment`] for the variants.
///
/// # Errors
///
/// Returns [`CompileAfterError::ConflictingClockGroup`] when a component
/// has two distinct non-empty explicit group values.
fn assign_clock_groups(
    entries: &[ExpandedEntry],
    id_to_idx: &BTreeMap<&str, usize>,
) -> Result<Vec<ClockGroupAssignment>, CompileAfterError> {
    let n = entries.len();

    // Build an undirected adjacency list.
    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
    for (i, entry) in entries.iter().enumerate() {
        if let Some(clause) = &entry.after {
            if let Some(&dep_idx) = id_to_idx.get(clause.ref_id.as_str()) {
                adj[i].push(dep_idx);
                adj[dep_idx].push(i);
            }
        }
    }

    let mut component_id = vec![usize::MAX; n];
    let mut components: Vec<Vec<usize>> = Vec::new();

    for start in 0..n {
        if component_id[start] != usize::MAX {
            continue;
        }
        let cid = components.len();
        let mut stack = vec![start];
        let mut members = Vec::new();
        while let Some(node) = stack.pop() {
            if component_id[node] != usize::MAX {
                continue;
            }
            component_id[node] = cid;
            members.push(node);
            for &next in &adj[node] {
                if component_id[next] == usize::MAX {
                    stack.push(next);
                }
            }
        }
        components.push(members);
    }

    let mut out: Vec<ClockGroupAssignment> =
        (0..n).map(|_| ClockGroupAssignment::Unassigned).collect();
    for members in &components {
        if members.len() < 2 {
            continue;
        }

        // Collect all distinct non-empty explicit clock_group values.
        let mut distinct: BTreeMap<&str, usize> = BTreeMap::new();
        for &idx in members {
            if let Some(cg) = entries[idx].clock_group.as_deref() {
                if !cg.is_empty() {
                    distinct.entry(cg).or_insert(idx);
                }
            }
        }

        let (resolved, is_auto) = match distinct.len() {
            0 => (auto_chain_name(members, entries), true),
            1 => {
                let (&k, _) = distinct.iter().next().expect("len == 1");
                (k.to_string(), false)
            }
            _ => {
                let mut iter = distinct.iter();
                let (&first_group, &first_idx) = iter.next().expect("len >= 2");
                let (&second_group, &second_idx) = iter.next().expect("len >= 2");
                return Err(CompileAfterError::ConflictingClockGroup {
                    first_entry: source_label(&entries[first_idx]).into_owned(),
                    first_group: first_group.to_string(),
                    second_entry: source_label(&entries[second_idx]).into_owned(),
                    second_group: second_group.to_string(),
                });
            }
        };

        for &idx in members {
            out[idx] = ClockGroupAssignment::Resolved {
                name: resolved.clone(),
                is_auto,
            };
        }
    }

    Ok(out)
}

/// Build a deterministic `chain_{lowest_lex_id}` name from a component's
/// member indices.
///
/// Every multi-member component reaches this helper via an `after` edge,
/// and `after.ref` can only target an entry that carries an `id` (that's
/// how reference resolution works in [`build_id_index`]). Therefore the
/// component always has at least one `id`-bearing member, and
/// [`Iterator::next`] on the sorted id list is guaranteed to be `Some`.
fn auto_chain_name(members: &[usize], entries: &[ExpandedEntry]) -> String {
    let mut ids: Vec<&str> = members
        .iter()
        .filter_map(|&i| entries[i].id.as_deref())
        .collect();
    ids.sort();
    let first = ids.first().unwrap_or_else(|| {
        unreachable!(
            "multi-entry component has no id-bearing member — `after.ref` \
             resolution guarantees every linked entry carries an id"
        )
    });
    format!("chain_{first}")
}

// ---------------------------------------------------------------------------
// Cycle detection
// ---------------------------------------------------------------------------

/// Find a cycle in the directed dependency graph for error reporting.
///
/// Uses DFS with gray/black coloring — on encountering a back-edge to a
/// gray vertex, the recursion stack is replayed to reconstruct the cycle
/// path. The first and last entries in the returned vector are always
/// equal, giving a readable display like `A -> B -> C -> A`.
fn find_cycle(entries: &[ExpandedEntry], id_to_idx: &BTreeMap<&str, usize>) -> Vec<String> {
    #[derive(Clone, Copy, PartialEq, Eq)]
    enum Color {
        White,
        Gray,
        Black,
    }

    let n = entries.len();
    let mut color = vec![Color::White; n];
    let mut stack: Vec<usize> = Vec::new();

    // Recursive DFS with a path-reconstruction vector: `stack` records the
    // current ancestor chain so that on a back-edge we can slice out the
    // cycle from `dep` to `node` without re-traversing the graph. Back-edge
    // detection is driven by `color[dep] == Gray`.
    fn dfs(
        node: usize,
        entries: &[ExpandedEntry],
        id_to_idx: &BTreeMap<&str, usize>,
        color: &mut [Color],
        stack: &mut Vec<usize>,
    ) -> Option<Vec<usize>> {
        color[node] = Color::Gray;
        stack.push(node);

        if let Some(clause) = &entries[node].after {
            if let Some(&dep) = id_to_idx.get(clause.ref_id.as_str()) {
                match color[dep] {
                    Color::White => {
                        if let Some(cycle) = dfs(dep, entries, id_to_idx, color, stack) {
                            return Some(cycle);
                        }
                    }
                    Color::Gray => {
                        // Back-edge: reconstruct the cycle from `dep` to `node`.
                        let start = stack.iter().position(|&x| x == dep).unwrap_or(0);
                        let mut cycle: Vec<usize> = stack[start..].to_vec();
                        cycle.push(dep);
                        return Some(cycle);
                    }
                    Color::Black => {}
                }
            }
        }

        color[node] = Color::Black;
        stack.pop();
        None
    }

    for start in 0..n {
        if color[start] == Color::White {
            if let Some(cycle) = dfs(start, entries, id_to_idx, &mut color, &mut stack) {
                return cycle
                    .into_iter()
                    .map(|i| source_label(&entries[i]).into_owned())
                    .collect();
            }
        }
    }

    vec!["<unknown cycle>".to_string()]
}

// ---------------------------------------------------------------------------
// Utilities
// ---------------------------------------------------------------------------

/// Map an [`AfterOp`] (v2 AST) onto the alias-free [`Operator`] used by
/// the timing math.
fn operator_from(op: &AfterOp) -> Operator {
    match op {
        AfterOp::LessThan => Operator::LessThan,
        AfterOp::GreaterThan => Operator::GreaterThan,
    }
}

/// Parse a duration string into fractional seconds, emitting a compiler
/// error with field context on failure.
fn parse_duration_secs(
    input: &str,
    source_id: &str,
    field: &'static str,
) -> Result<f64, CompileAfterError> {
    parse_duration(input)
        .map(|d| d.as_secs_f64())
        .map_err(|e| CompileAfterError::InvalidDuration {
            source_id: source_id.to_string(),
            field,
            input: input.to_string(),
            reason: e.to_string(),
        })
}

/// Resolve an optional duration string to seconds, falling back to
/// `default_secs` when `None`.
///
/// Parse failures surface as [`TimingError::InvalidDuration`] tagged with
/// the alias parameter name (e.g. `"flap.up_duration"`). The outer
/// [`timing_to_error`] then maps this straight into
/// [`CompileAfterError::InvalidDuration`] — the same variant used for
/// top-level `after.delay` and `phase_offset` parse failures — so users
/// see consistent diagnostics for every duration-shaped input regardless
/// of where it appears on the generator config.
fn duration_or_default(
    input: Option<&str>,
    default_secs: f64,
    field: &'static str,
) -> Result<f64, TimingError> {
    match input {
        Some(s) => {
            parse_duration(s)
                .map(|d| d.as_secs_f64())
                .map_err(|e| TimingError::InvalidDuration {
                    field,
                    input: s.to_string(),
                    reason: e.to_string(),
                })
        }
        None => Ok(default_secs),
    }
}

/// Format an f64 seconds value as a duration string accepted by
/// [`parse_duration`].
///
/// The output prefers the shortest whole-unit representation (e.g. `"1m"`
/// for 60s, `"1h"` for 3600s) and falls back to fractional seconds for
/// values that cannot round-trip through a whole-unit form. Zero and
/// negative inputs normalize to `"0s"`. In debug builds a
/// `debug_assert!` guards against non-finite or negative inputs — these
/// can only arise from programmer error; the release fallback preserves
/// the `"0s"` normalization so production code never panics.
///
/// Sub-second values are emitted as fractional seconds (`0.5s` →
/// `"0.5s"`) rather than milliseconds; callers that need a specific
/// display form should format locally. All emitted strings round-trip
/// cleanly through [`parse_duration`] to the same [`std::time::Duration`].
pub fn format_duration_secs(secs: f64) -> String {
    debug_assert!(
        secs.is_finite() && secs >= 0.0,
        "format_duration_secs received non-finite or negative value: {secs}"
    );
    if !secs.is_finite() || secs <= 0.0 {
        return "0s".to_string();
    }

    // Prefer whole-unit forms.
    let ms = (secs * 1000.0).round() as u64;
    if ms.is_multiple_of(1000) {
        let whole_secs = ms / 1000;
        if whole_secs > 0 && whole_secs.is_multiple_of(3600) {
            return format!("{}h", whole_secs / 3600);
        }
        if whole_secs > 0 && whole_secs.is_multiple_of(60) {
            return format!("{}m", whole_secs / 60);
        }
        return format!("{whole_secs}s");
    }

    // Sub-millisecond: fall back to fractional seconds.
    if ms < 1 {
        return format!("{secs}s");
    }

    // Fractional seconds expressible in whole milliseconds → use seconds
    // with enough precision to round-trip through parse_duration. Three
    // decimals is sufficient because `ms` is already whole ms.
    let secs_rounded = (ms as f64) / 1000.0;
    format!("{secs_rounded}s")
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::compiler::expand::expand;
    use crate::compiler::expand::InMemoryPackResolver;
    use crate::compiler::normalize::normalize;
    use crate::compiler::parse::parse;

    // -----------------------------------------------------------------------
    // Helpers
    // -----------------------------------------------------------------------

    /// Compile a v2 YAML string end-to-end through parse → normalize →
    /// expand → compile_after, using the provided pack resolver.
    fn compile(yaml: &str) -> Result<CompiledFile, String> {
        compile_with_resolver(yaml, &InMemoryPackResolver::new())
    }

    fn compile_with_resolver(
        yaml: &str,
        resolver: &InMemoryPackResolver,
    ) -> Result<CompiledFile, String> {
        let parsed = parse(yaml).map_err(|e| format!("parse: {e}"))?;
        let normalized = normalize(parsed).map_err(|e| format!("normalize: {e}"))?;
        let expanded = expand(normalized, resolver).map_err(|e| format!("expand: {e}"))?;
        compile_after(expanded).map_err(|e| format!("compile_after: {e}"))
    }

    // -----------------------------------------------------------------------
    // Reference resolution
    // -----------------------------------------------------------------------

    #[test]
    fn unknown_ref_surfaces_available_ids() {
        let yaml = r#"
version: 2
scenarios:
  - id: cpu
    signal_type: metrics
    name: cpu_saturation
    rate: 1
    generator: { type: saturation, baseline: 0, ceiling: 100, time_to_saturate: 60s }
  - id: log_entry
    signal_type: logs
    name: errors
    rate: 1
    log_generator: { type: template, templates: [{ message: "hi" }] }
    after: { ref: nonexistent, op: ">", value: 50 }
"#;
        let err = compile(yaml).expect_err("should fail");
        assert!(err.contains("nonexistent"), "got: {err}");
        assert!(err.contains("Available"), "got: {err}");
    }

    #[test]
    fn self_reference_is_rejected() {
        let yaml = r#"
version: 2
scenarios:
  - id: loop
    signal_type: metrics
    name: util
    rate: 1
    generator: { type: saturation, baseline: 0, ceiling: 100, time_to_saturate: 60s }
    after: { ref: loop, op: ">", value: 50 }
"#;
        let err = compile(yaml).expect_err("self-ref is rejected");
        assert!(err.contains("references itself"), "got: {err}");
    }

    // -----------------------------------------------------------------------
    // Simple crossing per operator/generator
    // -----------------------------------------------------------------------

    #[test]
    fn saturation_greater_than_sets_offset() {
        let yaml = r#"
version: 2
scenarios:
  - id: util
    signal_type: metrics
    name: util
    rate: 1
    generator: { type: saturation, baseline: 20, ceiling: 85, time_to_saturate: 120s }
  - id: follower
    signal_type: metrics
    name: latency
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: util, op: ">", value: 70 }
"#;
        let compiled = compile(yaml).expect("should compile");
        let follower = &compiled.entries[1];
        let expected_secs = (70.0 - 20.0) / (85.0 - 20.0) * 120.0;
        let expected_str = format_duration_secs(expected_secs);
        assert_eq!(
            follower.phase_offset.as_deref(),
            Some(expected_str.as_str())
        );
    }

    #[rustfmt::skip]
    #[rstest::rstest]
    // Flap `<` crosses at the up_duration boundary (60s → "1m").
    #[case::flap_less_than(r#"
version: 2
scenarios:
  - id: link
    signal_type: metrics
    name: oper_state
    rate: 1
    generator: { type: flap, up_duration: 60s, down_duration: 30s }
  - id: follower
    signal_type: metrics
    name: util
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: link, op: "<", value: 1 }
"#, "1m")]
    // spike_event `<` crosses at the spike_duration boundary (10s).
    #[case::spike_event_less_than(r#"
version: 2
scenarios:
  - id: burst
    signal_type: metrics
    name: errs
    rate: 1
    generator: { type: spike_event, baseline: 0, spike_height: 100, spike_duration: 10s, spike_interval: 60s }
  - id: follower
    signal_type: metrics
    name: recovery
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: burst, op: "<", value: 50 }
"#, "10s")]
    // Step `>`: ceil((55-0)/10) = 6 ticks, rate=2 -> 3.0s.
    #[case::step_greater_than(r#"
version: 2
scenarios:
  - id: counter
    signal_type: metrics
    name: req_count
    rate: 2
    generator: { type: step, start: 0, step_size: 10 }
  - id: follower
    signal_type: metrics
    name: alert
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: counter, op: ">", value: 55 }
"#, "3s")]
    // Sequence `<`: index 2 (value 2) is the first < 3; rate=2 -> 1.0s.
    #[case::sequence_less_than(r#"
version: 2
scenarios:
  - id: seq
    signal_type: metrics
    name: values
    rate: 2
    generator: { type: sequence, values: [10, 5, 2, 1], repeat: false }
  - id: follower
    signal_type: metrics
    name: alert
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: seq, op: "<", value: 3 }
"#, "1s")]
    fn follower_phase_offset_matches_expected_crossing(
        #[case] yaml: &str,
        #[case] expected_offset: &str,
    ) {
        let compiled = compile(yaml).expect("should compile");
        assert_eq!(
            compiled.entries[1].phase_offset.as_deref(),
            Some(expected_offset)
        );
    }

    #[test]
    fn step_less_than_is_unsupported() {
        let yaml = r#"
version: 2
scenarios:
  - id: counter
    signal_type: metrics
    name: x
    rate: 1
    generator: { type: step, start: 0, step_size: 1 }
  - id: follower
    signal_type: metrics
    name: y
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: counter, op: "<", value: 5 }
"#;
        let err = compile(yaml).expect_err("step < is unsupported");
        assert!(err.contains("step"), "got: {err}");
    }

    // -----------------------------------------------------------------------
    // Targets that cannot be resolved to a crossing time.
    //
    // `constant` values are out-of-range when the threshold is unreachable;
    // `sine`, `steady`, and `uniform` are blanket-unsupported because their
    // values never settle into a predictable threshold-crossing schedule.
    // Each error message must name the offending generator type so the
    // diagnostic points the user at the right signal.
    // -----------------------------------------------------------------------

    #[rustfmt::skip]
    #[rstest::rstest]
    #[case::constant(r#"
version: 2
scenarios:
  - id: k
    signal_type: metrics
    name: k
    rate: 1
    generator: { type: constant, value: 42 }
  - id: follower
    signal_type: metrics
    name: y
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: k, op: ">", value: 100 }
"#, "constant")]
    #[case::sine(r#"
version: 2
scenarios:
  - id: wave
    signal_type: metrics
    name: s
    rate: 1
    generator: { type: sine, amplitude: 10, period_secs: 60, offset: 50 }
  - id: follower
    signal_type: metrics
    name: f
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: wave, op: ">", value: 55 }
"#, "sine")]
    #[case::steady(r#"
version: 2
scenarios:
  - id: base
    signal_type: metrics
    name: s
    rate: 1
    generator: { type: steady, center: 50, amplitude: 5, period: 60s }
  - id: follower
    signal_type: metrics
    name: f
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: base, op: ">", value: 55 }
"#, "steady")]
    #[case::uniform(r#"
version: 2
scenarios:
  - id: u
    signal_type: metrics
    name: u
    rate: 1
    generator: { type: uniform, min: 0, max: 10, seed: 1 }
  - id: follower
    signal_type: metrics
    name: f
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: u, op: ">", value: 5 }
"#, "uniform")]
    fn unresolvable_target_generator_is_rejected(
        #[case] yaml: &str,
        #[case] expected_substring: &str,
    ) {
        let err = compile(yaml).expect_err("target generator must be rejected");
        assert!(
            err.contains(expected_substring),
            "expected error to mention {expected_substring:?}, got: {err}"
        );
    }

    // -----------------------------------------------------------------------
    // Transitive chains + delay additivity
    // -----------------------------------------------------------------------

    #[test]
    fn transitive_chain_accumulates() {
        let yaml = r#"
version: 2
scenarios:
  - id: a
    signal_type: metrics
    name: a
    rate: 1
    generator: { type: flap, up_duration: 60s, down_duration: 30s }
  - id: b
    signal_type: metrics
    name: b
    rate: 1
    generator: { type: saturation, baseline: 20, ceiling: 85, time_to_saturate: 120s }
    after: { ref: a, op: "<", value: 1 }
  - id: c
    signal_type: metrics
    name: c
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: b, op: ">", value: 70 }
"#;
        let compiled = compile(yaml).expect("chain compiles");
        let expected_b_secs = 60.0;
        let expected_c_secs = 60.0 + (70.0 - 20.0) / (85.0 - 20.0) * 120.0;
        assert_eq!(
            compiled.entries[1].phase_offset.as_deref(),
            Some(format_duration_secs(expected_b_secs).as_str())
        );
        assert_eq!(
            compiled.entries[2].phase_offset.as_deref(),
            Some(format_duration_secs(expected_c_secs).as_str())
        );
    }

    #[test]
    fn delay_is_added_to_crossing_time() {
        let yaml = r#"
version: 2
scenarios:
  - id: link
    signal_type: metrics
    name: a
    rate: 1
    generator: { type: flap, up_duration: 60s, down_duration: 30s }
  - id: follower
    signal_type: metrics
    name: b
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: link, op: "<", value: 1, delay: 15s }
"#;
        let compiled = compile(yaml).expect("compile");
        assert_eq!(compiled.entries[1].phase_offset.as_deref(), Some("75s"));
    }

    #[test]
    fn explicit_phase_offset_is_added() {
        let yaml = r#"
version: 2
scenarios:
  - id: link
    signal_type: metrics
    name: a
    rate: 1
    generator: { type: flap, up_duration: 60s, down_duration: 30s }
  - id: follower
    signal_type: metrics
    name: b
    rate: 1
    generator: { type: constant, value: 1 }
    phase_offset: 10s
    after: { ref: link, op: "<", value: 1 }
"#;
        let compiled = compile(yaml).expect("compile");
        assert_eq!(compiled.entries[1].phase_offset.as_deref(), Some("70s"));
    }

    #[test]
    fn phase_offset_delay_and_crossing_sum() {
        let yaml = r#"
version: 2
scenarios:
  - id: link
    signal_type: metrics
    name: a
    rate: 1
    generator: { type: flap, up_duration: 60s, down_duration: 30s }
  - id: follower
    signal_type: metrics
    name: b
    rate: 1
    generator: { type: constant, value: 1 }
    phase_offset: 10s
    after: { ref: link, op: "<", value: 1, delay: 5s }
"#;
        let compiled = compile(yaml).expect("compile");
        // 10s + 60s crossing + 5s delay = 75s.
        assert_eq!(compiled.entries[1].phase_offset.as_deref(), Some("75s"));
    }

    // -----------------------------------------------------------------------
    // Cycle detection
    // -----------------------------------------------------------------------

    #[test]
    fn two_entry_cycle_is_detected() {
        let yaml = r#"
version: 2
scenarios:
  - id: a
    signal_type: metrics
    name: a
    rate: 1
    generator: { type: saturation, baseline: 0, ceiling: 100, time_to_saturate: 60s }
    after: { ref: b, op: ">", value: 1 }
  - id: b
    signal_type: metrics
    name: b
    rate: 1
    generator: { type: saturation, baseline: 0, ceiling: 100, time_to_saturate: 60s }
    after: { ref: a, op: ">", value: 1 }
"#;
        let err = compile(yaml).expect_err("cycle should fail");
        assert!(err.contains("circular"), "got: {err}");
        assert!(err.contains("a") && err.contains("b"), "got: {err}");
    }

    #[test]
    fn three_entry_cycle_path_is_returned() {
        let yaml = r#"
version: 2
scenarios:
  - id: a
    signal_type: metrics
    name: a
    rate: 1
    generator: { type: saturation, baseline: 0, ceiling: 100, time_to_saturate: 60s }
    after: { ref: c, op: ">", value: 1 }
  - id: b
    signal_type: metrics
    name: b
    rate: 1
    generator: { type: saturation, baseline: 0, ceiling: 100, time_to_saturate: 60s }
    after: { ref: a, op: ">", value: 1 }
  - id: c
    signal_type: metrics
    name: c
    rate: 1
    generator: { type: saturation, baseline: 0, ceiling: 100, time_to_saturate: 60s }
    after: { ref: b, op: ">", value: 1 }
"#;
        let err = compile(yaml).expect_err("cycle should fail");
        assert!(err.contains("circular"), "got: {err}");
        assert!(
            err.contains("a -> "),
            "cycle path should have an arrow. got: {err}"
        );
    }

    // -----------------------------------------------------------------------
    // Clock-group assignment (matrix 11.15 / 11.16)
    // -----------------------------------------------------------------------

    #[test]
    fn clock_group_auto_assigned_as_chain_plus_lowest_id() {
        let yaml = r#"
version: 2
scenarios:
  - id: alpha
    signal_type: metrics
    name: a
    rate: 1
    generator: { type: flap, up_duration: 60s, down_duration: 30s }
  - id: bravo
    signal_type: metrics
    name: b
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: alpha, op: "<", value: 1 }
"#;
        let compiled = compile(yaml).expect("compile");
        assert_eq!(
            compiled.entries[0].clock_group.as_deref(),
            Some("chain_alpha")
        );
        assert_eq!(
            compiled.entries[1].clock_group.as_deref(),
            Some("chain_alpha")
        );
    }

    #[test]
    fn explicit_clock_group_propagates_to_chain_members() {
        let yaml = r#"
version: 2
scenarios:
  - id: alpha
    signal_type: metrics
    name: a
    rate: 1
    clock_group: failover
    generator: { type: flap, up_duration: 60s, down_duration: 30s }
  - id: bravo
    signal_type: metrics
    name: b
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: alpha, op: "<", value: 1 }
"#;
        let compiled = compile(yaml).expect("compile");
        assert_eq!(compiled.entries[0].clock_group.as_deref(), Some("failover"));
        assert_eq!(compiled.entries[1].clock_group.as_deref(), Some("failover"));
    }

    #[test]
    fn conflicting_clock_groups_are_rejected() {
        let yaml = r#"
version: 2
scenarios:
  - id: alpha
    signal_type: metrics
    name: a
    rate: 1
    clock_group: group_a
    generator: { type: flap, up_duration: 60s, down_duration: 30s }
  - id: bravo
    signal_type: metrics
    name: b
    rate: 1
    clock_group: group_b
    generator: { type: constant, value: 1 }
    after: { ref: alpha, op: "<", value: 1 }
"#;
        let err = compile(yaml).expect_err("conflicting groups fail");
        assert!(err.contains("conflicting clock_group"), "got: {err}");
        assert!(
            err.contains("group_a") && err.contains("group_b"),
            "got: {err}"
        );
    }

    #[test]
    fn independent_signals_keep_no_clock_group() {
        let yaml = r#"
version: 2
scenarios:
  - id: independent
    signal_type: metrics
    name: a
    rate: 1
    generator: { type: saturation, baseline: 0, ceiling: 100, time_to_saturate: 60s }
"#;
        let compiled = compile(yaml).expect("compile");
        assert!(compiled.entries[0].clock_group.is_none());
    }

    #[test]
    fn clock_group_empty_string_mixed_with_some_x_uses_x() {
        // An explicit empty string is filtered out (treated as "no value")
        // and the concrete `"x"` wins for the whole component — no conflict.
        let yaml = r#"
version: 2
scenarios:
  - id: alpha
    signal_type: metrics
    name: a
    rate: 1
    clock_group: ""
    generator: { type: flap, up_duration: 60s, down_duration: 30s }
  - id: bravo
    signal_type: metrics
    name: b
    rate: 1
    clock_group: x
    generator: { type: constant, value: 1 }
    after: { ref: alpha, op: "<", value: 1 }
"#;
        let compiled = compile(yaml).expect("compile");
        assert_eq!(compiled.entries[0].clock_group.as_deref(), Some("x"));
        assert_eq!(compiled.entries[1].clock_group.as_deref(), Some("x"));
    }

    #[test]
    fn clock_group_whitespace_variants_conflict() {
        // `"x "` and `"x"` differ under string equality, so the component
        // carries two distinct non-empty values -> ConflictingClockGroup.
        let yaml = r#"
version: 2
scenarios:
  - id: alpha
    signal_type: metrics
    name: a
    rate: 1
    clock_group: "x "
    generator: { type: flap, up_duration: 60s, down_duration: 30s }
  - id: bravo
    signal_type: metrics
    name: b
    rate: 1
    clock_group: x
    generator: { type: constant, value: 1 }
    after: { ref: alpha, op: "<", value: 1 }
"#;
        let err = compile(yaml).expect_err("trailing whitespace must conflict");
        assert!(err.contains("conflicting clock_group"), "got: {err}");
    }

    // -----------------------------------------------------------------------
    // Cross-signal-type after (spec §3.5, matrix 11.11)
    // -----------------------------------------------------------------------

    #[test]
    fn log_signal_can_depend_on_metrics_target() {
        let yaml = r#"
version: 2
scenarios:
  - id: err_rate
    signal_type: metrics
    name: http_error_rate
    rate: 1
    generator: { type: saturation, baseline: 1, ceiling: 30, time_to_saturate: 90s }
  - id: err_logs
    signal_type: logs
    name: app_logs
    rate: 1
    log_generator: { type: template, templates: [{ message: "upstream timeout" }] }
    after: { ref: err_rate, op: ">", value: 10 }
"#;
        let compiled = compile(yaml).expect("cross-signal after compiles");
        assert!(compiled.entries[1].phase_offset.is_some());
    }

    #[test]
    fn metrics_entry_cannot_depend_on_logs_target() {
        let yaml = r#"
version: 2
scenarios:
  - id: log_src
    signal_type: logs
    name: lg
    rate: 1
    log_generator: { type: template, templates: [{ message: "hi" }] }
  - id: follower
    signal_type: metrics
    name: f
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: log_src, op: ">", value: 0 }
"#;
        let err = compile(yaml).expect_err("logs target rejected");
        assert!(err.contains("logs signal"), "got: {err}");
    }

    // -----------------------------------------------------------------------
    // Alias desugaring correctness: `flap` after-math matches desugared
    // sequence.
    // -----------------------------------------------------------------------

    #[test]
    fn flap_alias_produces_expected_up_duration_offset() {
        let yaml_alias = r#"
version: 2
scenarios:
  - id: link
    signal_type: metrics
    name: s
    rate: 1
    generator: { type: flap, up_duration: 60s, down_duration: 30s }
  - id: follower
    signal_type: metrics
    name: f
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: link, op: "<", value: 1 }
"#;
        let compiled = compile(yaml_alias).expect("compile");
        assert_eq!(compiled.entries[1].phase_offset.as_deref(), Some("1m"));
    }

    // -----------------------------------------------------------------------
    // Pack sub-signal refs (matrix 11.7, 11.12, 11.13)
    // -----------------------------------------------------------------------

    fn resolver_with_test_pack() -> InMemoryPackResolver {
        // Simple pack with unique-by-name metrics.
        let yaml = r#"
name: testpack
category: test
description: test
metrics:
  - name: state_flap
    generator: { type: flap, up_duration: 60s, down_duration: 30s }
  - name: util_sat
    generator: { type: saturation, baseline: 0, ceiling: 100, time_to_saturate: 120s }
"#;
        let pack =
            serde_yaml_ng::from_str::<crate::packs::MetricPackDef>(yaml).expect("pack parses");
        let mut r = InMemoryPackResolver::new();
        r.insert("testpack", pack);
        r
    }

    #[test]
    fn dotted_pack_ref_resolves() {
        let yaml = r#"
version: 2
scenarios:
  - id: dev
    signal_type: metrics
    rate: 1
    pack: testpack
  - id: follower
    signal_type: metrics
    name: alert
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: dev.state_flap, op: "<", value: 1 }
"#;
        let compiled = compile_with_resolver(yaml, &resolver_with_test_pack()).expect("compile");
        // Look for the follower entry (non-pack).
        let follower = compiled
            .entries
            .iter()
            .find(|e| e.id.as_deref() == Some("follower"))
            .expect("follower present");
        assert_eq!(follower.phase_offset.as_deref(), Some("1m"));
    }

    #[test]
    fn ambiguous_bare_pack_ref_is_rejected() {
        // Use a pack with two specs sharing the metric name.
        let pack_yaml = r#"
name: ambig
category: test
description: test
metrics:
  - name: cpu_util
    labels: { mode: user }
    generator: { type: sawtooth, min: 0, max: 100, period_secs: 60 }
  - name: cpu_util
    labels: { mode: system }
    generator: { type: sawtooth, min: 0, max: 100, period_secs: 60 }
"#;
        let pack =
            serde_yaml_ng::from_str::<crate::packs::MetricPackDef>(pack_yaml).expect("pack parses");
        let mut r = InMemoryPackResolver::new();
        r.insert("ambig", pack);

        let yaml = r#"
version: 2
scenarios:
  - id: host
    signal_type: metrics
    rate: 1
    pack: ambig
  - id: follower
    signal_type: metrics
    name: alert
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: host.cpu_util, op: ">", value: 50 }
"#;
        let err = compile_with_resolver(yaml, &r).expect_err("bare ref is ambiguous");
        assert!(err.contains("ambiguous"), "got: {err}");
        assert!(
            err.contains("host.cpu_util#0") && err.contains("host.cpu_util#1"),
            "candidates should be listed. got: {err}"
        );
    }

    // -----------------------------------------------------------------------
    // InvalidDuration coverage — every code path that can construct this
    // variant must have a dedicated regression test.
    //
    // Each case names the source id of the failing entry, the field that
    // flagged the malformed duration, and the literal input string so the
    // error round-trip is byte-exact.
    // -----------------------------------------------------------------------

    #[rustfmt::skip]
    #[rstest::rstest]
    // `compile_after` is the first validation pass that actually parses
    // `after.delay` as a `std::time::Duration` — the parser only checks
    // the shape of the YAML. A malformed delay string must surface as
    // `CompileAfterError::InvalidDuration` tagged with
    // `field == "after.delay"`.
    #[case::after_delay(r#"
version: 2
scenarios:
  - id: src
    signal_type: metrics
    name: a
    rate: 1
    generator: { type: flap, up_duration: 60s, down_duration: 30s }
  - id: follower
    signal_type: metrics
    name: b
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: src, op: "<", value: 1, delay: "10seconds" }
"#, "follower", "after.delay", "10seconds")]
    // `phase_offset: "0s"` is a well-known `parse_duration` rejection
    // (zero durations are invalid). Because the entry's `phase_offset`
    // is parsed inside `compile_after`, this must surface as
    // `CompileAfterError::InvalidDuration` with `field == "phase_offset"`.
    #[case::phase_offset_zero(r#"
version: 2
scenarios:
  - id: src
    signal_type: metrics
    name: a
    rate: 1
    generator: { type: flap, up_duration: 60s, down_duration: 30s }
  - id: follower
    signal_type: metrics
    name: b
    rate: 1
    phase_offset: "0s"
    generator: { type: constant, value: 1 }
    after: { ref: src, op: "<", value: 1 }
"#, "follower", "phase_offset", "0s")]
    // Invalid alias duration params (e.g. `flap.up_duration: "oops"`) must
    // also route through `InvalidDuration` — historically these were
    // folded into `OutOfRangeThreshold` because `duration_or_default`
    // wrapped them as `TimingError::OutOfRange`. PR 5 review flagged the
    // mis-classification; this regression anchors the fix.
    #[case::alias_flap_up_duration(r#"
version: 2
scenarios:
  - id: src
    signal_type: metrics
    name: a
    rate: 1
    generator: { type: flap, up_duration: "oops", down_duration: 30s }
  - id: follower
    signal_type: metrics
    name: b
    rate: 1
    generator: { type: constant, value: 1 }
    after: { ref: src, op: "<", value: 1 }
"#, "follower", "flap.up_duration", "oops")]
    fn invalid_duration_surfaces_invalid_duration(
        #[case] yaml: &str,
        #[case] expected_source_id: &str,
        #[case] expected_field: &str,
        #[case] expected_input: &str,
    ) {
        let err = match compile_after_from_yaml(yaml) {
            Err(e) => e,
            Ok(_) => panic!("invalid duration must fail"),
        };
        match err {
            CompileAfterError::InvalidDuration {
                ref source_id,
                field,
                ref input,
                ..
            } => {
                assert_eq!(source_id, expected_source_id);
                assert_eq!(field, expected_field);
                assert_eq!(input, expected_input);
            }
            other => panic!("expected InvalidDuration, got {other:?}"),
        }
    }

    /// Pipe YAML straight to `compile_after` and return the typed error
    /// (rather than the stringified form the other helpers use). Enables
    /// the `InvalidDuration` tests above to pattern-match on the variant
    /// shape without redundant string assertions.
    fn compile_after_from_yaml(yaml: &str) -> Result<CompiledFile, CompileAfterError> {
        let parsed = parse(yaml).expect("parse");
        let normalized = normalize(parsed).expect("normalize");
        let expanded = expand(normalized, &InMemoryPackResolver::new()).expect("expand");
        compile_after(expanded)
    }

    // -----------------------------------------------------------------------
    // format_duration_secs round-trip
    // -----------------------------------------------------------------------

    #[rustfmt::skip]
    #[rstest::rstest]
    #[case::whole_seconds(30.0,            "30s")]
    #[case::whole_minutes(120.0,           "2m")]
    #[case::whole_hours(3600.0,            "1h")]
    // Exact zero (and the `-0.0` variant, which compares equal to 0.0)
    // both route through the `<= 0.0` fallback and emit `"0s"`.
    #[case::zero(0.0,                      "0s")]
    #[case::negative_zero(-0.0,            "0s")]
    fn format_duration_whole_units(#[case] secs: f64, #[case] expected: &str) {
        assert_eq!(format_duration_secs(secs), expected);
    }

    #[test]
    fn format_duration_fractional_seconds_round_trip() {
        let result = format_duration_secs(92.307);
        let dur = parse_duration(&result).expect("round-trip");
        assert!(
            (dur.as_secs_f64() - 92.307).abs() < 0.01,
            "got {}, expected ~92.307",
            dur.as_secs_f64()
        );
    }
}