hatchet-client 0.1.0

Rust SDK for Hatchet: run workers and trigger tasks
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
//! Workflows, and the mapping from a declaration to the registration request.

use std::collections::{HashMap, HashSet, VecDeque};
use std::fmt;

use hatchet_proto::v1;
use serde_json::Value;

use super::task::Task;
use super::{
    Concurrency, ConditionAction, Gates, Idempotency, Priority, RegisteredAction, StickyStrategy,
    TaskDef, TaskOptions, WorkflowOptions, action_id, timeout_string, wire_name,
};
use crate::config::namespace;
use crate::{Error, Result};

mod sealed {
    pub trait Sealed {}
}

/// Something a worker can register: a standalone [`Task`] or a [`Workflow`].
pub trait Register: sealed::Sealed {
    /// The type-erased declaration.
    #[doc(hidden)]
    fn definition(&self) -> WorkflowDef;
}

/// A named set of tasks, ordered into a DAG by their parents.
///
/// Every task in a workflow receives the *workflow's* input; a task reads
/// what came before it with
/// [`Context::parent_output`](crate::Context::parent_output). Triggers
/// (events, crons), the description, the version and the default priority
/// belong to the workflow rather than to its tasks.
///
/// Parents are attached to a task before it is moved in, so declare them in
/// dependency order:
///
/// ```
/// use hatchet_client::{TaskBuilder, Workflow};
///
/// let fetch = TaskBuilder::<(), u32>::new("fetch").handler(|_ctx, _input| async { Ok(21) });
/// let summarize = TaskBuilder::<(), String>::new("summarize")
///     .handler({
///         let fetch = fetch.clone();
///         move |ctx: hatchet_client::Context, _input: ()| {
///             let fetch = fetch.clone();
///             async move {
///                 let total: u32 = ctx.parent_output(&fetch)?;
///                 Ok(format!("total {total}"))
///             }
///         }
///     })
///     .parent(&fetch);
///
/// let pipeline = Workflow::new("pipeline")
///     .cron("0 * * * *")
///     .task(&fetch)
///     .task(&summarize);
/// assert_eq!(pipeline.name(), "pipeline");
/// ```
///
/// Mistakes — duplicate task names, a parent that was never added, trigger
/// options set on a task instead of on the workflow — are reported as
/// [`Error::InvalidDeclaration`] when the workflow is registered.
#[derive(Clone)]
#[must_use = "a declared workflow runs nothing until it is registered on a worker"]
pub struct Workflow {
    name: String,
    options: WorkflowOptions,
    tasks: Vec<TaskDef>,
    /// The task to run when the workflow fails. At most one; a second
    /// declaration is reported by `validate`, not by a panic.
    on_failure: Vec<TaskDef>,
    /// The task to run once, after every other task has succeeded. At most
    /// one; a second declaration is reported by `validate`, not by a panic.
    on_success: Vec<TaskDef>,
    /// Tasks that carried standalone-only options; reported at registration.
    tasks_with_standalone_options: Vec<String>,
}

/// Names the workflow and its tasks; the tasks' handlers are closures with
/// nothing to print.
impl fmt::Debug for Workflow {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Workflow")
            .field("name", &self.name)
            .field("tasks", &task_names(&self.tasks))
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for WorkflowDef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WorkflowDef")
            .field("name", &self.name)
            .field("tasks", &task_names(&self.tasks))
            .field("is_standalone", &self.is_standalone)
            .finish_non_exhaustive()
    }
}

fn task_names(tasks: &[TaskDef]) -> Vec<&str> {
    tasks.iter().map(|task| task.name.as_str()).collect()
}

impl Workflow {
    /// Starts declaring a workflow.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            options: WorkflowOptions::default(),
            tasks: Vec::new(),
            on_failure: Vec::new(),
            on_success: Vec::new(),
            tasks_with_standalone_options: Vec::new(),
        }
    }

    /// The workflow's name as declared.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Describes the workflow.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.options.description = Some(description.into());
        self
    }

    /// Labels this version of the workflow.
    pub fn version(mut self, version: impl Into<String>) -> Self {
        self.options.version = Some(version.into());
        self
    }

    /// Runs the workflow whenever one of these event keys is pushed. May be
    /// called repeatedly; event keys accumulate.
    pub fn on_events(mut self, keys: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.options
            .on_events
            .extend(keys.into_iter().map(Into::into));
        self
    }

    /// Runs the workflow on a cron schedule. May be called repeatedly; cron
    /// expressions accumulate.
    pub fn cron(mut self, expression: impl Into<String>) -> Self {
        self.options.on_crons.push(expression.into());
        self
    }

    /// The input given to cron-triggered runs.
    pub fn cron_input(mut self, input: Value) -> Self {
        self.options.cron_input = Some(input);
        self
    }

    /// The priority of runs that do not specify one.
    pub fn default_priority(mut self, priority: Priority) -> Self {
        self.options.default_priority = Some(priority);
        self
    }

    /// Adds a concurrency limit across runs of the whole workflow.
    pub fn concurrency(mut self, concurrency: Concurrency) -> Self {
        self.options.concurrency.push(concurrency);
        self
    }

    /// Pins each run's tasks to one worker.
    ///
    /// ```
    /// use hatchet_client::{StickyStrategy, TaskBuilder, Workflow};
    ///
    /// let load = TaskBuilder::<(), ()>::new("load").handler(|_ctx, _input| async { Ok(()) });
    /// let build = Workflow::new("build").sticky(StickyStrategy::Hard).task(&load);
    /// # let _ = build;
    /// ```
    pub fn sticky(mut self, strategy: StickyStrategy) -> Self {
        self.options.sticky = Some(strategy);
        self
    }

    /// Makes the engine refuse a second run whose key matches a claimed one.
    ///
    /// ```
    /// use std::time::Duration;
    ///
    /// use hatchet_client::{Idempotency, TaskBuilder, Workflow};
    ///
    /// let charge = TaskBuilder::<(), ()>::new("charge").handler(|_ctx, _input| async { Ok(()) });
    /// let checkout = Workflow::new("checkout")
    ///     .idempotency(Idempotency::until_run_ends("input.order_id", Duration::from_secs(600)))
    ///     .task(&charge);
    /// # let _ = checkout;
    /// ```
    pub fn idempotency(mut self, idempotency: Idempotency) -> Self {
        self.options.idempotency = Some(idempotency);
        self
    }

    /// Adds a task. Its parents must be added to this workflow too.
    ///
    /// The task is taken by reference and cloned in (a [`Task`] is a cheap
    /// handle: an `Arc` around the handler plus its options), so the caller
    /// keeps its own handle for `Context::parent_output` and
    /// [`WorkflowResult::output`](crate::WorkflowResult::output).
    ///
    /// Mistakes (duplicate names, unknown parents, trigger options set on the
    /// task instead of the workflow) are reported as
    /// [`Error::InvalidDeclaration`] when the workflow is registered.
    pub fn task<I, O>(mut self, task: &Task<I, O>) -> Self {
        if !task.standalone.is_empty() {
            self.tasks_with_standalone_options
                .push(task.def.name.clone());
        }
        self.tasks.push(task.def.clone());
        self
    }

    /// Runs `task` once if the workflow fails, whatever failed in it.
    ///
    /// The task receives the *workflow's* input, and its output is
    /// discarded. It reads what went wrong with
    /// [`Context::step_run_errors`](crate::Context::step_run_errors). It is
    /// not one of the workflow's tasks — it has no parents, nothing depends
    /// on it, and it never runs when the workflow succeeds.
    ///
    /// Declaring it twice, giving it a parent, passing a task that is
    /// already one of the workflow's tasks, or setting standalone-only
    /// options on it are all [`Error::InvalidDeclaration`] at registration.
    ///
    /// It keeps the name it was declared with, which is a third behaviour:
    /// the official Go SDK renames the on-failure task to `on-failure`, and
    /// the official Python SDK appends `-on-failure` to the declared name.
    /// Only a [`Workflow`] can have one — unlike Go, a standalone task
    /// cannot; wrap it in a one-task workflow instead.
    ///
    /// ```
    /// use hatchet_client::{Context, TaskBuilder, Workflow};
    ///
    /// let charge = TaskBuilder::<(), ()>::new("charge")
    ///     .handler(|_ctx, _input| async { Ok(()) });
    /// let alert = TaskBuilder::<(), ()>::new("alert").handler(|ctx: Context, _input: ()| async move {
    ///     for (task, error) in ctx.step_run_errors() {
    ///         eprintln!("{task} failed: {error}");
    ///     }
    ///     Ok(())
    /// });
    ///
    /// let checkout = Workflow::new("checkout")
    ///     .task(&charge)
    ///     .on_failure(&alert);
    /// # let _ = checkout;
    /// ```
    pub fn on_failure<I, O>(mut self, task: &Task<I, O>) -> Self {
        if !task.standalone.is_empty() {
            self.tasks_with_standalone_options
                .push(task.def.name.clone());
        }
        self.on_failure.push(task.def.clone());
        self
    }

    /// Runs `task` once, after every other task in the workflow has
    /// succeeded.
    ///
    /// The engine has no field for this — `CreateWorkflowVersionRequest`
    /// only carries `on_failure_task`. So this is registered as an ordinary
    /// task whose parents are every *leaf* of the workflow (the tasks no
    /// other task depends on), which is how the official Python SDK does
    /// it. The Go SDK has no equivalent at all.
    ///
    /// Being an ordinary task, it can read its parents' outputs with
    /// [`Context::parent_output`](crate::Context::parent_output), and a
    /// failure anywhere upstream means it never runs.
    ///
    /// Declaring it twice, giving it parents of its own, passing a task
    /// that is already one of the workflow's tasks or its on-failure task,
    /// or setting standalone-only options on it are all
    /// [`Error::InvalidDeclaration`] at registration.
    ///
    /// It keeps the name it was declared with, where the official Python SDK
    /// appends `-on-success` to it.
    ///
    /// ```
    /// use hatchet_client::{TaskBuilder, Workflow};
    ///
    /// let fetch = TaskBuilder::<(), u32>::new("fetch").handler(|_ctx, _input| async { Ok(1) });
    /// let lint = TaskBuilder::<(), ()>::new("lint")
    ///     .handler(|_ctx, _input| async { Ok(()) })
    ///     .parent(&fetch);
    /// let build = TaskBuilder::<(), ()>::new("build")
    ///     .handler(|_ctx, _input| async { Ok(()) })
    ///     .parent(&fetch);
    /// let announce = TaskBuilder::<(), ()>::new("announce")
    ///     .handler(|_ctx, _input| async { Ok(()) });
    ///
    /// // `announce` is registered with `lint` and `build` as its parents:
    /// // they are the workflow's leaves, and `fetch` is not.
    /// let pipeline = Workflow::new("pipeline")
    ///     .task(&fetch)
    ///     .task(&lint)
    ///     .task(&build)
    ///     .on_success(&announce);
    /// # let _ = pipeline;
    /// ```
    pub fn on_success<I, O>(mut self, task: &Task<I, O>) -> Self {
        if !task.standalone.is_empty() {
            self.tasks_with_standalone_options
                .push(task.def.name.clone());
        }
        self.on_success.push(task.def.clone());
        self
    }
}

impl sealed::Sealed for Workflow {}

impl Register for Workflow {
    fn definition(&self) -> WorkflowDef {
        WorkflowDef {
            name: self.name.clone(),
            options: self.options.clone(),
            tasks: self.tasks.clone(),
            on_failure: self.on_failure.clone(),
            on_success: self.on_success.clone(),
            tasks_with_standalone_options: self.tasks_with_standalone_options.clone(),
            is_standalone: false,
        }
    }
}

impl<I, O> sealed::Sealed for Task<I, O> {}

impl<I, O> Register for Task<I, O> {
    fn definition(&self) -> WorkflowDef {
        WorkflowDef {
            name: self.def.name.clone(),
            options: self.standalone.clone(),
            tasks: vec![self.def.clone()],
            on_failure: Vec::new(),
            on_success: Vec::new(),
            tasks_with_standalone_options: Vec::new(),
            is_standalone: true,
        }
    }
}

/// A declaration with its types erased. Not nameable outside this crate.
#[derive(Clone)]
pub struct WorkflowDef {
    name: String,
    options: WorkflowOptions,
    tasks: Vec<TaskDef>,
    on_failure: Vec<TaskDef>,
    on_success: Vec<TaskDef>,
    tasks_with_standalone_options: Vec<String>,
    /// Whether this declaration came from a standalone [`Task`] rather than
    /// a [`Workflow`]; standalone tasks may not have parents.
    is_standalone: bool,
}

impl WorkflowDef {
    pub(crate) fn wire_name(&self, namespace: &str) -> String {
        wire_name(namespace, &self.name)
    }

    /// Every action this declaration serves, with its handler.
    ///
    /// Fails exactly when [`to_request`](Self::to_request) fails.
    pub(crate) fn actions(&self, namespace: &str) -> Result<Vec<(String, RegisteredAction)>> {
        self.validate()?;
        let workflow = self.wire_name(namespace);
        Ok(self
            .declared_tasks()
            .map(|task| {
                (
                    action_id(&workflow, &task.name),
                    RegisteredAction {
                        handler: task.handler.clone(),
                        durable: task.durable,
                        eviction_policy: task.options.eviction_policy.clone(),
                        batch: task.batch.as_ref().map(|batch| batch.handler.clone()),
                    },
                )
            })
            .collect())
    }

    /// Every task this declaration serves, hooks included.
    fn declared_tasks(&self) -> impl Iterator<Item = &TaskDef> {
        self.tasks
            .iter()
            .chain(self.on_failure.iter())
            .chain(self.on_success.iter())
    }

    /// Whether anything here asks the engine for a `default` slot.
    ///
    /// The on-failure and on-success hooks count: declaring one of them
    /// durable is allowed, and a worker that did not register the matching
    /// slot pool would never be assigned it.
    pub(crate) fn has_default(&self) -> bool {
        self.declared_tasks().any(|task| !task.durable)
    }

    /// Whether anything here asks the engine for a `durable` slot.
    pub(crate) fn has_durable(&self) -> bool {
        self.declared_tasks().any(|task| task.durable)
    }

    /// Validates the declaration and maps it to the registration request.
    pub(crate) fn to_request(&self, namespace: &str) -> Result<v1::CreateWorkflowVersionRequest> {
        self.validate()?;
        let workflow = self.wire_name(namespace);
        let options = &self.options;

        let mut tasks: Vec<v1::CreateTaskOpts> = self
            .tasks
            .iter()
            .map(|task| task_opts(namespace, &workflow, task))
            .collect();
        if let Some(hook) = self.on_success.first() {
            let mut opts = task_opts(namespace, &workflow, hook);
            opts.parents = leaf_names(&self.tasks);
            tasks.push(opts);
        }

        Ok(v1::CreateWorkflowVersionRequest {
            tasks,
            description: options.description.clone().unwrap_or_default(),
            version: options.version.clone().unwrap_or_default(),
            event_triggers: options
                .on_events
                .iter()
                .map(|key| namespace::apply(namespace, key))
                .collect(),
            cron_triggers: options.on_crons.clone(),
            cron_input: options.cron_input.as_ref().map(Value::to_string),
            default_priority: options.default_priority.map(Priority::to_proto),
            concurrency_arr: options
                .concurrency
                .iter()
                .map(Concurrency::to_proto)
                .collect(),
            on_failure_task: self
                .on_failure
                .first()
                .map(|task| task_opts(namespace, &workflow, task)),
            sticky: options.sticky.map(StickyStrategy::to_proto),
            idempotency: options.idempotency.as_ref().map(Idempotency::to_proto),
            name: workflow,
            ..Default::default()
        })
    }

    /// Fails when this declaration asks for something `engine_version` does
    /// not do. Checked once, at registration, because the alternative is the
    /// engine silently ignoring the field.
    pub(crate) fn check_engine_features(&self, engine_version: &str) -> Result<()> {
        if self.options.idempotency.is_some() {
            crate::version::ensure_feature(
                "idempotency",
                crate::version::IDEMPOTENCY_MIN_ENGINE_VERSION,
                engine_version,
            )?;
        }
        if self.declared_tasks().any(|task| task.batch.is_some()) {
            // Checked before the worker exists rather than when a batch
            // arrives, because on an older engine none ever will: the
            // registration is taken, the batch config is dropped, and every run
            // is assigned singly to a handler that expects a whole batch.
            crate::version::ensure_feature(
                "batch tasks",
                crate::version::BATCH_MIN_ENGINE_VERSION,
                engine_version,
            )?;
        }
        Ok(())
    }

    fn validate(&self) -> Result<()> {
        let name = &self.name;

        if let Some(reason) = invalid_name_reason(name) {
            return Err(Error::InvalidDeclaration(format!(
                "a workflow or standalone task name `{name}` is invalid: {reason}"
            )));
        }
        if self.tasks.is_empty() {
            return Err(Error::InvalidDeclaration(format!(
                "workflow `{name}` has no tasks"
            )));
        }
        if let Some(task) = self.tasks_with_standalone_options.first() {
            return Err(Error::InvalidDeclaration(format!(
                "task `{task}` in workflow `{name}` sets standalone-only options \
                 (description, version, event or cron triggers, cron input, default \
                 priority, workflow concurrency, sticky, idempotency); set them on the \
                 workflow instead"
            )));
        }

        let mut seen = HashSet::new();
        for task in &self.tasks {
            if let Some(reason) = invalid_name_reason(&task.name) {
                return Err(Error::InvalidDeclaration(format!(
                    "task `{}` in workflow `{name}` has an invalid name: {reason}",
                    task.name
                )));
            }
            if !seen.insert(task.name.to_lowercase()) {
                return Err(Error::InvalidDeclaration(format!(
                    "workflow `{name}` has more than one task named `{}` (names are compared case-insensitively)",
                    task.name
                )));
            }
        }

        for (label, hooks) in [
            ("on_failure", &self.on_failure),
            ("on_success", &self.on_success),
        ] {
            if hooks.len() > 1 {
                return Err(Error::InvalidDeclaration(format!(
                    "workflow `{name}` declares {label} more than once; there can be only one"
                )));
            }
            for hook in hooks {
                if let Some(reason) = invalid_name_reason(&hook.name) {
                    return Err(Error::InvalidDeclaration(format!(
                        "the {label} task `{}` of workflow `{name}` has an invalid name: {reason}",
                        hook.name
                    )));
                }
                if !hook.parents.is_empty() {
                    return Err(Error::InvalidDeclaration(format!(
                        "the {label} task `{}` of workflow `{name}` has parents; they are set \
                         automatically, so it cannot declare its own",
                        hook.name
                    )));
                }
                if !seen.insert(hook.name.to_lowercase()) {
                    return Err(Error::InvalidDeclaration(format!(
                        "task `{}` of workflow `{name}` is used more than once (as a task, an \
                         on-failure task or an on-success task); names are compared \
                         case-insensitively",
                        hook.name
                    )));
                }
                for concurrency in &hook.options.concurrency {
                    concurrency.validate().map_err(|reason| {
                        Error::InvalidDeclaration(format!(
                            "the {label} task `{}` of workflow `{name}`: {reason}",
                            hook.name
                        ))
                    })?;
                }
                for limit in &hook.options.rate_limits {
                    limit.validate().map_err(|reason| {
                        Error::InvalidDeclaration(format!(
                            "the {label} task `{}` of workflow `{name}`: {reason}",
                            hook.name
                        ))
                    })?;
                }
                if label == "on_failure" && !conditions_are_empty(&hook.options) {
                    return Err(Error::InvalidDeclaration(format!(
                        "the on_failure task `{}` of workflow `{name}` sets wait_for, \
                         skip_if or cancel_if; an on-failure task runs because the \
                         workflow failed, and the engine is not sent conditions for it",
                        hook.name
                    )));
                }
                if label == "on_success" {
                    // Its parents are the leaves the SDK will give it.
                    check_conditions(name, &hook.name, &hook.options, &leaf_names(&self.tasks))?;
                }
            }
        }

        if self.is_standalone && self.tasks.iter().any(|task| !task.parents.is_empty()) {
            return Err(Error::InvalidDeclaration(
                "a standalone task cannot have parents".to_string(),
            ));
        }

        let known: HashSet<&str> = self.tasks.iter().map(|task| task.name.as_str()).collect();
        for task in &self.tasks {
            if let Some(parent) = task
                .parents
                .iter()
                .find(|parent| !known.contains(parent.as_str()))
            {
                return Err(Error::InvalidDeclaration(format!(
                    "task `{}` has parent `{parent}`, which is not part of workflow `{name}`",
                    task.name
                )));
            }
        }

        for task in &self.tasks {
            if task.parents.iter().any(|parent| parent == &task.name) {
                return Err(Error::InvalidDeclaration(format!(
                    "task `{}` in workflow `{name}` lists itself as a parent",
                    task.name
                )));
            }
        }

        self.check_no_cycles(name)?;

        // An eviction policy is worker-side only and never leaves this
        // process, so nothing downstream would ever complain about one that
        // cannot fire. Both of these are refused here rather than warned
        // about, because both mean the declaration says something it cannot
        // do.
        for task in self.declared_tasks() {
            let Some(policy) = &task.options.eviction_policy else {
                continue;
            };
            if !task.durable {
                return Err(Error::InvalidDeclaration(format!(
                    "task `{}` in workflow `{name}` has an eviction policy but an ordinary \
                     handler; only a durable task is ever parked on the engine, so only a \
                     `durable_handler` can be evicted",
                    task.name
                )));
            }
            if !policy.has_ttl() {
                return Err(Error::InvalidDeclaration(format!(
                    "task `{}` in workflow `{name}` has an eviction policy with a TTL of zero, \
                     which never evicts on time at all; give it the time a wait may last, or \
                     leave the policy off",
                    task.name
                )));
            }
        }

        // A batch task says things the rest of a declaration cannot
        // contradict, and every contradiction is silent if it is let through:
        // a config the engine reads as nothing buffers nothing, and `retries`
        // is forced to zero without a word by both official SDKs
        // (`sdks/go/batch_task_test.go:75-87`,
        // `sdks/python/hatchet_sdk/runnables/workflow.py:1650`).
        for task in self.declared_tasks() {
            let Some(batch) = &task.batch else {
                continue;
            };
            if let Some(reason) = batch.config.invalid_reason() {
                return Err(Error::InvalidDeclaration(format!(
                    "task `{}` in workflow `{name}`: {reason}",
                    task.name
                )));
            }
            if task.options.retries != 0 {
                return Err(Error::InvalidDeclaration(format!(
                    "task `{}` in workflow `{name}` is a batch task with retries ({}); a batch \
                     handler runs once for a whole group of runs, so there is no single run for \
                     the task's retries to be about. Engines do honour the field, but both \
                     official SDKs force it to zero and this one refuses the declaration rather \
                     than quietly changing it — fail a member with a retryable `TaskError` \
                     instead, and the engine re-batches that member on its own",
                    task.name, task.options.retries
                )));
            }
        }
        for (label, hooks) in [
            ("on_failure", &self.on_failure),
            ("on_success", &self.on_success),
        ] {
            if let Some(hook) = hooks.iter().find(|hook| hook.batch.is_some()) {
                return Err(Error::InvalidDeclaration(format!(
                    "the {label} task `{}` of workflow `{name}` is a batch task; a hook runs \
                     because one particular run ended, so there is nothing to batch it with",
                    hook.name
                )));
            }
        }

        for concurrency in &self.options.concurrency {
            concurrency.validate().map_err(|reason| {
                Error::InvalidDeclaration(format!("workflow `{name}`: {reason}"))
            })?;
        }
        if let Some(idempotency) = &self.options.idempotency {
            idempotency.validate().map_err(|reason| {
                Error::InvalidDeclaration(format!("workflow `{name}`: {reason}"))
            })?;
        }
        for task in &self.tasks {
            for concurrency in &task.options.concurrency {
                concurrency.validate().map_err(|reason| {
                    Error::InvalidDeclaration(format!(
                        "task `{}` in workflow `{name}`: {reason}",
                        task.name
                    ))
                })?;
            }
            for limit in &task.options.rate_limits {
                limit.validate().map_err(|reason| {
                    Error::InvalidDeclaration(format!(
                        "task `{}` in workflow `{name}`: {reason}",
                        task.name
                    ))
                })?;
            }
        }

        for task in &self.tasks {
            check_conditions(name, &task.name, &task.options, &task.parents)?;
        }

        Ok(())
    }

    /// Kahn-style topological pass over task parents; errors naming a task
    /// on the cycle when the parent graph is not a DAG.
    fn check_no_cycles(&self, name: &str) -> Result<()> {
        let mut in_degree: HashMap<&str, usize> = self
            .tasks
            .iter()
            .map(|task| (task.name.as_str(), task.parents.len()))
            .collect();
        let mut children: HashMap<&str, Vec<&str>> = HashMap::new();
        for task in &self.tasks {
            for parent in &task.parents {
                children
                    .entry(parent.as_str())
                    .or_default()
                    .push(task.name.as_str());
            }
        }

        let mut queue: VecDeque<&str> = in_degree
            .iter()
            .filter(|&(_, &degree)| degree == 0)
            .map(|(&task, _)| task)
            .collect();
        let mut processed = 0usize;
        while let Some(task) = queue.pop_front() {
            processed += 1;
            if let Some(kids) = children.get(task) {
                for &kid in kids {
                    if let Some(degree) = in_degree.get_mut(kid) {
                        *degree -= 1;
                        if *degree == 0 {
                            queue.push_back(kid);
                        }
                    }
                }
            }
        }

        if processed < self.tasks.len() {
            let cyclic = in_degree
                .iter()
                .find(|&(_, &degree)| degree > 0)
                .map(|(&task, _)| task)
                .unwrap_or_default();
            return Err(Error::InvalidDeclaration(format!(
                "workflow `{name}` has a cycle among task parents, involving task `{cyclic}`"
            )));
        }
        Ok(())
    }
}

/// Why a workflow or task name cannot be sent to the engine, if any: names
/// must be non-empty, not just whitespace, and must not contain `:` (which
/// would corrupt the `workflow:task` action id).
fn invalid_name_reason(name: &str) -> Option<&'static str> {
    if name.trim().is_empty() {
        Some("names must not be empty or whitespace-only")
    } else if name.contains(':') {
        Some("names must not contain `:`")
    } else {
        None
    }
}

/// The tasks nothing else depends on, in declaration order.
///
/// Only the workflow's own tasks are considered: the on-failure task is not
/// one of them, and the on-success task is the one whose parents are being
/// computed.
fn leaf_names(tasks: &[TaskDef]) -> Vec<String> {
    let has_a_child: HashSet<&str> = tasks
        .iter()
        .flat_map(|task| task.parents.iter().map(String::as_str))
        .collect();
    tasks
        .iter()
        .filter(|task| !has_a_child.contains(task.name.as_str()))
        .map(|task| task.name.clone())
        .collect()
}

/// One task's three condition gates: `wait_for`, `skip_if`, `cancel_if`, in
/// that order.
fn gates(options: &TaskOptions) -> Gates<'_> {
    [
        (ConditionAction::Queue, &options.wait_for),
        (ConditionAction::Skip, &options.skip_if),
        (ConditionAction::Cancel, &options.cancel_if),
    ]
}

fn conditions_are_empty(options: &TaskOptions) -> bool {
    options.wait_for.is_empty() && options.skip_if.is_empty() && options.cancel_if.is_empty()
}

/// Checks one task's conditions: the conditions themselves, and that every
/// parent condition names a task this one really runs after.
///
/// `parents` is the task's own parents — for the on-success hook, the leaves
/// the SDK will parent it on.
fn check_conditions(
    workflow: &str,
    task: &str,
    options: &TaskOptions,
    parents: &[String],
) -> Result<()> {
    super::condition::validate(gates(options)).map_err(|reason| {
        Error::InvalidDeclaration(format!("task `{task}` in workflow `{workflow}`: {reason}"))
    })?;
    for (_, set) in gates(options) {
        for parent in set.parent_names() {
            if !parents.iter().any(|declared| declared == parent) {
                return Err(Error::InvalidDeclaration(format!(
                    "task `{task}` in workflow `{workflow}` has a condition on parent \
                     `{parent}`, which is not one of its parents; a parent condition reads \
                     that parent's output, so the task must run after it"
                )));
            }
        }
    }
    Ok(())
}

fn task_opts(namespace: &str, workflow_wire_name: &str, task: &TaskDef) -> v1::CreateTaskOpts {
    let options = &task.options;
    v1::CreateTaskOpts {
        readable_id: task.name.clone(),
        action: action_id(workflow_wire_name, &task.name),
        timeout: options
            .execution_timeout
            .map(timeout_string)
            .unwrap_or_default(),
        schedule_timeout: options.schedule_timeout.map(timeout_string),
        inputs: "{}".to_string(),
        parents: task.parents.clone(),
        retries: super::options::saturating_i32(options.retries),
        backoff_factor: options.backoff.map(|(factor, _)| factor),
        backoff_max_seconds: options
            .backoff
            .map(|(_, max)| super::options::saturating_i32(max)),
        rate_limits: options
            .rate_limits
            .iter()
            .map(|limit| limit.to_proto())
            .collect(),
        concurrency: options
            .concurrency
            .iter()
            .map(Concurrency::to_proto)
            .collect(),
        worker_labels: options
            .worker_labels
            .iter()
            .map(|(key, label)| (key.clone(), label.to_proto()))
            .collect(),
        is_durable: task.durable,
        // One slot of the kind this task needs, as the official Python SDK
        // sends it (`sdks/python/hatchet_sdk/runnables/task.py:183-185`): a
        // durable task waits on the engine rather than on the worker, so it
        // is charged to a pool of its own.
        slot_requests: HashMap::from([(
            if task.durable { "durable" } else { "default" }.to_string(),
            1,
        )]),
        conditions: super::condition::to_proto(namespace, gates(options)),
        // The one field a batch task adds. Everything else about it is an
        // ordinary task's registration, down to the single `default` slot: a
        // batch is one unit of work for the worker however many runs it
        // answers for (`sdks/python/hatchet_sdk/runnables/task.py:175-185`).
        batch: task
            .batch
            .as_ref()
            .map(|batch| batch.config.to_proto(batch.broadcast)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        Concurrency, ConcurrencyLimitStrategy, Condition, DesiredLabel, Error, Idempotency,
        Priority, RateLimit, StickyStrategy, TaskBuilder,
    };
    use hatchet_proto::v1;
    use serde_json::json;
    use std::collections::HashMap;
    use std::sync::Arc;
    use std::time::Duration;

    fn task(name: &str) -> crate::Task<serde_json::Value, serde_json::Value> {
        TaskBuilder::new(name).handler(|_ctx, input| async move { Ok(input) })
    }

    fn default_slots() -> HashMap<String, i32> {
        HashMap::from([("default".to_string(), 1)])
    }

    #[test]
    fn debug_names_the_workflow_and_its_tasks_and_says_it_is_not_all_of_it() {
        let workflow = Workflow::new("pipeline")
            .task(&task("fetch"))
            .task(&task("build"));

        let debug = format!("{workflow:?}");
        assert!(debug.starts_with("Workflow"), "{debug}");
        assert!(debug.contains("pipeline"), "{debug}");
        assert!(
            debug.contains("fetch") && debug.contains("build"),
            "{debug}"
        );
        assert!(debug.contains(".."), "{debug}");

        let debug = format!("{:?}", workflow.definition());
        assert!(debug.starts_with("WorkflowDef"), "{debug}");
        assert!(debug.contains("pipeline"), "{debug}");
    }

    #[test]
    fn standalone_task_maps_to_a_one_task_workflow() {
        let agent_run = TaskBuilder::<serde_json::Value, serde_json::Value>::new("Agent-Run")
            .retries(1)
            .execution_timeout(Duration::from_secs(2 * 3600))
            .handler(|_ctx, input| async move { Ok(input) });

        let request = agent_run.definition().to_request("dev_").unwrap();

        assert_eq!(
            request,
            v1::CreateWorkflowVersionRequest {
                name: "dev_agent-run".to_string(),
                tasks: vec![v1::CreateTaskOpts {
                    readable_id: "Agent-Run".to_string(),
                    action: "dev_agent-run:agent-run".to_string(),
                    timeout: "7200s".to_string(),
                    inputs: "{}".to_string(),
                    retries: 1,
                    slot_requests: default_slots(),
                    ..Default::default()
                }],
                ..Default::default()
            }
        );
    }

    /// Criterion 1: a durable declaration says so on the wire, and asks for a
    /// slot of its own kind — an ordinary one is untouched.
    #[test]
    fn a_durable_task_registers_as_durable_and_asks_for_a_durable_slot() {
        let durable = TaskBuilder::<Value, Value>::new("approve")
            .durable_handler(|_ctx, input| async move { Ok(input) });
        let request = durable.definition().to_request("dev_").unwrap();

        let task = &request.tasks[0];
        assert!(task.is_durable);
        assert_eq!(
            task.slot_requests,
            HashMap::from([("durable".to_string(), 1)])
        );

        let plain = self::task("fetch").definition().to_request("dev_").unwrap();
        assert!(!plain.tasks[0].is_durable);
        assert_eq!(plain.tasks[0].slot_requests, default_slots());
    }

    /// What the worker's `slot_config` is computed from, hooks included.
    #[test]
    fn a_declaration_reports_which_slot_kinds_it_needs() {
        let durable = TaskBuilder::<Value, Value>::new("approve")
            .durable_handler(|_ctx, input| async move { Ok(input) });
        let plain = task("fetch");

        let only_durable = durable.definition();
        assert!(only_durable.has_durable());
        assert!(!only_durable.has_default());

        let only_default = plain.definition();
        assert!(!only_default.has_durable());
        assert!(only_default.has_default());

        let mixed = Workflow::new("pipeline")
            .task(&plain)
            .task(&durable)
            .definition();
        assert!(mixed.has_durable());
        assert!(mixed.has_default());

        // A durable hook counts too: a worker that did not register the pool
        // would never be assigned it.
        let hooked = Workflow::new("hooked")
            .task(&plain)
            .on_failure(&durable)
            .definition();
        assert!(hooked.has_durable());
    }

    #[test]
    fn without_a_namespace_names_are_only_lowercased() {
        let request = task("Agent-Run").definition().to_request("").unwrap();
        assert_eq!(request.name, "agent-run");
        assert_eq!(request.tasks[0].action, "agent-run:agent-run");
    }

    #[test]
    fn a_name_that_already_carries_the_namespace_is_not_prefixed_again() {
        let request = task("dev_agent-run")
            .definition()
            .to_request("dev_")
            .unwrap();
        assert_eq!(request.name, "dev_agent-run");
    }

    #[test]
    fn dag_parents_are_readable_ids() {
        let fetch = task("Fetch");
        let build = task("build").parent(&fetch);
        let workflow = Workflow::new("Pipeline").task(&fetch).task(&build);

        let request = workflow.definition().to_request("dev_").unwrap();

        assert_eq!(request.name, "dev_pipeline");
        assert_eq!(request.tasks.len(), 2);
        assert_eq!(request.tasks[0].readable_id, "Fetch");
        assert_eq!(request.tasks[0].action, "dev_pipeline:fetch");
        assert!(request.tasks[0].parents.is_empty());
        assert_eq!(request.tasks[1].readable_id, "build");
        assert_eq!(request.tasks[1].action, "dev_pipeline:build");
        assert_eq!(request.tasks[1].parents, ["Fetch"]);
    }

    #[test]
    fn task_level_options_map_onto_create_task_opts() {
        let task = TaskBuilder::<serde_json::Value, serde_json::Value>::new("agent-run")
            .retries(2)
            .retry_backoff(1.5, 120)
            .execution_timeout(Duration::from_secs(90))
            .schedule_timeout(Duration::from_secs(30))
            .concurrency(
                Concurrency::expr("input.device_id")
                    .max_runs(1)
                    .strategy(ConcurrencyLimitStrategy::GroupRoundRobin),
            )
            .rate_limit(RateLimit::new("github-api", 2))
            .worker_label("os", DesiredLabel::eq("macos").required())
            .worker_label("mem", DesiredLabel::gte(8).weight(50))
            .handler(|_ctx, input| async move { Ok(input) });

        let request = task.definition().to_request("").unwrap();

        assert_eq!(
            request.tasks[0],
            v1::CreateTaskOpts {
                readable_id: "agent-run".to_string(),
                action: "agent-run:agent-run".to_string(),
                timeout: "90s".to_string(),
                schedule_timeout: Some("30s".to_string()),
                inputs: "{}".to_string(),
                retries: 2,
                backoff_factor: Some(1.5),
                backoff_max_seconds: Some(120),
                concurrency: vec![v1::Concurrency {
                    expression: "input.device_id".to_string(),
                    max_runs: Some(1),
                    limit_strategy: Some(v1::ConcurrencyLimitStrategy::GroupRoundRobin as i32),
                    ..Default::default()
                }],
                rate_limits: vec![v1::CreateTaskRateLimit {
                    key: "github-api".to_string(),
                    units: Some(2),
                    ..Default::default()
                }],
                worker_labels: HashMap::from([
                    (
                        "os".to_string(),
                        v1::DesiredWorkerLabels {
                            str_value: Some("macos".to_string()),
                            required: Some(true),
                            comparator: Some(v1::WorkerLabelComparator::Equal as i32),
                            ..Default::default()
                        },
                    ),
                    (
                        "mem".to_string(),
                        v1::DesiredWorkerLabels {
                            int_value: Some(8),
                            required: Some(false),
                            comparator: Some(v1::WorkerLabelComparator::GreaterThanOrEqual as i32),
                            weight: Some(50),
                            ..Default::default()
                        },
                    ),
                ]),
                slot_requests: default_slots(),
                ..Default::default()
            }
        );
        assert!(
            request.concurrency_arr.is_empty(),
            "task concurrency stays on the task"
        );
        assert!(request.concurrency.is_none());
    }

    #[test]
    fn workflow_options_map_onto_the_request() {
        let workflow = Workflow::new("pipeline")
            .description("Build and ship")
            .version("v3")
            .on_events(["approval.granted"])
            .cron("0 * * * *")
            .cron_input(json!({"repo": "hatchet-rs"}))
            .default_priority(Priority::High)
            .concurrency(Concurrency::expr("input.repo").max_runs(2))
            .task(&task("build"));

        let request = workflow.definition().to_request("dev_").unwrap();

        assert_eq!(request.description, "Build and ship");
        assert_eq!(request.version, "v3");
        assert_eq!(
            request.event_triggers,
            ["dev_approval.granted"],
            "event keys are namespaced"
        );
        assert_eq!(
            request.cron_triggers,
            ["0 * * * *"],
            "cron expressions are not"
        );
        assert_eq!(
            request.cron_input.as_deref(),
            Some(r#"{"repo":"hatchet-rs"}"#)
        );
        assert_eq!(request.default_priority, Some(3));
        assert_eq!(
            request.concurrency_arr,
            [v1::Concurrency {
                expression: "input.repo".to_string(),
                max_runs: Some(2),
                ..Default::default()
            }]
        );
        assert!(
            request.concurrency.is_none(),
            "the singular field is never used"
        );
    }

    #[test]
    fn standalone_trigger_options_map_onto_the_request() {
        let task = TaskBuilder::<serde_json::Value, serde_json::Value>::new("on-approval")
            .on_events(["approval.granted"])
            .cron("*/5 * * * *")
            .default_priority(Priority::Low)
            .handler(|_ctx, input| async move { Ok(input) });

        let request = task.definition().to_request("dev_").unwrap();

        assert_eq!(request.event_triggers, ["dev_approval.granted"]);
        assert_eq!(request.cron_triggers, ["*/5 * * * *"]);
        assert_eq!(request.default_priority, Some(1));
    }

    #[test]
    fn duplicate_task_names_are_an_error_not_a_panic() {
        let workflow = Workflow::new("pipeline")
            .task(&task("build"))
            .task(&task("build"));
        let err = workflow.definition().to_request("").unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("build"), "{err}");
    }

    #[test]
    fn task_names_that_collide_after_lowercasing_are_an_error() {
        let workflow = Workflow::new("pipeline")
            .task(&task("Build"))
            .task(&task("build"));
        let err = workflow.definition().to_request("").unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
    }

    #[test]
    fn a_parent_outside_the_workflow_is_an_error_naming_it() {
        let fetch = task("fetch");
        let workflow = Workflow::new("pipeline").task(&task("build").parent(&fetch));
        let err = workflow.definition().to_request("").unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("fetch"), "{err}");
    }

    #[test]
    fn a_hook_task_cannot_be_a_parent_of_an_ordinary_task() {
        for hook_is_on_failure in [true, false] {
            let hook = task("cleanup");
            let build = task("build").parent(&hook);
            let workflow = Workflow::new("pipeline").task(&task("fetch")).task(&build);
            let workflow = if hook_is_on_failure {
                workflow.on_failure(&hook)
            } else {
                workflow.on_success(&hook)
            };
            let err = workflow.definition().to_request("").unwrap_err();
            assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
            assert!(err.to_string().contains("cleanup"), "{err}");
        }
    }

    #[test]
    fn a_workflow_without_tasks_is_an_error() {
        let err = Workflow::new("empty")
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
    }

    #[test]
    fn empty_names_are_errors() {
        assert!(task("").definition().to_request("").is_err());
        assert!(
            Workflow::new("")
                .task(&task("a"))
                .definition()
                .to_request("")
                .is_err()
        );
    }

    #[test]
    fn trigger_options_on_a_task_inside_a_workflow_are_an_error() {
        let triggered = TaskBuilder::<serde_json::Value, serde_json::Value>::new("build")
            .on_events(["push"])
            .handler(|_ctx, input| async move { Ok(input) });
        let err = Workflow::new("pipeline")
            .task(&triggered)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("build"), "{err}");
    }

    #[test]
    fn standalone_parents_are_an_error() {
        let fetch = task("fetch");
        let err = task("build")
            .parent(&fetch)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
    }

    #[test]
    fn actions_pair_each_action_id_with_its_handler() {
        let fetch = task("Fetch");
        let build = task("build").parent(&fetch);
        // Keep handles to the source tasks' handlers before the tasks are
        // moved into the workflow, so we can prove the *pairing* below, not
        // just that the right ids come out.
        let fetch_handler = fetch.def.handler.clone();
        let build_handler = build.def.handler.clone();
        let definition = Workflow::new("Pipeline")
            .task(&fetch)
            .task(&build)
            .definition();

        let actions = definition.actions("dev_").unwrap();
        let ids: Vec<&str> = actions.iter().map(|(id, _)| id.as_str()).collect();
        assert_eq!(ids, ["dev_pipeline:fetch", "dev_pipeline:build"]);
        assert_eq!(definition.wire_name("dev_"), "dev_pipeline");

        let fetch_action = actions
            .iter()
            .find(|(id, _)| id == "dev_pipeline:fetch")
            .unwrap();
        let build_action = actions
            .iter()
            .find(|(id, _)| id == "dev_pipeline:build")
            .unwrap();
        assert!(
            Arc::ptr_eq(&fetch_action.1.handler, &fetch_handler),
            "dev_pipeline:fetch should be paired with fetch's own handler"
        );
        assert!(
            Arc::ptr_eq(&build_action.1.handler, &build_handler),
            "dev_pipeline:build should be paired with build's own handler"
        );
        assert!(
            !Arc::ptr_eq(&fetch_action.1.handler, &build_handler),
            "fetch's action must not be paired with build's handler"
        );
    }

    /// An eviction policy is worker-side only: the registration request must
    /// be the very same bytes it would have been without one.
    #[test]
    fn an_eviction_policy_reaches_the_worker_and_never_the_wire() {
        let plain = TaskBuilder::<serde_json::Value, serde_json::Value>::new("approve")
            .durable_handler(|_ctx, input| async move { Ok(input) });
        let policy = crate::EvictionPolicy::ttl(Duration::from_secs(30)).priority(-3);
        let evictable = TaskBuilder::<serde_json::Value, serde_json::Value>::new("approve")
            .eviction_policy(policy.clone())
            .durable_handler(|_ctx, input| async move { Ok(input) });

        assert_eq!(
            evictable.definition().to_request("dev_").unwrap(),
            plain.definition().to_request("dev_").unwrap(),
        );
        let actions = evictable.definition().actions("dev_").unwrap();
        assert_eq!(actions[0].1.eviction_policy.as_ref(), Some(&policy));
        assert!(actions[0].1.durable);
        assert_eq!(
            plain.definition().actions("dev_").unwrap()[0]
                .1
                .eviction_policy,
            None,
        );
    }

    #[test]
    fn an_eviction_policy_on_an_ordinary_task_is_refused() {
        let wrong = TaskBuilder::<serde_json::Value, serde_json::Value>::new("approve")
            .eviction_policy(crate::EvictionPolicy::default())
            .handler(|_ctx, input| async move { Ok(input) });
        let err = wrong.definition().to_request("dev_").unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("durable_handler"), "{err}");
        // The same declaration inside a workflow, and its on-failure hook.
        let inside = Workflow::new("pipeline").task(&wrong).definition();
        assert!(
            matches!(inside.actions("dev_"), Err(Error::InvalidDeclaration(_))),
            "a policy on an ordinary task in a workflow is refused too",
        );
        let err = Workflow::new("pipeline")
            .task(&task("build"))
            .on_failure(&wrong)
            .definition()
            .to_request("dev_")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
    }

    #[test]
    fn an_eviction_policy_with_no_ttl_at_all_is_refused() {
        let never = TaskBuilder::<serde_json::Value, serde_json::Value>::new("approve")
            .eviction_policy(crate::EvictionPolicy::ttl(Duration::ZERO))
            .durable_handler(|_ctx, input| async move { Ok(input) });
        let err = never.definition().to_request("dev_").unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("TTL"), "{err}");
        // The control: one millisecond more and it is a policy.
        TaskBuilder::<serde_json::Value, serde_json::Value>::new("approve")
            .eviction_policy(crate::EvictionPolicy::ttl(Duration::from_millis(1)))
            .durable_handler(|_ctx, input| async move { Ok(input) })
            .definition()
            .to_request("dev_")
            .unwrap();
    }

    #[test]
    fn actions_reject_what_to_request_rejects() {
        let definition = Workflow::new("pipeline")
            .task(&task("build"))
            .task(&task("build"))
            .definition();

        assert!(
            matches!(definition.actions(""), Err(Error::InvalidDeclaration(_))),
            "actions should reject what to_request rejects"
        );
        assert!(matches!(
            definition.to_request(""),
            Err(Error::InvalidDeclaration(_))
        ));
    }

    #[test]
    fn whitespace_only_names_are_invalid() {
        let err = task("   ").definition().to_request("").unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");

        let err = Workflow::new("pipeline")
            .task(&task("   "))
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("pipeline"), "{err}");
    }

    #[test]
    fn a_colon_in_a_name_is_invalid() {
        let err = Workflow::new("dev:pipeline")
            .task(&task("build"))
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("dev:pipeline"), "{err}");

        let err = Workflow::new("pipeline")
            .task(&task("build:step"))
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("build:step"), "{err}");
    }

    #[test]
    fn a_task_that_lists_itself_as_a_parent_is_invalid_inside_a_workflow() {
        let a = task("s");
        let err = Workflow::new("w")
            .task(&a.clone().parent(&a))
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains('s'), "{err}");
    }

    #[test]
    fn a_standalone_task_that_lists_itself_as_a_parent_says_standalone_tasks_cannot_have_parents() {
        let a = task("s");
        let err = a
            .clone()
            .parent(&a)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(
            err.to_string()
                .contains("standalone task cannot have parents"),
            "{err}"
        );
    }

    #[test]
    fn a_cycle_among_task_parents_is_invalid_and_names_a_task_on_it() {
        let a0 = task("a");
        let b = task("b").parent(&a0);
        let a = task("a").parent(&b);
        let err = Workflow::new("w")
            .task(&a)
            .task(&b)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        let message = err.to_string();
        assert!(message.contains('a') || message.contains('b'), "{message}");
    }

    #[test]
    fn concurrency_max_runs_zero_is_invalid_at_workflow_level() {
        let err = Workflow::new("pipeline")
            .concurrency(Concurrency::expr("input.repo").max_runs(0))
            .task(&task("build"))
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("max_runs"), "{err}");
    }

    #[test]
    fn concurrency_max_runs_zero_is_invalid_at_task_level() {
        let bad_task = TaskBuilder::<serde_json::Value, serde_json::Value>::new("build")
            .concurrency(Concurrency::expr("input.repo").max_runs(0))
            .handler(|_ctx, input| async move { Ok(input) });
        let err = Workflow::new("pipeline")
            .task(&bad_task)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("max_runs"), "{err}");
    }

    #[test]
    fn a_dynamic_rate_limit_without_a_limit_is_an_invalid_declaration() {
        let bad_task = TaskBuilder::<serde_json::Value, serde_json::Value>::new("build")
            .rate_limit(RateLimit::dynamic("input.tenant"))
            .handler(|_ctx, input| async move { Ok(input) });
        let err = Workflow::new("pipeline")
            .task(&bad_task)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("limit_expr"), "{err}");
    }

    #[test]
    fn a_task_without_timeouts_maps_to_the_engine_defaults() {
        let request = task("build").definition().to_request("").unwrap();
        assert_eq!(request.tasks[0].timeout, "");
        assert_eq!(request.tasks[0].schedule_timeout, None);
    }

    #[test]
    fn task_level_concurrency_inside_a_workflow_stays_on_the_task() {
        let concurrent_task = TaskBuilder::<serde_json::Value, serde_json::Value>::new("build")
            .concurrency(Concurrency::expr("input.repo").max_runs(1))
            .handler(|_ctx, input| async move { Ok(input) });
        let request = Workflow::new("pipeline")
            .task(&concurrent_task)
            .definition()
            .to_request("")
            .unwrap();

        assert_eq!(
            request.tasks[0].concurrency,
            [v1::Concurrency {
                expression: "input.repo".to_string(),
                max_runs: Some(1),
                ..Default::default()
            }]
        );
        assert!(
            request.concurrency_arr.is_empty(),
            "task-level concurrency must not leak into the workflow-level field"
        );
    }

    #[test]
    fn an_on_failure_task_maps_to_its_own_field_and_not_to_tasks() {
        let build = task("build");
        let cleanup = task("cleanup");
        let definition = Workflow::new("pipeline")
            .task(&build)
            .on_failure(&cleanup)
            .definition();

        let request = definition.to_request("dev_").unwrap();
        assert_eq!(
            task_names(&definition.tasks),
            ["build"],
            "the on-failure task is not one of the workflow's tasks"
        );
        assert_eq!(request.tasks.len(), 1);
        assert_eq!(request.tasks[0].readable_id, "build");
        let on_failure = request
            .on_failure_task
            .expect("the on-failure task is sent in its own field");
        assert_eq!(
            on_failure,
            v1::CreateTaskOpts {
                readable_id: "cleanup".to_string(),
                action: "dev_pipeline:cleanup".to_string(),
                inputs: "{}".to_string(),
                slot_requests: default_slots(),
                ..Default::default()
            }
        );

        let ids: Vec<String> = definition
            .actions("dev_")
            .unwrap()
            .into_iter()
            .map(|(id, _)| id)
            .collect();
        assert_eq!(
            ids,
            ["dev_pipeline:build", "dev_pipeline:cleanup"],
            "the worker must register the on-failure action too"
        );
    }

    #[test]
    fn the_same_task_in_task_and_on_failure_is_an_error_not_a_panic() {
        let build = task("build");
        let err = Workflow::new("pipeline")
            .task(&build)
            .on_failure(&build)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("build"), "{err}");
    }

    #[test]
    fn declaring_two_on_failure_tasks_is_an_error() {
        let err = Workflow::new("pipeline")
            .task(&task("build"))
            .on_failure(&task("a"))
            .on_failure(&task("b"))
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("on_failure"), "{err}");
    }

    #[test]
    fn an_on_failure_task_with_a_parent_is_an_error() {
        let build = task("build");
        let err = Workflow::new("pipeline")
            .task(&build)
            .on_failure(&task("cleanup").parent(&build))
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("cleanup"), "{err}");
    }

    #[test]
    fn standalone_only_options_on_an_on_failure_task_are_an_error() {
        let triggered = TaskBuilder::<serde_json::Value, serde_json::Value>::new("cleanup")
            .on_events(["push"])
            .handler(|_ctx, input| async move { Ok(input) });
        let err = Workflow::new("pipeline")
            .task(&task("build"))
            .on_failure(&triggered)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("cleanup"), "{err}");
    }

    #[test]
    fn an_on_success_task_is_an_ordinary_task_parented_on_every_leaf() {
        // fetch → build → package, and fetch → lint. Leaves: package, lint.
        let fetch = task("fetch");
        let build = task("build").parent(&fetch);
        let package = task("package").parent(&build);
        let lint = task("lint").parent(&fetch);
        let announce = task("announce");

        let request = Workflow::new("pipeline")
            .task(&fetch)
            .task(&build)
            .task(&package)
            .task(&lint)
            .on_success(&announce)
            .definition()
            .to_request("dev_")
            .unwrap();

        assert_eq!(
            request
                .tasks
                .iter()
                .map(|task| task.readable_id.as_str())
                .collect::<Vec<_>>(),
            ["fetch", "build", "package", "lint", "announce"],
            "the on-success task is the last of the workflow's tasks"
        );
        let announce_opts = request.tasks.last().unwrap();
        assert_eq!(announce_opts.action, "dev_pipeline:announce");
        assert_eq!(
            announce_opts.parents,
            ["package", "lint"],
            "its parents are exactly the leaves, in declaration order"
        );
        assert!(request.on_failure_task.is_none());
    }

    #[test]
    fn a_single_task_workflow_parents_its_on_success_task_on_that_task() {
        let build = task("build");
        let request = Workflow::new("pipeline")
            .task(&build)
            .on_success(&task("announce"))
            .definition()
            .to_request("")
            .unwrap();
        assert_eq!(request.tasks.last().unwrap().parents, ["build"]);
    }

    #[test]
    fn an_on_success_task_may_not_collide_with_a_task_or_be_declared_twice() {
        let build = task("build");
        let err = Workflow::new("pipeline")
            .task(&build)
            .on_success(&build)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");

        let err = Workflow::new("pipeline")
            .task(&task("build"))
            .on_success(&task("a"))
            .on_success(&task("b"))
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("on_success"), "{err}");
    }

    #[test]
    fn on_success_and_on_failure_may_not_share_a_name() {
        let err = Workflow::new("pipeline")
            .task(&task("build"))
            .on_failure(&task("after"))
            .on_success(&task("After"))
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
    }

    #[test]
    fn an_on_success_task_is_registered_as_an_action() {
        let definition = Workflow::new("pipeline")
            .task(&task("build"))
            .on_failure(&task("cleanup"))
            .on_success(&task("announce"))
            .definition();
        let ids: Vec<String> = definition
            .actions("")
            .unwrap()
            .into_iter()
            .map(|(id, _)| id)
            .collect();
        assert_eq!(
            ids,
            ["pipeline:build", "pipeline:cleanup", "pipeline:announce"]
        );
    }

    #[test]
    fn workflow_concurrency_on_a_standalone_task_goes_to_the_workflow_field() {
        let agent_run = TaskBuilder::<serde_json::Value, serde_json::Value>::new("agent-run")
            .workflow_concurrency(Concurrency::expr("input.key").max_runs(1))
            .handler(|_ctx, input| async move { Ok(input) });

        let request = agent_run.definition().to_request("").unwrap();

        assert_eq!(
            request.concurrency_arr,
            [v1::Concurrency {
                expression: "input.key".to_string(),
                max_runs: Some(1),
                ..Default::default()
            }]
        );
        assert!(
            request.tasks[0].concurrency.is_empty(),
            "workflow-level concurrency must not land on the task"
        );
        assert!(
            request.concurrency.is_none(),
            "the singular field is never used"
        );
    }

    #[test]
    fn task_concurrency_on_a_standalone_task_stays_on_the_task() {
        let agent_run = TaskBuilder::<serde_json::Value, serde_json::Value>::new("agent-run")
            .concurrency(Concurrency::expr("input.key").max_runs(1))
            .handler(|_ctx, input| async move { Ok(input) });

        let request = agent_run.definition().to_request("").unwrap();

        assert_eq!(request.tasks[0].concurrency.len(), 1);
        assert!(request.concurrency_arr.is_empty());
    }

    #[test]
    fn workflow_concurrency_on_a_task_inside_a_workflow_is_an_error() {
        let bad = TaskBuilder::<serde_json::Value, serde_json::Value>::new("build")
            .workflow_concurrency(Concurrency::expr("input.key").max_runs(1))
            .handler(|_ctx, input| async move { Ok(input) });
        let err = Workflow::new("pipeline")
            .task(&bad)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("workflow concurrency"), "{err}");
    }

    #[test]
    fn a_tenant_scoped_entry_without_a_name_is_rejected_at_registration() {
        let err = Workflow::new("pipeline")
            .concurrency(Concurrency::expr("input.tenant").tenant_scoped())
            .task(&task("build"))
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("name"), "{err}");
    }

    /// Criterion 1. The milestone wrote `sleep_for: "30s"`; this SDK sends
    /// whole milliseconds, as the official Go SDK does — see the plan's
    /// corrections and the spike findings.
    #[test]
    fn a_wait_for_sleep_maps_to_a_queue_sleep_condition() {
        let gated = TaskBuilder::<serde_json::Value, serde_json::Value>::new("gated")
            .wait_for(Condition::sleep(Duration::from_secs(30)))
            .handler(|_ctx, input| async move { Ok(input) });
        let request = Workflow::new("pipeline")
            .task(&gated)
            .definition()
            .to_request("dev_")
            .unwrap();

        let conditions = request.tasks[0]
            .conditions
            .as_ref()
            .expect("the task carries conditions");
        assert!(conditions.user_event_conditions.is_empty());
        assert!(conditions.parent_override_conditions.is_empty());
        let [sleep] = conditions.sleep_conditions.as_slice() else {
            panic!("one sleep condition: {conditions:?}");
        };
        assert_eq!(sleep.sleep_for, "30000ms");
        let base = sleep.base.as_ref().unwrap();
        assert_eq!(base.action, v1::Action::Queue as i32);
        assert_eq!(base.readable_data_key, "sleep:30000ms");
        assert_eq!(base.or_group_id.len(), 36);
    }

    /// Criterion 2.
    #[test]
    fn a_skip_if_parent_maps_to_a_skip_parent_override_condition() {
        let a = task("a");
        let b = TaskBuilder::<serde_json::Value, serde_json::Value>::new("b")
            .skip_if(Condition::parent(&a).expression("output.ok == false"))
            .handler(|_ctx, input| async move { Ok(input) })
            .parent(&a);
        let request = Workflow::new("pipeline")
            .task(&a)
            .task(&b)
            .definition()
            .to_request("dev_")
            .unwrap();

        let conditions = request.tasks[1].conditions.as_ref().expect("conditions");
        let [parent] = conditions.parent_override_conditions.as_slice() else {
            panic!("one parent condition: {conditions:?}");
        };
        assert_eq!(parent.parent_readable_id, "a");
        let base = parent.base.as_ref().unwrap();
        assert_eq!(base.action, v1::Action::Skip as i32);
        assert_eq!(base.expression, "output.ok == false");
        assert!(
            request.tasks[0].conditions.is_none(),
            "`a` has no conditions"
        );
    }

    /// Criterion 3: the event key is namespaced, the readable key is not.
    /// The `wait_for` is not decoration — a cancelling event condition on
    /// its own would never be reached, and is rejected.
    #[test]
    fn a_cancel_if_event_is_namespaced() {
        let gated = TaskBuilder::<serde_json::Value, serde_json::Value>::new("gated")
            .wait_for(Condition::sleep(Duration::from_secs(60)))
            .cancel_if(Condition::on_event("kill"))
            .handler(|_ctx, input| async move { Ok(input) });
        let request = Workflow::new("pipeline")
            .task(&gated)
            .definition()
            .to_request("dev_")
            .unwrap();

        let conditions = request.tasks[0].conditions.as_ref().expect("conditions");
        let [event] = conditions.user_event_conditions.as_slice() else {
            panic!("one event condition: {conditions:?}");
        };
        assert_eq!(event.user_event_key, "dev_kill");
        let base = event.base.as_ref().unwrap();
        assert_eq!(base.action, v1::Action::Cancel as i32);
        assert_eq!(base.readable_data_key, "kill");
    }

    /// Criterion 4, second half: a duplicate readable key is an error, not
    /// a panic, and the message says how to fix it.
    #[test]
    fn two_conditions_sharing_a_readable_key_are_an_error() {
        let gated = TaskBuilder::<serde_json::Value, serde_json::Value>::new("gated")
            .wait_for(Condition::on_event("go"))
            .skip_if(Condition::on_event("go"))
            .handler(|_ctx, input| async move { Ok(input) });
        let err = Workflow::new("pipeline")
            .task(&gated)
            .definition()
            .to_request("dev_")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("gated"), "{err}");
        assert!(err.to_string().contains("readable_key"), "{err}");
    }

    #[test]
    fn a_parent_condition_naming_a_task_that_is_not_a_parent_is_an_error() {
        let a = task("a");
        let b = TaskBuilder::<serde_json::Value, serde_json::Value>::new("b")
            .skip_if(Condition::parent(&a).expression("output.ok"))
            .handler(|_ctx, input| async move { Ok(input) });
        // `b` never declares `a` as a parent.
        let err = Workflow::new("pipeline")
            .task(&a)
            .task(&b)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("`a`"), "{err}");
        assert!(err.to_string().contains("parent"), "{err}");
    }

    /// Readable ids reach the engine exactly as they were declared — they are
    /// not lowercased the way workflow and action names are — so a parent
    /// condition whose spelling differs only in case would never match, and
    /// is rejected rather than hanging.
    #[test]
    fn a_parent_condition_whose_case_differs_from_the_parent_is_an_error() {
        let a = task("a");
        let b = TaskBuilder::<serde_json::Value, serde_json::Value>::new("b")
            .skip_if(Condition::parent_by_name("A").expression("output.ok"))
            .handler(|_ctx, input| async move { Ok(input) })
            .parent(&a);
        let err = Workflow::new("pipeline")
            .task(&a)
            .task(&b)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("`A`"), "{err}");
        assert!(err.to_string().contains("parent"), "{err}");
    }

    #[test]
    fn a_parent_condition_on_a_standalone_task_is_an_error() {
        let lonely = TaskBuilder::<serde_json::Value, serde_json::Value>::new("lonely")
            .wait_for(Condition::parent_by_name("nobody"))
            .handler(|_ctx, input| async move { Ok(input) });
        let err = lonely.definition().to_request("").unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("nobody"), "{err}");
    }

    #[test]
    fn a_standalone_task_may_still_wait_for_a_sleep_or_an_event() {
        let lonely = TaskBuilder::<serde_json::Value, serde_json::Value>::new("lonely")
            .wait_for(Condition::sleep(Duration::from_secs(5)))
            .cancel_if(Condition::on_event("stop"))
            .handler(|_ctx, input| async move { Ok(input) });
        let request = lonely.definition().to_request("dev_").unwrap();
        let conditions = request.tasks[0].conditions.as_ref().expect("conditions");
        assert_eq!(conditions.sleep_conditions.len(), 1);
        assert_eq!(conditions.user_event_conditions.len(), 1);
    }

    /// An event `skip_if` with nothing to queue on would leave the task
    /// waiting for ever, so the declaration is rejected, naming the task.
    #[test]
    fn a_skip_if_event_without_a_wait_for_is_an_error() {
        let gated = TaskBuilder::<serde_json::Value, serde_json::Value>::new("gated")
            .skip_if(Condition::on_event("skip"))
            .handler(|_ctx, input| async move { Ok(input) });
        let err = Workflow::new("pipeline")
            .task(&task("build"))
            .task(&gated)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("gated"), "{err}");
        assert!(err.to_string().contains("wait_for"), "{err}");
    }

    /// Carry-over from P1: the Go SDK's on-failure dump never sends
    /// conditions (`sdks/go/internal/task/task.go:375-387`), so a condition
    /// there would be a silent no-op at best.
    #[test]
    fn conditions_on_the_on_failure_hook_are_an_error() {
        let cleanup = TaskBuilder::<serde_json::Value, serde_json::Value>::new("cleanup")
            .wait_for(Condition::sleep(Duration::from_secs(5)))
            .handler(|_ctx, input| async move { Ok(input) });
        let err = Workflow::new("pipeline")
            .task(&task("build"))
            .on_failure(&cleanup)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("cleanup"), "{err}");
        assert!(err.to_string().contains("on_failure"), "{err}");
    }

    #[test]
    fn the_on_success_hook_may_carry_conditions_but_only_on_a_leaf() {
        let build = task("build");
        let announce = TaskBuilder::<serde_json::Value, serde_json::Value>::new("announce")
            .skip_if(Condition::parent(&build).expression("output.quiet == true"))
            .handler(|_ctx, input| async move { Ok(input) });
        let request = Workflow::new("pipeline")
            .task(&build)
            .on_success(&announce)
            .definition()
            .to_request("")
            .unwrap();
        let hook = request.tasks.last().expect("the on-success task is last");
        assert_eq!(hook.readable_id, "announce");
        assert_eq!(hook.parents, ["build"]);
        assert_eq!(
            hook.conditions
                .as_ref()
                .expect("conditions")
                .parent_override_conditions[0]
                .parent_readable_id,
            "build"
        );

        let stray = TaskBuilder::<serde_json::Value, serde_json::Value>::new("announce")
            .skip_if(Condition::parent_by_name("root").expression("output.x"))
            .handler(|_ctx, input| async move { Ok(input) });
        let root = task("root");
        let leaf = task("leaf").parent(&root);
        let err = Workflow::new("pipeline")
            .task(&root)
            .task(&leaf)
            .on_success(&stray)
            .definition()
            .to_request("")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidDeclaration(_)), "{err:?}");
        assert!(err.to_string().contains("root"), "{err}");
    }

    #[test]
    fn a_sticky_workflow_carries_its_strategy() {
        let request = Workflow::new("pipeline")
            .sticky(StickyStrategy::Hard)
            .task(&task("work"))
            .definition()
            .to_request("dev_")
            .unwrap();
        assert_eq!(request.sticky, Some(v1::StickyStrategy::Hard as i32));
    }

    #[test]
    fn a_workflow_without_sticky_leaves_the_field_unset() {
        let request = Workflow::new("pipeline")
            .task(&task("work"))
            .definition()
            .to_request("dev_")
            .unwrap();
        assert_eq!(request.sticky, None);
    }

    #[test]
    fn a_standalone_task_carries_its_own_sticky_strategy() {
        let solo = TaskBuilder::<(), ()>::new("solo")
            .sticky(StickyStrategy::Soft)
            .handler(|_ctx, _input| async { Ok(()) });
        let request = solo.definition().to_request("dev_").unwrap();
        assert_eq!(request.sticky, Some(v1::StickyStrategy::Soft as i32));
    }

    #[test]
    fn sticky_on_a_task_inside_a_workflow_is_a_standalone_only_option() {
        let work = TaskBuilder::<(), ()>::new("work")
            .sticky(StickyStrategy::Hard)
            .handler(|_ctx, _input| async { Ok(()) });
        let error = Workflow::new("pipeline")
            .task(&work)
            .definition()
            .to_request("dev_")
            .unwrap_err();
        assert!(matches!(error, Error::InvalidDeclaration(_)), "{error:?}");
        assert!(error.to_string().contains("standalone-only"), "{error}");
    }

    #[test]
    fn an_idempotent_workflow_carries_its_config() {
        let request = Workflow::new("checkout")
            .idempotency(Idempotency::until_run_ends(
                "input.order_id",
                Duration::from_secs(600),
            ))
            .task(&task("charge"))
            .definition()
            .to_request("dev_")
            .unwrap();
        assert_eq!(
            request.idempotency,
            Some(v1::IdempotencyConfig {
                expression: "input.order_id".to_string(),
                ttl_ms: 600_000,
                method: Some(v1::IdempotencyMethod::Status as i32),
            })
        );
    }

    #[test]
    fn an_empty_idempotency_expression_is_an_invalid_declaration_not_a_panic() {
        let error = Workflow::new("checkout")
            .idempotency(Idempotency::ttl("", Duration::from_secs(60)))
            .task(&task("charge"))
            .definition()
            .to_request("dev_")
            .unwrap_err();
        assert!(matches!(error, Error::InvalidDeclaration(_)), "{error:?}");
        assert!(error.to_string().contains("checkout"), "{error}");
    }

    #[test]
    fn a_task_added_to_a_workflow_is_still_usable_afterwards() {
        let fetch = task("fetch");
        let build = task("build").parent(&fetch);
        let workflow = Workflow::new("pipeline").task(&fetch).task(&build);

        // The point of taking `&Task`: the handles are still ours, so a
        // caller can read the run's output by task handle without having
        // cloned them first.
        assert_eq!(fetch.name(), "fetch");
        assert_eq!(build.name(), "build");
        assert_eq!(task_names(&workflow.definition().tasks), ["fetch", "build"]);
    }
}