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
//! Running the actions the engine assigns: slots, panic capture, per-run
//! cancellation, reporting, and letting go at shutdown.
//!
//! Network-agnostic on purpose: reports leave through an injected
//! [`Reporter`], so everything below can be tested without a socket.

use std::any::Any;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;

use hatchet_proto::root::{ActionType, AssignedAction, BatchActionEvent, StepActionEvent};
use serde_json::Value;
use tokio::sync::{Notify, Semaphore};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::{Instrument, Span};

use super::events;
use crate::batch::{self, BatchMemberId, BatchReport};
use crate::context::Slot;
use crate::declare::RegisteredAction;
use crate::durable::DurableInvocation;
use crate::durable::eviction::EvictionBook;
use crate::durable::stream::DurableStream;
use crate::{Client, Context, TaskError, otel};

/// How a report reaches the engine.
///
/// Returning `()` is deliberate: retrying and logging a failed report belong
/// to the implementation the `Worker` plugs in, and a run must never be held
/// up — or ended — by a report that would not go through.
#[allow(clippy::type_complexity)]
pub(crate) type Reporter =
    Arc<dyn Fn(StepActionEvent) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;

/// How a batch's reports reach the engine.
///
/// Separate from [`Reporter`] because the engine takes batch events on an RPC
/// of their own (`/Dispatcher/SendBatchActionEvent`), not because a batch is
/// reported any differently: the same "log it and move on" rule applies.
#[allow(clippy::type_complexity)]
pub(crate) type BatchReporter =
    Arc<dyn Fn(BatchActionEvent) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>;

/// How long a run that was asked to stop is given to wind down before the
/// worker stops waiting for it and drops it where it stands.
pub(crate) const CANCEL_SETTLE: Duration = Duration::from_secs(1);

/// Runs the actions assigned to one worker, bounded by its slots.
///
/// Cheap to clone-by-reference through [`Arc`] internally: every run holds a
/// handle to the same state, so a run can unregister itself long after the
/// action that started it was forgotten.
///
/// That independence cuts both ways. Dropping a `Runner` does not stop its
/// runs: each one executes in a task that holds its own handle on the state,
/// and only [`drain`](Self::drain) or [`abort_all`](Self::abort_all) ends
/// them. Nor do those two end *reporting*: a STARTED report is sent from a
/// task of its own so that a slow one does not delay the work, and one already
/// in flight can outlive the call that dropped its run — how long is the
/// [`Reporter`]'s business, bounded by whatever retry and timeout policy the
/// worker plugged in.
pub(crate) struct Runner {
    inner: Arc<Inner>,
}

/// Everything a run needs once it is on its own.
struct Inner {
    worker_id: String,
    client: Option<Client>,
    handlers: HashMap<String, RegisteredAction>,
    slots: Arc<Semaphore>,
    /// What the durable actions need, `None` when nothing durable is
    /// registered.
    durable: Option<DurableRuntime>,
    report: Reporter,
    report_batch: BatchReporter,
    /// The runs this worker has taken on, by `task_run_external_id` — or, for a
    /// batch, by [`batch::run_key`]: those waiting for a slot as well as those
    /// executing.
    runs: Mutex<HashMap<String, Run>>,
    /// Notified when the last run unregisters.
    idle: Notify,
    next_seq: AtomicU64,
}

/// What the runner keeps for a run it has taken on.
struct Run {
    /// Tells this registration apart from a later one with the same id, so a
    /// finishing run cannot unregister its own successor.
    seq: u64,
    /// Asks the handler to stop, and suppresses the run's terminal event.
    cancel: CancellationToken,
    /// Drops the run where it stands: the slot permit and the handler's task
    /// go with the future this cancels.
    kill: CancellationToken,
}

/// What a runner needs for the durable actions it serves: how many `durable`
/// slots to keep, the stream those actions talk to, and the engine version the
/// durable gates read. All of it is present together, or not at all.
pub(crate) struct DurableSetup {
    pub(crate) slots: usize,
    pub(crate) stream: DurableStream,
    /// The worker's eviction ledger, when any registered durable task carries
    /// a policy. `None` keeps the whole mechanism out of the way: no run is
    /// recorded, no wait is counted, and no manager is running to read it.
    pub(crate) eviction: Option<Arc<EvictionBook>>,
    /// What `Dispatcher/GetVersion` said when the worker was built, carried on
    /// to every durable invocation: the gate on
    /// [`DurableContext::spawn`](crate::DurableContext::spawn) can only be
    /// checked when a handler calls it.
    pub(crate) engine_version: Arc<str>,
}

/// [`DurableSetup`] once the runner owns it.
struct DurableRuntime {
    /// The `durable` slot pool, kept apart from the ordinary `slots` so a
    /// durable run that is parked on the engine does not occupy one of the
    /// slots the worker executes ordinary tasks with.
    slots: Arc<Semaphore>,
    stream: DurableStream,
    engine_version: Arc<str>,
    eviction: Option<Arc<EvictionBook>>,
}

impl From<DurableSetup> for DurableRuntime {
    fn from(setup: DurableSetup) -> Self {
        Self {
            slots: Arc::new(Semaphore::new(setup.slots)),
            stream: setup.stream,
            engine_version: setup.engine_version,
            eviction: setup.eviction,
        }
    }
}

impl Runner {
    /// A runner for one worker. `durable` is `Some` only when something
    /// durable is registered.
    pub(crate) fn new(
        worker_id: String,
        client: Option<Client>,
        handlers: HashMap<String, RegisteredAction>,
        slots: usize,
        durable: Option<DurableSetup>,
        report: Reporter,
        report_batch: BatchReporter,
    ) -> Self {
        Self {
            inner: Arc::new(Inner {
                worker_id,
                client,
                handlers,
                slots: Arc::new(Semaphore::new(slots)),
                durable: durable.map(DurableRuntime::from),
                report,
                report_batch,
                runs: Mutex::new(HashMap::new()),
                idle: Notify::new(),
                next_seq: AtomicU64::new(0),
            }),
        }
    }

    /// Takes on one assigned action. Never blocks: a run that cannot start
    /// yet waits for its slot in a task of its own, so the caller can keep
    /// reading the action stream.
    pub(crate) fn dispatch(&self, action: AssignedAction) {
        match ActionType::try_from(action.action_type) {
            Ok(ActionType::StartStepRun) => self.start(action),
            Ok(ActionType::StartBatch) => self.start_batch(action),
            Ok(ActionType::CancelStepRun) => {
                // Python's span (`instrumentor.py:524-541`); Go names it but
                // opens none for a cancellation.
                let span = otel::cancel_step_run(&action.task_run_external_id);
                span.in_scope(|| self.cancel(&action.task_run_external_id));
            }
            Ok(other) => tracing::warn!(
                action_type = other.as_str_name(),
                action_id = %action.action_id,
                task_run_external_id = %action.task_run_external_id,
                "ignoring an action type this SDK does not run",
            ),
            Err(_) => tracing::warn!(
                action_type = action.action_type,
                action_id = %action.action_id,
                "ignoring an action type this SDK does not know",
            ),
        }
    }

    /// How many runs this worker is holding: waiting for a slot or executing.
    pub(crate) fn in_flight(&self) -> usize {
        self.inner.in_flight()
    }

    /// Waits up to `grace` for the runs in flight to finish on their own,
    /// then asks the stragglers to stop, and drops whatever is still there
    /// [`CANCEL_SETTLE`] later.
    ///
    /// Returns as soon as nothing is in flight.
    pub(crate) async fn drain(&self, grace: Duration) {
        if tokio::time::timeout(grace, self.inner.wait_until_idle())
            .await
            .is_ok()
        {
            return;
        }

        let asked = self.inner.cancel_all();
        tracing::info!(
            runs = asked,
            "the grace period is over; asking the runs still in flight to stop",
        );
        if tokio::time::timeout(CANCEL_SETTLE, self.inner.wait_until_idle())
            .await
            .is_ok()
        {
            return;
        }

        self.drop_everything("dropping runs that did not stop when asked to")
            .await;
    }

    /// Stops every run at once, without waiting for any of them. For the
    /// paths where reporting is pointless anyway — a broken connection — and
    /// for tearing a worker down in a hurry.
    pub(crate) async fn abort_all(&self) {
        self.inner.cancel_all();
        self.drop_everything("dropping the runs still in flight")
            .await;
    }

    fn start(&self, action: AssignedAction) {
        let id = action.task_run_external_id.clone();
        let cancel = CancellationToken::new();
        let kill = CancellationToken::new();
        let seq = self.inner.register(&id, cancel.clone(), kill.clone());
        // Built here rather than inside the task: a task that is dropped
        // before its first poll never runs its body, and the registration
        // would leak. Built out here it is owned by the future itself, so
        // dropping the future gives it up either way.
        let registration = Registration {
            inner: Arc::clone(&self.inner),
            id,
            seq,
        };

        let inner = Arc::clone(&self.inner);
        tokio::spawn(async move {
            // The registration is given up on the way out however this task
            // ends — including a panic somewhere in the reporting — so a
            // worker can never be left waiting on a run that is over.
            let _registration = registration;
            tokio::select! {
                // Dropping `run` here releases the slot permit and aborts the
                // handler's task, which is why a killed run needs no cleanup
                // of its own.
                () = kill.cancelled() => {}
                () = run(&inner, action, cancel) => {}
            }
        });
    }

    /// Takes on one batch, which is **one** run of this worker however many
    /// buffered task runs it answers for: one slot, one handler call, one
    /// place in the ledger.
    ///
    /// Booked under [`batch::run_key`] rather than a `task_run_external_id`,
    /// which a `START_BATCH` does not carry.
    fn start_batch(&self, action: AssignedAction) {
        let id = batch::run_key(&action);
        let cancel = CancellationToken::new();
        let kill = CancellationToken::new();
        let seq = self.inner.register(&id, cancel.clone(), kill.clone());
        // Owned by the future, for the reason `start` spells out.
        let registration = Registration {
            inner: Arc::clone(&self.inner),
            id,
            seq,
        };

        let inner = Arc::clone(&self.inner);
        tokio::spawn(async move {
            let _registration = registration;
            tokio::select! {
                () = kill.cancelled() => {}
                () = run_batch(&inner, action, cancel) => {}
            }
        });
    }

    /// Asks one run to stop, by `task_run_external_id`: the token fires and
    /// the run's terminal event is suppressed, because a cancelled run belongs
    /// to the engine. This is the path an engine-sent `CANCEL_STEP_RUN` takes,
    /// the one a `server_evict` on the durable stream takes, and the one the
    /// worker's own eviction manager takes once the engine has acknowledged an
    /// eviction it asked for.
    pub(crate) fn cancel(&self, id: &str) {
        if self.inner.cancel_run(id) {
            tracing::debug!(task_run_external_id = %id, "a run was asked to stop");
        } else {
            // Routine: the engine cancels a run this worker never had, or one
            // it has already finished.
            tracing::debug!(
                task_run_external_id = %id,
                "ignoring a cancellation for a run this worker is not holding",
            );
        }
    }

    async fn drop_everything(&self, reason: &str) {
        let dropped = self.inner.kill_all();
        if dropped > 0 {
            tracing::warn!(runs = dropped, "{reason}");
            // Give the dropped runs a turn to unwind — release their slots
            // and abort their handlers — before the caller moves on.
            tokio::task::yield_now().await;
        }
    }
}

impl Inner {
    fn register(&self, id: &str, cancel: CancellationToken, kill: CancellationToken) -> u64 {
        let seq = self.next_seq.fetch_add(1, Ordering::Relaxed);
        // Registering here, before the run's task is even spawned, is what
        // makes a cancellation that arrives right behind the assignment land
        // on a run that has not started yet.
        let previous = self
            .runs
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(id.to_string(), Run { seq, cancel, kill });
        if let Some(previous) = previous {
            tracing::warn!(
                task_run_external_id = %id,
                "the engine assigned a run that is already in flight; dropping the earlier one",
            );
            previous.cancel.cancel();
            previous.kill.cancel();
        }
        seq
    }

    /// Unregisters a run, unless it has already been replaced or dropped.
    fn finish(&self, id: &str, seq: u64) {
        let idle = {
            let mut runs = self.runs.lock().unwrap_or_else(PoisonError::into_inner);
            if runs.get(id).is_some_and(|run| run.seq == seq) {
                runs.remove(id);
            }
            runs.is_empty()
        };
        if idle {
            self.idle.notify_waiters();
        }
    }

    fn in_flight(&self) -> usize {
        self.runs
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .len()
    }

    /// Fires one run's cancellation token. `false` when there is no such run.
    fn cancel_run(&self, id: &str) -> bool {
        let token = self
            .runs
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(id)
            .map(|run| run.cancel.clone());
        match token {
            Some(token) => {
                token.cancel();
                true
            }
            None => false,
        }
    }

    /// Asks every run to stop, leaving them registered and running.
    fn cancel_all(&self) -> usize {
        let tokens: Vec<CancellationToken> = self
            .runs
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .values()
            .map(|run| run.cancel.clone())
            .collect();
        for token in &tokens {
            token.cancel();
        }
        tokens.len()
    }

    /// Drops every run where it stands and unregisters it, so the worker is
    /// idle the moment this returns rather than whenever the runs notice.
    fn kill_all(&self) -> usize {
        let runs = {
            let mut guard = self.runs.lock().unwrap_or_else(PoisonError::into_inner);
            std::mem::take(&mut *guard)
        };
        for run in runs.values() {
            run.cancel.cancel();
            run.kill.cancel();
        }
        if !runs.is_empty() {
            self.idle.notify_waiters();
        }
        runs.len()
    }

    /// The slot pool one action is charged to: the durable one for a durable
    /// action, the default one for everything else — including an action this
    /// worker does not serve, which fails in [`execute`] a moment later.
    ///
    /// A durable task that is parked on the engine is not doing any work, so
    /// charging it to the same pool as an ordinary run would starve the worker
    /// for no reason (`sdks/go/client.go:439-491`).
    fn slots_for(&self, action_id: &str) -> Arc<Semaphore> {
        let durable = self
            .handlers
            .get(action_id)
            .is_some_and(|registered| registered.durable);
        match (durable, &self.durable) {
            (true, Some(runtime)) => Arc::clone(&runtime.slots),
            _ => Arc::clone(&self.slots),
        }
    }

    /// Completes once no run is registered.
    async fn wait_until_idle(&self) {
        loop {
            let notified = self.idle.notified();
            tokio::pin!(notified);
            // Registering before the count is read is what keeps a run that
            // finishes in between from being missed.
            notified.as_mut().enable();
            if self.in_flight() == 0 {
                return;
            }
            notified.await;
        }
    }
}

/// One run, from its slot to its report.
async fn run(inner: &Inner, action: AssignedAction, cancel: CancellationToken) {
    // A run cancelled while it waits for a slot never happened: no STARTED, no
    // handler, and no terminal event. Waiting on the cancellation *alongside*
    // the slot is what lets it go at once rather than when its turn finally
    // comes — a queued run that sat out a full drain would hold the worker
    // open for nothing. `biased` so an already-cancelled run cannot take a
    // free slot on a coin toss.
    let acquired = tokio::select! {
        biased;
        () = cancel.cancelled() => {
            tracing::debug!(
                task_run_external_id = %action.task_run_external_id,
                "a run was cancelled while it waited for a slot; not starting it",
            );
            return;
        }
        permit = inner.slots_for(&action.action_id).acquire_owned() => permit,
    };
    let Ok(permit) = acquired else {
        tracing::error!("the worker's slots were closed; dropping the run");
        return;
    };
    // The permit does not simply live in this frame: it goes into a slot the
    // run's `Context` shares, so a handler that asks for its slot back — to
    // wait on a child run, say — really frees this worker to start another
    // run, not just the engine's count of it. The guard empties that slot
    // however this run ends (a return below, a panic, or the `kill` that
    // drops this future), so a handler that leaked a `Context` clone into a
    // detached task cannot keep the slot after the run is over.
    let slot = Slot::holding(permit);
    let _slot_guard = SlotGuard(slot.clone());

    // The same check again, for a cancellation that lands in the moment
    // between winning the slot and reporting STARTED.
    if cancel.is_cancelled() {
        tracing::debug!(
            task_run_external_id = %action.task_run_external_id,
            "a run was cancelled before it started; not starting it",
        );
        return;
    }

    // The run's span, from STARTED to its terminal report — the extent of Go's
    // middleware around a step run (`sdks/go/opentelemetry/middleware.go:50-68`).
    // With the `otel` feature it continues the trace the action's metadata
    // names. A run that never started (cancelled while queued, above) has none.
    let span = otel::start_step_run(&action, &inner.worker_id);

    // STARTED goes out while the handler runs, so a slow report does not
    // delay the work.
    let started = tokio::spawn({
        let report = Arc::clone(&inner.report);
        let event = events::started(&action, &inner.worker_id);
        async move { report(event).await }
    });

    let outcome = execute(inner, &action, cancel.clone(), slot, &span)
        .instrument(span.clone())
        .await;

    // ...but the run's terminal event must never overtake its STARTED.
    if let Err(error) = started.await {
        tracing::warn!(
            %error,
            task_run_external_id = %action.task_run_external_id,
            "reporting that a run started did not finish",
        );
    }

    if cancel.is_cancelled() {
        // A cancelled run belongs to the engine now: whatever the handler
        // returned, completing or failing it here would fight that.
        tracing::debug!(
            task_run_external_id = %action.task_run_external_id,
            "a cancelled run finished; not reporting an outcome",
        );
        return;
    }

    let event = match outcome {
        Outcome::Completed(output) => {
            otel::record_ok(&span);
            events::completed(&action, &inner.worker_id, &output)
        }
        Outcome::Failed(error) => {
            otel::record_error(&span, error.message());
            span.in_scope(|| {
                tracing::warn!(
                    task_run_external_id = %action.task_run_external_id,
                    action_id = %action.action_id,
                    retryable = error.is_retryable(),
                    message = error.message(),
                    "a task run failed",
                );
            });
            events::failed(&action, &inner.worker_id, &error)
        }
        Outcome::Stopped => return,
    };
    (inner.report)(event).await;
}

/// Runs the handler for one action, turning everything that can go wrong into
/// an outcome the worker can report.
async fn execute(
    inner: &Inner,
    action: &AssignedAction,
    cancel: CancellationToken,
    slot: Slot,
    span: &Span,
) -> Outcome {
    let Some(registered) = inner.handlers.get(&action.action_id).cloned() else {
        return Outcome::Failed(TaskError::non_retryable(format!(
            "this worker has no task registered for the action `{}`",
            action.action_id
        )));
    };
    // The ledger entry is held in *this* frame, so the eviction book gives the
    // run up however this frame ends — including the drop a killed run's
    // future takes. Tying it to the durable invocation instead would leave a
    // handler that leaked a `Context` clone counting towards capacity for
    // ever, exactly as it once could have kept a slot.
    let (durable, _registration) = if registered.durable {
        let Some(runtime) = inner.durable.as_ref() else {
            // A durable action on a worker with no durable stream: the handler
            // would stop for ever on its first wait, so fail it plainly.
            return Outcome::Failed(TaskError::non_retryable(format!(
                "the action `{}` is durable but this worker has no durable stream",
                action.action_id
            )));
        };
        // The engine leaves the count out on the first invocation
        // (`sdks/go/client.go:390-396`), and 0 means the same thing.
        let invocation_count = action.durable_task_invocation_count.unwrap_or(1).max(1);
        // On the books before the handler starts, and off them when this
        // frame ends however it ends. Every durable run is recorded, policy
        // or not: capacity pressure is measured in occupied durable slots,
        // and a run with no policy occupies one just the same — it is simply
        // never chosen (`durable::eviction::EvictionBook::candidate`).
        let registration = runtime.eviction.as_ref().map(|book| {
            book.take_on(
                &action.task_run_external_id,
                invocation_count,
                registered.eviction_policy.clone(),
            )
        });
        (
            Some(Arc::new(DurableInvocation::new(
                runtime.stream.clone(),
                action.task_run_external_id.clone(),
                invocation_count,
                Arc::clone(&runtime.engine_version),
                runtime.eviction.clone(),
            ))),
            registration,
        )
    } else {
        (None, None)
    };
    let handler = registered.handler;
    let context = match Context::new(
        action.clone(),
        inner.worker_id.clone(),
        inner.client.clone(),
        cancel,
        slot,
        durable,
    ) {
        Ok(context) => context,
        Err(reason) => return Outcome::Failed(TaskError::non_retryable(reason)),
    };
    let input = context.input().clone();

    // The handler gets a task of its own so that a panic inside it fails the
    // run instead of unwinding the worker. The guard makes sure the handler
    // cannot outlive the run that owns it.
    //
    // The handler's task carries the run's span: a task of its own does not
    // inherit the caller's, and everything the handler opens — a child run's
    // trigger above all — belongs under it.
    let mut handler_task = AbortOnDrop(tokio::spawn(
        async move { handler(context, input).await }.instrument(span.clone()),
    ));
    match (&mut handler_task.0).await {
        Ok(Ok(output)) => Outcome::Completed(output),
        Ok(Err(error)) => Outcome::Failed(error),
        Err(error) if error.is_panic() => {
            let message = panic_message(error.into_panic());
            tracing::error!(
                task_run_external_id = %action.task_run_external_id,
                action_id = %action.action_id,
                message,
                "a task handler panicked",
            );
            // A panic might not happen again, so this is retryable: it is the
            // task's `retries` that decide.
            Outcome::Failed(TaskError::new(message))
        }
        // The handler's task was dropped out from under us. Whoever did that
        // is tearing the run down and is not waiting for a report.
        Err(_) => Outcome::Stopped,
    }
}

/// One batch, from its slot to its reports.
///
/// The shape of [`run`], with three differences that are all the same
/// difference — a batch is one run standing in for many:
///
/// - what is reported is a list of members, not one run;
/// - every way this can go wrong has to end in an outcome for **every** member,
///   because a member the engine never hears about stays `Running` until it
///   times out and is never assigned again;
/// - a cancellation — the worker shutting down, since no single member can be
///   cancelled — suppresses the terminal reports of the whole batch, exactly as
///   it suppresses an ordinary run's.
async fn run_batch(inner: &Inner, action: AssignedAction, cancel: CancellationToken) {
    // Read before anything else can fail: these ids are who a failure would
    // have to be reported to.
    let members = batch::member_ids(&action);
    if members.is_empty() {
        // Nothing can be reported, because there is nobody to report about: an
        // empty batch, or a payload that is not a map of items at all.
        tracing::error!(
            action_id = %action.action_id,
            batch_id = ?action.batch_id,
            "a batch arrived naming no members; dropping it",
        );
        return;
    }

    // One slot for the whole batch: it is one handler call, however many runs
    // it answers for. Cancelled while it waits, and it never happened — no
    // STARTED, no handler, nothing terminal.
    let acquired = tokio::select! {
        biased;
        () = cancel.cancelled() => {
            tracing::debug!(
                batch_id = ?action.batch_id,
                "a batch was cancelled while it waited for a slot; not starting it",
            );
            return;
        }
        permit = inner.slots_for(&action.action_id).acquire_owned() => permit,
    };
    let Ok(permit) = acquired else {
        tracing::error!("the worker's slots were closed; dropping the batch");
        return;
    };
    let slot = Slot::holding(permit);
    let _slot_guard = SlotGuard(slot.clone());

    if cancel.is_cancelled() {
        tracing::debug!(
            batch_id = ?action.batch_id,
            "a batch was cancelled before it started; not starting it",
        );
        return;
    }

    // One span for the whole batch, as it is one handler call; see
    // `otel::start_batch_run`.
    let span = otel::start_batch_run(&action, &inner.worker_id, members.len());

    // STARTED names every member and goes out before the handler is called,
    // as both official SDKs do (`pkg/worker/worker.go:867-885`), from a task of
    // its own so that a slow report does not delay the work.
    let started = tokio::spawn({
        let report = Arc::clone(&inner.report_batch);
        let event = events::batch_started(&action, &inner.worker_id, &members);
        async move { report(event).await }
    });

    let outcome = execute_batch(inner, &action, cancel.clone(), slot, &span)
        .instrument(span.clone())
        .await;

    // ...but nothing terminal may overtake that STARTED.
    if let Err(error) = started.await {
        tracing::warn!(
            %error,
            batch_id = ?action.batch_id,
            "reporting that a batch started did not finish",
        );
    }

    if cancel.is_cancelled() {
        tracing::debug!(
            batch_id = ?action.batch_id,
            "a cancelled batch finished; not reporting an outcome",
        );
        return;
    }

    let report = match outcome {
        // Already one entry per member: the handler wrapper reconciles what the
        // handler answered against what it was given.
        // A member that failed is that member's report, not the handler's
        // failure: the handler call itself went through.
        BatchOutcome::Reported(report) => {
            otel::record_ok(&span);
            report
        }
        BatchOutcome::FailedAll(error) => {
            otel::record_error(&span, error.message());
            span.in_scope(|| {
                tracing::warn!(
                    batch_id = ?action.batch_id,
                    action_id = %action.action_id,
                    members = members.len(),
                    retryable = error.is_retryable(),
                    message = error.message(),
                    "a batch failed as a whole",
                );
            });
            batch::fail_all(&members, &error)
        }
        BatchOutcome::Stopped => return,
    };

    let mut completed: Vec<(BatchMemberId, Value)> = Vec::new();
    let mut failed: Vec<(BatchMemberId, TaskError)> = Vec::new();
    for (id, result) in report {
        match result {
            Ok(output) => completed.push((id, output)),
            Err(error) => failed.push((id, error)),
        }
    }

    // Two reports at most, because one `event_type` covers a whole event.
    // Completions first: if the second call never goes through, the members
    // whose work is done are recorded as done.
    if !completed.is_empty() {
        (inner.report_batch)(events::batch_completed(
            &action,
            &inner.worker_id,
            &completed,
        ))
        .await;
    }
    if !failed.is_empty() {
        tracing::warn!(
            batch_id = ?action.batch_id,
            action_id = %action.action_id,
            members = failed.len(),
            "some members of a batch failed",
        );
        (inner.report_batch)(events::batch_failed(&action, &inner.worker_id, &failed)).await;
    }
}

/// Runs the batch handler for one action, turning everything that can go wrong
/// into something every member can be told.
async fn execute_batch(
    inner: &Inner,
    action: &AssignedAction,
    cancel: CancellationToken,
    slot: Slot,
    span: &Span,
) -> BatchOutcome {
    let Some(handler) = inner
        .handlers
        .get(&action.action_id)
        .and_then(|registered| registered.batch.clone())
    else {
        return BatchOutcome::FailedAll(TaskError::non_retryable(format!(
            "this worker has no batch task registered for the action `{}`",
            action.action_id
        )));
    };
    // The batch's own context: its per-run accessors are empty, which
    // `Context`'s rustdoc says in as many words. Cancellation and the slot are
    // what a batch handler can really use, and both are the whole batch's.
    let context = match Context::new(
        action.clone(),
        inner.worker_id.clone(),
        inner.client.clone(),
        cancel,
        slot,
        None,
    ) {
        Ok(context) => context,
        Err(reason) => return BatchOutcome::FailedAll(TaskError::non_retryable(reason)),
    };

    // A task of its own, so a panic inside the handler fails the batch instead
    // of unwinding the worker, and cannot outlive the batch that owns it.
    let assignment = action.clone();
    let mut handler_task = AbortOnDrop(tokio::spawn(
        async move { handler(context, assignment).await }.instrument(span.clone()),
    ));
    match (&mut handler_task.0).await {
        Ok(Ok(report)) => BatchOutcome::Reported(report),
        // The handler failed, or its items could not be read at all: either
        // way nothing is known about any one member, so they all fail alike.
        Ok(Err(error)) => BatchOutcome::FailedAll(error),
        Err(error) if error.is_panic() => {
            let message = panic_message(error.into_panic());
            tracing::error!(
                batch_id = ?action.batch_id,
                action_id = %action.action_id,
                message,
                "a batch handler panicked",
            );
            // Retryable for the same reason an ordinary run's panic is: it
            // might not happen again. A batch task has no retries of its own,
            // so it is the engine that decides what that means.
            BatchOutcome::FailedAll(TaskError::new(message))
        }
        Err(_) => BatchOutcome::Stopped,
    }
}

/// What a batch has to say for itself.
enum BatchOutcome {
    /// One outcome per member, as the handler wrapper reconciled them.
    Reported(BatchReport),
    /// Every member fails the same way: the handler returned an error or
    /// panicked, the payload could not be read, or there was no handler to
    /// call.
    FailedAll(TaskError),
    /// Nothing to report: the batch was dropped before it produced anything.
    Stopped,
}

/// What a run has to say for itself.
enum Outcome {
    Completed(Value),
    Failed(TaskError),
    /// Nothing to report: the run was dropped before it produced anything.
    Stopped,
}

/// A run's place in the runner's books, given up when the run's task ends.
struct Registration {
    inner: Arc<Inner>,
    id: String,
    seq: u64,
}

impl Drop for Registration {
    fn drop(&mut self) {
        self.inner.finish(&self.id, self.seq);
    }
}

/// Gives a run's slot back to the worker when the run's future is dropped —
/// which is every way a run can end, since the future owns this guard.
///
/// Releasing here rather than letting the last [`Slot`] clone do it is what
/// keeps a `Context` a handler leaked into a detached task from holding the
/// worker's slot after the run is over. Releasing a slot the handler already
/// released is a no-op, so the two paths cannot both credit the semaphore.
struct SlotGuard(Slot);

impl Drop for SlotGuard {
    fn drop(&mut self) {
        self.0.release();
    }
}

/// A task that is aborted when this handle is dropped.
struct AbortOnDrop<T>(JoinHandle<T>);

impl<T> Drop for AbortOnDrop<T> {
    fn drop(&mut self) {
        self.0.abort();
    }
}

/// The message a panic carried, if it carried one this SDK can read: `panic!`
/// with a literal or a formatted string covers nearly every handler.
fn panic_message(payload: Box<dyn Any + Send>) -> String {
    let detail = payload
        .downcast_ref::<&'static str>()
        .map(|message| (*message).to_string())
        .or_else(|| payload.downcast_ref::<String>().cloned());
    match detail {
        Some(detail) => format!("task panicked: {detail}"),
        None => "task panicked".to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Register, TaskBuilder, TaskError};
    use hatchet_proto::root::{ActionType, StepActionEventType};
    use serde::{Deserialize, Serialize};
    use serde_json::{Value, json};
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use tokio::sync::Semaphore;
    use tokio::sync::mpsc;
    use tokio::sync::mpsc::error::TryRecvError;
    use tokio::time::Instant;

    #[derive(Deserialize, Serialize)]
    struct In {
        repo: String,
    }

    #[derive(Deserialize, Serialize)]
    struct Out {
        pr: String,
    }

    /// Nothing in these tests may block forever: a regression should fail the
    /// test rather than hang the suite.
    const NEVER: Duration = Duration::from_secs(10);

    /// The first action of a declaration, with its handler.
    fn handler_of<R: Register>(task: &R) -> (String, RegisteredAction) {
        let mut actions = task
            .definition()
            .actions("")
            .expect("the task declaration is valid");
        actions.remove(0)
    }

    /// A runner whose reports land in the returned channel. Its batch reports
    /// go nowhere: [`runner_with_batch`] is for those.
    fn runner_with(
        handlers: Vec<(String, RegisteredAction)>,
        slots: usize,
    ) -> (Runner, mpsc::UnboundedReceiver<StepActionEvent>) {
        let (tx, rx) = mpsc::unbounded_channel();
        let report: Reporter = Arc::new(move |event: StepActionEvent| {
            let tx = tx.clone();
            Box::pin(async move {
                let _ = tx.send(event);
            })
        });
        let runner = Runner::new(
            "worker-1".to_string(),
            None,
            handlers.into_iter().collect(),
            slots,
            None,
            report,
            discarded_batch_reports(),
        );
        (runner, rx)
    }

    /// A runner whose **batch** reports land in the returned channel.
    fn runner_with_batch(
        handlers: Vec<(String, RegisteredAction)>,
        slots: usize,
    ) -> (Runner, mpsc::UnboundedReceiver<BatchActionEvent>) {
        let (tx, rx) = mpsc::unbounded_channel();
        let report_batch: BatchReporter = Arc::new(move |event: BatchActionEvent| {
            let tx = tx.clone();
            Box::pin(async move {
                let _ = tx.send(event);
            })
        });
        let runner = Runner::new(
            "worker-1".to_string(),
            None,
            handlers.into_iter().collect(),
            slots,
            None,
            Arc::new(|_event| Box::pin(async {})),
            report_batch,
        );
        (runner, rx)
    }

    /// Batch reports that go nowhere, for the tests that are about ordinary
    /// runs.
    fn discarded_batch_reports() -> BatchReporter {
        Arc::new(|_event| Box::pin(async {}))
    }

    fn start_action(action_id: &str, run_id: &str, input: Value) -> AssignedAction {
        start_action_with_payload(action_id, run_id, &json!({ "input": input }).to_string())
    }

    fn start_action_with_payload(action_id: &str, run_id: &str, payload: &str) -> AssignedAction {
        AssignedAction {
            action_type: ActionType::StartStepRun as i32,
            action_id: action_id.to_string(),
            task_run_external_id: run_id.to_string(),
            action_payload: payload.to_string(),
            ..AssignedAction::default()
        }
    }

    fn cancel_action(run_id: &str) -> AssignedAction {
        AssignedAction {
            action_type: ActionType::CancelStepRun as i32,
            task_run_external_id: run_id.to_string(),
            ..AssignedAction::default()
        }
    }

    fn event_type(event: &StepActionEvent) -> StepActionEventType {
        StepActionEventType::try_from(event.event_type).expect("a known event type")
    }

    /// The next item, or a failed test — never a hang.
    async fn next<T>(rx: &mut mpsc::UnboundedReceiver<T>) -> T {
        tokio::time::timeout(NEVER, rx.recv())
            .await
            .expect("timed out waiting for the next item")
            .expect("the channel is still open")
    }

    /// Awaits something that is meant to finish, or fails the test. The bound
    /// is never reached when the code under test behaves.
    async fn within<F: Future>(future: F) -> F::Output {
        tokio::time::timeout(NEVER, future)
            .await
            .expect("timed out waiting for the worker to let go")
    }

    /// Waits for the runner to hold `count` runs, without sleeping.
    async fn wait_for_in_flight(runner: &Runner, count: usize) {
        for _ in 0..1000 {
            if runner.in_flight() == count {
                return;
            }
            tokio::task::yield_now().await;
        }
        panic!("{} runs stayed in flight, not {count}", runner.in_flight());
    }

    /// Waits for the runner to let go of every run, without sleeping.
    async fn wait_until_idle(runner: &Runner) {
        wait_for_in_flight(runner, 0).await;
    }

    /// A task that always succeeds, plus a channel that reports every entry
    /// into its handler.
    fn gated_task(
        name: &str,
        gate: Arc<Semaphore>,
    ) -> (crate::Task<Value, Value>, mpsc::UnboundedReceiver<()>) {
        let (entered_tx, entered_rx) = mpsc::unbounded_channel();
        let task = TaskBuilder::<Value, Value>::new(name).handler(move |_ctx, input: Value| {
            let gate = Arc::clone(&gate);
            let entered = entered_tx.clone();
            async move {
                let _ = entered.send(());
                gate.acquire().await.expect("the gate stays open").forget();
                Ok(input)
            }
        });
        (task, entered_rx)
    }

    #[tokio::test]
    async fn success_reports_started_then_completed() {
        let task = TaskBuilder::<In, Out>::new("agent-run")
            .handler(|_ctx, input: In| async move { Ok(Out { pr: input.repo }) });
        let (action_id, handler) = handler_of(&task);
        let (runner, mut events) = runner_with(vec![(action_id.clone(), handler)], 4);

        runner.dispatch(start_action(&action_id, "run-1", json!({"repo": "x"})));

        let started = next(&mut events).await;
        assert_eq!(
            event_type(&started),
            StepActionEventType::StepEventTypeStarted
        );
        assert_eq!(started.task_run_external_id, "run-1");
        assert_eq!(started.worker_id, "worker-1");
        assert_eq!(started.event_payload, "");

        let completed = next(&mut events).await;
        assert_eq!(
            event_type(&completed),
            StepActionEventType::StepEventTypeCompleted
        );
        assert_eq!(completed.event_payload, json!({"pr": "x"}).to_string());
        assert_eq!(completed.should_not_retry, None);

        wait_until_idle(&runner).await;
    }

    #[tokio::test]
    async fn a_retryable_error_reports_failed_without_should_not_retry() {
        let task = TaskBuilder::<Value, Value>::new("flaky")
            .handler(|_ctx, _input: Value| async move { Err(TaskError::new("the api was down")) });
        let (action_id, handler) = handler_of(&task);
        let (runner, mut events) = runner_with(vec![(action_id.clone(), handler)], 4);

        runner.dispatch(start_action(&action_id, "run-1", json!(null)));

        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeStarted
        );
        let failed = next(&mut events).await;
        assert_eq!(
            event_type(&failed),
            StepActionEventType::StepEventTypeFailed
        );
        assert_eq!(failed.event_payload, "\"the api was down\"");
        assert_eq!(failed.should_not_retry, None);
    }

    #[tokio::test]
    async fn a_non_retryable_error_reports_failed_with_should_not_retry() {
        let task =
            TaskBuilder::<Value, Value>::new("doomed").handler(|_ctx, _input: Value| async move {
                Err(TaskError::non_retryable("the repo does not exist"))
            });
        let (action_id, handler) = handler_of(&task);
        let (runner, mut events) = runner_with(vec![(action_id.clone(), handler)], 4);

        runner.dispatch(start_action(&action_id, "run-1", json!(null)));

        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeStarted
        );
        let failed = next(&mut events).await;
        assert_eq!(
            event_type(&failed),
            StepActionEventType::StepEventTypeFailed
        );
        assert_eq!(failed.event_payload, "\"the repo does not exist\"");
        assert_eq!(failed.should_not_retry, Some(true));
    }

    #[tokio::test]
    async fn a_panic_reports_failed_and_the_runner_keeps_working() {
        let exploding = TaskBuilder::<Value, Value>::new("exploding")
            .handler(|_ctx, _input: Value| async move { panic!("boom") });
        let fine = TaskBuilder::<Value, Value>::new("fine")
            .handler(|_ctx, input: Value| async move { Ok(input) });
        let (bad_id, bad_handler) = handler_of(&exploding);
        let (good_id, good_handler) = handler_of(&fine);
        let (runner, mut events) = runner_with(
            vec![
                (bad_id.clone(), bad_handler),
                (good_id.clone(), good_handler),
            ],
            4,
        );

        runner.dispatch(start_action(&bad_id, "run-1", json!(null)));
        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeStarted
        );
        let failed = next(&mut events).await;
        assert_eq!(
            event_type(&failed),
            StepActionEventType::StepEventTypeFailed
        );
        assert!(failed.event_payload.contains("boom"), "{failed:?}");
        assert_eq!(
            failed.should_not_retry, None,
            "a panic might not repeat, so it stays retryable"
        );

        runner.dispatch(start_action(&good_id, "run-2", json!("still here")));
        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeStarted
        );
        let completed = next(&mut events).await;
        assert_eq!(
            event_type(&completed),
            StepActionEventType::StepEventTypeCompleted
        );
        assert_eq!(completed.task_run_external_id, "run-2");
    }

    #[tokio::test]
    async fn input_of_the_wrong_shape_reports_a_non_retryable_failure_and_the_runner_keeps_working()
    {
        let task = TaskBuilder::<In, Out>::new("agent-run")
            .handler(|_ctx, input: In| async move { Ok(Out { pr: input.repo }) });
        let (action_id, handler) = handler_of(&task);
        let (runner, mut events) = runner_with(vec![(action_id.clone(), handler)], 4);

        runner.dispatch(start_action(&action_id, "run-1", json!({"repo": 42})));
        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeStarted
        );
        let failed = next(&mut events).await;
        assert_eq!(
            event_type(&failed),
            StepActionEventType::StepEventTypeFailed
        );
        assert_eq!(failed.should_not_retry, Some(true));
        assert!(failed.event_payload.contains("input"), "{failed:?}");

        runner.dispatch(start_action(&action_id, "run-2", json!({"repo": "x"})));
        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeStarted
        );
        let completed = next(&mut events).await;
        assert_eq!(
            event_type(&completed),
            StepActionEventType::StepEventTypeCompleted
        );
        assert_eq!(completed.event_payload, json!({"pr": "x"}).to_string());
    }

    #[tokio::test]
    async fn a_payload_that_is_not_json_reports_a_non_retryable_failure() {
        let task = TaskBuilder::<Value, Value>::new("fine")
            .handler(|_ctx, input: Value| async move { Ok(input) });
        let (action_id, handler) = handler_of(&task);
        let (runner, mut events) = runner_with(vec![(action_id.clone(), handler)], 4);

        runner.dispatch(start_action_with_payload(
            &action_id,
            "run-1",
            "not json at all",
        ));

        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeStarted
        );
        let failed = next(&mut events).await;
        assert_eq!(
            event_type(&failed),
            StepActionEventType::StepEventTypeFailed
        );
        assert_eq!(failed.should_not_retry, Some(true));
        assert!(failed.event_payload.contains("payload"), "{failed:?}");
        wait_until_idle(&runner).await;
    }

    #[tokio::test]
    async fn an_unknown_action_reports_a_non_retryable_failure_naming_it() {
        let (runner, mut events) = runner_with(Vec::new(), 4);

        runner.dispatch(start_action("ghost:step", "run-1", json!(null)));

        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeStarted
        );
        let failed = next(&mut events).await;
        assert_eq!(
            event_type(&failed),
            StepActionEventType::StepEventTypeFailed
        );
        assert_eq!(failed.should_not_retry, Some(true));
        assert!(failed.event_payload.contains("ghost:step"), "{failed:?}");
    }

    #[tokio::test]
    async fn cancel_fires_the_token_and_suppresses_the_terminal_event() {
        let observed = Arc::new(AtomicBool::new(false));
        let waiting = TaskBuilder::<Value, Value>::new("waiting").handler({
            let observed = Arc::clone(&observed);
            move |ctx: crate::Context, _input: Value| {
                let observed = Arc::clone(&observed);
                async move {
                    ctx.cancelled().await;
                    observed.store(true, Ordering::SeqCst);
                    Ok(json!("finished anyway"))
                }
            }
        });
        let fine = TaskBuilder::<Value, Value>::new("fine")
            .handler(|_ctx, input: Value| async move { Ok(input) });
        let (waiting_id, waiting_handler) = handler_of(&waiting);
        let (fine_id, fine_handler) = handler_of(&fine);
        let (runner, mut events) = runner_with(
            vec![
                (waiting_id.clone(), waiting_handler),
                (fine_id.clone(), fine_handler),
            ],
            4,
        );

        runner.dispatch(start_action(&waiting_id, "run-1", json!(null)));
        let started = next(&mut events).await;
        assert_eq!(
            event_type(&started),
            StepActionEventType::StepEventTypeStarted
        );
        assert_eq!(started.task_run_external_id, "run-1");

        runner.dispatch(cancel_action("run-1"));
        wait_until_idle(&runner).await;
        assert!(
            observed.load(Ordering::SeqCst),
            "the handler never saw the cancellation"
        );

        // The next events on the wire belong to another run: the cancelled
        // one reported nothing after STARTED.
        runner.dispatch(start_action(&fine_id, "run-2", json!("ok")));
        let started = next(&mut events).await;
        assert_eq!(
            event_type(&started),
            StepActionEventType::StepEventTypeStarted
        );
        assert_eq!(started.task_run_external_id, "run-2");
        let completed = next(&mut events).await;
        assert_eq!(
            event_type(&completed),
            StepActionEventType::StepEventTypeCompleted
        );
        assert_eq!(completed.task_run_external_id, "run-2");
        assert!(matches!(events.try_recv(), Err(TryRecvError::Empty)));
    }

    #[tokio::test]
    async fn a_report_that_panics_still_lets_go_of_the_run() {
        let task = TaskBuilder::<Value, Value>::new("fine")
            .handler(|_ctx, input: Value| async move { Ok(input) });
        let (action_id, handler) = handler_of(&task);
        let (tx, mut events) = mpsc::unbounded_channel();
        let report: Reporter = Arc::new(move |event: StepActionEvent| {
            let tx = tx.clone();
            Box::pin(async move {
                let terminal = event.event_type != StepActionEventType::StepEventTypeStarted as i32;
                let _ = tx.send(event);
                assert!(!terminal, "this reporter refuses terminal events");
            })
        });
        let runner = Runner::new(
            "worker-1".to_string(),
            None,
            HashMap::from([(action_id.clone(), handler)]),
            4,
            None,
            report,
            discarded_batch_reports(),
        );

        runner.dispatch(start_action(&action_id, "run-1", json!("ok")));
        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeStarted
        );
        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeCompleted
        );

        // The reporting task panics right after; the run must still give up
        // its place, or the worker would never drain.
        wait_until_idle(&runner).await;
    }

    #[tokio::test]
    async fn cancel_for_an_unknown_run_is_ignored() {
        let task = TaskBuilder::<Value, Value>::new("fine")
            .handler(|_ctx, input: Value| async move { Ok(input) });
        let (action_id, handler) = handler_of(&task);
        let (runner, mut events) = runner_with(vec![(action_id.clone(), handler)], 4);

        runner.dispatch(cancel_action("a-run-from-another-worker"));
        assert_eq!(runner.in_flight(), 0);

        // The runner is unharmed.
        runner.dispatch(start_action(&action_id, "run-1", json!("ok")));
        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeStarted
        );
        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeCompleted
        );
    }

    fn batch_action(action_id: &str, payload: &str) -> AssignedAction {
        AssignedAction {
            action_type: ActionType::StartBatch as i32,
            action_id: action_id.to_string(),
            action_payload: payload.to_string(),
            batch_id: Some("b-1".to_string()),
            ..AssignedAction::default()
        }
    }

    /// There is nobody to report to, so the batch is dropped rather than
    /// reported about — the one case where silence is the only answer.
    #[tokio::test]
    async fn a_batch_naming_no_members_is_dropped_without_a_report() {
        let task = TaskBuilder::<Value, Value>::new("t")
            .batch_handler(crate::BatchConfig::max_size(2), |_ctx, _batch| async move {
                Ok(crate::BatchOutput::new())
            });
        let (action_id, handler) = handler_of(&task);
        let (runner, mut events) = runner_with_batch(vec![(action_id.clone(), handler)], 4);

        for nobody in ["{}", "[1, 2]", "not json at all", ""] {
            runner.dispatch(batch_action(&action_id, nobody));
        }

        wait_until_idle(&runner).await;
        assert!(
            matches!(events.try_recv(), Err(TryRecvError::Empty)),
            "a batch with no members reported something",
        );
    }

    /// The engine assigned a batch for an action this worker does not serve:
    /// every member has to be told, or every one of them hangs.
    #[tokio::test]
    async fn a_batch_for_an_unknown_action_fails_every_member() {
        let (runner, mut events) = runner_with_batch(Vec::new(), 4);

        runner.dispatch(batch_action(
            "ghost:step",
            &json!({"run-a": {}, "run-b": {}}).to_string(),
        ));

        let started = next(&mut events).await;
        assert_eq!(
            started.event_type,
            StepActionEventType::StepEventTypeStarted as i32
        );
        assert_eq!(started.items.len(), 2);
        let failed = next(&mut events).await;
        assert_eq!(
            failed.event_type,
            StepActionEventType::StepEventTypeFailed as i32
        );
        assert_eq!(failed.items.len(), 2);
        assert!(
            failed.items[0].event_payload.contains("ghost:step"),
            "{:?}",
            failed.items[0],
        );
        assert!(
            failed
                .items
                .iter()
                .all(|item| item.should_not_retry == Some(true))
        );
        wait_until_idle(&runner).await;
    }

    #[tokio::test]
    async fn unsupported_action_types_are_ignored() {
        let task = TaskBuilder::<Value, Value>::new("fine")
            .handler(|_ctx, input: Value| async move { Ok(input) });
        let (action_id, handler) = handler_of(&task);
        let (runner, mut events) = runner_with(vec![(action_id.clone(), handler)], 4);

        runner.dispatch(AssignedAction {
            action_type: ActionType::StartGetGroupKey as i32,
            ..start_action(&action_id, "run-1", json!(null))
        });

        for _ in 0..10 {
            tokio::task::yield_now().await;
        }
        assert_eq!(runner.in_flight(), 0);
        assert!(matches!(events.try_recv(), Err(TryRecvError::Empty)));
    }

    #[tokio::test]
    async fn slots_bound_concurrency() {
        let gate = Arc::new(Semaphore::new(0));
        let running = Arc::new(AtomicUsize::new(0));
        let peak = Arc::new(AtomicUsize::new(0));
        let (entered_tx, mut entered) = mpsc::unbounded_channel();
        let task = TaskBuilder::<Value, Value>::new("gated").handler({
            let gate = Arc::clone(&gate);
            let running = Arc::clone(&running);
            let peak = Arc::clone(&peak);
            move |_ctx, input: Value| {
                let gate = Arc::clone(&gate);
                let running = Arc::clone(&running);
                let peak = Arc::clone(&peak);
                let entered = entered_tx.clone();
                async move {
                    let now = running.fetch_add(1, Ordering::SeqCst) + 1;
                    peak.fetch_max(now, Ordering::SeqCst);
                    let _ = entered.send(());
                    gate.acquire().await.expect("the gate stays open").forget();
                    running.fetch_sub(1, Ordering::SeqCst);
                    Ok(input)
                }
            }
        });
        let (action_id, handler) = handler_of(&task);
        let (runner, mut events) = runner_with(vec![(action_id.clone(), handler)], 2);

        for n in 1..=3 {
            runner.dispatch(start_action(&action_id, &format!("run-{n}"), json!(n)));
        }

        for _ in 0..2 {
            assert_eq!(
                event_type(&next(&mut events).await),
                StepActionEventType::StepEventTypeStarted
            );
        }
        assert!(
            matches!(events.try_recv(), Err(TryRecvError::Empty)),
            "only two runs hold a slot, so nothing else can be reported yet"
        );
        for _ in 0..2 {
            next(&mut entered).await;
        }
        assert!(
            matches!(entered.try_recv(), Err(TryRecvError::Empty)),
            "a third run entered its handler without a slot"
        );
        assert_eq!(runner.in_flight(), 3);

        gate.add_permits(3);
        let mut completed = 0;
        while completed < 3 {
            if event_type(&next(&mut events).await) == StepActionEventType::StepEventTypeCompleted {
                completed += 1;
            }
        }
        assert_eq!(
            peak.load(Ordering::SeqCst),
            2,
            "more than two handlers ran at once"
        );
        wait_until_idle(&runner).await;
    }

    /// Waits for one run's event, reading past everything else on the wire,
    /// and hands back what was read on the way.
    async fn drain_until(
        events: &mut mpsc::UnboundedReceiver<StepActionEvent>,
        run_id: &str,
        kind: StepActionEventType,
    ) -> Vec<StepActionEvent> {
        let mut seen = Vec::new();
        loop {
            let event = next(events).await;
            let found = event.task_run_external_id == run_id && event_type(&event) == kind;
            seen.push(event);
            if found {
                return seen;
            }
        }
    }

    /// The local half of `Context::release_slot`: a handler that gives its
    /// slot back must free this worker to start another run at once, not
    /// merely the engine's count of it. And exactly once — a slot given back
    /// twice would leave the worker running one more task than it has slots,
    /// for the rest of its life.
    #[tokio::test]
    async fn release_slot_frees_the_local_slot_for_the_next_run() {
        let waiting_gate = Arc::new(Semaphore::new(0));
        let (releasing_tx, mut released) = mpsc::unbounded_channel();
        let releasing = TaskBuilder::<Value, Value>::new("releasing").handler({
            let gate = Arc::clone(&waiting_gate);
            move |ctx: crate::Context, input: Value| {
                let gate = Arc::clone(&gate);
                let entered = releasing_tx.clone();
                async move {
                    // What `Context::release_slot` does once the engine has
                    // agreed — this context has no engine to ask.
                    ctx.release_local_slot();
                    let _ = entered.send(());
                    gate.acquire().await.expect("the gate stays open").forget();
                    Ok(input)
                }
            }
        });
        let fine = TaskBuilder::<Value, Value>::new("fine")
            .handler(|_ctx, input: Value| async move { Ok(input) });
        let second_gate = Arc::new(Semaphore::new(0));
        let (gated, mut gated_entered) = gated_task("gated", Arc::clone(&second_gate));

        let (releasing_id, releasing_handler) = handler_of(&releasing);
        let (fine_id, fine_handler) = handler_of(&fine);
        let (gated_id, gated_handler) = handler_of(&gated);
        // One slot: nothing else runs here until the first run gives it back.
        let (runner, mut events) = runner_with(
            vec![
                (releasing_id.clone(), releasing_handler),
                (fine_id.clone(), fine_handler),
                (gated_id.clone(), gated_handler),
            ],
            1,
        );

        runner.dispatch(start_action(&releasing_id, "run-1", json!(null)));
        next(&mut released).await;

        // The first handler is still blocked on its gate, but its slot is
        // free: the second run must start and finish regardless.
        runner.dispatch(start_action(&fine_id, "run-2", json!("second")));
        let seen = drain_until(
            &mut events,
            "run-2",
            StepActionEventType::StepEventTypeCompleted,
        )
        .await;
        assert!(
            !seen.iter().any(|event| {
                event.task_run_external_id == "run-1"
                    && event_type(event) == StepActionEventType::StepEventTypeCompleted
            }),
            "the first run finished before its gate opened: {seen:?}",
        );

        waiting_gate.add_permits(1);
        drain_until(
            &mut events,
            "run-1",
            StepActionEventType::StepEventTypeCompleted,
        )
        .await;
        wait_until_idle(&runner).await;

        // The worker is back to exactly one slot, not two: of the next two
        // runs, one starts and the other waits.
        runner.dispatch(start_action(&gated_id, "run-3", json!(null)));
        runner.dispatch(start_action(&gated_id, "run-4", json!(null)));
        next(&mut gated_entered).await;
        wait_for_in_flight(&runner, 2).await;
        for _ in 0..100 {
            tokio::task::yield_now().await;
        }
        assert!(
            matches!(gated_entered.try_recv(), Err(TryRecvError::Empty)),
            "two runs held the worker's single slot: the permit was released twice",
        );

        second_gate.add_permits(2);
        wait_until_idle(&runner).await;
    }

    /// A handler may hand a `Context` clone to something that outlives the
    /// run. The slot belongs to the run, not to the clone.
    #[tokio::test]
    async fn a_leaked_context_clone_does_not_pin_the_slot() {
        let leaky = TaskBuilder::<Value, Value>::new("leaky").handler(
            |ctx: crate::Context, input: Value| async move {
                tokio::spawn(async move {
                    let _leaked = ctx;
                    std::future::pending::<()>().await;
                });
                Ok(input)
            },
        );
        let fine = TaskBuilder::<Value, Value>::new("fine")
            .handler(|_ctx, input: Value| async move { Ok(input) });
        let (leaky_id, leaky_handler) = handler_of(&leaky);
        let (fine_id, fine_handler) = handler_of(&fine);
        // One slot, so the second run can only start if the first let go.
        let (runner, mut events) = runner_with(
            vec![
                (leaky_id.clone(), leaky_handler),
                (fine_id.clone(), fine_handler),
            ],
            1,
        );

        runner.dispatch(start_action(&leaky_id, "run-1", json!(null)));
        drain_until(
            &mut events,
            "run-1",
            StepActionEventType::StepEventTypeCompleted,
        )
        .await;
        wait_until_idle(&runner).await;

        runner.dispatch(start_action(&fine_id, "run-2", json!("ok")));
        let completed = drain_until(
            &mut events,
            "run-2",
            StepActionEventType::StepEventTypeCompleted,
        )
        .await;
        assert_eq!(
            completed.last().expect("the run completed").event_payload,
            "\"ok\""
        );
    }

    #[tokio::test]
    async fn cancelling_a_queued_run_skips_it_entirely() {
        let gate = Arc::new(Semaphore::new(0));
        let (task, mut entered) = gated_task("gated", Arc::clone(&gate));
        let (action_id, handler) = handler_of(&task);
        let (runner, mut events) = runner_with(vec![(action_id.clone(), handler)], 1);

        runner.dispatch(start_action(&action_id, "run-1", json!("first")));
        let started = next(&mut events).await;
        assert_eq!(started.task_run_external_id, "run-1");
        next(&mut entered).await;

        // The second run has nowhere to go until the first finishes.
        runner.dispatch(start_action(&action_id, "run-2", json!("second")));
        assert_eq!(runner.in_flight(), 2);

        // Cancelling it must let it go at once — while the gate is still shut,
        // so the slot it was queued for has not come free. A queued run that
        // waited for its turn before noticing would hold a shutting-down
        // worker open for the whole drain.
        runner.dispatch(cancel_action("run-2"));
        wait_for_in_flight(&runner, 1).await;

        gate.add_permits(1);
        let completed = next(&mut events).await;
        assert_eq!(
            event_type(&completed),
            StepActionEventType::StepEventTypeCompleted
        );
        assert_eq!(completed.task_run_external_id, "run-1");
        wait_until_idle(&runner).await;

        assert!(
            matches!(entered.try_recv(), Err(TryRecvError::Empty)),
            "the cancelled run ran its handler"
        );
        assert!(
            matches!(events.try_recv(), Err(TryRecvError::Empty)),
            "the cancelled run reported something"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn drain_waits_for_in_flight_runs() {
        let task =
            TaskBuilder::<Value, Value>::new("slow").handler(|_ctx, input: Value| async move {
                tokio::time::sleep(Duration::from_secs(3)).await;
                Ok(input)
            });
        let (action_id, handler) = handler_of(&task);
        let (runner, mut events) = runner_with(vec![(action_id.clone(), handler)], 4);

        let started_at = Instant::now();
        runner.dispatch(start_action(&action_id, "run-1", json!("slow")));
        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeStarted
        );

        within(runner.drain(Duration::from_secs(30))).await;

        let elapsed = started_at.elapsed();
        assert!(
            (Duration::from_secs(3)..Duration::from_secs(4)).contains(&elapsed),
            "drain returned after {elapsed:?}"
        );
        assert_eq!(runner.in_flight(), 0);
        let completed = next(&mut events).await;
        assert_eq!(
            event_type(&completed),
            StepActionEventType::StepEventTypeCompleted
        );
    }

    #[tokio::test(start_paused = true)]
    async fn drain_cancels_what_outlives_the_grace_period() {
        let observed = Arc::new(AtomicBool::new(false));
        let task = TaskBuilder::<Value, Value>::new("waiting").handler({
            let observed = Arc::clone(&observed);
            move |ctx: crate::Context, input: Value| {
                let observed = Arc::clone(&observed);
                async move {
                    ctx.cancelled().await;
                    observed.store(true, Ordering::SeqCst);
                    Ok(input)
                }
            }
        });
        let (action_id, handler) = handler_of(&task);
        let (runner, mut events) = runner_with(vec![(action_id.clone(), handler)], 4);

        let started_at = Instant::now();
        runner.dispatch(start_action(&action_id, "run-1", json!("waiting")));
        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeStarted
        );

        within(runner.drain(Duration::from_secs(5))).await;

        let elapsed = started_at.elapsed();
        assert!(
            (Duration::from_secs(5)..Duration::from_millis(6_500)).contains(&elapsed),
            "drain returned after {elapsed:?}"
        );
        assert!(
            observed.load(Ordering::SeqCst),
            "the handler never saw the cancellation"
        );
        assert_eq!(runner.in_flight(), 0);
        assert!(
            matches!(events.try_recv(), Err(TryRecvError::Empty)),
            "a cancelled run reported a terminal event"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn drain_aborts_handlers_that_ignore_cancellation() {
        let task = TaskBuilder::<Value, Value>::new("stuck").handler(|_ctx, _input: Value| async {
            std::future::pending::<()>().await;
            Ok(json!(null))
        });
        let (action_id, handler) = handler_of(&task);
        let (runner, mut events) = runner_with(vec![(action_id.clone(), handler)], 4);

        let started_at = Instant::now();
        runner.dispatch(start_action(&action_id, "run-1", json!(null)));
        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeStarted
        );

        within(runner.drain(Duration::from_secs(5))).await;

        let elapsed = started_at.elapsed();
        assert!(
            elapsed < Duration::from_secs(7),
            "drain returned after {elapsed:?}"
        );
        assert_eq!(runner.in_flight(), 0);
        assert!(matches!(events.try_recv(), Err(TryRecvError::Empty)));
    }

    #[tokio::test(start_paused = true)]
    async fn abort_all_drops_running_runs_and_frees_their_slots() {
        let (entered_tx, mut entered) = mpsc::unbounded_channel();
        let stuck =
            TaskBuilder::<Value, Value>::new("stuck").handler(move |_ctx, _input: Value| {
                let entered = entered_tx.clone();
                async move {
                    let _ = entered.send(());
                    std::future::pending::<()>().await;
                    Ok(json!(null))
                }
            });
        let fine = TaskBuilder::<Value, Value>::new("fine")
            .handler(|_ctx, input: Value| async move { Ok(input) });
        let (stuck_id, stuck_handler) = handler_of(&stuck);
        let (fine_id, fine_handler) = handler_of(&fine);
        // One slot, so the second run can only start if the first let go.
        let (runner, mut events) = runner_with(
            vec![
                (stuck_id.clone(), stuck_handler),
                (fine_id.clone(), fine_handler),
            ],
            1,
        );

        runner.dispatch(start_action(&stuck_id, "run-1", json!(null)));
        assert_eq!(
            event_type(&next(&mut events).await),
            StepActionEventType::StepEventTypeStarted
        );
        next(&mut entered).await;

        within(runner.abort_all()).await;
        assert_eq!(runner.in_flight(), 0);

        runner.dispatch(start_action(&fine_id, "run-2", json!("ok")));
        let started = next(&mut events).await;
        assert_eq!(
            event_type(&started),
            StepActionEventType::StepEventTypeStarted
        );
        assert_eq!(started.task_run_external_id, "run-2");
        let completed = next(&mut events).await;
        assert_eq!(
            event_type(&completed),
            StepActionEventType::StepEventTypeCompleted
        );
        assert_eq!(
            completed.task_run_external_id, "run-2",
            "the dropped run must not report anything"
        );
    }
}